Can the inverse function theorem be extended to regions?

Question: The inverse function theorem states that:
If the determinant of the Jacobian of a function $F:\mathbb{R}^n \rightarrow \mathbb{R}^n$ is non-zero at a point $\vec{x}_0\in\mathbb{R}^n$, then there exists an inverse function $F^{-1}$ in a neighborhood of $\vec{x}_0$ such that $F^{-1}(F(\vec x)) = \vec x$.
Can the theorem be extended to regions in some way? For example, suppose that the Jacobian of $F$ is non-zero in an open set $\Omega \subset\mathbb{R}^n$. Does it follow that $F$ has an inverse in all of $\Omega$?
Comment: @rogerl The Jacobian determinant has to be *non-zero* for the inverse to exist.
Comment: Because you can start with a neighborhood guaranteed by the theorem around $x_0$, then apply the theorem to another point $x_1$ within this neighborhood, and construct an inverse within a neighborhood of $x_1$. Obviously the inverses must be the same in both neighborhoods. You can continue like this, with an endless sequence of points $x_0, x_1, \dots$. My intuition is that in some cases, such a construction can cover a domain.
Comment: What is true is that if the Jacobian is zero at $x_0$ then $F$ is invertible in some neighborhood of $x_0$. See the [Wikipedia article](https://en.wikipedia.org/wiki/Inverse_function_theorem), for example.
Comment: Ack. Of course I meant to write "if the Jacobian is *non*zero"
Comment: @rogerl What is the difference between your statement and what I wrote?
Comment: You are trying to take a local result for a big set into a global result for a smaller set. Why would you think this could be done?
Answer: Try
$$
f(x)=x^2
$$
On the open set $(-1,0)\cup (0,1)=\Omega$. The Jacobian is nonvanishing but we still do not have injectivity on $\Omega$.
Comment: What about a connected domain? I am trying to figure out the conditions I need to add to the theorem to extend it to a region.
Answer: No in the case $n>1:$ That's because every ball $B(a,r)\subset \mathbb R^n$ is diffeomorphic to $\mathbb R^n$ itself. You seem to be aware that if $n>1,$ that there exists $F:\mathbb R^n \to \mathbb R^n$ with $\det F(x) \ne 0$ everywhere, but such that $F$ is not injective. Composing with the above diffeomorphism yields a counterexample for $B(a,r).$
Comment: Can you construct an explicit example?


C Zephyr SDK CRC16 Implementation

Question: I was looking around in the zephyr implementations and found this method for computing a crc16 checksum:
u16_t crc16(const u8_t *src, size_t len, u16_t polynomial,
        u16_t initial_value, bool pad)
{
    u16_t crc = initial_value;
    size_t padding = pad ? sizeof(crc) : 0;
    size_t i, b;

    /* src length + padding (if required) */
    for (i = 0; i < len + padding; i++) {

        for (b = 0; b < 8; b++) {
            u16_t divide = crc & 0x8000UL;

            crc = (crc << 1U);

            /* choose input bytes or implicit trailing zeros */
            if (i < len) {
                crc |= !!(src[i] & (0x80U >> b));
            }

            if (divide != 0U) {
                crc = crc ^ polynomial;
            }
        }
    }

    return crc;
}

And I tripped over this line here:
                crc |= !!(src[i] & (0x80U >> b));

I do not understand why they are using a boolean operator (!!) in this line. From my understanding this is what it does:
It basically does an implicit "casting" where it considers its operand on the right to be a boolean and negates it twice, which does not do anything besides making the output a 0 or a 1 depending on if the expression (src[i] & (0x80U >> b)) was bigger then 0 to start with.
Is this correct? Why are they using the operator in this way?
Comment: It's an idiom for turning values into canonical true (1) and false (0) values.
Comment: `!!x` is equivalent to `x != 0`.  Also, `!!` isn't an operator.  It's two applications of the `!` operator, i.e. `!!x` is `!(!x)`
Comment: @TomKarzes thanks. can you imagine why they would go for this? is this a common way  to do this?
Comment: There is what I consider a design flaw with the way parameters are handled with this CRC. The initial value is cycled 16 times before including any source data bits into the CRC. This means that it can't be used to chain calls, where a second call would use the CRC returned from the first call to continue a CRC calculation over data split up into groups.
Answer: It is inserting bit 7-b from src[i] into the low bit of crc. If that bit is a 1, which will be somewhere in the result of the &, the !! turns it into a 1 in the low bit, which is then or'ed into crc.
This is truly painful to look at. A better and cleaner way to do it is crc |= (src[i] >> b) & 1;, where b counts down instead of up. E.g. int b = 8; do { b--; ... } while (b);. Better still would be to just exclusive-or the byte after the loop, which does the same thing:
/* src length + padding (if required) */
for (i = 0; i < len + padding; i++) {
    for (b = 0; b < 8; b++)
        crc = crc & 0x8000 ? (crc << 1) ^ polynomial : crc << 1;
    if (i < len)
        crc ^= src[i];
}

An optimizing compiler will unroll the b loop.

C Zephyr SDK CRC16 Implementation


Why is this property of the Cron service initialized in this manner?

Question: I wish someone could help me understand this code statement found on the core cRON service (\Drupal\Core\Cron), especially in the constructor method for this class.
public function __construct(ModuleHandlerInterface $module_handler, LockBackendInterface $lock, QueueFactory $queue_factory, StateInterface $state, AccountSwitcherInterface $account_switcher, LoggerInterface $logger, QueueWorkerManagerInterface $queue_manager, TimeInterface $time = NULL) {
  // Omissis
  $this->time = $time ?: \Drupal::service('datetime.time');
}

What does this line do? Why isn't $this->time = $time; instead used?
The service is already injected using arguments.
class: Drupal\Core\Cron
arguments:
  - '@module_handler'
  - '@lock'
  - '@queue'
  - '@state'
  - '@account_switcher'
  - '@logger.channel.cron'
  - '@plugin.manager.queue_worker'
  - '@datetime.time'
lazy: true

Answer: It's backward compatibility.
Strictly speaking, constructors are excluded from BC, but the reality is that it is fairly common that one has to override them to inject additional dependencies.
The fallback to the global service means that if such a child class calls the constructor without that argument, it is not going to fatal.
That's especially common for base classes like ContentEntityForm, ControllerBase and other base classes that are specifically designed to be subclassed.
It can also be helpful during updating from an old version, because when running update.php in the UI, the class might be instantiated before Drupal has a chance to rebuild the container and provide the new arguments.
Comment: Yes, exactly. The other services were I think there since 8.0, while the time service was added last october, so it is new in Drupal 8.5.
Comment: Why that one service specifically, though? The cron service injects module handler, lock, queue, state and a bunch of others...what's special about the time service? Is it literally that `datetime.time` was added as a dependency later?
Comment: Makes sense, cheers


How to call JQuery CheckBox Changed Event inside a Jquery Accordion Header?

Question: Thanks for all your valuable responses to the questions that I have asked before, those suggestions helped me a lot.
I have one more question here.
I am using a JQuery accordion control in my page,and the accordion header contains a checkbox,
Based on the checkbox selection, I need to retrieve some date from the DB.
So, I need the checkbox changed event to get fired, but The event never gets fired for some reason. I am building the checkboxes dynamically through code.
Code:
string sa= '';
sa+= '
<input type=checkbox runat=server OnCheckedChanged=chkScores_CheckedChanged id=chkScorecard' + i + '>Auckland Aces</input>

';

after creating checkboxes like above, I am adding them to the accordion div.
If you observe, I am giving OnCheckedChanged event, but that event is not firing.
Any idea..Why it is happening like that. I have been trying for past 6 hours on this, but no luck.
Can you guys please tell me if I am doing anything wrong, or is there any alternate approach to this.
Thanks and appreciate your feedback.
Answer: you write
OnCheckedChanged=chkScores_CheckedChanged

covert it to

OnCheckedChanged="chkScores_CheckedChanged"

EDIT:
true, this will not work because it an html input and the event oncheckedchanged, and this event is for asp:CheckBox and at runtime it will covert to input html with
onclick="javascript:setTimeout('__doPostBack(\'checkBox1\',\'\')', 0)"

so, if you want, you can add onclick javascript function to the input and in this function call the server side,
Example using JQuery:
Insert input checkbox:
var htmlTags = '<input id="checkboxID" type="checkbox" runat="server"  onclick="CheckboxChange(this.id)" enableviewstate="true" />';

Add an Button to call it event:
<asp:Button ID="lbtnRefreshGV" runat="server" Text="" Height="0px" Width="0px" Style="visibility: hidden"  OnClick="lbtnRefreshGV_Click"></asp:Button>

Add javascript function
function CheckboxChange(id) {
        alert("In CheckboxChange");
        alert(id);
        $('#lbtnRefreshGV').trigger('click');
        alert("Out CheckboxChange");
    }

Comment: Its not wotking even if I give OnCheckedChanged="chkScores_CheckedChanged"


How to enable field_ui "Manage display" for a custom entity?

Question: I have written a module that creates a custom Content Entity that has a number of fields including an entity_reference field with a "file" target type. The field_ui module adds location task tabs, alongside my entity settings page, for editing field properties (good!). However, clicking on the field_ui "Manage display" tab for my custom Entity settings crashes Drupal (and not in my code). Has anyone else seen this problem? What "file" plugin is it referring to? This happens in multiple versions of Drupal (8.0.6, 8.1.1, 8.1.7):
The website encountered an unexpected error. Please try again later.
Drupal\Component\Plugin\Exception\PluginNotFoundException: The "file" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition() (line 57 of core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php).
Drupal\Core\Plugin\DefaultPluginManager->getDefinition('file')
Drupal\Core\Field\FormatterPluginManager->createInstance('file', Array)
Drupal\Core\Plugin\DefaultLazyPluginCollection->initializePlugin('file')
Drupal\Component\Plugin\LazyPluginCollection->get('file')
Drupal\Component\Plugin\LazyPluginCollection->getIterator()
Drupal\Core\Plugin\DefaultLazyPluginCollection->getConfiguration()
Drupal\Core\Config\Entity\ConfigEntityBase->preSave(Object, 1)
Drupal\Core\Entity\EntityDisplayBase->preSave(Object)
Drupal\Core\Entity\EntityStorageBase->doPreSave(Object)
Drupal\Core\Entity\EntityStorageBase->save(Object)
Drupal\Core\Config\Entity\ConfigEntityStorage->save(Object)
Drupal\Core\Entity\Entity->save()
Drupal\Core\Config\Entity\ConfigEntityBase->save()
Drupal\field_ui\Form\EntityDisplayFormBase->buildFieldRow(Object, Array, Object)
Drupal\field_ui\Form\EntityViewDisplayEditForm->buildFieldRow(Object, Array, Object)
Drupal\field_ui\Form\EntityDisplayFormBase->form(Array, Object)
Drupal\Core\Entity\EntityForm->buildForm(Array, Object)
call_user_func_array(Array, Array)
Drupal\Core\Form\FormBuilder->retrieveForm('entity_view_display_edit_form', Object)
Drupal\Core\Form\FormBuilder->buildForm(Object, Object)
Drupal\Core\Controller\FormController->getContentResult(Object, Object)
call_user_func_array(Array, Array)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}()
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}()
call_user_func_array(Object, Array)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1)
Stack\StackedHttpKernel->handle(Object, 1, 1)
Drupal\Core\DrupalKernel->handle(Object)
Answer: I'm pretty sure your view display configuration there is invalid, there is no "file" formatter. There are many formatters for file fields but none is called just file, there is file_link, file_uri, file_default and many more, you have to pick the one you want.
Granted, the error handling there could be better. Feel free to open a core issue about that.


Accessing from Internet to a svn installed in a machine of a Wireless LAN

Question: I would like to install a svn in a machine of a Wireless LAN (in my home: I haven´t bought any public IP), and access to it from internet. I would like to use Apache 2.2 + Subversion + SSL. In my wireless LAN, I have set a static IP for the machine with the SVN, to make it easier. My question is: when I install the Apache server, do I need a public network domain to serve my SVN, or is enough with my external IP (assigned to the router)? If I set it to the router, how should I redirect the traffic to my SVN server (that is in a machine with a private IP)?
Thanks in advance.
Answer: You should configure your router to forward svn ports to your svn server.
This includes port 80 and port 3690.
Then your svn will be accessible through your external IP.
You also can use no-ip.com to get a permanent domain name that will point to your dynamic IP.
Comment: but if I redirect port 80, the other machines in the LAN cannot use Internet, can them?
Comment: There is a inbound and outbound traffic. When you are surfing the net, you are using others port 80. When you serve an application, you are using your own port 80. Setting up svn won't affect your ability to surf the net.
Comment: 1. 3690 is for svn:// access, useless for Apache-based 2. Incoming 80 on router is handled (and must be) by router's mini-http-server. YOU FAILED
Answer: If your router have embedded http-server on 80 port, you can only redirect incoming port for https.
For external world your repo will be https://hostname-of-router/repo/path/, but served by internal host


HTML tags of an article not working

Question: I came across this issue. I wrote an article in editor and I put there basic HTML tags like  and so on. The thing is, in editor it shows right, but when I publish the article, the HTML tags dont do anything and they are displayed just like normal text.
Do you have any idea why is this happening?
Thank you for any reply
Answer: i hope , you have used basic html filter. Basic filter doesn't support all of the tags of html. you have to use full html filter instead of basic html.
Comment: Yes, just found out about it now. Is there any way I can set Full HTML on multiple nodes at once? I have to set it on multiple nodes, so if it is possible to set it on multiple nodes at once so I dont have to edit every node one by one.
Comment: use hook_node_add or hook_node_preserve to achieve this to multiples nodes.
Comment: Alright, can you please tell me where should I put this? I am totally new to Drupal.
Comment: https://api.drupal.org/api/drupal/modules%21node%21node.api.php/group/node_api_hooks/7.x
Comment: just put this in your .module file
Comment: `hook_node_add()` and `hook_node_preserve()` are hooks Drupal core invokes.
Comment: The question is for Drupal 8. The list of node hooks invoked from Drupal core 7 isn't much helpful to the OP.
Comment: its also available on drupal 8. just check node api of drupal 8. will get the solution
Comment: In that case, the link should directly take to the Drupal 8 page. With a link for Drupal 7, the OP could think all those hooks are used from Drupal 8 too, which is not the case. Most of those hooks are not for batch processing nodes, so they aren't helping the OP.
Answer: You need to configure the HTML accepted by the filter in use to match your wysiwyg settings, otherwise you are likely to get mismatches like this, where the editor generates HTML that is filtered out before display, or shown as plain text.
Fortunately the field data stored in the database will include the HTML, so you may be able to fix this purely by adjusting the settings of the filter.
Be careful, though, you also need to consider what different classes of users are allowed to do, so if you have a filter that's available to all users you probably want to keep it restricted in terms of the HTML. Configure (and add) filters and editor settings to match user requirements.
Comment: Exactly. I added that in the answer, so the OP cannot think this is not the case described in the question.
Comment: The OP said the HTML tags are showing as plain text. If that is the case, HTML tags aren't filtered out.
Comment: Good catch, in that case the filter must be a plain text one which escapes HTML. Either way, the filter isn't set up right.

HTML tags of an article not working


Need help understanding the behavior of a request in IIS pipeline

Question: lately I am working on a case of unwanted redirects on our Azure hosted ASP .NET Core app which uses IIS. We have a problem with request containing two HTTP/HTTPS prefixes. I entered the Failed Request Tracing logs and see this (look at the RequestURL value):

Which then later gets shortened to this:

Anybody can help me understand why it happens? It happens before the request enters the rewrite pipeline, and even then, we don't have any rewrite rules which could cause it.
Our IIS rewrite rule after which redirection is happening:
<rule name="Add trailing slash" stopProcessing="true">
    <match url="(.*[^/])$"  ignoreCase="true"/>
    <conditions>
        <add input="{URL}" pattern="^(.+?)/$" negate="true"/>
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        <add input="{REQUEST_FILENAME}" pattern="(.*?)\.html$" negate="true" />
        <add input="{REQUEST_FILENAME}" pattern="(.*?)\.xml$" negate="true" />
        <add input="{REQUEST_FILENAME}" pattern="(.*?)\.aspx$" negate="true" />
        <add input="{URL}" pattern="^/(.*?)?(/?)(siteassets|globalassets|contentassets|SysSiteAssets|bundles|api|papirfly|dist|Static/HouseProductDemo|mini-profiler-resources|custom-routes|auth0|dam.papirfly)\/" negate="true"/>
        <add input="{URL}" pattern="^/(.*?)?(/?)(robots.txt|favicon.ico|Sitemap.xml|sitemap-index.xml)" negate="true"/>
        <add input="{URL}" pattern="^/(.*?)?(/?)(modules/Protected|EPiServer|EPiServer/CMS/admin|util|modulesbin|IndexingService/IndexingService.svc)" negate="true"/>
        <add input="{URL}" pattern="^/(.*?)?(/?)(productsOverviewAsync|languageSelectorAsync)" negate="true"/>
        <add input="{URL}" pattern="^/(.*?)?(/?)(documentationListAsync|downloadAndOrderItemsAsync|videoListAsync|commerceDocumentLibraryAsync)" negate="true"/>
        <add input="{URL}" pattern="^/(.*?)?(/?)(GatedContentPageAsync)" negate="true"/>
        <add input="{URL}" pattern="^/.*/sitemap.xml$" negate="true"/>
        <add input="{URL}" pattern="^(https?:/[^/]+){2,}" negate="true" />
    </conditions>
    <action type="Redirect" redirectType="Permanent" url="{R:1}/" />
</rule>

Comment: Those look like _script-kiddie hacker-bots_ testing your site for vulnerabilities.
Comment: _"We have a problem with request containing two HTTP/HTTPS prefixes"_ - that's not actually possible: HTTP requests don't actually contain the URI scheme (they _only really_ exist in a browser's address bar, honestly)  and anyway, Azure's App Service front-end load-balancers will reject malformed HTTP requests.
Comment: Anything occurred in the very first row came from outside of IIS pipeline. This, if this is all you can provide, no one can explain why that specific URL was used. Like the other comment indicated, it didn't usually come from a legit source.
Comment: This request came actually from us when we noticed that it's possible to make a redirect from URL parameter, we wanted to investigate the issue.
Comment: The edits of adding the rewrite rule do not help either, as this rule alone won't lead to the kind of URLs you dislike. Please hire an experienced consultant and share more details with him/her on the investigation. Stack Overflow, however, isn't the right place.
Comment: The format of the RequestURL `"http://rock-dev-web-01__06b0:80/http:/wp.pl"` looks incorrect. You may need to check the request sent by the client as well as the configuration on the server side to determine what is causing this incorrect URL.
Answer: "We have a problem with request containing two HTTP/HTTPS prefixes"

First, (and at risk of being accused of pedantry) they're not called "HTTP/HTTPS prefixes" - they're called URI schemes.
Second, the request you logged there does not actually contain two URI schemes; I'll explain...

But before that, please have a quick read through part 3 the current IETF specification that defines what a URI is and to learn terminology for its syntactical components.

The /http:/wp.pl text in your log does look like the start of a new URI when taken out of context, but it was still interpreted as the path component of the incoming request because that's what web-servers are programmed to do.

Fun-fact: HTTP requests do not (normally) contain a fully-qualified URI representation of the request (granted, they might have it stored in a private HTTP request header if they're hiding behind a reverse-proxy, and that also applies here as you're on Azure App Services (see the X-WAWS-Unencoded-URL header, but that's not fully-qualified...), but anyway).

Inside a HTTP request, there is no URI scheme or "protocol"  substirng: the server knows if the request is coming from http: or https: based on the incoming port-number and TLS exchange anyway.
The authority part of the URI will be sent separately in the Host: header.
So it's only the path part and optional query parts that gets sent in the HTTP GET /path/goes/here part.
While any #fragment part won't be sent to the server at all.

So in this case, the request that you logged there is perfectly valid because there's no prohibition on colons (whether percent-encoded or not) in the path component of an  absolute URI or "rooted" URI. It's only relative URIs paths that cannot contain a : in their initial path-segment as that renders them ambiguously formatted.
Comment: In which case you should move the `rewriteModule`'s registration to the top of the `` list so it gets invoked before the others then. (In Azure App Services this is done by using a XDT file to apply the change to your `ApplicationHost.config` file) - BTW, don't confuse that `` element with the (now _very obsolete_) `` from WebForms days....
Comment: Thank you for your input, I understand that, but the problem which we are facing is that the request like shown on the attached screenshot is entering our IIS rewrite pipeline, then is evaluated until it reaches the rule which adds a trailing slash at the end of URL and then the redirection is being made. So  https://example.com/http:/google.com is being redirected to to google and that's not a desired outcome for us.
Comment: @95XF Just change your `` rules to reject requests with paths containing colons. But if you're asking for help with your rewrite rules, you need to include them in your question-post.
Comment: We have quite a few of them, but only the the one with adding the trailing slash is relevant to the case, so I will add that one.
Comment: You don't need to change all of them - just add a new rule at the very top (with `stopProcessing="true"`) which will match any requests with slashes-that-you-don't-like and reject them - **but** it's bad-practice to handle requests differently simply based on  trailing slashes _alone_.
Comment: The problem is that with the problematic URLs, only the part starting with the second http/https is evaluated inside the rewrite pipeline, so in case of https://example.com/http:/google.com, only the http:/google.com part is taken into account (as shown in the first screenshot).
Comment: @95XF It sounds like your `` rules were written incorrectly then, because what you're describing would only happen if those rewrite rules were using _reconstituted_ fully-qualified URIs (i.e. you're concatenting the HTTP `Host:` header with the Request Path) - **don't do that** and you won't have this problem. You should only ever use `{HTTP_HOST}` in a `` by itself - and to not re-create full URIs - that's how vulnerabilities like _request-smuggling_ happen...
Comment: But like I said before the URL split happens even before the first rewrite rule is being evaluated, so they cannot be the culprit here.


Please help with indetifying subformulas in the propositional logic.

Question: In my textbook of the propositional logic I should indentify all subformulas of the following formula: ¬(a∧b)⟺(c⇒a).
According to the textbook the formula (a∧b)⟺(c⇒a) is not a subformula of the formula ¬(a∧b)⟺(c⇒a). Why?
They also argue that ¬(a∧b)⟺(c⇒a) is a subformula of itself, is that correct?
Answer: The formula $\lnot(a \land b) \iff (c \Rightarrow a)$ can be ambiguous if we do not assume a convention about omitting parentheses.
According to the usual convention, the negation symbol applies to as little as possible.
This means that the above formula is an abbreviation for :

$(\lnot(a \land b)) \iff (c \Rightarrow a)$.

Regarding the second part of the question, the answer is YES: a formula is a sub-formula of itself, as must be evident reviewing the definition of sub-formula in your textbook.

Subformulas can be "mechanically" generated from the original formula (which is a sub-formula of itself) removing the main connective (there is only one).
Thus, from $(\lnot(a \land b)) \iff (c \Rightarrow a)$ we have to remove $\iff$ to produce two new sub-formulas :

$\lnot(a \land b)$ and $(c \Rightarrow a)$.

Now we apply the same procedure to $\lnot(a \land b)$ removing the negation sign to produce the new sub-formula $a \land b$ and again to get : $a$ and $b$.
The same for $(c \Rightarrow a)$.
Comment: Than you for your answer. Since English is not my first language I am not sure if you have answered the first question I have asked. It seems to me reasonable to say that  (a∧b)⟺(c⇒a) is a subformula of the formula (¬(a∧b))⟺(c⇒a), but in the textbook they are not arguing that. Why?
Comment: Well I know that I can omit parentheses but my question targets to the symbol for NOT. If this (a AND b) is a subformula for NOT(a AND b), than why (a AND b)IFF(c IMPLY a) is not a subformula of (NOT(a AND b))IFF(c IMPLY a) ?
Comment: The biconditional has higher precedence than the negation.  The formula has a tree structure with the biconditional symbol as the root.$$\lower{4ex}{\neg{\lower{3ex}{\lower{3ex}{(a}\wedge\lower{3ex}{b)}}}}\quad\Leftrightarrow\quad\lower{4ex}{\lower{3ex}{(a}\Rightarrow\lower{3ex}{c)}}$$
Answer: If the statement was ¬[(a∧b)⟺(c⇒a)] (i.e. if the statement was the negation of a biconditional), then (a∧b)⟺(c⇒a) would indeed be a subformula. But, the given formula ¬(a∧b)⟺(c⇒a) is a biconditional between ¬(a∧b) and c⇒a. So, those are both subformulas, but (a∧b)⟺(c⇒a) is not
Keep in mind that a subformula is not the same as a substring! Rather, try and understand how the operations are applied to the parts: that will tell you waht the subformulas are.
And yes, any formula is a subformula of itself ... kind of like how every set is a subset of itself.  If we want to exclude the formula itself, we would call for strict subformulas.


Do any of the regex syntaxes in the standard library support (?(DEFINE) for subpattern referencing?

Question: With PCRE you can define subpatterns which can be referenced later on. Here's a trivial example:
# start delimiter
/

# define non-matching subpatterns, is this supported by <regex>?
(?(DEFINE)
  (?<alpha> [A-Za-z])
  (?<num> [0-9])
)

# actual pattern, referencing subpattern definitions
^ (?&alpha){2} (?&num){2} $

#end delimiter and extended flag to ignore whitespace in pattern
/x

Do any of the regex syntaxes from the standard library <regex> support this, or is this really a PCRE-specific feature, perhaps?
I'm working with C++11.
Comment: You can see all supported syntax's here: https://en.cppreference.com/w/cpp/regex/syntax_option_type
Comment: @NathanOliver Thanks. I've seen this, but I don't know enough about all those syntaxes to know whether they support it. A reasonably thorough search yielded no results either, so far. That's probably a good indicator. But, coming from a PHP background, as PHP supports PCRE, yet doesn't mention this syntax in its own documentation either, I thought perhaps this could be a feature, that's somehow supported, but undocumented.
Comment: PHP doesn't have a solid documentation on PCRE and I think community shouldn't work on it either. It's just enough to know which regex flavor is being used in a language or environment.
Answer: The <regex> library supports the following grammars:

ECMAScript:    The Modified ECMAScript regular expression grammar;
basic:     The basic POSIX regular expression grammar;
extended:  The extended POSIX regular expression grammar;
awk:   The regular expression grammar used by the awk utility in
POSIX;
grep:  The regular expression grammar used by the grep utility in
POSIX. This is effectively the same as the basic option with the
addition of newline '\n' as an alternation separator;
egrep:     The regular expression grammar used by the grep utility,
with the -E option, in POSIX. This is effectively the same as the
extended option with the addition of newline '\n' as an alternation
separator in addtion to '|'.

Unfortunately, none of them support this feature.
More information on cppreference.com.


Dynamic resizing of JPanel

Question: I have a JPanel, within a JScrollPanel and when the whole program is compiled and run, a gui is displayed containing the JPanel and the JScrollPanel (and other components as well). Whenever a user draws something at the edge of the JPanel (say within n pixels near the lower or left edge) then the gui should automatically resize the JPanel, that is, increase the size of the JPanel.
I have used mouse event listeners (MouseDragged, MouseClicked, MousePressed; used for drawing) and within these listeners I set the new increased size for the JPanel. So whenever something is drawn at the edge the JPanel's size should be increased (and as it is within the JScrollPane, if the increase is substantial, then a scroll bar should appear). But the resizing is not happening.
Comment: For better help sooner, post a [MCTaRE](http://stackoverflow.com/help/mcve) (Minimal Complete Tested and Readable Example).
Answer: The scrollbar will appear automatically when the preferred size of the component added to the viewport of the scrollpane is greater than the size of the scrollpane. So, you need to override the getPreferrredSize() method of you JPanel to dynamically recalculate the preferred size.
The preferred size calculation will need to take into account:

the size of all the components being painted on the panel. So yo will probably use an ArayList to track all the components. Then you just loop through the list to determine the largest width/heigh position of any component.
the mouse location when the mouse is being dragged. If this value is greater than the width/height of the above calculation then you need to use this value. You will also need to invoke revalidate() for every mouseDragged event to make sure the layout of the component is done.

Dynamic resizing of JPanel


Dificuldade para implementar Vlibras usando JavaScript

Question: Preciso de uma ajuda.
Quero implementar um plugin do governo federal chamado vlibras (https://vlibras.gov.br/doc/widget/installation/webpageintegration.html?_ga=2.128060687.2041692944.1622566259-1292342778.1622566259).
O exemplo de implementação da documentação segue abaixo:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" type="text/css" media="screen" href="main.css" />

Dessa forma o vlibras é carregado!

Seguindo a documentação só preciso copiar e colar o código. Isso funciona mas eu preferiria não replica-lo em todas as minhas páginas.
Criei um javascript para fazer essa implementação "em tempo de execução", mas não consigo identificar o erro que impede o widget de ser criado. Não recebo erros no console mas o widget não aparece, apesar da estrutura de divs estar presente.
Abaixo o HTML da minha página:
<!DOCTYPE html>

    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Page Title</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <link rel='stylesheet' type='text/css' media='screen' href='main.css'>

E o vibras_new.js:
//Quando o HTML termina de carregar, executa a função vlibras
window.addEventListener('load', () => {
    vlibras();
});

function vlibras() {

    //cria a tag que importa o vlibras
    var scriptVlibras = document.createElement("script");
    scriptVlibras.setAttribute("src", "https://vlibras.gov.br/app/vlibras-plugin.js");

    //Obtém a div "target"
    var targetDiv = document.getElementById("ptifrmtarget");
    console.log(targetDiv);

    //Verifica se as divs já existem
    var divsVlibras = targetDiv.getElementsByClassName("enabled")[0];
    console.log("divsVlibras: ", divsVlibras);

    if (divsVlibras == undefined) {
        //Cria as novas divs
        var div1 = document.createElement("div");
        div1.setAttribute("vw", "");
        div1.setAttribute("class", "enabled");
        div1.setAttribute("id", "divVlibras");

        var div2 = document.createElement("div");
        div2.setAttribute("vw-access-button", "");
        div2.setAttribute("class", "active");

        var div3 = document.createElement("div");
        div3.setAttribute("vw-plugin-wrapper", "");

        var div4 = document.createElement("div");
        div4.setAttribute("class", "vw-plugin-top-wrapper");

        //Monta a estrutura das divs
        div3.appendChild(div4);
        div1.appendChild(div2);
        div1.appendChild(div3);

        //Insere as divs criadas
        targetDiv.appendChild(scriptVlibras);
        targetDiv.appendChild(div1);
        console.log(targetDiv);
    }

    //Apos carregar o vlibras, abre o widget
    scriptVlibras.addEventListener('load', () => {
        console.log("Chamando widget!");
        new window.VLibras.Widget("https://vlibras.gov.br/app");
    });

}

Obrigado desde já!
Answer: Fockink,
Fazendo alguns testes aqui, o script não está sendo gerado no momento correto para que o VLibras identifique o DOM e execute a ação do plugin. Modifiquei o evento que está sendo monitorado para a inclusão antes do documento estar completamente carregado. Nos meus testes funcionou. verifique como ficou para você.
No script abaixo faltam as verificações de já haver o plugin na tela, caso necessário.
let CreateDOMObjects = () => {
    const DOM = `

    `;
    document.body.insertAdjacentHTML('beforeend', DOM);
}

let ImportScriptFile = () => {
    let script = document.createElement('script');
    script.src = 'https://vlibras.gov.br/app/vlibras-plugin.js';
    script.onload = () => {
        new window.VLibras.Widget('https://vlibras.gov.br/app');
    };
    document.head.appendChild(script)
}

(() => {
    window.addEventListener('DOMContentLoaded', e => {
        CreateDOMObjects();
        ImportScriptFile();
    });
})();

Dessa forma também não é mais necessária a div:


CSS - inline divs size

Question: I have 4 divs.
1 - Divs '.left' and '.right' should be 150px min. - > OK
2 - Divs '.middle1' and '.middle2' should get the remaining with
divided by them. -> NOT OK
Why do I have a blank space between the '.middle2' and '.right'?

.container {
    width: 100%;
    display: table;
}
.left {
    float: left;
    display: table-cell;
    padding: 0;
    background-color: red;
    height: 30px;
    width: 15%;
    min-width:150px;
}
.middle1 {
    float: left;
    display: table-cell;
    padding: 0;
    background-color: blue;
    height: 30px;
    width: 35%;
}
.middle2 {
    float: left;
    display: table-cell;
    padding: 0;
    background-color: grey;
    height: 30px;
    width: 35%;
}
.right {
    display: table-cell;
    background-color: green;
    height: 30px;
    width: 15%;
    min-width:150px;
}
input {
  margin:5px;
  width:100px;
  background: #FFF;
}
.list{
  margin: 0 2px;
  color: #FFF;
}

    <input type="text">
    list

Comment: how do you want to display them ,all of them in single row?
Comment: None of your divs are `inline`...they all have non-inline display properties. You need to clarufy what it is you are trying to achieve,
Comment: Because `min-width:150px` is of course _more_ than `width: 15%` if the screen width is small enough ...
Answer: Not sure how do you want to display. Instead of playing around with floats, you can use display:flex to achieve the same.
Check the below snippet

.container {
 display:flex;
}
.left {

    padding: 0;
    background-color: red;
    height: 30px;
    width: 15%;
    min-width:150px;
}
.middle1 {

    padding: 0;
    background-color: blue;
    height: 30px;
    width: 35%;
}
.middle2 {

    padding: 0;
    background-color: grey;
    height: 30px;
    width: 35%;
}
.right {

    background-color: green;
    height: 30px;
    width: 15%;
    min-width:150px;
}
input {
  margin:5px;
  width:100px;
  background: #FFF;
}
.list{
  margin: 0 2px;
  color: #FFF;
}

    <input type="text">
    list

m1

m2

right

Answer: Hi this is not the best way to do this.
You should make a div with three sections of it and divide the middle one into two sections.
So basically the structure you need is
Div > 3 columns and then the middle column has two columns conatined.
However, here is a quick fix for your code :
 - Apply float:right to .middle2
 - Fix the width percetage for .middle1 and .middle2
.container {
    width: 100%;
    display: table;
}
.left {
    float: left;
    display: table-cell;
    padding: 0;
    background-color: red;
    height: 30px;
    width: 15%;
    min-width:150px;
}
.middle1 {
    float: left;
    display: table-cell;
    padding: 0;
    background-color: blue;
    height: 30px;
    width: 31%;
}
.middle2 {
    float: right;
    display: table-cell;
    padding: 0;
    background-color: grey;
    height: 30px;
    width: 31%;
}
.right {
    display: table-cell;
    background-color: green;
    height: 30px;
    width: 15%;
    min-width:150px;
}
input {
  margin:5px;
  width:100px;
  background: #FFF;
}
.list{
  margin: 0 2px;
  color: #FFF;
}

CSS - inline divs size


Probability of logical implication

Question: In my opinion, a carelessly formulated problem on my instructor's exam read:
$$P(\text{if the card is not a face card, it is divisible by 3})$$
It was graded graded as having the following meaning:
$$P(\text{not a face card $\land$ divisible by 3})$$
It seems to me that the vacuous case of the implication allows for face cards to be included in the event described by the implication. This would mean that the two formulations are not the same.
The course is not one in logic, does the instructor have grounds to argue that the two events are equivalent?
In general, can events be described in terms of logical implication, i.e., $P(p \Rightarrow q)$?
Answer: I see it like this:
event A = card is not a face card

event B = card is divisible by 3

the first probability you mention I would interpret like this:
P(B|A) = #cards_divisible_by_3 / (#all_cards - #face_cards)
P(B|A) = 12 / (52 - 12) = 0.3

the second probability you mention I would interpret like this
P(A,B) = #cards_divisible_by_3 / #all_cards
P(A,B) = 12 / 52 = 0.23

(all cards divisible by 3 are non-face cards)
Comment: Thanks. I clarified the question a bit. I understand that you interpret the statement "if the card is not a face card, it is divisible by 3" as "the card is divisible by 3 given that it is not a face card" from which you then reasoned using conditional probability. I am not sure if that is correct, looking at it rigorously. I agree with you on the second probability.

Probability of logical implication


Regex: using dot all flag, how to prefix each line?

Question: What would be the proper regex to prefix each line?
Say i have the the input data:
SOME OTHER DATA

TABLE
ROW
ROW
ROW
END

SOME OTHER DATA

Im only interested in what is between and including TABLE and END.
In php you can write a regex like the following /TABLE.*?END/s which would match the first occurence of TABLE to the first occurence of END. But is there a way i can prefix each line with %? so the result would become:
SOME OTHER DATA

%TABLE
%ROW
%ROW
%ROW
%END

SOME OTHER DATA

Any help is appreciated.
Comment: Easiest and most straightforward would be to do this with two expressions.
Comment: Would you mind providing an example?
Comment: Is input data in one line or in an array?
Answer: You can do it with a single replacement:
$txt = preg_replace('~^(?:TABLE\R|\G(?!\A)(?:END$|.+\R|.+\z))~m', '%$0', $txt);

Note that this pattern assume there's always a closing END "tag". If it isn't the case the replacement will continue until an empty line (cause of the + quantifier) or the end of the string.
You can also make the choice to check if the TABLE tag is closed with an END tag:
$pattern = '~^(?:TABLE\R(?=(?:.+\R)*?END$)|\G(?!\A)(?:END$|.+\R|.+\z))~m';

First pattern details:
^                   # matches the start of a line
(?:                 # open a non-capturing group
    TABLE \R        # TABLE and a newline (CR, LF or CRLF)
  |                 # OR
    \G (?!\A)       # contigous to a precedent match but not
                    # at the start of the string
    (?:             #
        END $       # END at the end of a line
      |             #
        .+ \R       # a line (not empty) and a newline
      |             #
        .+ \z       # the last line of the string
    )               # close the non-capturing group
)                   #

Additional lookahead details:
(?=             # open the lookahead
    (?:.+\R)*?  # matches zero or more lines lazily
    END$        # until the line END
)

An other way
$arr = preg_split('/\R/', $txt);
$state = false;
foreach ($arr as &$line) {
    if ($state || $line === 'TABLE') {
        $state = ($line !== 'END');
        $line = '%' . $line;
    }
}
$txt = implode("\n", $arr);

The behaviour of this code is the same as the first pattern, note that you obtain a string with UNIX format newlines.
Answer: Here you go. I did created one regex and commented it properly for you:
/(?:
 #start by finding the initial position of the table start, in order to store the match position for \G
    TABLE\n\K|
    #after we've found the table head, continue matching using this position. make sure we arent at the beginning of the string
    \G(?<!^)
)
#capture the data we're interested in
(?:
    #make sure there is no 'END' in the string
    (?!END)
    #match everything until the line ending
    .
)*
#consume the newline at the end of the string
\n/x

Replace the result with %$0
See it in action here: http://regex101.com/r/rA5bV1
--
I do recommend however, if you do not understand the regex I have created, to use an alternative method. Create a regex that would capture the contents of the table, and then just append % to every line. Use the following expression to capture the contents: /TABLE\n((?:(?!END).)*)END/. I did not comment this, you should be able to figure it out by reading the comments of the other expression.
Answer: You should do it with 2 regex :
$txt = file_get_contents('input.txt');
preg_match("#(.*(?<=TABLE\n))(.*\nEND)(.*)#ms",$txt,$m);
$new = $m[1].preg_replace("#^#ms","%",$m[2]).$m[3];
print $new;

ms modifiers make the regex act like the whole text is one line and the \n is match like a normal character with ..
If you want to do it in only one regex, you will have to use special matching blocks like one of theses:

Regex match everything between two string, spaning multiline
Regex Match all characters between two strings

Hope that helps.


show full name on hover limitTo Content Using angularjs?

Question: I have a products array.it consist of name,price,qty. i am Using limitTo When name length reaches to 20.
when hover on product how to show full name please hlep me?

{{ item.name| limitTo: 20 }}{{item.name.length > 20 ? '...' : ''}}

Answer: you can use the title property

or if you what to use angular for it and not the tooltip

angular.module('app', [])
.controller('myController', function($scope) {
$scope.myText = "some very very very very very long text";
})
.directive('hoverText', function () {
    return {
        restrict: 'A',
        scope: {
            hoverText: '=',
            maxChars: '='
        },
        link: function (scope, element) {
          element.text(scope.hoverText.substr(0, scope.maxChars) + '...')
            element.on('mouseenter', function() {
                element.text(scope.hoverText);
            });
            element.on('mouseleave', function() {
                element.text(scope.hoverText.substr(0, scope.maxChars) + '...');
            });
        }
    };
})
p

Comment: this is shows tool tip. but don't want tool tip.expand on the same place.
Comment: ok i added an alternative directive, i recommend the directive method, because it is reusable in your code + if you have a loop for your products using a flag for mouseenter and leave will trigger all of them! unless you make it a property in the product item itself
Comment: if you can add that library to your code i would also highly recommend it... i also use it constantly
Answer: You could do something like below.
Markup

    {{ item.name| limitTo: limit }} 20 ? '...' : ''">

Controller
$scope.limit = 20;

Demo Plunkr

Though I would suggest you to look at CSS option where you can achieve the same using text-overflow: elipsis and making overflow: hidden. You can refer this link to implement the same
Comment: @WalksAway I see, that's why you updated your answer.. I don't want to repeat same thing in my answer, but your way seems awesome to me. :)
Comment: @WalksAway that was my next step I'm gonna do, but I head out for something in between, and you did the same. Therefore I won't be able to do it now :)
Comment: @WalksAway though I would love to use `text-overflow: elipsis` CSS property, I can't now. I'll upvote yours if you want :p I did it +1
Comment: yeah it is better but i had issues with it, like when you want to have multiple lines + ellipsis, it only gives you the first line


Minimising Posterior expected loss

Question: I am new to Bayesian statistics. I am not sure how I could find the best point estimator $T(x)$ for $\alpha$ that minimises the posterior expected loss, $$E_{\alpha|x} [L(\alpha, T(x)))] = \int L(\alpha, T(x)) p(\alpha|x) d\alpha$$.
Assuming we have zero-one loss.
Thanks to anyone who may be able to help.
Answer: If the $0-1$ loss function is defined as
$$L(\alpha,t)=1-\mathbb I_\alpha(t)=\begin{cases}
1 &\text{ if }t\ne\alpha\\
0 &\text{ if }t=\alpha
\end{cases}$$
and if the posterior distribution of $\alpha$ is absolutely continuous wrt the Lebesgue measure, the posterior probability that $\alpha=t$ is zero for every value of $t$, i.e.,
$$\mathbb E_{\alpha|x} [L(\alpha, t)] = \int_A L(\alpha, t) p(\alpha|x) \,\text d\alpha=1$$
meaning that every value of $t$ has the same posterior loss.
Comment: Thanks, I saw your comment above and was reading my notes again to try and address it. This was not obvious to me,

Minimising Posterior expected loss


Why is kurtosis compared to a normal distribution?

Question: Why is the kurtosis equation compared to a normal distribution? Are there cases where you would want to compare the tails versus some other types of distributions?
$$\gamma = \frac{M_4}{\sigma^4} -3$$
In the above equation would you simply replace the $3$ with the kurtosis of another distribution with which you would like to compare?
Answer: Subtracting $3$ has at least one other justification besides taking the normal distribution as the standard.  The functional $\kappa_4$ given by
$$
\kappa_4(X) = \operatorname{E}((X-\mu)^4) - 3(\operatorname{var}(X))^2, \quad \text{where } \mu = \operatorname{E}(X)
$$
is the fourth cumulant of the distribution of $X$.  It is

translation-invariant, i.e. $\kappa_4(X+c) = \kappa_4(X)$ if $c$ is constant (i.e. not random);
homogeneous of degree $4$, i.e. $\kappa_4(cX) = c^4\kappa_4(X)$;
"cumulative", i.e. $\kappa_4(X_1+\cdots+X_n) = \kappa_4(X_1)+\cdots+\kappa_4(X_n)$ if $X_1,\ldots,X_n$ are independent.

That last property holds only if the coefficient $-3$, rather than some other number, appears where it does.
Comment: Hi @Michael-Hardy can you expand on the bullets that you have listed. I'd like to understand what you have listed here, but not sure I fully understand the application of what you have stated.
Comment: @TylerFurrer : Recall from an introductory statistics course: $$ \begin{align} \operatorname{var}(X) & = \operatorname{var}(X+c) & & \text{if $c$ is constant}; \\ \operatorname{var}(cX) & = c^2\operatorname{var}(X) & & \text{if $c$ is constant}; \\ \operatorname{var}(X_1+\cdots + X_n) & = \operatorname{var}(X_1)+\cdots + \operatorname{var}(X_n) & & \text{if } X_1,\ldots,X_n \text{ are independent}.  \end{align} $$ The $4$th cumulant is like that, except it's $4$th degree rather than $2$nd degree. The $4$th cumulant is $\text{the }\ldots\qquad$
Comment: $\ldots\,4$th central moment minus $3$ times the square of the variance. $\qquad$
Comment: The difference is that $c^2$ appears when dealing with the variance and $c^4$ when dealing with the $4$th cumulant. The first two listed properties of the $4$th cumulant are true of the $4$th central moment and also of the square of the variance, but the third listed property is not true of those. $\qquad$
Answer: I think there are two conventions out there on what to call your $\gamma$: the first is "kurtosis" and the second is "excess kurtosis". The second term is more precise as it makes it clear that the Gaussian distribution is the benchmark. Also, the second convention implies that the "raw" kurtosis (without the -3 term) would not refer to any specific benchmark. So one answer is yes, you could make up your own "excess kurtosis with respect to distribution XYZ" by replacing the 3 with the kurtosis of that distribution. But in order to avoid confusion it's probably better to keep the Gaussian benchmark intact.
Comment: Given the generality of @Michael Hardy's answer, one might instead look at the "benchmark" as being unrelated to the Normal distribution.  The Normal distribution, after all, is not the only one with a kurtosis of $3$.
Comment: I agree that any distribution with kurtosis 3 could be regarded as an equally valid benchmark. But apart from the fact that you can of course construct such special cases, what are those other benchmark candidates, that is distributions that also have some practical appeal? (Honest question, don't know the answer right now.) Thanks.
Comment: The point is more conceptual than practical, but it might be worth noting that many Beta distributions have an excess kurtosis of 0, as well as any Binomial$(n, (1\pm\sqrt{1/3})/2)$ distribution.  It is difficult to find commonly used symmetric distributions with zero excess kurtosis.
Answer: Sure, you could use any distribution for comparison. Higher kurtosis for your distribution vs. the comparator implies your distribution has greater tail weight (or tail leverage; see below) than the comparison distribution. Lower kurtosis for your distribution vs. the comparator implies your distribution has less tail weight (leverage).
Logic is as follows. Consider your random variable $X$, having distribution $p_X(x)$. Assume finite fourth moment and let $V = \{(X-\mu)/\sigma\}^4$. Then the (non-excess) kurtosis of $X$ is $\kappa =  E(V)$.
A standard way of understanding expectation is the "point of balance" of the distribution. Thus the distribution $p_V(v)$ balances at $\kappa$, which is the kurtosis of your distribution $p_X(x)$.
Now, suppose your comparator distribution has kurtosis $\kappa_0$. Locate $\kappa_0$ on the horizontal axis of the graph of  $p_V(v)$ with a fulcrum. If  $p_V(v)$ falls to the right of the fulcrum at $\kappa_0$, then $\kappa > \kappa_0$ and your distribution $p_X(x)$ is heavier-tailed than the comparator.  If $p_V(v)$ falls to the left of the fulcrum at $\kappa_0$, then $\kappa < \kappa_0$ and your distribution $p_X(x)$ is lighter-tailed than the comparator.
Greater "heaviness" of tail refers to greater leverage of the tail rather than greater mass in the tail.  You can have less mass in the tail with greater leverage (higher kurtosis), provided the mass is sufficiently distant from the mean.


Custom function Wordpress not stopping after return

Question: Good day!
As the title says my custom function is not stopping after i do return.
I have created a child theme and create a function inside the functions.php file.
What i try to achieve is show the category title otherwise the string home as title.
What i end up getting now is both the category title and the string of home if i click on a category.
HTML:

<?php echo header_title() ?>

PHP:
function header_title() {

    if(single_cat_title() != NULL) {
        return single_cat_title();
    } else {
        return 'home';
    }
}

Anyone knows what went wrong here?
Any help will be appreciated here :)
Comment: You haven't provided nearly enough info to help debug this.
Comment: What do you mean by 'not stopping'?
Comment: I have edited my question, i hope its more clear now what the problem is. sorry for not clearing up things enough!
Comment: Its that exact function and the header_title isn't called anywhere else. I taught it might has something to do with wordpress since im new to it. but i dont think anything is wrong here with the code?
Answer: single_cat_title will only return a value if you set the second ($display) argument to false.  Since you're not specifying it, it's echoing the value, returning nothing, and you're dropping through to your else condition.
Try providing that parameter (eg if(single_cat_title('', false) != NULL) {) in both your calls.  Or store the result.
Comment: Thanks! and good reference to the codex! makes it a lot more clear! i was echo'ing twice ;-)
Comment: No problem - glad to help


JLayeredPane. Dynamically change layer index of JPanel

Question: I'm using a JLayeredPane to position my JPanels 3-dimensional, so that I may achieve a "zoom" effect when someone clicks on a jpanel, I there for need to dynamically change the layer index so the clicked component is always on "top".
JPanel jp = new JPanel();

JLayeredPane jlp = new JLayeredPane();
jlp.add(jp, new Integer(50));

Here is the first time I place my JPanel, but how can I "reach" it again and change the index?
Comment: Perhaps, you should keep the components in some kind of `Map`, associated with there current layer, or just keep them in a `List` of some kind. You can also use `JLayeredPane#getLayer` to get it's current layout. Assuming you're using a `MouseListener`, the `MouseEvent` returns the `source` of the event, but you can use `getComponent` as a connivance.
Comment: I am saving the JPanel in a list. But is the layer index not a function of the  JLayeredPane object?
Comment: So you need to maintain a reference of the `JLayeredPane` as an instance field
Answer: JLayeredPane has both a "Layer" and a "Position" concepts.
You can place all your components on the same Layer, but with different positions.
0 is the top-most position within the layer and -1 is the bottom-most position.
The JLayeredPane methods moveToFront, moveToBack and setPosition can be used to re-position a component within its layer.
Here's an example for this approach which brings to the front the component which the user clicks:
JLayeredPane pane = new JLayeredPane();
for (int i = 0; i < 4; i++) {
    JLabel lbl = new JLabel("Jlabel-"+(i+1));

    lbl.setOpaque(true);
    lbl.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            if (pane.getPosition(lbl) != 0)
                pane.moveToFront(lbl);
        }
    });
    lbl.setFont(lbl.getFont().deriveFont(48f));
    lbl.setForeground(new Color(i*10, i*50, i*50));
    lbl.setBorder(new LineBorder(Color.BLACK, 2));
    lbl.setBounds(i*100, i*25, lbl.getPreferredSize().width, lbl.getPreferredSize().height);
    pane.add(lbl, 0, new Integer(i+1));
}


How to get the text of a UIPickerView?

Question: I would like to know if i could get the selected String of a PickerView because when using the method func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) i only know the row selected and what i am using is if i know the row i know the position on the array i used to load the PickerViews but i wanted to do this pickerView.text to do something like this
if (pickerView.text == "hello"){
    doSomething(pickerView.text);
}

Because now i have to do much more code lines to do something like this
Sorry i forget to mention, i have 3 PickerView and to know the String is in the third picker view i have to see what row is selected in each one
Answer:
i only know the row selected and what i am using is if i know the row i know the position on the array

And that's the answer. Don't fight the framework; use it. The framework uses Model-View-Controller. The UIPickerView is view; it has no data. You have the data, and given the row, you can fetch it from the model.
Comment: Yes but i forget to mentioned i have 3 picker views and i have to see rows combination but i have know i taked a break and i though better and when selected a new row i can save the String

and thanks for the answer
Comment: It's a matter of designing your architecture sensibly. There would be nothing wrong with consulting all three picker views and all three data models; saving the string each time the user changes the selection is also a possibility, but that is riskier and less "model-view-controller" oriented.
Answer: extension UIPickerView {
    func selectedTitleForComponent(component: Int) -> String? {
        let row = selectedRowInComponent(component)
        return dataSource.pickerView(pickerView, titleForRow:row, forComponent:component)
    }
}

Then:
if pickerView.selectedTitleForComponent(0) == "hello" {
    ...
}

Comment: Thanks for the answer but that `extension UIPickerView` i do that where??

But like i said to other person who answered i can think i can save the String in a `var` when is selecting the row i have to test this but not now is late here :)
Comment: You can put that extension in any Swift file in your project, or make a new file for it. You cannot just "save the String" when the user is "selecting a row" without **getting** the string from somewhere. The picker view only gives you the row number, not the string, so you must look up the string using the row number. My answer shows you how to do that.
Comment: Yes i know but like i said if i know the row i know the position in the array and i can save the String of that array, instead of doing what i am doing now, only looking up for the String when the button is clicked.

How to get the text of a UIPickerView?


Why probability distribution function gives "~.40" probability when it should have been 1.0?

Question: I am following code given here- http://www.bigdataexaminer.com/how-to-implement-these-5-powerful-probability-distributions-in-python/

Under "Normal Distribution" section, the graph peaks at .40 when mean is 0. Shouldn't the value of probability be 1 intuitively? In other words, probability of finding something right at mean should be very high but it is only .40
Comment: The probability density shown here is just that, a probability density, **not** a probability. It's the total area under the curve that is $1$, not the highest value on the curve, which as you report is about $0.4$. To see that this checks out, imagine rearranging the area of the curve into a rectangle with base from $-5$ to $5$. The average density, the height of the rectangle, will be of the order of $0.1$, and $0.1 \times (5 - (-5))$ is $1$. (Note further that if the probability of value equal to the mean is $1$, that leaves zero scope for any other value to be observed.)
Comment: @user777 looks like a near duplicate to me, but I'd really like to let some others make that assessment as well.
Answer:
Probability of finding something right at mean should be very high...

Theoretically speaking, if $\mu$ is the mean of the distribution then the probability density function evaluated at $\mu $ is
$$p(\mu) = \frac{1}{\sqrt{2\pi\sigma^2}}\exp{\big(-\frac{(\mu-\mu)^2}{2\sigma^2}\big)} = \frac{1}{\sqrt{2\pi\sigma^2}}$$
$$\sigma^2 = 1 \implies p(\mu) = \frac{1}{\sqrt{2\pi}} \approx 0.39894228$$
So its value is determined by $\sigma^2$, and can be any positive finite number. (Yes, even larger than 1).
Notice that since this is a continuous distribution,
$$P(X = \mu) = \int^{\mu}_{\mu} p(x)dx = 0$$
So the probability of you getting exactly the mean is actually $0$. But becomes non-zero (and bounded by one) as soon as you consider an interval around $\mu$: $(\mu - \delta, \mu + \delta)$ in which case you find
$$P\big(X \in (\mu - \delta, \mu + \delta)\big) = \Phi(\mu + \delta) - \Phi(\mu - \delta)$$
Where $\Phi$ is the cumulative distribution function, and $\delta > 0$.
Comment: Helpful, but you don't mean "any finite number" as densities can't be negative.


Apache Kerberos Authentication with LDAP Authorization: access to / failed, reason: require directives present and no Authoritative handler

Question: I am trying to get a VirtualHost (well multiple VirutalHosts) up and running with kerberos authentication and group requirements.
My latest configuration within the <Directory> directive looks like this:
AllowOverride None
Order allow,deny
allow from all

AuthType Kerberos
AuthName "Kerberos Realm Login"
KrbAuthRealm LAN
Krb5KeyTab /etc/apache2/auth/apache2.keytab

KrbMethodK5Passwd On

KrbSaveCredentials On
KrbLocalUserMapping On
AuthzLDAPAuthoritative On

Require ldap-group devel

Testing this, after entering correct credentials, I get the following error:
 access to / failed, reason:
          require directives present and no Authoritative handler.

When entering wrong Kerberos credentials, it will deny access altogether. So authentication works, but it seems to not be able to check for the group requirement.
The server also has PAM configured to work with the same Kerberos realm and LDAP database.
I have found that "Require valid-user" gives the same error, but "Require user username" does not.
How can I properly configure this to keep authenticating against Kerberos and authorize it again LDAP?
I am using apache2.2.20 on Ubuntu 11.10 x64.
Answer: The documentation for mod_authnz_ldap suggests that AuthzLDAPAuthoritative is for authentication:

Description:  Prevent other authentication modules from authenticating the user if this one fails

You should try toggling this off to see if that will allow the kerberos authentication to succeed (yet still require the group membership).
Comment: Yes, true I've only added that line in an attempt trial and error attempt to get the things running. Kerberos authentication is succeeding in any case. Authorization is not.


Inserir quadrado em legenda googlemaps

Question: Estou tentando adicionar uma legenda em meu mapa do googlemaps.
Para montar a legenda eu criei um quadrado com a cor que representa um valor.
css:
.square{
    width: 48%;
    height: 0;              /* Quadrado */
    padding-bottom: 48%;
    margin: 1%;
    float: left;
    position: relative;
}
.block{
  position: absolute;
  text-align: center;                  /* Colorido*/
  background: #00FFFF;
  width: 3%;
  height: 3%;
}

css quadro da legenda:
 #legend {
        font-family: Arial, sans-serif;
        background: #fff;
        padding: 10px;
        margin: 10px;
        border: 3px solid #000;
      }

JavaScript para adicionar a legneda ao mapa:
var legend = document.getElementById('legend');
          var div = document.createElement('div');
          div.className ="block";
          div.innerHTML = 'Valor do quadrado';
          legend.appendChild(div);
        gmap.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(legend);

O meu resultado é um quadro de legenda apenas com o texto,sem o quadrado ao lado.
Imagino que a razão é por eu não ter um css para o texto ficar ao lado do quadrado.
Problema:
-Propriedade do css para colocar o texto a partir do quadrado.
-No JS que passei a eu adiciono a div.classname="block",mas falta a div square,caso eu faça dois appendChild eu consigo adicionar as duas divs?
Answer: Acredito que a melhor forma de você injetar o quadrado no seu elemento, seria usar um pseudoelemento no seu css. Ex:
#legend:before{
content:'';
position:relative;
left:0;
display:inline-block;
width:48%;height:0;
}

Dessa forma a responsabilidade fica no css e você não precisar fazer via javascript, você pode até pensar fazer a legenda assim também, caso ele não seja mutável.
Onde o valor da "propriedade content" seria a string da legenda. Ex: #legend:after{content:'Aqui o texto da legenda';}

Inserir quadrado em legenda googlemaps


Create Large File in /dev/shm in parallel: performance

Question: I need to create a large file (several gbytes) in /dev/shm. which is a RAMdisk on Linux machines.  This must be as fast as possible.  I'm currently using 5 separate POSIX threads in C to create sequential 100 mbyte segments, then I have another thread which concatenates them onto the main output file.
This is fast, but I want to go faster.  Can I eliminate the concatenate thread?  Is there any way to open a file, and have each thread write it's 100 mbyte segment to the correct place in the final output file?
Answer: The fastest way to do this is to just call truncate() or ftruncate() to expand the file to the size you want.
You can then mmap() the file into the process's memory space, and have each thread write its section into the mapped area.
Comment: I tried this, and it might work.  But I was able to 'create' files that were larger than the filesystem that contained them.  Somehow, that doesn't seem right.
Comment: So the basic idea is this: First, use truncate to create the huge file, then each thread uses lseek() to move forward to its spot in the file, then that thread writes the data there?  Is that right?
Comment: Okay.  mmap().  Hadn't thought of this.
Comment: `truncate` is not needed. `lseek` alone will do the job just fine.
Comment: Well, `truncate` is needed for the `mmap` approach, but not for `write`.
Answer: Simply open the file once for each thread, lseek to the position the thread is suppose to start at, and write normally. Or, you could use pwrite to specify the location of the write; in that case, a single open could be shared by all the threads since they don't need to use the current file position.
If you want to ensure in advance that there's space available and reserved for the entire final file, posix_fallocate should be able to take care of that for you.


Frameworks para testes em aplicativos Android

Question: Não há dúvidas que uma das principais fases do processo de desenvolvimento de Software seja a fase de testes.
Visando isso, por ser iniciante na área de testes, ainda mais para aplicativos Android, gostaria de saber se vocês utilizam algum Framework? Quais as melhores práticas, os melhores tipos de testes para aplicações móveis?
Answer: Tipos de teste recomendados para aplicativos móveis
Muitos testadores têm dúvidas em relação aos tipos de teste que devem ser executados em aplicações móveis.
A cada dia, o número de dispositivos móveis aumenta e o ambiente mobile é relativamente novo se comparado ao desktop. Os testes em aplicativos móveis se diferenciam dos testes em aplicativos desktop, pois a imensa variedade de dispositivos móveis não permite uma padronização do ambiente. Leve em consideração, por exemplo, que existem inúmeros tamanhos de tela e diferentes sistemas operacionais.
Podemos citar 6 tipos de teste que são geralmente executados em aplicações móveis para garantir a qualidade das mesmas:
1. Compatibilidade
O objetivo aqui é garantir que o aplicativo interaja e se comunique com o sistema operacional, hardware e todos os tipos de rede de maneira satisfatória. Caso a compatibilidade não seja verificada e atestada com cuidado, o aplicativo pode sofrer de lentidão, perda de dados ou travamento.
Um problema muito comum no quesito compatibilidade diz respeito à conexão com os diferentes tipos de rede. Por se tratar de dispositivos móveis, há diferentes tipos de conexões sendo executadas a todo momento.
2. Desempenho
Os testes dessa categoria devem focar na eliminação dos gargalos que provocam lentidão ou travamento do aplicativo. Nesse tipo de teste, deve-se criar situações de estresse, altas cargas e grande número de solicitações para cada função da aplicação. O código deve ser o mais leve possível quando se trata de dispositivos móveis.
3. Mobilidade
Aqui se testa a capacidade de comunicação do seu aplicativo com outros aplicativos. É muito comum haver compartilhamento de informações entre diferentes aplicativos e o seu deve estar bem estruturado para uma comunicação eficaz.
4. Sincronismo
Esse tipo de teste é relativamente novo e se tornou necessário a partir do momento em que começamos a utilizar a tecnologia de armazenamento de dados na nuvem. Precisamos atualizar os dados em um dispositivo e acessá-los futuramente de outro dispositivo e os dados devem estar íntegros e atualizados. Aqui deve-se verificar se não há perdas excessivas de pacotes e reenvios. Ou seja, verificar mesmo se a aplicação consegue fazer a sincronia dos dados na rede.
5. Usabilidade
Parecido com o teste de usabilidade comum aos aplicativos desktop. O foco deve ser a experiência do usuário, a facilidade e possibilidade de realizar as ações pretendidas.
6. Funcional
Tão importante que, muitas vezes, foca-se apenas nesse tipo de teste. Aqui, verifica-se se o aplicativo realmente executa as tarefas que deveria, conforme o que foi planejado. São feitos testes com intuito de se certificar de que todos os requisitos foram implementados e funcionam da maneira que deveriam.
Obviamente, há certos tipos de aplicações móveis que necessitam de testes específicos, de acordo com o tipo das funcionalidades que apresentam. Mas, de maneira geral, esses são os tipos de testes básicos que se deve fazer para garantir uma boa qualidade.
Há que se lembrar que não se distingue esses tipos de teste por marca de dispositivo ou sistema operacional. Eles servem de base para testar aplicativos android,  aplicativos Apple, aplicativos em java, windows mobile, etc.
Automação Android
A automação Android é dividida em duas partes, segundo o próprio site de desenvolvimento Android:
1.Testes Unitários
2.Testes UI (User Interface – Interface Gráfica)
Fundamentos de Teste
Antes de seguir com a explicação de Teste Unitário e Teste UI vamos conhecer pontos em comum entre os dois níveis de teste.
O Android tem um framework, chamado de Android Testing Framework, como parte da arquitetura de desenvolvimento que nos dá a possibilidade de efetuar testes de diferentes formas na plataforma.
Este framework possui alguns pontos chave:

As suítes de teste são baseadas em JUnit (versão 3).

As extensões do JUnit para Android que dispõe de métodos auxiliares
para a criação de mocks e controle do ciclo de vida de um componente.

As suítes de teste estão contidas dentro do mesmo projeto em um
pacote específico de teste.

A SDK disponibiliza uma séria de ferramentas e extensões disponíveis
via Eclipse ADT ou por linha de comando.

A SDK também disponibiliza o monkeyrunner que é uma api para
dispositivos em Python e também uma ferramenta via linha de comando
de stress-test enviando eventos aleatórios na interface gráfica.

O diagrama abaixo, retirado da página Testing Fundamentals, explica um pouco do processo de utilização de teste na plataforma:

A caixa de processo (process) é o coração, contendo a aplicação em si (pacote da aplicação) o InstrumentationTestRunner e o Test package (local onde os scripts de teste estão).
O Test package comunica com o InstrumentationTestRunner, classe de apoio contendo todos as facilidades para a instrumentação e acesos aos componentes. Este comunica com o Application package para acessar qualquer tipo de componente para a interação (e teste).
Test Tools e MokeyRunner executam de forma externa sobre a aplicação diretamente no InstrumentationTestRunner.
Para criar testes usamos o conjuto de três itens: JUnit, a Instrumentation e a classe de teste ( Test case classes) que irá acessar o processo. Também podemos utilizar Mocks para este trabalho.
Instrumentação
É um conjunto de métodos que controla os componentes. Não conseguimos controlar o ciclo de vida (onCreate, onResume, onDestroy. Consulte aqui o ciclo de vida) de qualquer componente via API. É através da instrumentação que outros frameworks conseguem "conversar" com os componentes.
Testes Unitários
Sabemos que o Teste Unitário é importante em qualquer tipo de aplicação, e no Android não seria diferente. Há três divisões para testes unitários.
ActivityTesting
Uma Activity é algo focada no usuário, logo focada na interação do usuário com uma tela. Ela é baseada na classe InstrumentationTestCase que habilita a instrumentação nas classes de teste.

Controlar o ciclo de vida de uma activity;

Criar Mocks;

Enviar ações de usuário, como digitação e toques;
Há três formas de testar uma activity com as classes:

AcitivityInstrumentationTestCase2: habilita o controle de teste
funcional dentro de uma activity, geralmente com o foco em múltiplas
activities.

ActivityUnitTestCase: habilita o controle de uma única activity
isoladamente, onde podemos criar mocks e validar seu comportamento
no ciclo de vida.

SingleLaunchActivityTestCase: hablita o controle de uma única
activity mas não habilita a criação de mocks, uma vez que ela mantém
o estado da activity e suas chamadas.

Content Provider
Content Provider gerencia o acesso a estruturas de dados na plataforma. Geralmente utilizada na obtenção de dados internos, como Calendário, Notas, Contatos, entre outros.
Neste tipo o foco do teste é garantir o isolamento dos dados para que não ocorra nenhum resultado indesejado ou falso-positivo.
Ele utiliza apenas uma classe, a ProviderTestCase2 para habilitar a injeção dos dados através de mocks.
Service Testing
Services são serviços que executam durante um longo período e não dispõe de interface gráfica.
Através da classe ServiceTestCase poderemos controlar o estado do serviço (se este está executando ou não) e garantido a comunicação com outros serviços ou agentes.
Testes UI
É outro nível de teste que estamos mais acostumados, e não menos importante: o testes da interface gráfica (tela).
Nos itens anteriores aprendemos um pouco sobre testes unitários e como são disponibilizados as classes para ajudar o desenvolvedor a testar o seu código. Mas agora chegou a nossa vez: testarmos com perspectiva de usuário.
Este tipo de teste em Android comumente é chamado de Black Box (caixa preta, que é um dos tipos de teste que conhecemos).
Todos os componentes visíveis na tela para o usuário precisam ser acessíveis, ou seja, precisam ter alguns atributos para que seja possível uma ferramenta encontra-los. Na maioria dos elementos os desenvolvedores devem inserir um conteúdo para o atributo contentDescription (que seria como um ID externo) e no caso de caixas de texto ( EditText) preencher o atributo hint.
A plafaforma Android dispõe de uma ferramenta chamada uiautomatorviewer que consegue analisar os componentes em tela e obter os dados acessíveis (contentDescription ou hint).
Você pode acessá-lo digitando na linha de comando o texto:
uiautomatorviwer

ou navegando até a pasta /tools, onde android_sdk é o caminho da pasta sdk do Android.
Os componentes encontrados, posteriormente, servirão de base para escrevermos o código para o script automatizado na interface gráfica do Android.

Considerações
Este artigo teve o intuito de apresentar aspectos de automação na plataforma Android para servir de base a outros artigos relacionados ao desenvolvimento.
É recomendado que você acesse e leia os links contidos neste artigo, que lhe darão uma melhor visão da plataforma e de cada recomendação.
Fonte: Tipos de testes para aplicações Android
Automação de Teste com android
Comment: Só sei que o JUnit é compatível com o **Android Stúdio**, não sei as outras ferramentas que citei, mas existem muitas outras disponíveis para o **Android Stúdio** como por exemplo o **http://robolectric.org/** e também o **http://simpligility.github.io/android-maven-plugin/**.
Comment: Ótima resposta, obrigado pela força amigo! Conhecia já um pouco de testes unitários o uso da JUnit, mas não tinha o conceito dos 6 tipos de testes que são comumentes executados no Android. Vai ajudar bastante :)
Comment: Boa teoria, porém faltou a prática (ferramentas).
Comment: Está na resposta, editei-a. Os tipos de testes não são muito diferentes para aplicações Android.
A ferramenta mais conhecida para testes unitários em aplicações que utilizam a linguagem Java é o JUnit, é claro que tem outras por aí basta procurar, mas a mais conhecida e conceitualmente melhor é a JUnit.

Outra coisa, o próprio SDK disponibiliza ferramentas de teste para a IDE Eclipse, além de que você pode também estar baixando a extensão **Eclema** para fazer a cobertura dos seus códigos.
Comment: Boa, já havia votado antes da edição, agora ficou completo. Pelo que ouvi falar o Eclipse não será mais suportado, sabe se o IDE da Google tem suporte a estes Frameworks de teste?
Comment: Que bom meu amigo, todos esses testes deixam o aplicativo mais consistente. Marque a resposta como correta se ajudou você.


How do I convert string to object type without using eval() in for loop?

Question: class Testclass:
def change(self, obj):
    if(self.ball):
        self.ball=False
        obj.ball=True

main():
A=Testclass()
B=Testclass()
seq=["AB", "BA", "AB"]
for val in seq:
    obj1, obj2=list(val)    #to split "AB" into A, B
    eval(obj1).change(eval(obj2))

.change() method changes object's boolean value to the other object's value. Just for the test.
How can I avoid using eval in this loop? Without eval(), following error appears:
'str' object has no attribute 'change'
I'm using python 3.10
Answer: Store the objects in a dict from their "name" to the instances (it's better to explicitly maintain such a mapping instead of falling to the trap of using locals() or globals()).
A = Testclass()
B = Testclass()

objects = {"A": A, "B": B}
seq = ["AB", "BA", "AB"]

for val in seq:
    obj1, obj2 = list(val)
    objects[obj1].change(objects[obj2])

BTW, it's possible to unpack a string directly without list:
ob1, obj2 = val

Comment: Thanks, I already had dictionary of my objects but didn't think of the [obj1], I tried (obj1] before so but it didn't work so I abandoned it. I will mark your answer as solution.
Answer: One option would be to use tuples instead of strings:
A = Testclass()
B = Testclass()
seq=[(A, B), (B, A), (A, B)]
for val in seq:
    obj1, obj2=list(val)    #to split "AB" into A, B
    obj1.change(obj2)

Or, combining the unpacking directly with the for loop:
A = Testclass()
B = Testclass()
seq=[(A, B), (B, A), (A, B)]
for obj1, obj2 in seq:
    obj1.change(obj2)

Generally speaking, you'd only use strings if you need to write and read the data to and from a file (or a database or some other external system) or for display on the screen; while it's inside the program, keep things as objects (or numbers etc), don't convert back and forth.
Comment: I had to convert string to object because the seq variable will actually store user input later on.
Comment: All good; user input is exactly where you would indeed use strings (and then carefully parse them because user input can be anything...)


Redirecionamento de de DNS para máquina da Amazon

Question: Olá, tenho uma maquina EC2 na amazon, e contratei tbm o servico Route 53, criei uma hosted zone, com isso tive 4 endereços dns, coloquei isso no meu dominio e mesmo assim está aparecendo que a pagina nao está disponível, eu deve instalar um servidor de dns na maquina algo assim?
Obrigado.
Answer: depois de criar o hosted zone, com o nome do seu dominio, crie entradas do tipo CNAME e A, para o PUBLIC DNS e IP da sua VM, exemplo:
<code>NAME                   TYPE   VALUE
seudominio.com.br       A      192.168.0.128
www.seudominio.com.br   CNAME  ec2-xx-xx-xx-xx.us-west-2.compute.amazonaws.com
</code>
O public DNS e o IP você pega no painel do EC2, logo após ter criado a VM
Agora dentro da VM, é preciso claro criar um ambiente web, você pode optar por nginx ou apache, dai ja é outra questão....
Também não esqueça de alterar o DNS de seu domínio, para os endereços de DNS criados pelo route53, e aguardar a propagação, que pode levar até umas 24h.
Comment: acredito que eu soh tenha esquecido de colocar as entradas CNAME e A, o resto ta blza, eu tenho o iis como servidor web e redirecionei os dns no dominio.
Comment: ah então acho q so faltou isso mesmo, testa ae, boa sorte
Comment: quanto a entrada CNAME eu tento criar somente com o nome do dominio aparece este erro:
"RRSet of type CNAME with DNS name piscicontrol.com.br. is not permitted at apex in zone piscicontrol.com.br."
Comment: posé eu errei, editei a resposta, o CNAME é para nomes e não IP's, substitui pelo public DNS da tua vm, la no route53
Comment: Aproveitando a dúvida, William Borba, pode me explicar qual a diferença da entrada do tipo A para entrada do tipo CNAME. Quando uso cada uma delas?
Comment: CNAME(canonical name) são utilizadas para subdominios, no caso "www" é um subdominio de "seudominio.com.br" e entradas do tipo A são para IP de dominios puros, é o q eu sei, assim, mais ou menos rs


Kendo UI for Angular Datepicker Localization doesn't work when module is loaded via ngIf

Question: This question pertains to an Angular 6 app that uses Kendo UI for Angular.
I have been working recently to get the dynamic globalization/localization of Kendo's DatePicker and TimePicker components to work. In the top right corner of the site, in the header, there is a language dropdown that the user can change the language/locale of the site dynamically. I wanted to implement a way to dynamically update Kendo's datepicker and timepicker components to automatically translate the text and update the DateTime formats of the Kendo component according to the locale that the user selects from the dropdown.
So I took Kendo's DatePicker and TimePicker components and wrapped them in their own module called "DatepickerWrapperModule". And everything works fine as long as this module is eagerly loaded (i.e. the module and corresponding component is not dynamically injected into the page).
However, if the module and corresponding component is loaded dynamically into the page via the *ngIf directive, then it breaks the dynamic localization that I have set up.
I assume this is due to the module being lazy loaded and thus creating new instances of the services that it depends on??? But after researching and trying many different things to get it to work, I have been unsuccessful so far. Is there any way to get this type of Kendo UI DatePicker dynamic localization to work with modules/components that are dynamically loaded via *ngIf ???
Normally, I would supply all the relevant code examples, but they are way too large and complex to display concisely in this question. In general, there is:

the AppModule
a SharedModule
and the DatepickerWrapperModule

The AppModule imports the SharedModule in the imports[] array, using the forRoot() method.
The SharedModule then imports the DatepickerWrapperModule in the imports[] array, and also exports it in the exports[] array. In the imports[] array, the DatepickerWrapperModule uses the forRoot() method.
The DatepickerWrapperModule then implements the DatePickerWrapper component, which contains the actual references to the Kendo DatePicker component.
Also, in the DatepickerWrapperModule's constructor, I am using @Optional() and @SkipSelf() constructor parameter decorators to see if the DatepickerWrapperModule is being loaded twice, and through some simple console.log statements, I confirmed that it is indeed getting initialized and loaded twice (once during the initial loading of the entire app/site, and once when the *ngIf condition is met on the particular page and for the particular component under consideration.
I would like to figure out how to get the module/component that loads via the *ngIf condition to use the instance of DatepickerWrapperModule that is already loaded as part of the entire app, instead of creating a new instance of it when the component is dynamically added to the DOM when the *ngIf condition is met.
Thanks in advance!
Comment: Have you tried the approach described [here](https://github.com/telerik/kendo-angular/issues/1455#issuecomment-405247258)
Comment: @SiliconSoul Yes, after much trial and error, I finally found the problem and the specific place when I needed to provide the IntlService and CldrIntlService.

But yes, the approach described in the link you provided lead me in the right direction and eventually solved my issue. Thanks!
Answer: Now that I finally solved my issue, I wanted to provide the answer to my own question that solved it for me, in case anyone else encounters this same issue in the future.
For reference, please see the recommended approach that eventually solved my issue here:
https://github.com/telerik/kendo-angular/issues/1455#issuecomment-405247258
Basically, the problem for me was related to how Lazy-Loaded Modules work when loaded via routes, such as:
{
    path: 'logistics',
    canActivate: [AuthGuardService],
    appData: 'APPDATA_LOGISTICS',
    loadChildren: './logistics/+logistics/logistics.module#LogisticsModule'
}

In the providers[] array of my AppModule, I have specified the LOCALE_ID, CldrIntlService, and IntlService as follows:
providers: [
    CldrIntlService,
    {
        provide: IntlService,
        useExisting: CldrIntlService
    },
    {
        provide: LOCALE_ID,
        useValue: 'en-US'
    }
]

This will provide these services to eagerly-loaded modules that are imported in AppModule or some child of AppModule, but for lazily-loaded modules that are not imported by or direct children of AppModule, it will create new instances of these services.
So, per the link above, once I specified the appropriate providers in the lazily-loaded LogisticsModule, the dynamic localization of the Kendo DatePicker and TimePicker components began working again as expected.
Here is the relevant part of the providers[] array in the LogisticsModule that resolved my issue:
providers: [

    .
    .
    .

    {
        provide: IntlService,
        useExisting: CldrIntlService
    }

    .
    .
    .

]

This tells the LogisticsModule to use the instance of the services already created (provided) in the AppModule (instead of creating new instances of the services when the module is lazy loaded).


Utilização de rotas no frontend ou backend

Question: Em relação ao roteamento, é mais adequado o roteamento ficar no front e o mesmo fazer requisições para o servidor através de AJAX, ou o roteamento ficar no back e o mesmo renderizar as views do front?
Comment: O que seria esse roteamento?
Answer: Falsa dicotomia, até porque roteamento em um ou outro existem para rotear o que está naquela camada, o fato de ter usado em uma camada não torna desnecessário usar em outra, claro, desde que vocês esteja usando arquiteturas que exigem roteamento. Ou seja, usar ou não, nada tem a ver com o que está preocupado na pergunta e sim se faz sentido na arquitetura usada naquela camada.
Você pode usar um roteamento em uma delas e não usar em outra simplesmente porque a arquitetura daquela camada foi pensada de uma forma que não precisa de roteamento.
Em geral roteamento é necessário para arquiteturas complexas, e houve um tempo que as pessoas só adotavam soluções complexas para problemas complexos (algumas pessoas ainda o fazem, ainda bem), mas hoje é comum as pessoas adotarem arquiteturas complexas porque está na moda, a pessoa adota sem nem entender porque está fazendo aquilo e que benefício terá com a adoção daquilo.
Eu vejo o pessoal evitando adotar roteamento com o React no frontend (ou era assim).


Fading edges of line/rect

Question: I have an svg <g> in which I have a line (can be rect too.. have tried both). This inner element has a fill/stroke that can rotate from 8 different colors or patterns. The shape is 5px height, with a dynamic width, and I should support fading left, right or both edges.
I would like to achieve this without creating extra elements on the svg and some how apply a mask/gradient but it seems I cannot get it to work.
Since the shape's X and Y, color, and width can change, I have not found a consistent way to make this happen without creating new elements with a bunch of color combinations. Does anyone have an idea on how to achieve this in the most simple and scalable way?
UPDATE
After Paul suggestion i created a fiddle to represent some how the scenario i have:
https://jsfiddle.net/0tnc9mq5/
So multiplelines/rects in same svg with different colors, positions and dimensions. What would be the way to apply some of those fades to some of those elements? How would i implement Paul's suggestion? Is there any other approach?
Thanks
Comment: Perhaps add a `` and then alter the `stop-color` and `offset` attributes of the individual `` elements with JavaScript?
Comment: Thanks Max but then the same linearGradient is used for different elements and i would have to create one gradient for each element to avoid changing another's fades
Comment: Perhaps loop through each of the rects/lines in JavaScript, and dynamically generate a mask/gradient for each one, which you could then append to the ``?
Answer: Here is one way to do it, using masks to produce the fading ends.  The fades are fixed in this example to be 10% of the length of the line.
We create a shared SVG that contains <symbol> elements for each of the three variants you need.  That only needs to appear once in your HTML.
Then anywhere you want one of the separators, include the mini SVG corresponding to the separator you desire.  You can set the width, height and colour of the separator using CSS.

svg.sep {
  width: 500px;
  height: 5px;
}

.one {
  color: red;
}

.two {
  color: green;
}

.three {
  color: blue;
}
<svg width="0" height="0" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <linearGradient id="gleft">
      <stop offset="0%" stop-color="black"/>
      <stop offset="10%" stop-color="white"/>
    </linearGradient>
    <linearGradient id="gright">
      <stop offset="90%" stop-color="white"/>
      <stop offset="100%" stop-color="black"/>
    </linearGradient>
    <linearGradient id="gboth">
      <stop offset="0%" stop-color="black"/>
      <stop offset="10%" stop-color="white"/>
      <stop offset="90%" stop-color="white"/>
      <stop offset="100%" stop-color="black"/>
    </linearGradient>

    <mask id="mleft">
      <rect width="1" height="1" fill="url(#gleft)"/>
    </mask>
    <mask id="mboth">
      <rect width="1" height="1" fill="url(#gboth)"/>
    </mask>
    <mask id="mright">
      <rect width="1" height="1" fill="url(#gright)"/>
    </mask>

    <symbol id="left" viewBox="0 0 1 1" preserveAspectRatio="none">
      <rect width="1" height="1" fill="currentColor" mask="url(#mleft)"/>
    </symbol>
    <symbol id="both" viewBox="0 0 1 1" preserveAspectRatio="none">
      <rect width="1" height="1" fill="currentColor" mask="url(#mboth)"/>
    </symbol>
    <symbol id="right" viewBox="0 0 1 1" preserveAspectRatio="none">
      <rect width="1" height="1" fill="currentColor" mask="url(#mright)"/>
    </symbol>
  </defs>
</svg>

 Lorem ipsum dolor sit

<svg viewBox="0 0 1 1" preserveAspectRatio="none" class="sep one">
  <use xlink:href="#left"/>
</svg>

 Lorem ipsum dolor sit

<svg viewBox="0 0 1 1" preserveAspectRatio="none" class="sep two">
  <use xlink:href="#right"/>
</svg>

 Lorem ipsum dolor sit

<svg viewBox="0 0 1 1" preserveAspectRatio="none" class="sep three">
  <use xlink:href="#both"/>
</svg>
Comment: Thanks Paul, i've update my question with a fiddle as an example of muy current scenario. Do you think of anyway to implement your solution on that case? Thanks
Comment: So your lines are all in one SVG?  I assumed you wanted something like custom ``s for your HTML.
Comment: The masks I have defined in my example (with a slight tweak) will work just fine with your set of `` elements.  You just need to copy the definitions into your SVG and apply them to the rects.  https://jsfiddle.net/0tnc9mq5/1/

Fading edges of line/rect


Gradient of ${\bf z} \mapsto- \frac12 \operatorname{tr} \left( {\bf A} \left( {\bf Y} - {\bf x} {\bf z}^\top \right) {\bf B} ( \cdot )^\top \right)$

Question: Given $3 \times 3$ symmetric matrix $\bf A$ and $5 \times 5 $ symmetric matrix $\bf B$, let the scalar field $f : \Bbb R^5 \to \Bbb R$ be defined by
$$ f ({\bf z}) :=  - \frac12 \operatorname{tr} \left( {\bf A} \left( {\bf Y} - {\bf x} {\bf z}^\top \right) {\bf B} \left( {\bf Y} - {\bf x} {\bf z}^\top \right)^\top \right) $$
where $\operatorname{tr}$ is trace operator, ${\bf x} = {\bf 1}_3$ and $\bf Y$ is a $3 \times 5$ matrix.
I can find $\nabla_{\bf z} f$ by expanding operations inside the trace and following the derivative of trace rules outlined in The Matrix Cookbook. However, those rules are based on the matrices. Since in my case I am taking a derivative with respect to a vector $\bf z$, would it be reasonable to use those rules? If not,  how can I find $\nabla_{\bf z} f$ in this setting?
Comment: Maybe you can state what you found and we can tell you if it is correct ?
Comment: Welcome to [math.se] SE. Take a [tour]. You'll find that simple "Here's the statement of my question, solve it for me" posts will be poorly received. What is better is for you to add context (with an [edit]): What you understand about the problem, what you've tried so far, *etc.*; something both to show you are part of the learning experience and to help us guide you to the appropriate help. You can consult [this link](https://math.meta.stackexchange.com/q/9959) for further guidance.
Comment: @AnotherUser thanks. I edited the question.
Comment: I think it is reasonable to think $z$ as an $n \times 1$ matrix.
Comment: @obareey But then you can't get rid of the trace
Comment: @Steph What I found is $ x^{T} A(Y- x z^{T})B$. However, I assumed x and z are matrices to get this result.
Comment: @RodrigodeAzevedo Could you please elaborate on what you suggested and show me how to proceed with this?
Comment: It is correct. I think it is better (in my opinion) to express the gradient with the same dimension as the vector you are differentiating so I would suggest the transpose of your result.
Answer: Using the cyclic property of the trace,
$$ f ({\bf z}) :=  - \frac12 \operatorname{tr} \left( {\bf A} \left( {\bf Y} - {\bf x} {\bf z}^\top \right) {\bf B} \left( {\bf Y} - {\bf x} {\bf z}^\top \right)^\top \right) = \cdots =  - \frac12 \left( \left( {\bf x}^\top {\bf A} \, {\bf x} \right) \left( {\bf z}^\top {\bf B} \, {\bf z} \right) - 2 \left\langle {\bf B} \, {\bf Y}^\top {\bf A} \, {\bf x} , {\bf z} \right\rangle + \operatorname{tr} \left( {\bf A} {\bf Y} {\bf B} {\bf Y}^\top \right) \right) $$
Can you take it from here?
Comment: Thanks this is much better. I get the following:
$$ \nabla_{z}f = -\frac{1 }{2 } \left( 2(\mathbf{x}^{T} A \mathbf{x} ) B \mathbf{z}    - 2^{T} \right )$$

If my above derivation is correct, then what I found previously by assuming $\mathbf{x}$ and $\mathbf{z}$ as matrices is not correct?
Comment: @parx That gradient is correct


Debug maven mojo with eclipse mars

Question: I need to make a tool work inside maven (3.X) I am using mars/git for development of the mojo. This is what I have gathered so far:
*) debugging needs to be remote.
*) I would need to install the mojo in maven (with sources attached)  and have a dummy maven project that triggers the session.
Is this correct? Am I missing steps?
Thanks a lot in advance!!
Comment: Selecting the "run-its" profile from the ide project's context menu allows me to at least launch the debug session. Let's see how far this takes me
Comment: But it does not attach any source to the debug session. The breakpoint is hit but no source path lookups work
Comment: checked the dynamic source lookup. It works
Answer: See the comments above. And below
Selecting the "run-its" profile from the ide project's context menu allows me to at least launch the debug session. Let's see how far this takes me – efekctive Feb 20 at 23:25
But it does not attach any source to the debug session. The breakpoint is hit but no source path lookups work – efekctive Feb 20 at 23:33
checked the dynamic source lookup. It works.
Comment: If you answered your own question and you want to post an answer, make it a full, complete answer that's likely to help someone else.

Debug maven mojo with eclipse mars


Interpreting  negative binomial regression output in R

Question: I've got a question concerning a negbin regression: suppose that you have the following commands
<code>require(MASS)
attach(cars)
mod.NB<-glm.nb(dist~speed)
summary(mod.NB)
detach(cars)
</code>
(note that cars is a dataset which is available in R) and don't care if this model makes sense. What I'd like to know is, how can I interpret the variable theta (at the bottom of the summary). Is this the shape parameter of the negbin distribution and is it possible to interpret it as a measure of skewness? I appreciate every thought!
Comment: this is a better fit for cross validated.
Answer: If Y is NB with  mean  $\mu$  then $var(Y) = \mu  + \mu^2/\theta$. Skewness would not be an appropriate interpretation, but the departure from $\theta= 1$  is often taken as "extra-Poisson" dispersion.