Conditions for the map of sheaves $F\to F\otimes_{\mathcal O_Y}f_\ast \mathcal O_X$ to be an isomorphism

Question: Let $f:X\to Y$ be an immersion of locally noetherian separated schemes, for instance (not necessarily reduced) varieties over a field $k$. We can us assume $Y$ is affine.
Let $F$ be a quasi-coherent sheaf on $Y$. There is a canonical map
$$
F\overset{u}{\longrightarrow}F\otimes_{\mathcal O_Y}f_\ast \mathcal O_X.
$$
I wonder under what conditions on $f$ or on the sheaf $F$ the map $u$ is an isomorphism.

If $f$ is a closed immersion, then $u$ is surjective. Even in simple cases, like the thickening of a point $f:X=\textrm{Spec }\mathbb C\to Y=\textrm{Spec }\mathbb C[\epsilon]$, I do not seem to get beyond surjectivity.
If $f$ is an open immersion, I have the following example in mind. Suppose $f$ is the immersion of a distinguished open set, namely $f:X=\textrm{Spec }B_h\to Y=\textrm{Spec }B$ for some $h\in B$. Then for a $B$-module $F$, we are asking whether the $B$-linear localization map $F\to F\otimes_BB_h=F_h$ is an isomorphism. I would not expect this to happen very often. (For instance if $F=B$ then I do not think one can aim at anything better than injectivity.)

Even with such easy examples I tried to build, the condition I am after seems to fail pretty often for fixed $F$. So, keeping for simplicity the condition that $f$ be an immersion, I would like to ask:

What conditions on $F$ (possibly combined with additional conditions
  on $f$) make the map $u$ an isomorphism?

Example. Take case 2 ($f$ open immersion). Since $\mathcal O_Y\to f_\ast \mathcal O_X$ is an isomorphism when restricted to $X$, I was thinking to fix the previous bug by including the condition that the (scheme-theoretic) support of $F$ is contained in the image of $f$. Would that make sense?
Thanks!
Comment: You are right that in case 2 the map $u$ will only very rarely be surjective. Offhand I can only think of push-forward of coherent sheaves on closed subschemes included in the open subset (cf. my answer). For example a sky-scraper sheaf concentrated on a closed point of the open subset.
Comment: Just to make sure I understand: the Proposition in your answer (as well as the last sentence) refers to $f$ closed immersion right? But if $f:X\to Y$ is an open immersion and $X$ is an open neighborhood of the support of $F$, then are you saying $u$ is an isomorphism? In case $Supp(F)\subset X$, $F$ is certainly the pushforward of a sheaf on $X$.
Comment: Yes, the Proposition in my answer concerns a closed subscheme $f:X\hookrightarrow Y$. Suppose now that $i:U\hookrightarrow  Y$ is an open subscheme which happens to contain $X$, namely $j:X\hookrightarrow U$. Now, let $H$ be a quasi-coherent sheaf of $\mathcal O_X$-Modules on $X$ and let $G=j_\ast H$, a quasi-coherent sheaf of $\mathcal O_U$-Modules on $U$. The sheaf $F=i_\ast G$ has the required property that $u$ is an isomorphism (to be continued) .
Comment: (Continuation) The sheaf $G$ has indeed support in $X$, but it is not true that any quasi-coherent sheaf on U with support in $X$ is a sheaf of $\mathcal O_X$-Modules: cf. [this answer](http://math.stackexchange.com/a/1694206/3217). Hence my prudent formulation in terms of a quasi-coherent sheaf on $X$, and not in terms of support.
Answer: Here is the answer in the case of a closed immersion of schemes:
1) The affine case
Let $Y=\operatorname {Spec}(A)$ be an affine scheme and let $ F=\widetilde M$ be a quasi-coherent sheaf,  associated to the $A$-module $M$.
 Suppose $X=V(I)=\operatorname {Spec}(A/I)\hookrightarrow Y$ is the closed subscheme associated to the ideal $I\subset A$.
Then the map $F\overset{u}{\longrightarrow}F\otimes_{\mathcal O_Y}f_\ast \mathcal O_X$ corresponds to the $A$-module morphism $$M\overset{v}{\longrightarrow}M\otimes_AA/I=M/IM$$ That map is always surjective and will be injective iff $IM=0$,  which means exactly that $M$ is obtained by restricting scalars to $A$ from an $A/I$-module $N$ i.e. $M=N_{[A]}$.
2) Globalization: the general case
Let $Y$ be a scheme, $f: X\hookrightarrow Y$  a closed subscheme and $ F$  a quasi coherent sheaf on $Y$.
Proposition
The canonical map $F\longrightarrow F\otimes_{\mathcal O_Y}f_\ast \mathcal O_X $ of quasi-coherent shaves on $Y$ is always surjective.
It is bijective if and only if there exists a quasi-coherent sheaf $E$ on $X$ such that $F=f_\ast(E)$.


ISLR splines - degrees of freedom confusion?

Question: I'm working through the ISLR book and I am incredibly confused by question 9)d) of chapter 7. It uses the MASS::Boston dataset, and the question is as follows:

Use the bs() function to fit a regression spline to predict nox using dis. Report the output for the fit using four degrees of freedom. How did you choose the knots? Plot the resulting fit.

My understanding from the book is that a cubic spline with $K$ knots uses $4+K$ degrees of freedom. This makes sense to me, because if you have a cubic spline with $K = 1$ knot $\xi$, it can be represented by a cubic plus an additional truncated power basis function:
$$y = \beta_0 + \beta_1 x + \beta_2 x^2 + \beta_3 x^3 + \beta_4(x - \xi)_{+}^3$$
so there are  $5$ parameters to estimate. But if a cubic spline with one knot has 5 degrees of freedom, how am I supposed to select knots that achieve a "fit with 4 degrees of freedom"?
I thought it could possibly be a typo or perhaps the authors want me to use a quadratic spline instead so I have 'room' for a knot. If I just pass df = 4 into the bs() function in my linear model, I get a cubic spline with 1 knot, but since the model also has an intercept, my final fit has 5!
library(MASS)
library(gam)

spline_fit <- lm(nox ~ bs(dis, df = 4), data = Boston)

attr(bs(Boston$dis, df = 4), "knots") # 1 knot at 50%

summary(spline_fit)$df[1] # 5 degrees of freedom in total

I feel like the only way to reduce this to 4 degrees of freedom and still have at least 1 knot is to move from a cubic spline to quadratic/linear splines, but there the book almost exclusively uses cubic splines in the questions and examples so I am unsure if that's really what is expected.
There is something i'm not grasping here, but I don't know what! What model are the authors expecting when they say "Report the output for the fit using four degrees of freedom"?
Answer: There's several possibilities:

They intend you to fit an ordinary cubic regression spline with 4 df total. (In the context of this chapter, I think this is probably what they meant.)
The answer to "how did you choose the knots" is just "I didn't -- there's no d.f. left for any".

They meant "with 4 knots" rather than with 4df.
In this case you can proceed without difficulty. This may have been the intent but I doubt it.

They didn't intend you to count the intercept, leaving you with one knot.
This presents no difficulty. In this case (given the context of the chapter and the question) I doubt this was the intent.

They meant ns() not bs()
In this case you can proceed without difficulty. This might have been the intent but I'm not convinced of this either.

They meant bs and 4 df but intend you to use a lower order of polynomial.
In this case I'd tend to expect to see a linear spline rather than a quadratic, but they didn't mention either one. I don't think this was the intent; if it was I'd really expect them to mention it explicitly.

If you want to use the book as a personal learning tool, rather than just answer questions for some other purpose (say for an assignment), you would perhaps be better to consider each possibility in turn and try to fit them. That's usually my approach with self learning -- if it's not clear what the intent was, just do everything it might have been. With the data already there and so forth, the extra time to try each thing is pretty small.
Comment: Some books do omit it in regression discussion (counting the predictors rather than the parameters), but the ISLR discussion of `bs` doesn't. Nevertheless it's possible for them to forget that when writing the question.
Comment: Thanks a lot for the detailed answer! In part 3 about not including the intercept, is whether the intercept 'counts' as a degree of freedom something the varies from text to text? I was having trouble answering this question online, but I just stumbled across [this resource](https://www.andrew.cmu.edu/user/achoulde/95791/lectures/lecture02/lecture02-95791.pdf), slides 19 & 20, that seem to imply that this is the case. This isn't an assignment so I will follow your advice here and try all methods!


Error 404--Not Found aplicação Spring MVC

Question: Estou obtendo o erro

Error 404--Not Found: The server has not found anything matching the Request-URI

ao tentar acessar qualquer url da minha aplicação, o estranho é que a página index.jsp funciona normalmente, inclusive carregando os resources que defino no springmv-servlet.xml.
Estrutura do projeto:
+ siebelutilities
+-- WebContent/
  +-- META-INF/
  +-- resources/
  +-- WEB-INF/
    +-- jsp/
     +-- lib/
     +-- springmvc-servlet.xml
     +-- tiles.xml
     +-- web.xml
     +-- weblogic.xml

web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
    <display-name>siebelutilities</display-name>
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <listener>
        <listener-class>org.apache.tiles.extras.complete.CompleteAutoloadTilesListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>Tiles Dispatch Servlet</servlet-name>
        <servlet-class>org.apache.tiles.web.util.TilesDispatchServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Tiles Dispatch Servlet</servlet-name>
        <url-pattern>*.tiles</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

springmvc-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <context:component-scan base-package="com.eduardo.siebutil.service" />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <mvc:resources mapping="/resources/**" location="/resources/" cache-period="31556926" />
    <mvc:annotation-driven />
</beans>

Estou o @RequestMapping assim:
@RequestMapping(value = "/account/create")
public ModelAndView create() {
    ModelAndView model = new ModelAndView("/account/create");

    return model;
}

Comment: Colocando um debug na linha do ModelAndView model chega a passar ou não? Minha dúvida é se não está conseguindo encontrar o arquivo JSP ou o método, porque pelo erro esta dando a entender que ele não está encontrando um arquivo. O servidor não encontrou nada com a URL que foi passada. Acredito que dentro do construtor do ModelAndView você precisa passar o arquivo correspondente.
Comment: @GiancarloGiulian ele nem captura o breakpoint, eu utilizo essa configuração de servlet pra outros projetos Spring e funciona normalmente.
Answer: Resolvido, porém de maneira estranha, detectei um import de uma lib que eu não possuía no meu classpath e o eclipse não me acusava esse erro (The import xxx cannot be resolved). Ao fazer uma alteração no pom.xml fiz um update do projeto maven e aí foi detectado, então fiz um Project > Clean e minhas páginas estão sendo chamadas.
Comment: A princípio eu não estou enxergando nada, @GiancarloGiulian. Pensei que eu tinha desativado a Validação do eclipse para esse projeto mas ela está ativada, por isso não descarto a ideia de que o problema possa ser outro que acabou sendo resolvido indiretamente.
Comment: Obrigado pelo seu retorno, será que não tem uma configuração no seu Eclipse que esta ignorando esse erro?


Magento - Different image gallery block for specific products or categories

Question: I'm trying to change how the image gallery is displayed but only for specific products or specific categories. Using the developer display hints, I can see that the block I want to modify for certain products is output by media.phtml.
Suppose I have an alternate file called media-special.phtml, what XML do I need to use and where do I put that XML, to use media-special.phtml instead of media.phtml for specific products or specific categories?
Answer: Both categories and products allow you to save layout xml along with the entity record. In this field for the desired entities, add the following:
<code><action method="setTemplate" block="product.info.media">
    <tpl>path/to/media-special.phtml</tpl>
</action>
</code>
Comment: Thanks, one more question if you can please -- how did you find block="product.info.media"? Now I have the same problem trying to change other blocks with a custom .phtml file, where do you find the name of the block?
Comment: Turn on template path hints and search for the template names in layout XML, or (BETTER!) I recommend [Fabrizio Branca's Advanced Template Path Hints 2.0](http://www.fabrizio-branca.de/magento-advanced-template-hints-20.html).


Why does kivy fail when used with python's "elevate()" function?

Question: When using the elevate() function from the elevate module, kivy is unable to start. The relevant section of code is as follows:
from elevate import elevate
from os import environ

environ['DISPLAY'] = ':0'
environ['KIVY_WINDOW'] = 'sdl2'

elevate()

Later on, I give code for a kivy app and attempt to run it. I receive the following error when doing so:
[INFO   ] [Logger      ] Record log in /root/.kivy/logs/kivy_20-10-04_91.txt
[INFO   ] [Kivy        ] v2.0.0rc3, git-20c14b2, 20200615
[INFO   ] [Kivy        ] Installed at "/usr/local/lib/python3.8/dist-packages/Kivy-2.0.0rc3-py3.8-linux-x86_64.egg/kivy/__init__.py"
[INFO   ] [Python      ] v3.8.5 (default, Aug  2 2020, 15:09:07)
[GCC 10.2.0]
[INFO   ] [Python      ] Interpreter at "/usr/bin/python3"
[INFO   ] [Factory     ] 185 symbols loaded
[INFO   ] [Image       ] Providers: img_tex, img_dds, img_sdl2, img_pil (img_ffpyplayer, img_gif ignored)
[INFO   ] [KivyMD      ] 0.104.2.dev0, git-f0a8217, 2020-09-27 (installed at "/usr/local/lib/python3.8/dist-packages/kivymd-0.104.2.dev0-py3.8.egg/kivymd/__init__.py")
[INFO   ] [Text        ] Provider: sdl2
[INFO   ] [Window      ] Provider: sdl2
No protocol specified
[CRITICAL] [Window      ] Unable to find any valuable Window provider. Please enable debug logging (e.g. add -d if running from the command line, or change the log level in the config) and re-run your app to identify potential causes
sdl2 - RuntimeError: b'No available video device'
  File "/usr/local/lib/python3.8/dist-packages/Kivy-2.0.0rc3-py3.8-linux-x86_64.egg/kivy/core/__init__.py", line 70, in core_select_lib
    cls = cls()
  File "/usr/local/lib/python3.8/dist-packages/Kivy-2.0.0rc3-py3.8-linux-x86_64.egg/kivy/core/window/window_sdl2.py", line 152, in __init__
    super(WindowSDL, self).__init__()
  File "/usr/local/lib/python3.8/dist-packages/Kivy-2.0.0rc3-py3.8-linux-x86_64.egg/kivy/core/window/__init__.py", line 982, in __init__
    self.create_window()
  File "/usr/local/lib/python3.8/dist-packages/Kivy-2.0.0rc3-py3.8-linux-x86_64.egg/kivy/core/window/window_sdl2.py", line 287, in create_window
    self.system_size = _size = self._win.setup_window(
  File "kivy/core/window/_window_sdl2.pyx", line 112, in kivy.core.window._window_sdl2._WindowSDL2Storage.setup_window
  File "kivy/core/window/_window_sdl2.pyx", line 74, in kivy.core.window._window_sdl2._WindowSDL2Storage.die

[CRITICAL] [App         ] Unable to get a Window, abort.

How can I resolve this? I have tried setting environ['DISPLAY'] = '*:0', but receive the same error, except without the "no protocol found". Note that this is an app which must run on more machines than just my own, so I need a fix that can be put into the code rather than a one-time command to run with bash.
I should also mention, the app works fine when I run sudo python3 main.py. It's only when I use python3 main.py (which causes the elevate() function to prompt me with a login) that I get this error.
Comment: Try `elevate(graphical=False)`. I also had to remove the `environ` stuff.
Comment: What if I want the graphical prompt? Is there any way to accomodate that?
Answer: The reason that it fails is that after switching to root, the DISPLAY and XAUTHORITY environment variables are not set. You can set these to solve that issue. Here is a sample that will do that:
def is_root():
    return os.getuid() == 0

file_name = os.path.join(gettempdir(), 'f.txt')
if not is_root():
    print('saving DISPLAY:', os.environ['DISPLAY'])
    print('saving XAUTHORITY:', os.environ['XAUTHORITY'])
    with open(file_name, mode='w') as f:
        f.write(os.environ['DISPLAY'] + ' ' + os.environ['XAUTHORITY'])
else:
    with open(file_name) as f:
        txt = f.readline()
    tokens = txt.split()
    os.environ['DISPLAY'] = tokens[0]
    os.environ['XAUTHORITY'] = tokens[1]
    print('restored DISPLAY:', os.environ['DISPLAY'])
    print('rstored XAUTHORITY:', os.environ['XAUTHORITY'])
    os.remove(file_name)

This is just a proof of concept. You should consider security and choice of file_name. Obviously, this applies only to posix systems and will not work on Windows. I considered trying to use the python tempfile module, but I believe any tempfile written will be removed before you have a chance to read it. I haven't tested that.


Integral of square of variable in expression in square root in denominator

Question: I'm having trouble with following integral
$$
\int \frac{1}{\sqrt{1+4x^2+4y^2}} dy
$$
that according to WolframAlpha is
$$
\frac{1}{2} \ln( \sqrt{1+4x^2+4y^2} + 2y) + c
$$
which I can verify but I can't figure out what substitution to apply or what functions to use for integration by parts in original integral. What would be your first step to attack this integral please? Thank you.
Comment: Standard substitution for the form $a^2+ x^2$ is $x = a tan\theta$.  That works here and gets you to $\int sec\theta\; d\theta$.
Comment: set $$\sqrt{4y^2+4x^2+1}=2y+t$$
Comment: @Dr.SonnhardGraubner thank you, I've tried this but I can't get rid of y with this substitution.
Answer: Notice, the standard formula $$\color{red}{\int\frac{dx}{\sqrt{a^2+x^2}}=\ln(x+\sqrt{a^2+x^2})+c}$$ For derivation, let $x=a\tan \theta \implies dx=a\sec^2\theta d\theta $ $$\int\frac{dx}{\sqrt{a^2+x^2}}=\int\frac{a\sec^2 \theta d\theta}{\sqrt{a^2+(a\tan\theta)^2}}=$$ $$=\int\frac{\sec^2 \theta d\theta}{\sec\theta}=\int\sec\theta d\theta=\ln(\sec\theta+\tan\theta)+c$$  $$=\ln(\sqrt{1+\tan^2\theta}+\tan\theta)+c$$ Now, substituting the value of $\tan \theta=\frac{x}{a}$ $$=\ln(x+\sqrt{a^2+x^2})+c$$
In the given integration, $x $ is treated as a constant. Now we have  $$\int \frac{1}{\sqrt{1+4x^2+4y^2}} dy $$ $$ =\int \frac{1}{\sqrt{(1+4x^2)+(2y)^2}} dy $$ Let, $2y=t \implies 2dy=dt\ or\ dy=\frac{dt}{2}$ $$ =\frac{1}{2}\int \frac{dt}{\sqrt{(1+4x^2)+t^2}}+c$$ $$ =\frac{1}{2}\ln(t+\sqrt{(1+4x^2)+t^2})+c $$  $$ =\frac{1}{2}\ln(2y+\sqrt{(1+4x^2)+(2y)^2})+c$$  $$ =\frac{1}{2}\ln(\sqrt{1+4x^2+4y^2}+2y)+c $$
Comment: Thank you! Very clear. I couldn't find this standard formula anywhere but I can verify it holds =).
Comment: Alright, Can I add its derivation  at the top of answer?
Comment: I think that would be great.
Comment: You may see the derivation of the standard formula in the edited answer
Comment: Thank you! And thank you @lulu. Unfortunately I cannot upvote your answer yet.
Comment: Nicely done.  +1!


example of Sturm-Liouville problem with Lu=u'' differential operator

Question: I'm in the process of understanding Sturm-Liouville theory and I was reading this example Sturm-Liouville example from wikipedia.
I don't understand why they solve $Lu=x$, like where does this come from?

Given the preceding, let us now solve the inhomogeneous problem $Lu=x, \ x\in(0,\pi)$

When the original problem is finding an eigenfunction $u$ to the problem $Lu:=u''=\lambda u$
I see that functions of the type $\sin(kx)$ are solutions with $\lambda=-k^2$ but I don't see how this step fits into the reasoning, it seems to come from nowhere (though it does work in the end, I realize that)
Answer: Because the homogeneous solution can be used to make inhomogeneous solution. In the article, (Wikipedia you linked) they delve into homogeneous problem $Lu=(\frac{d^2}{dx^2}-\lambda)u=0$ first, (I guess you misread this part, since they changed the semantic for the operator) then used this result to solve $Lu=(\frac{d^2}{dx^2}-\lambda)u=x$.
Does this make sense?


passing Data Between Different Controllers and Views

Question: I have two Controllers named Home and Index and two views named the same in ASP.NET-Core 3.1.
I want to pass data between Home Controller and Index View**. I tried to use ViewBag and ViewData but I can not solve the problem.
Comment: Can you share the code which you tried?
Answer: You can try:
HttpContext.Session.SetString(SessionKeyName, "The Value You Want To Store");
Reference: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-3.1
You also need to set up the session first:
public void ConfigureServices(IServiceCollection services)
{
    services.AddDistributedMemoryCache();

    services.AddSession(options =>
    {
        options.IdleTimeout = TimeSpan.FromSeconds(10);
        options.Cookie.HttpOnly = true;
        options.Cookie.IsEssential = true;
    });

    services.AddControllersWithViews();
    services.AddRazorPages();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseSession();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapDefaultControllerRoute();
        endpoints.MapRazorPages();
    });
}

Comment: thank you so much, but when i try to use this way, i face the error ::                                An object reference is required for the non-static field, method, or property 'System.Web.Mvc.Controller.HttpContext.get'
Answer: You really should be passing a model instead of using viewbag or viewdata.
Define a Model like the following:
public class ViewModel
{
    public string FirstName { get; set; }

    public string LastName { get; set; }
}

In your HomeController create an IActionResult like the following:
    public IActionResult Home()
    {
        ViewModel viewmodel = new ViewModel
        {
            FirstName = "Alex",
            LastName = "Leo"
        };

        return View("/Views/Index/Index.cshtml",viewmodel);
    }

Your Index.cshtml will take a model passed and it will be defined as following:
@model ViewModel

@{
    ViewData["Title"] = "Index Page";
}

@Model.FirstName
@Model.LastName

In this example when the application starts - the index page will be displayed with the passed model
Answer: There are two primary options here:

Session and state management
If you only need the data within the session and aren't working with enormous data objects, this is the way to go. Keep in mind in order to use session state, you need to configure it first.

The Repository Pattern
This requires a bit more setup but will allow you to maintain data outside of a session in an abstracted data layer


How can I programmatically copy all blocks of a given theme into the same regions of a new theme?

Question: I would like to switch admin themes from a core theme (seven) to a custom sub-theme so I can add some customization without hacking core.
When I install the new sub-theme it creates all the block placement settings and leaves them header or content. I haven't changed any regions between the two themes, and just want to copy all the blocks from the seven theme to the current theme. I know I can check block settings with block plugin manager (plugin.manager.block) but I don't know what blocks to edit. I would like to know how to get a list of all the blocks from the old theme and copy all the placement to new theme programmatically.
Answer: You can entity query your relevant block config then create a cloned entity object via Block::createDuplicateBlock() then modify the sub-theme clones before saving the new block config into sub-theme region.
For example:
$block_ids = \Drupal::entityQuery('block')->condition('theme', 'my_base_theme')->condition('region','my_region')->execute();
foreach ($block_ids as $block_id) {
  $parent_block = \Drupal\block\Entity\Block::load($block_id);

  $new_id = str_replace('my_base_theme', 'my_sub_theme', $parent_block->get('id'));
  $child_block = $parent_block->createDuplicateBlock($new_id, 'my_sub_theme');
  // @TODO: set other properties that might need to be unique to this new theme's block

  $child_block->save();
}

Answer: I have done this before but it's been a while. First, make sure the regions match between your two themes. I think this is what I did:

Export configs:

$ drush cex

Use text editor to locate all of the config files that start with block.block....
Run a bulk find theme: seven and replace with theme: subtheme.
Delete the uuid: ... line from each of the updated config files.
Import configs:

drush cim

Comment: Thank you, but I am asking how to this in an update hook programmatically.
Comment: @FrankRobertAnderson – Maybe add that for clarification to your question.
Comment: The post already says that I am asking for a programmatic solution.
Comment: I apologize, @FrankRobertAnderson, sometimes I see programmatically and I just think "not with the GUI." Shawn Conn's answer seems like more the approach you need.
Comment: No need to apologize @IsaiahNixon


Como fazer slideToggle() de div que foi requisitada via ajax?

Question: Prezado(a)s,
tenho uma div que é preenchida via ajax:
    function atualizaConteudo(){
        $.ajax({
            url: 'getters/conteudo_amanha.php',
            success: function(data) {
                $('#conteudo_amanha').html(data);
            }
        });
    }
    atualizaConteudo();

A div fica da seguinte forma:

        <button type="button" class="novo-detalhe" data-id_conteudo="4">
            Mostrar conteudos
        </button>

            Conteudos recuperados

Tento fazer o slideToggle():
    $('.novo-detalhe').on('click',function(){
        var id_conteudo= $(this).data('id_conteudo');
        $('#conteudo_'+id_conteudo).slideToggle();
    });

Preciso que a div recuperada via ajax (#conteudo_4), seja ocultada/mostrada quando o usuário clicar no botão, coloquei a div dentro da página (em vez de utilizar o ajax para inserir dentro da div #conteudo_amanhã), deu certo, mas não estou conseguindo fazer funcionar usando a requisição ajax.
Sou novo com ajax e jquery...
Answer: Já tive um problema igual e o meu eu resolvi assim:
function atualizaConteudo(){
    $.ajax({
        url: 'getters/conteudo_amanha.php',
        success: function(data) {
            $('#conteudo_amanha').html(data);
            $('.novo-detalhe').on('click',function(){
                 var id_conteudo= $(this).data('id_conteudo');
                 $('#conteudo_'+id_conteudo).slideToggle();
            });
        }
    });
}
atualizaConteudo();

O onclick deve ser setado apos o conteúdo ser carregado.
Answer: Quando o elemento é criado depois do DOM ter sido totalmente carregado, a delegação de eventos do jQuery não costuma funcionar.
Para delegação de eventos de elementos criados dinamicamente, use o seguinte código:
$(document).on('click', '.novo-detalhe', function () {

     var id_conteudo = $(this).data('id_conteudo');

     $('#conteudo_'+id_conteudo).slideToggle();
})

Isso basicamente fará que todos os elementos que tenham a classe novo-detalhe disparem o evento click, idependente de serem criados dinamicamente ou não.
Na delegação de eventos para elementos dinâmicos, sempre é preciso definir como seletor o elemento pai, que é fixo no documento, para poder definir os filhos que serão dinâmicos. No nosso caso, usamos document, pois é a "raiz" de todo o documento, mas poderíamos usar outro elemento como base para a delegação dinâmica, no caso o #conteudo_amanha, que parece ser fixo no seu caso.
Sendo ele o "pai" que recebe os "filhos" dinâmicos, poderíamos fazer assim:
 $("#conteudo_amanha").on('click', '.novo-detalhe', function () {
     // faça sua mágica acontecer aqui
 })

Observação: A resposta anterior resolve o seu problema, mas não é a melhor maneira.
Dê uma olhada nessa pergunta do Stackoverflow InglÊs:

https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements
Comment: Opa, deu certo, obrigado


Make use of the gmail api through a service account from the server side avoiding the OAUTH2 GUI

Question: I have an application developed in python that uses the SMPT service to connect to a gmail account. This type of connection is typified as an "Access of insecure applications" lesssecureapps.
To remedy this I have set myself the task of updating my app, using the gmail api and for authentication to use a private key generated from a service account (without using G-Suit).
I have created a first proof of concept and it seems that it connects and authenticates correctly, but when trying to get the labels of the gmail account I get the following message:
<code><HttpError 400 when requesting https://gmail.googleapis.com/gmail/v1/users/me/labels?alt=json returned "Precondition check failed.">
</code>
I recap the steps I have followed to configure my google account:

I access Google Api Console and enable the use of the gmail api through the button that appears at the top: Enable apis and services
I access the credentials section, click on the top button: "create credentials" and select Service account
I create a service account and then generate a private key in json format

I add a small code snippet with my proof of concept and it that returns the error that I comment on the top:
<code>    from google.oauth2 import service_account
    from googleapiclient.discovery import build

    SCOPES = ['https://mail.google.com/','https://www.googleapis.com/auth/gmail.modify','https://www.googleapis.com/auth/gmail.readonly','https://www.googleapis.com/auth/gmail.labels','https://www.googleapis.com/auth/gmail.metadata','https://www.googleapis.com/auth/gmail.addons.current.message.metadata','https://www.googleapis.com/auth/gmail.addons.current.message.readonly']
    SERVICE_ACCOUNT_FILE = '/home/user/keys/privatekey_from_service_account.json'

    credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)

    service = build('gmail', 'v1', credentials=credentials)

    # Call the Gmail API
    results = service.users().labels().list(userId='me').execute()
    labels = results.get('labels', [])

    if not labels:
        print('No tienes labels.')
    else:
        print('Labels:')
        for label in labels:
            print(label['name'])
</code>
How can I solve my problem without using g-suite?
Answer:
"Precondition check failed."

Means that you are not allowed to do what you are trying to do.

use a private key generated from a service account (without using G-Suit).

The Gmail api does not support service accounts for non gsuite domains.  You can only use a service account with a Gsuite domain account and gsuite domain emails.
Services account wont work with normal google gmail accounts.
Comment: Thanks for your answer. And how else can I use the Gmail api from the server side without interacting with the OAUTH GUI using a normal gemail account?
Comment: You can use Oauth2 to authenticate your application once store the refresh token, then use the refresh token every time you need to access the API.  This is your only option without gsuite.  TIP: I recommend looking into the verification process of an app using gmail scopes it can be quite expensive and time consuming its best to start the process early.


How do I set up a QPainter window when logical coordinates are small and fractional?

Question: I want to render a scene on a QWidget, and I need to define a transofrmation from world coordinates to screen coordinates. QPainter::setWindow seems to be the correct function to use but it defines its logical coordinates as int, not float.
My logical coordinates are not only floating-point, they are also very small. The window of logical coordinates is something like (1.5,1.5)..(1.54,1.53).
I can't use setWindow because the rouding errors utterly destroy my coordinates, so how do I set up a QPainter transformation such that rendering the rectangle (x,y)..(x+width,y+height) will exactly fill the widget, when the rectangle has arbitrary floating-point values?
(The rectangle has already been chosen to have the correct aspect ratio to fit the widget.)
Comment: Is there any reason you can perform another simple transformation?  That is, rather than specifying a logical coordinate as 1.54 "things" could it instead be 1540 milli-"things"?
Comment: a) the widget is for zooming in, b) transformations are not integer-based in general
Answer: You could probably write your own "floating point" version of QPainter::setWindow...
void set_painter_window (QPainter &painter, const QRectF &logical_rect)
{
  QTransform xform;
  xform.scale(painter.viewport().width() / logical_rect.width(),
              painter.viewport().height() / logical_rect.height());
  xform.translate(-logical_rect.left(), -logical_rect.top());
  painter.setTransform(xform);
}

Appears to work as expected in the few simple tests I've cobbled together.


Magento 1.9 - Página de produto configurável, botão de comprar aparecendo lá embaixo

Question: Tenho um trabalho em um projeto pessoal com o Magento 1.9.
Instalei a base de exemplo, ele está funcionando sem problema algum nas suas funcionalidades. Mas o layout da página de um produto configurável está estranha. As opções configuráveis exemplo: Cor e tamanho. E o botão de comprar, estão ficando lá embaixo depois das fotos do produto.
Porém, em um produto configurável da base de exemplo. O layout está normal, com as opções de "cor" e "tamanho" em um bloco logo abaixo do nome do produto e preço.
Comment: Bem-vindo ao StackOverflow Eduardo. Por favor, poste um trecho do código que você já tem para termos uma ideia melhor do problema, sugiro que leia esse artigo da ajuda do site: [Como criar um exemplo Mínimo, Completo e Verificável](https://pt.stackoverflow.com/help/mcve).
Answer: geralmente problemas de layout sao decorrentes de codigo CSS.
quando vc experimenta um novo tema, o problema persiste?
o problema ocorre com todos os produtos configuraveis que voce cria? ou apenas com alguns produtos criados por vc?
pois eh possivel q na descricao/titulo do produto vc tenha inserido um caracter invalido q esta quebrando o codigo.
sucesso ai.


Form element #default_value and AJAX

Question: I can't get a form to display a (default?) value after an AJAX call. I am using the following code:
function foo_form ($form, &$form_state, $foo) {

  $form['#prefix'] = '
';
  $form['#suffix'] = '
';

  $form['copy'] = array(
    '#type' => 'submit',
    '#value' => t('Copy foo'),
    '#limit_validation_errors' => array(),
    // #submit is required to use #limit_validation_errors
    '#submit' => array('foo_form_submit'),
    '#ajax' => array(
      'wrapper' => 'foo-form-wrapper',
      'callback' => 'foo_form_callback',
    ),
  );

  $form['description'] = array(
    '#type' => 'textarea',
    '#title' => t('Short description'),
    '#required' => TRUE,
    '#maxlength' => 255,
    '#default_value' => $foo->description,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );

  return $form;
}

function foo_form_callback($form, $form_state) {
  return $form;
}

function foo_form_submit ($form, &$form_state) {
  if (!isset($form_state['triggering_element']['#ajax'])) {
    $foo = (object)$form_state['values'];

    entity_get_controller('foo')->save($foo);

    $form_state['redirect'] = 'admin/foo';
    return;
  } else {
    form_set_value($form['description'], 'description text', $form_state);
    $form_state['rebuild'] = true;
  }
}

As I understand it, the form should automatically try to display the value if it is set in $form_state. When the callback is executed and the form is built, $form_state['values']['description'] is the value set in foo_form_submit. However, nothing is being displayed.
Comment: hook_form should have only 2 arguments. Where $foo is coming from?
Comment: It's an entity passed in as parameter. When the form is called there's either an empty entity passed (create) or one that's loaded from the database (update). You can pass additional arguments with [drupal_get_form](http://api.drupal.org/api/drupal/includes--form.inc/group/form_api/7).
Answer: I know this is late, but for people like me who are still experiencing similar problems with ajax and forms in Drupal, here's how I fixed this.
In your ajax callback function, instead of returning just the render array, you need to call the form_builder() function and return its result.
Eg., my code goes like this:
function inventory_purchase_item_add_ajax(&$form, &$form_state) {
    //...

    unset($form_state['input']['line']);
    unset($form_state['values']['line']);

    //Update the form's lines array
    $lines = update_inventory_purchase_form_lines($form_state['node']->line, $purchase_item_count);
    $form['vtab1']['purchase']['items_wrapper']['line'] = $lines;
    return form_builder($form['#id'], $lines, $form_state);
}

Comment: This worked for me. For my case, I stored the original form element in `$form_state['storage']` and then replaced in the Ajax callback. Thanks a lot!
Answer: this bug even exists in drupal 8 and is presented HERE.
simplest simple solution is to remove input value of form element in form builder function before creating that element:
unset($form_state['input']['description']);
$form['description'] = array(
    '#type' => 'textarea',
    '#title' => t('Short description'),
    '#required' => TRUE,
    '#maxlength' => 255,
    '#default_value' => $foo->description,
 );

Another solution:
in some cases where there is no java script event handler attached to that element you can have different name for element so input doesn't come in the way, example:
$name='description_'.rand();
$form[$name] = array(
    '#type' => 'textarea',
    '#title' => t('Short description'),
    '#required' => TRUE,
    '#maxlength' => 255,
    '#default_value' => $foo->description,
 );

and save the name in $form for later use (in validation,submittion,...):
$form['a_unique_name']=$name;

Answer: I've experienced similar problems especially with textfields, checkboxes and radios.  The solution I found (and I can't guarantee is the "correct" solution) is to change the $form_state['input'][VARIABLE] field.  Do this in the validation function:
function foo_form_validate ($form, &$form_state) {
  // this will take a entered value from one element and make it display in another
  $form_state['input']['some_value_to_change'] = $form_state['values']['another_element'];
}

Comment: In my case it was the other way round: "$form_state['values']['bla'] = $form_state['input']['bla'];". Thanks for the answer.
Answer: thanks, this code works for me, the input method works for me ...
if (isset($form_state['values']['task-name'])) {
  $form_state['input']['task-description'] = show_task_description($form_state['values']['task-name']);
}

Form element #default_value and AJAX


How can I redirect the contents of a folder to other domain?

Question: We have moved our website to wordpress but we do rely on several folders and we already have link and images pointing to the old locations.
for example:
http://domain.com/t/image_001.png

but I do not want to add all images again to the new web location, I would rather set a sub domain and keep them in the same place
How can I redirect
http://domain.com/t/*.* to http://t.domain.com/*.*?
something I need to do in php.ini file? or it's a website configuration?
Answer: As it's an IIS Server (as the tag specifies) you have 2 options:
create the folder you want in the new site and add a web.config file with this content:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <httpRedirect enabled="true" destination="http://t.domain.com" />
    </system.webServer>
</configuration>

or, if you want to use the GUI
Select the folder, and open HTTP Redirect under "IIS"

and set the new domain
Comment: Blegh, I completely missed that :)
Comment: How do I keep the querystring values?


How to add classes to every X number of node in a array

Question: How do I write a preprocess_node function to add a class to every second/third node it generated?
Scenario: add .last to every 2nd node, so that i can apply margin-right: 0; for the last column in the row.
Answer: For node listings for which the node.tpl.php (or a different node template) is being used you have variables like $zebra and $id at your disposal that you can use for this kind of tasks. You can see all the available variables with descriptions in the node modules node.tpl.php file or here.
For example if you want to add the necessary class to this line:
<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

you could use code snippets like these:

<?php $classes .= ' '.$zebra; ?> - add 'odd' to every first and 'even' to every second node in the list
<?php if (!($id % 2)) $classes .= ' last'; ?> - add 'last' class to every second node.
<?php if (!($id % 3)) $classes .= ' last'; ?> - add 'last' class to every third node.
Comment: @devric You shouldn't edit the core. I added code snippets to my answer that you can use instead (easier and better).
Comment: hm, couldn't find where they have this $zebra function in the core module, need to edit that for every 3third
Comment: nice! much easier that what i was about to do,...which was trying to use preprocess function to do so.
Answer: Sounds like you want to use the :nth-child(N) CSS selector:
.table-class td:nth-child(even) {
  margin-right: 0;
}

Or even better:
.table-class td:nth-child(2) {
  margin-right: 0;
}

The selector does this:

This pseudo-class matches elements on the basis of their positions within a parent element's list of child elements. The pseudo-class accepts an argument, N, which can be a keyword, a number, or a number expression of the form an+b.

The selector works on a one-based index, not zero, so "even" will work if you've only got 2 columns; you'd be better using the second example though, which specifically targets the second  of a parent
 within the given table.
Comment: @Clive :D really, no - if I really want to support IE with a site I use CSS3 PIE, which provides a fix for those transparency issues.

But see, I've just added that comment for completeness sake. Nowadays I don't even bother to test with IE - I work with Chrome (dev) most of the time and tell folks to get a sane browser as soon as I see them using IE. :)
Comment: using pseudo class is too risky, unless there is absolutely no way to do it from the backend.
Comment: The only real problem with :nth-child is that we still have the greatest-ever browser - IE - alive. IE 8 and below doesn't support that (at least, I don't know what's up with IE9). So if you would like to use that, you have to use a polyfill like Selectivizr (http://selectivizr.com/).
Comment: @scorchio ie7 and below don't support alpha transparency properly - do you therefore never include transparent images in a website because those browsers still exist? I would argue no. If people want to live in the dark ages that's their problem...if everybody dropped this "we must support every version of ie with every website" attitude then the users of those browsers would start seeing a lot more websites that don't work properly...and would be encouraged to upgrade to a real browser :)
Comment: if i really need to do it that way, i rather use jQuery to select it and use a normal class name. keep in mind that CSS pie will heat up cpu for slower pc when you use it a lot, and you will definitely be tempted to use a lot. @Clive, ie6-7-8 you need to use -ms-filter to achieve alpha.
Comment: unfortunately corporate environment requires minimum support of ie8, which is reasonable. I've already worked on a few sites heavy with css3, but the corporate market space are at least 45% users with ie8.
Comment: @devric Yep, my point was that a lack of native CSS support in a browser is exactly as prohibitive as a lack of alpha transparency support - You can get round it, while still using the newer technologies


Getting an all blank bar chart with Matplotlib

Question: I've run this code in both Jupyter Notebook and PyCharm and get the same blank bar chart in both.
Anyone know why this is happening and how to get the bar coloured?
import pandas as pd
import matplotlib.pyplot as plt

data = {
'Elements' : ['Item_1', 'Item_2', 'Item_3', 'Item_4', 'Item_5'],
'Count' : [300,10,90,100,15],
'Produces': [1,140,10,5, 90]
}

df = pd.DataFrame(data)
df['potential'] = df['Count'] * df['Produces']

plt.figure()
plt.bar(x = df['Elements'], height = ['potential'])
plt.show()

Screenshot
Answer: I think you forget df in-front of the height = df['potential'].
It should work as expected.
import pandas as pd
import matplotlib.pyplot as plt

data = {
'Elements' : ['Item_1', 'Item_2', 'Item_3', 'Item_4', 'Item_5'],
'Count' : [300,10,90,100,15],
'Produces': [1,140,10,5, 90]
}

df = pd.DataFrame(data)
df['potential'] = df['Count'] * df['Produces']

plt.figure()
plt.bar(x = df['Elements'], height = df['potential'])
plt.show()

Answer: You for got one df:
plt.bar(x = df['Elements'], height = df['potential'])
#                                    ^ this

Also consider
df.plot.bar(x='Elements', y='potential')


Find numerical approximation for MLE of marginal distribution approximation

Question: Say that I have the joint pdf $p(x,y)$ for random variables $X$ and $Y$ and that I'm looking for the maximiser $x_0$ of the marginal distribution $p(x)$. Suppose further that $p(x)$ cannot be computed analytically from $p(x,y)$. What sort of procedure could be used here?
Originally, I thought that I could perform a Monte Carlo approximation of the marginal distribution, and then use some searching algorithm to find the maximiser. Unfortunately, with the software that I'm stuck with, I don't believe that I can use the searching algorithm without having the analytical form of the objective function (the marginal distribution).
Comment: So p(x, y) is given as a formula or as a representative sample of p(x, y)? p(x) cannot bei computed from p(x,y) but what do you expect? Doe you expect a formula or a large sample? Might bootstrapping be a usefull procedure here?
Comment: p(x,y) is an explicit formula, but it cannot be integrated by hand to get p(x). I'm using this as a simplification. In reality, I have p(x1,x2,...,x11) and I need to maximize p(x1,x2,x3).
Answer: When the EM algorithm can be implemented, it is a natural approach for this type of marginal (or missing data) optimisation problem. In our book, Introducing Monte Carlo methods with R, there is an entire chapter on Monte Carlo optimisation, covering the optimisation of functions defined by integrals such as $$m(x) = \int p(x,y)\text{d}y$$by techniques such as

EM
optimisation of Monte Carlo approximations of $m(x)
Monte Carlo EM
stochastic gradient methods such as Robbins-Monro replacing the gradient with a Monte Carlo approximation

With A. Doucet and S. Godsill, we further designed a marginal optimisation algorithm called SAME that exploits the marginal structure to design an automated simulated annealing algorithm. (This algorithm was later re-invented under other names.) Birge and Polson have a similar version involving slice sampling.


How do I configure the REST API?

Question: A couple months back I successfully setup a development site to learn about the Drupal 8 REST API with version 8.0.x using the REST UI module for configuration. When I heard about the improvements to the REST Services in Drupal 8.2 I was pretty excited (from my understanding it is now possible to access configuration data such as content types and taxonomy terms) so I setup a new install using version 8.2.1. However, understanding the configuration for 8.2 is pretty daunting, and since it's so new there are very little resources around the setup and configuration.
I was able to locate this resource and I imported the example configuration provided, but was still unsure on how to configure other REST Endpoints.
I used the default configuration provided in the above resource. It looks like this:
langcode: en
status: true
dependencies:
 module:
   - basic_auth
   - hal
   - node
id: entity.node
plugin_id: 'entity:node'
granularity: resource
configuration:
 methods:
   - GET
   - POST
   - PATCH
   - DELETE
 formats:
   - hal_json
 authentication:
   - basic_auth

How do I edit the configuration once it's imported via the configuration manager?
Where can I find the available plugin_id's so that I can configure other resources? Where can I learn more about plugins?
How would I begin to implement my own REST endpoint?

I know this is a lot to ask, but at the time of writing there is little to no information covering these topics so I figure other people might be confused as well. I would like to create a guide on this, but that would first require that I understand it first.
Comment: There is no user interface for Restful interfaces in core (other than Views Rest exports). However there is a contrib module, restui, that adds one, but unfortunately as of 10/13/2016 it is not up-to-date with 8.2.x changes. There is an issue and a patch for it though - https://www.drupal.org/node/2758563. At the moment you will need to import configuration i.e. sync configuration changes via YAML.
Comment: A lot of the current documentation pages for developers are in flux as we make improvements to drupal.org's Documentation section. One of those sections was on plugins and is now missing from the Develop for Drupal page, but that is where I would go prior to this.
Comment: Found it, it's now at https://www.drupal.org/docs/8/api
Comment: @mradcliffe So I just need to create a `rest-config` directory in my drupal installation and put all of my .yml config files in there and then copy / paste them into the single import when I want to update them?

I'm still a bit confused on how I would discover the rest plugins available by default. Maybe you could post a resource config of another resource then I might begin to see the pattern?
Answer: I search a lot too after 8.2x and this is how i got it working :
Example for a custom user ressource :

myModule/config/install
rest.resource.user.rest_ressource.yml

langcode: en
status: true
dependencies:
  module:
    - basic_auth
id: user.rest_ressource
plugin_id: 'user_rest_ressource'
granularity: resource
configuration:
  methods:
    - GET
  formats:
    - json
  authentication:
    - basic_auth

In myModule/src/Plugin/rest/resource
UserRestRessource.php

<?php

namespace Drupal\myModule\Plugin\rest\resource;

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Psr\Log\LoggerInterface;

/**
 * Provides a resource to get view modes by entity and bundle.
 *
 * @RestResource(
 *   id = "user_rest_ressource",
 *   label = @Translation("User Rest"),
 *   uri_paths = {
 *     "canonical" = "/api/user/getInfo"
 *   }
 * )
 */
class UserRestRessource extends ResourceBase {

  /**
   * A current user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Constructs a Drupal\rest\Plugin\ResourceBase object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param array $serializer_formats
   *   The available serialization formats.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   A current user instance.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    AccountProxyInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

    $this->currentUser = $current_user;

  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('restimadiff'),
      $container->get('current_user')
    );
  }

  /**
   * Responds to GET requests.
   *
   *
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   *   Throws exception expected.
   */
  public function get() {

      $responseResource=new ResourceResponse(
          array()

      );
    return $responseResource;
  }

}

Comment: Do you have to add rest via a module?
Answer: Since posting this, the documentation on drupal.org/docs/8/ has been updated appropriately.

How do I configure the REST API?


How to delete/change type of bus in the channel strip in Logic Pro X?

Question: I'm playing around mixer atm, and I wanted to try to set pre/post fader send on one of my channels. Thing is that I'm able to add a bus, but I have no idea how to remove it, or change it's type. There are two buttons on the send - one to enable the send, and other (the one with two arrows up and down) which simply doesnt work...
Is it a bug or am I doing something wrong? Is Logic a stack of bugs? Every 10 pages of the manual I encounter some kind of problems :( Am I able to fix it somehow? Does it work for you guys? What can be the issue here?
Answer: Ok, I was about to say sorry, and that I'm an idiot and "why I didnt come up on it earlier!", but no. The solution is not intuitive, because it is not consistent with how other up/down button works (on the insert for example)...
The answer is to hold down a left mouse button on the up/down button of the send until you'll get the contextual menu with options.


With ImageMagick, how can you see all available fonts?

Question: ImageMagick can draw text into a picture in a given font, how can I see all available fonts for my system?
Answer: depending on your imagemagick version:
convert -list type       # for IM older than v6.3.5-7
convert -list font       # for newer versions

also the output format changed...
-- update For OsX (Answer from Charles Merriam) if the command above does not produce any results:
For a full tutorial with description see http://gothick.org.uk/2008/03/14/using-os-x-fonts-in-imagemagick/ for the rest &tldr:
# use fondu to convert fonts and update locatedb
sudo port install fondu
cd /usr/local/share/fonts/
fondu /Library/Fonts/*.dfont
/etc/periodic/weekly/310.locate

# generate imagemagick type.xml
cd ~
mkdir ~/.magick
wget http://www.imagemagick.org/Usage/scripts/imagick_type_gen
perl imagick_type_gen > ~/.magick/type.xml

Comment: What do you do if `convert -list font` prints nothing?
Comment: is it possible to list fonts for a particular language ?
Comment: I upgraded from imagemagick 6.8.7-7 to 6.8.9-7 which did the trick for me.
Comment: The above answer is not correct. For `convert -list fonts` to work, the fonts need to be in the type.xml file for ImageMagick. To get all your compatible fonts in the type.xml file, see my answer below.
Answer: To list only the font names, do convert -list font | grep Font
Answer: The fonts are a bit tricky.   ImageMagick will not usually 'see' your system fonts.   On OS/X, fonts are stored in a non-standard format.
Use convert -list font to see the fonts ImageMagick currently knows about.   It may be blank.
ImageMagick looks for $HOME/.magick/type.xml for the list of fonts.  If you are on OS/X, go see the well written tutorial at http://gothick.org.uk/2008/03/14/using-os-x-fonts-in-imagemagick/.
Answer: Your OS file system will list all your fonts.
But if you are asking about fonts that Imagemagick knows about for use by name, then use convert -list font to see all those fonts listed in its type.xml file.
If that shows nothing, then if you are on a unix-like platform, you can use the perl script by Anthony Thyssen to install your fonts into the type.xml file rather than doing them by hand. See https://www.imagemagick.org/Usage/scripts/imagick_type_gen.
Then doing convert -list font should list the ones that Imagemagick recognizes and you can then use them by name -font fontname . Otherwise, you need to provide the full path to the font file -font path/to/font.suffx.
Answer: If you have recently installed a font which is not appearing when using:
convert -list font
You can flush your font cache with:
fc-cache -f -v
Answer: I find the gnome-font-viewer more useful to see all the fonts visually compared to a list of names returned on the command line.


Creating a function that returns an array of strings

Question: I'm trying to create a string parser that breaks a string up into an array of strings using a delimiter. I'm using the function "strtok" which I understand how to use. What I don't understand is how to get my parsing fuction to return an array of the different words in my string. It's been quite some time since I've used C, so this is proving to be quite difficult.
char ** parseString(char * inString){

    char **ptr; //What I want to return, an array of strings
    int count = 0;

    ptr[count] = strtok(inString, " ");
    count++;
    while(inString!=NULL){
         ptr[count]=strtok(NULL, " ");
         count++;
    }
    return ptr;
}

I know that this above code won't work. I vaguely remember how to use malloc, and I know that my above code will result in a seg fault since I haven't malloced, but above is essentially what I want to have happen. How do I appropriately malloc if I don't even know how many words I need to have in my array of strings?
Comment: Option 1) Take a guess. If the array fills up, `realloc` to make it bigger. If you made it too big, `realloc` to make it smaller at the end.
Comment: Option 2), Parse the string twice. The first time, you just count how big the array needs to be. Do the actual work the second time
Comment: When does, does the data  pointed to by `inString` need to be as its was originally?
Answer: For allocating the vector since you don't know from the start its size there are a couple of strategies:

you can first parse inString to get the number of words, allocate then parse again.
you can reallocate for each word.
you can reallocate with a geometric growth.

In the first variant you do the parsing twice, making it the worst of them
The second has the disadvantage of multiple reallocations, but could be acceptable on small strings and if the function is not critical.
The third one is the best and is what std::vector in C++ does.
I show you the 2nd variant here.
You also need to keep the size of the vector in a separate variable.
char** parseString(char* inString, size_t* tokensLen)
{
    char **tokens = NULL; // realloc on NULL acts like malloc so we simplify the code
    size_t i = 0;

    // parse the first word
    char* inToken = strtok(inString, " ");

    while (inToken)
    {
        // allocate for one more pointer
        tokens = realloc(tokens, (i + 1) * sizeof *tokens);
        assert(tokens);

        // point to word
        tokens[i] = inToken;

        // parse the next word
        inToken = strtok(NULL, " ");
        ++i;
    }

    // set size
    *tokensLen = i;

    return tokens;
}

int main()
{
    char str[] = "here we go";
    size_t len;
    char** tokens = parseString(str, &len);

    for (size_t i = 0; i < len; ++i)
    {
        printf("%s\n", tokens[i]);
    }
}

Comment: Thanks so much, that makes a lot of sense!
Comment: `size_t* tokensLen` and `int i = 0;` make more sense using the same type.  Suggest `size_t`.
Comment: @mattgallant24 you are welcome. If you think this helped you consider upvoting it. If it answers your question consider marking it as accepted.
Comment: This answer modifies the original string.  That is (IMO) a poor practice.  Suggest use `strlen()` and `malloc()` to copy the string to a local dynamic array.and performing all the parsing there


Compactness Theorem for Non-elementary classes

Question: Let $\mathcal{L}$ be a first-order language and let $\mathcal{C}$ be a class of $\mathcal{L}$-structures which is not necessarily an elementary class (i.e. there does not exist  a theory $T$ such that $\mathcal{C}=mod(T)$).
Let $\Sigma$ be a set of $\mathcal{L}$-sentences such that for every finite subset $\Sigma_0$ of $\Sigma$ there is a member $\mathcal{M}_{}\in\mathcal{C}$ so that $\mathcal{M}\models \Sigma_0$. Then, can we conclude that there is a member $\mathcal{N}\in\mathcal{C}$ such that $\mathcal{N}\models \Sigma$?
Answer: No, we cannot. For example, take $\mathcal{C}$ to be the class of all finite structures in our language, let $\varphi_n$ be the sentence asserting that there exist at least $n$ elements in the universe - that is, $\varphi_n$ is the sentence $$\exists x_1,..., x_n(\bigwedge_{1\le i<j\le n}\neg x_i=x_j),$$ which is clearly first-order - and let $\Sigma=\{\varphi_n:n\in\mathbb{N}\}$. Every finite subset of $\Sigma$ is satisfied in all sufficiently large finite structures, but $\Sigma$ itself is only satisfied in infinite structures.

Note that we can do a similar trick with larger cardinalities, assuming a large enough language. For any infinite cardinal $\kappa$, let $C_\kappa$ be the language consisting of $\kappa$-many distinct constant symbols $c_\eta$ ($\eta<\kappa$), take $\Sigma=\{\neg c_\eta=c_\theta: \eta<\theta<\kappa\}$, and take $\mathcal{C}$ to be the class of all structures of cardinality $<\kappa$. Then every subset of $\Sigma$ with cardinality $<\kappa$ (not just every finite subset) is satisfied in some element of $\mathcal{C}$, but no element of $\mathcal{C}$ satisfies all of $\Sigma$.
Comment: If $\mathcal{C}$ has sufficiently large members. Then can we still filnd an example?
Comment: @Alice.H You can replicate the same idea "in a formula" - e.g. take our language to have a single unary predicate symbol $U$, and let $\mathcal{C}$ be the class of all structures $M$ with $U^M$ finite.
Comment: That said - at the same time it's worth noting that there are logics stronger than first order which are compact. Any class of structures which is elementary with respect to such a logic will, well, be compact for first-order theories and indeed theories in that larger logic. So one thing you might be interested in is what sort of compact logics there are. The relevant topic here is [**abstract model theory**](https://projecteuclid.org/euclid.pl/1235417263). It's worth noting that there are no logics stronger than first-order which are compact and have the downwards Lowenheim-Skolem property.
Comment: This latter result is [Lindstrom's theorem](https://en.wikipedia.org/wiki/Lindstr%C3%B6m%27s_theorem), which was the result which kicked of AMT in the first place.


Exibir aviso quando a página for aberta no Mozilla Firefox

Question: Gostaria de saber como fazer o alerta abaixo ser exibido quando a página for aberta no navegador Mozilla Firefox
alert("Alguns elementos desta página podem não ser exibidos no Firefox. Para evitar problemas, utilize o Google Chrome. Atenciosamente - Designed");

Answer:

        if (navigator.userAgent.indexOf("Firefox") > 0) {
                alert("Alguns elementos desta página podem não ser exibidos no Firefox. Para evitar problemas, utilize o Google Chrome. Atenciosamente - Designed");

        }


How to pass value of paragraph to controller

Question: I have a paragraph tag that is manipulated using jquery. I have a list of checkboxes which changes the value of the paragraph everytime a new checkbox is selected. I would like to know if it is possible to pass that value across to the controller.

My checkboxes:
<input type="checkbox" class="slectOne" data-id="R @item.standard_400.00 (per day)" />
<input type="checkbox" class="slectOne" data-id="R @item.super_400.00 (per day)" />

My paragraph tag:

Please choose cover to continue

Comment: Only if you have a form control for it (or you pass it via an ajax call)
Answer: You can... but you probably don't want to. Instead you would post the value of the checkboxes that influence the paragraph...
If you do need to, you can get it as:
$(".result").val();

and post either using AJAX, or by appending a <input type='hidden'> to a form and then posting it.
Comment: I actually saw this way as the easiest way out until I figure how to pass the "data-id" of the selected checkbox to the controller
Comment: $(".slectOne[checked]").attr("data-id")


Use hook to get the domain configuration from language

Question: We have enabled English, Spanish, and French on our site. On Regional and language >> Languages detection we selected URL for Content language detection >> Detection Method. For Part of the URL that determines language, we selected Domain. We then set the following domains.

English: example.com
Spanish: es.example.com
French: fr.example.com

How can we programmatically obtain the domain associated to each language? What code should we use in a preprocess function?
Using the following code, we obtained the list of the language, but we are far
 from getting the domain that has been associated with each language.
function mymodule_preprocess_html(&$variables) {
  // to get all enabled languages
  $languages = \Drupal::languageManager()->getLanguages();

  // Did not find method to retrieve the domain configuration.
  foreach($languages as $key => $value) {
    ksm($languages[$key]);
    //stuck here on how to get domain configuration per language.
  }
}

Answer: The domain associated with each language is stored as configuration. Using the following code, $prefix will contain the prefix, and $domain the domain used.
  $config = \Drupal::configFactory()->get('language.negotiation');
  $languages = \Drupal::languageManager()->getLanguages();
  $prefixes = $config->get('url.prefixes');
  $domains = $config->get('url.domains');
  foreach ($languages as $langcode => $language) {
    $prefix = $prefixes[$langcode];
    $domain = $domains[$langcode];
  }

I wrote the code basing on NegotiationUrlForm::buildForm(), which is the form builder for the form that sets the negotiation URL for each language.
Comment: that got me exactly what i needed using the `$config = \Drupal::configFactory()->get('language.negotiation');`


Imagemagick ENOENT error

Question: Not only I have this issue: Node js + imagemagick + Error: spawn ENOENT
console.log(appPath + '/public/avatar/tmp_' + filename);
var path = appPath + '/public/avatar/tmp_' + filename;
try {
    fs.accessSync(path, fs.F_OK);
    // Do something
    console.log('file exists!');
} catch (e) {
    // It isn't accessible
    console.log('file does NOT exist!');
}

console.log('trying...');
// crop/resize image
im.crop({
    srcPath: path,
    dstPath: 'test1.png',
    width: 60,
    height: 60
}, function(err, stdout, stderr){
    console.log('here');
    if (err) {
        console.log('trololololol '+err);
        reject(err);
    }
    console.log('resized to fit within 60x60px');
    resolve();
});

I get the console output:
C:\www\instantynode\src/public/avatar/tmp_1458064183594_la5v9vcuc27hw7b9.png
file exists!
trying...
events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: spawn identify ENOENT
    at exports._errnoException (util.js:870:11)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:178:32)
    at onErrorNT (internal/child_process.js:344:16)
    at nextTickCallbackWith2Args (node.js:442:9)
    at process._tickCallback (node.js:356:17)

Answer: ENOENT means identify can't be found. Make sure that you have installed ImageMagick and that it is installed in a path that is found in $PATH.
Comment: I have same issue, I have installed the imagemagick using npm install imagemagick - not cleare what I have to do now.
Comment: can you explain exactly what we have to do after `npm install imagemagick`?
Answer: I realize this several years late but I just ran into this issue and was able to solve it.
I thought I'd post the solution here for the next poor sap who runs into this.
identify is a legacy utility that can optionally be installed with ImageMagick.
By default, it is not installed.
Comment: Ahh what does this do exactly, do you know?
Comment: From the [ImageMagick documentation](https://imagemagick.org/script/identify.php): The identify program describes the format and characteristics of one or more image files. It also reports if an image is incomplete or corrupt. The information returned includes the image number, the file name, the width and height of the image, whether the image is colormapped or not, the number of colors in the image, the number of bytes in the image, the format of the image (JPEG, PNM, etc.), and finally the number of seconds it took to read and process the image.
Answer: I was also having this error , what I did was made a copy of imagemagick.exe in the installation directory (which was c:\Program Files\ImageMagic for me) and renamed the file to identify.exe
Answer: Just making npm install imagemagick does not suffice because the npm package does not contain any binaries, just node scripts which rely on the binaries.
You still have to install the binaries, in Debian/Ubuntu, you just need to do
sudo apt install imagemagick

Imagemagick ENOENT error


Find all primes $x$ in a Euclidean domain $ Z[i]$ for which $|x|^2 \leq 16$.

Question:
Find all primes $x$ in a Euclidean domain $ Z[i]$ for which $|x|^2 \leq 16$.

Any help or hint is appreciated. From my understanding, is it true that $x$ can only be $2$ and $3$?
Comment: No. For one thing, $2$ is not a Gaussian prime. $1+i$ is, though.
Comment: Is $|x|$ the complex absolute value or the Gaussian norm?
Answer: If we write $x=a+ib$ where $a,b \in \mathbb Z$ :
$$|x|^2\leq 16 \iff |x|\leq4 \iff a^2+b^2\leq 4\\\iff (a,b)=(0,\pm2)\text{ or }(a,b)=(\pm2,0)\text{ or }(a,b)=(0,\pm1)\text{ or }(a,b)=(\pm1,0)\text{ or }(a,b)=(\pm1,\pm1)\text{ or }(a,b)=(0,0)\\\iff x=\pm2i\text{ or }x=\pm2\text{ or }x=\pm i\text{ or }x=\pm1\text{ or }x=\pm1\pm i\text{ or }x=0$$
Now you can check which of these possible solutions are prime.


Problem with sprintf function, last parameters are wrong when written

Question: So I use sprintf
sprintf(buffer, "%f|%f|%f|%f|%f|%f|%d|%f|%d", x, y, z, u, v, w, nID, dDistance, nConfig);

But when I print the buffer I get the 2 last parameters wrong, they are lets suppose to be 35.0000 and 0 and in the string they are 0.00000 and 10332430 and my buffer is long enough and all the other parameters are good in the string
Any idea? Is there a length limit to sprintf or something?
I checked the types of all the numbers and they are right, but what seems to be the problem is the dDistance.  When I remove it from the sprint, the nConfig gets the right value in the string, but when I remove nConfig, dDistance still doesn't get the right value. I checked and dDistance is a double.  Any idea?
Since people don't seem to believe me I did this :
char test[255]={0};
int test1 = 2;
double test2=35.00;
int test3 = 0;

sprintf(test,"%d|%f|%d",test1,test2,test3);

and I get this in my string:
2|0.000000|1078034432

Comment: Very difficult to comment. Post a minimal compilable source that reproduces this issue. At least, try to print the values on the console. Check the return value of `sprintf`.
Comment: what are the types of x,y,z, etc?
Comment: Why not single step through the call to sprintf in the debugger and see what it is doing? This is a bit dull to do, but the results are usually enlightening.
Comment: Sorry, but have you checked the values are actually correct?
Comment: What happens if you try to `sprintf` out only those last two parameters?
Comment: @Péter Török  They get it right
@Vinko Vrsalovic yes all the values are good prior sprintf and they still are after sprintf, it's just sprintf that messes up when creating the string I suppose.
All the ones that are %f they are doubles and the %d are ints.
Comment: It's clear that u-z and dDistance are supposed to be floating point, and nID and nConfig are supposed to be integers.  Are they?  Have you printed them out?  Is that the actual sprintf from your program? How big is your buffer?
Comment: My buffer is 255 long, I get 84 as a return value.
Comment: Maybe you've corrupted the stack elsewhere. Without more code, there's nothing more we can add.
Comment: Force your compiler to check your `printf` format string against the arguments by passing in `-Wformat -Werror` to your gcc compiler command.
Answer: I'd check to make sure your argument types match up with your format string elements.  Trying to display a double as an integer type (%d) or vice versa can give you strange output.
Answer: Are you sure your data types match your format spec?
Try printing out your data, that is, create a printf with the same format and see what happens that is:
printf("%f|%f|%f|%f|%f|%f|%d|%f|%d", x, y, z, u, v, w, nID,dDistance, nConfig);

Try using streams, for example
stringstream ss;

ss << x << "|" << y << "|" << z << "|" << u << "|" << v << "|" << w << "|"
   << nID << "|"<< dDistance << "|"<< nConfig;

string s = ss.str();

and then do something with s;
Comment: They match but then when I try and swap lets say the first one with the last one and swap the %f with the %d as well I get the right string.
Comment: I don't understand what you mean, explain further please?
Comment: If I swap x with nconfig and put %f and %d to their respective places, I get the right string.
Comment: so are you saying that this statement works?
printf("%d|%f|%f|%f|%f|%f|%d|%f|%f", nConfig, y, z, u, v, w, nID,dDistance, x);

because /that/ makes it sound like you've got a typo somewhere
Answer: What size are long and int?
If nID is a long being printed with an 'int' format and sizeof(int) != sizeof(long) then you get misaligned data access (in the sense that the alignment is not correct) from there on.
Which compiler are you using? GCC should diagnose the problem without difficulty if that is the trouble.   Similarly, if nID is a 'long long', you could have problems.

To answer your question - yes, there is an lower-bound on the upper-limit of the length of string that sprintf() must be able to handle.  The number is 509 for C89 systems, and 4095 for C99 systems.
To be precise, C99 says (fprintf(), section §126.96.36.199, para 15):

The number of characters that can be produced by any single conversion shall be at least
  4095.

There is no further qualification on sprintf().

With fixed version of amended example converted into compilable code:
#include <stdio.h>
int main(void)
{
    char  test[255] = {0};
    int    test1 = 2;
    double test2 = 35.00;
    int    test3 = 0;
    sprintf(test, "%d|%f|%d", test1, test2, test3);
    puts(test);
    return(0);
}

I get the output I would expect:
2|35.000000|0

To be getting the output you show, you have to be working with a very weird setup.

What platform are you on?

The behaviour you are showing indicates that the sprintf() function you are using is confused about the alignment or size of something.  Do you have a prototype in scope - that is, have you #included <stdio.h>?  With GCC, I get all sorts of warnings when I omit the header:
x.c: In function 'main':
x.c:8: warning: implicit declaration of function 'sprintf'
x.c:8: warning: incompatible implicit declaration of built-in function 'sprintf'
x.c:9: warning: implicit declaration of function 'puts'

But even with test2 redefined as a float I get the correct result.
If I change test2 into a long double, then I get a different set of warnings and a different result:
x.c: In function 'main':
x.c:8: warning: implicit declaration of function 'sprintf'
x.c:8: warning: incompatible implicit declaration of built-in function 'sprintf'
x.c:8: warning: format '%f' expects type 'double', but argument 4 has type 'long double'
x.c:9: warning: implicit declaration of function 'puts'

2|0.000000|0

This is closer to what you are seeing, though far from identical.
Since we don't have the platform information, I'm suspicious that you are working with a truly ancient (or do I mean buggy?) version of C.  But I'm still at something of a loss to see how you get what you show - unless you're on a big-endian machine (I'm testing on Intel Mac with MacOS X 10.6.2) ...pause... on a SPARC machine running Solaris 10, without #include <stdio.h> and with long double test2 = 35.0;, I get:
gcc -O x.c -o x && ./x
x.c: In function 'main':
x.c:8: warning: incompatible implicit declaration of built-in function 'sprintf'
2|-22446048024026502740613283801712842727785152907992454451420278635613183447049251888877319095301502091725503415850736723945766334416305449970423980980099172087880564051243997662107950451281495566975073444407658980167407319222477077473080454782593800009947058951029590025152409694784570786541673131117073399808.000000|0

That's different; it also generates 321 characters of output, so there's a buffer overflow in there - it is better to use 'snprintf()' to prevent that from occurring.  When things are declared properly, of course, I get the expected result.
So, can you post compilable code that shows your problem, instead of a snippet that does not?  And can you identify your platform - machine type, operating system version, compiler version (and maybe C library version)?
Answer: Is dDistance of type double? It looks like your %f is only grabbing four bytes of a double and then the next four bytes are treated as an integer, the real integer value is then ignored.
This question is tagged C++; are you able to use std::ostringstream which would eliminate any possible problems with the conversion string?
Comment: Everything is a double except for nID and nConfig which are int.
Comment: From your latest update, if you convert 35.0 to an IEEE double you get bit pattern 0x107803443200000000. If you take just the upper four bytes, it just happens to convert in integer form to 1078034432 (this only applies if your architecture is little endian). In your test program try %lf instead of %f to see if your library maybe isn't handling the %f-to-double format correctly.


404 page not found error even though the page exists

Question: On my Drupal 7 website, I'm getting a 404 page not found error on the front page: http://mydomain.com even though I can view the page just fine. Google Webmaster tools wouldn't validate my site; w3 website validator stops with 404 error.
I looked at my error logs in the database, and noticed that this is coming from node/1 which doesn't exist anymore. I set my home page to a different node, node/133.
This doesn't make sense to me. Either a page exists or it doesn't!
Answer: I finally resolved this after a lot of hair-pulling and gnashing of teeth by adding a URL alias from node/133 to node/1. Google Webtools now validates, and do does w3 link validator.
I discovered the solution by looking in the error logs:
 - admin/reports/page-not-found
I noticed that the specific page throwing the error was node/1 . Neither google Webmaster Tools, nor the validator helped as they reported only the 404 on the main domain name.


Proving that (X,Y) is not bivariate normal

Question: Let $X \sim N(0,1)$ and $Y=X$ if $|X|>c$ and $Y=-X$ if $|X|<c$, for any $c>0$.
I've already proved that $Y \sim N(0,1)$.
How do we prove that $(X,Y)$ is not a bivariate normal?
I've tried proving that $Cov(X,Y)=0$ and because they are not independent, then we reached our desired conclusion. However, I only get $Cov(X,Y)= 1-E(X^2\mathbb{1}_{|X|<c})$ which is $0$ only for some $c$... and doesn't prove for all values of $c>0$.
Then how can I prove this?
Answer: Showing that $Cov(X,Y) = 0$ is not going to lead you anywhere, since if $Cov(X,Y) = 0$, would just indicate that their covariance is 0, and say nothing much about the existence of a joint distribution.
By the definition of a multivariate normal distribution, $(X,Y)$ is bivariate normal if every linear combination of X and Y is Normal. So to show that $(X,Y)$ is not jointly normal, you need to find $a$ and $b$ such that
$$aX + bY \not \sim \text{Normally distributed} $$
So consider $X - Y$.
\begin{align*}
X - Y &=
\begin{cases}
X - |X| & \text{when} |X| > c\\
X + |X| & \text{when} |X| < c
\end{cases}\\
& = \begin{cases}
0 & \text{ when } |X| > \max\{0, c\}\\
0 & \text{ when } c <0 \text{ and } \min\{0,c\} < |X| < \max\{0, c\}\\
2X & \text{ when } c \geq 0 \text{ and }\min\{0,c\} < |X| < \max\{0, c\}\\
2X & \text {when } |X| < \min\{0, c\}
\end{cases}\\
\end{align*}
Then, trivially, irrespective of the value of $c$,  $P(X - Y = 0) > 0$, and thus $X - Y$ is not normally distributed. Thus, $X$ and $Y$ are not bivariate normal.
Comment: @Klenke2ed That is reasonable logic, but you only know they they are not independent by intuition, and not by definition. So it may not lead to a sound proof by contradiction. Anyway, glad I could help.
Comment: Thanks for the help. Just a point, though. If Cov =0 and had they had joint normal distribution, then it would imply that they were independent. Since, they clearly are not, we would be able to say that they didn't have joint normal distr.
Answer: An interesting observation:

If $(X,Y)$ is a bivariate normal then the support takes every values of $\mathbb{R^2}$. Then $XY$ takes every value in Real line.

Now here $XY=X^2$ if $|X|>c$ and $XY=-X^2$ if $|X|<c$. Then $XY$ do not take any less than $-c^2$, which leads to $(X,Y)$ can not be a bivariate normal.


Save in plist to a program directory

Question: i need to save a .plist file NOT to documents, but to the core of program.
For example my program called "123" and if i save data, then send my app to my friend and he opens this app he could see saved data, no matter where he puts this program. I can't find solution to this problem, please help me.
I'm making mac app.
and i save plist with
 [NSKeyedArchiver archiveRootObject:FBCover1.text=
 [NSString stringWithFormat:@"%@",Cover1.attributedStringValue]
 toFile:@"/Users/admin/FBCover1.plist"];

Comment: Use the Application Support folder sub folder for your app. (Create it if it does not exist)
Comment: "Application Support" doesn't (easily) transfer between computers, @uchuugaka
Comment: No easier nor difficult than the app bundle. What is your point? If you need to update data, update data in the proper places provided. If you need to update an app, do that properly. Code Sign. If you are not doing this you hate your users and customers because you don't care at all about security and you want to be an attack vector.
Answer: General answer:
If you're trying to do this on iPhone (you didn't tag this for iOS or MacOS), this isn't going to work as this will break your code signing.
If you're doing this on MacOS and you're using code signing, you'll have the same problem.
There may be places where you could save and share data, such as Game Center or DropBox or Box or some other cloud storage mechanism, but you'll need to pick up and make use of some additional API's or frameworks.
Specific answer just for you:
Instead of:
[NSKeyedArchiver archiveRootObject:FBCover1.text=[NSString stringWithFormat:@"%@",Cover1.attributedStringValue] toFile:@"/Users/admin/FBCover1.plist"];

which is big and ugly and I don't know what the heck it's doing, why not save your string this way?
NSString * stringToSave = [NSString stringWithFormat:@"%@",Cover1.attributedStringValue];
if(stringToSave)
{
    NSError * error = nil;
    BOOL success = [stringToSave writeToFile: @"/Users/admin/FBCovert1.txt" atomically: YES encoding: NSUTF8StringEncoding error: @error];
    if(!success)
    {
        NSLog( @"error in saving - %@", [error localizedDescription]);
    }
}

This saves the raw string into a file.
If you want to do it as a plist, then create a NSDictionary and save your string as the value with some appropriate key.
Comment: add info to the question.
Comment: That "`.plist`" file is going into the home folder of a user named "`admin`", which is *not* the core of the program. Does your friend have an account named "`admin`" also? Is your MacOS going to be code signed?
Comment: Not it's not going to be signed.
Comment: In my case, now i use this path in order to test, but that's the point, i want to change it.
Answer: Preamble: this is an awful idea. What you should do is create a document-based application and pass your document backwards and forwards.
Literal answer:
You can use NSBundle to get the path of the resources folder within your application bundle with something like:
[[NSBundle mainBundle] resourcePath]

The resources folder is where application resources, such as plists, are meant to go. You're supposed to consider your application bundle as read-only in general but that's as good a choice as any if you want to hack away.

Save in plist to a program directory


Do I need automatic IIS pool recycle every N hours?

Question: By default IIS has "Recycling" app pool settings set to "Regular Time Interval (minutes) == 1740" which makes the application pool restart every 29 hours no matter what happens and what load the server responds to.
How do I know if I need this "automatic recycle every N hours" policy enabled?
Answer: Depends on your application. I have some applications that i don't want to recycle when it's busy on the website. Therefore i changed the regular interval into Specific times. These time are late in the evening and early in the morning. This way the recycle doesn't interfere with the user interaction on the site.
For regular websites it wouldn't be a problem to have the regular interval.
Als you could choose to recycle based on requests and memory. This also depends on your specifications of the webserver (RAM).
Comment: What about not recycling at all?
Answer: These are my thoughts on the matter, so it's best to perform your own research and arrive at your own conclusion. While it can be extreme, recycling should not be used to "resolve" a resource leak or a hang. If you are on an environment that is limited in resource and host multiple sites, then I can see recycling/throttling to best use resources. However, let's pretend I build a windows service instead of a website on IIS for a company. If my service would hang when running for 24 hours or would consume all the memory in a server and I don't state that in the specifications, asking to schedule a task to restart the service every 29 hours probably won't be acceptable to some customers and they would ask me to fix that. Well, that is what recycling is doing. Of course it brings a new worker process up before terminating the old one, but you will see the effects of a cold start of a worker process. Hence, I would recommend testing how the site runs without recycling or the idle-timeout and adjust accordingly.
Comment: In my case I have a Windows Service AND a Website which perform the same action -- The Windows Service does an automated action but when there is an error the user can manually initiate the same action from the website.  Both the windows service and website intermittantly return false on a directory.exist using a unc path.  If I recycle the app pool it works -- if I restart the web service it works.  I have a domain user account as identity for both the windows service and app pool.  Maybe this is a network permission issue or server timeout?  We wrote some retry logic until we figure it out.


Finding Last Used Row in filtered data

Question: Code to find the last used row in filtered data.
Sub find()

Dim rFiltered As Range

With ActiveSheet.AutoFilter.Range
    Set rFiltered = .Resize(.Rows.Count - 1).Offset(1).Columns(2).SpecialCells(xlCellTypeVisible)
End With

'is shows 419 - and that is fine
FirstRow = rFiltered.Cells(1, 1).End(xlToLeft).Row
'it shows the very last row 1048576, not the last row in a filtered range
'it should be 423
LastRow = rFiltered.Cells(FirstRow).End(xlDown).Row

For r = FirstRow To LastRow
    If Sheet1.Cells(r, 2).Value = "Maria L" Then
        Rows(r).Interior.Color = rgbBlue
    End If
Next r

End Sub

Sample data that is filtered
R Number    Name
4879668 Maria L
4879668 Thomas Y
4879668 Eleanor B
4879668 Eleanor B
4879668 Sandra J

The first used row here is 419, the last one is 423, but it shows the very last row 1048576.
The code shows correct LastRow only when filtered data begins from second row.
Comment: That is one of the problem using `xlDown`. You may want to see [THIS](https://stackoverflow.com/questions/11169445/error-in-finding-last-used-cell-in-excel-with-vba/11169920#11169920)
Comment: Check here `rFiltered = .Resize(.Rows.Count - 1)`
Comment: The only way I can replicate your issue, using your code, is if I filter the list via a column other than the 2nd, so that the 2nd column is completely blank.
Answer: Say we start with:

and then apply a filter:

The following will get the row number of the last visible row in the filtered data:
Sub framm()
    Dim r1 As Range, r2 As Range, r3 As Range, Last As Long

    Set r1 = ActiveSheet.AutoFilter.Range
    Set r2 = r1.SpecialCells(xlCellTypeVisible)
    Set r3 = r2.SpecialCells(xlCellTypeLastCell)
    Last = r3.Row

    MsgBox Last
End Sub

Answer: I changed this part:
LastRow = rFiltered.Cells(FirstRow).End(xlDown).Row

to this:
LastRow = Sheet1.Range("A" & Sheet1.Rows.Count).End(xlUp).Row

Answer: To explain why add some debug.print statement.
With ActiveSheet.AutoFilter.Range
    Set rFiltered = .Resize(.Rows.Count - 1).Offset(1).Columns(2).SpecialCells(xlCellTypeVisible)
End With
Debug.Print rFiltered.Address

firstrow = rFiltered.Cells(1, 1).End(xlToLeft).Row
Debug.Print firstrow
Debug.Print rFiltered.Cells(firstrow).Address

Applying the filter for Eleanor B and single step with F8
1st print shows $B$4:$B$5 for the filtered address
2nd print shows 4 for $B$4 row
3rd print shows $B$7 ? Why, because it's the 4th row of filter range "$B$4:$B$5"
$B$7 is empty so the last row is the bottom.
Answer: This is a tricky proposition at best. Do you have headers? Do you have totals?
So I came up with this code to at least cope with the totals (actually subtotals):
Sub GetLastRowFiltered()

    Dim rng1   As Range
    Dim rng2   As Range
    Dim lFirst As Long
    Dim lLast  As Long
    Dim lCol   As Long

    Set rng1 = ActiveSheet.AutoFilter.Range
    Set rng2 = rng1.SpecialCells(xlCellTypeVisible)

    lFirst = rng2.Row()
    lCol = rng2.Column()
    lLast = Cells(Application.Rows.Count, lCol).End(xlUp).Row()

    MsgBox "First Row: " & Format(lFirst, "###") & vbCrLf & _
           "Last  Row: " & Format(lLast, "###"), _
           vbInformation + vbOKOnly, _
           "Filtered Range Info:"

End Sub 'GetLastRowFiltered

As shown above you'll get this answer:

If you add 1 to: lCol = rng2.Column() + 1
You'll get this:

Haven't even started thinking about getting the first real data row.
BTW: Gary's solution kept giving me 233 as the last row, and the last row in my list is 186, 187 with totals. I have no idea why.
HTH

Finding Last Used Row in filtered data


Add multiple fields in +Add more button causes problem in sequence

Question: I am implementing a form and in that form it requires that two form element should be coming under one Add more button, so user can add any number of fields.
Here is the code which i am using to create a form.
function ajax_example_add_more($form, &$form_state, $no_js_use = FALSE) {
  $form['description'] = array(
    '#markup' => '
' . t('This example shows an add-more and a remove-last button. The AJAX version does it without page reloads; the non-js version is the same code but simulates a non-javascript environment, showing it with page reloads.',
      array('!ajax' => url('examples/ajax_example/add_more'), '!multistep' => url('examples/ajax_example/add_more_no_js')))
    . '
',
  );

  $form['#tree'] = TRUE;
  $form['names_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('People coming to the picnic'),
    '#prefix' => '
',
    '#suffix' => '
',
  );
  if (empty($form_state['num_names'])) {
    $form_state['num_names'] = 1;
  }
  for ($i = 0; $i < $form_state['num_names']; $i++) {
    $form['names_fieldset']['name'][$i] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
    );
    $form['names_fieldset']['surname'][$i] = array(
            '#type' => 'textfield',
            '#title' => t('SurName'),
    );
  }
  $form['names_fieldset']['add_name'] = array(
    '#type' => 'submit',
    '#value' => t('Add one more'),
    '#submit' => array('ajax_example_add_more_add_one'),
    '#ajax' => array(
      'callback' => 'ajax_example_add_more_callback',
      'wrapper' => 'names-fieldset-wrapper',
    ),
  );
  if ($form_state['num_names'] > 1) {
    $form['names_fieldset']['remove_name'] = array(
      '#type' => 'submit',
      '#value' => t('Remove one'),
      '#submit' => array('ajax_example_add_more_remove_one'),
      '#ajax' => array(
        'callback' => 'ajax_example_add_more_callback',
        'wrapper' => 'names-fieldset-wrapper',
      ),
    );
  }
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  if ($no_js_use) {
    // Remove the #ajax from the above, so ajax.js won't be loaded.
    if (!empty($form['names_fieldset']['remove_name']['#ajax'])) {
      unset($form['names_fieldset']['remove_name']['#ajax']);
    }
    unset($form['names_fieldset']['add_name']['#ajax']);
  }

  return $form;
}

/**
 * Callback for both ajax-enabled buttons.
 *
 * Selects and returns the fieldset with the names in it.
 */
function ajax_example_add_more_callback($form, $form_state) {
  return $form['names_fieldset'];
}

/**
 * Submit handler for the "add-one-more" button.
 *
 * Increments the max counter and causes a rebuild.
 */
function ajax_example_add_more_add_one($form, &$form_state) {
  $form_state['num_names']++;
  $form_state['rebuild'] = TRUE;
}

/**
 * Submit handler for the "remove one" button.
 *
 * Decrements the max counter and causes a form rebuild.
 */
function ajax_example_add_more_remove_one($form, &$form_state) {
  if ($form_state['num_names'] > 1) {
    $form_state['num_names']--;
  }
  $form_state['rebuild'] = TRUE;
}

The above code is taken from the example module with little modification. In this code i have added one more text field called surname with name textfield.
Now when i access form it gives me the form fields as shown in the image given below.
Before clicking on Add more button:

Now when i click on the Add more button two fields are added as shown in the below image.

Here you can notice that there are two continuous Name and then two continuous Surname fields.
But actually i want to show these fields like in group. So the first group of name and surname and then second group of name and surname field.

How can i achieve as per the above snapshot ?
Answer: The answer is - you really shouldn't try. The logic behind your form now shows one person with two Names and two SurNames. What you want, I bet, is two persons with one Name and one SurName each. So just group Name and SurName in fieldset and you're good.
If you insist on not doing it, read further. You use $form['names_fieldset']['name'][$i] and $form['names_fieldset']['surname'][$i]. It means $form['names_fieldset']['name'] is created before $form['names_fieldset']['surname'], so everything you put in it will be together and before surname. Just swap indexes and make them look like this: $form['names_fieldset'][$i]['name'], $form['names_fieldset'][$i]['surname'] and you'll be good. Of course $form['names_fieldset'][$i] can be a fieldset by itself, so we are back to first paragraph.
Comment: Did the same mistake not so long ago, you know ;)
Comment: Thanks for this. I have also found that Name and Surname will be in sequence because it goes by alphabet. In my case I had  Name and Email, which works together as per this answer, but were swapped because of alphabet. Solution: add another index: $form['names_fieldset'][$i][0]['name'] and $form['names_fieldset'][$i][1]['email']