text! within requireJS

Question: Lately I see often 'text!' within requireJS modules - an example below:
define(['text!./awesome.hbs'], function(template) {
  return {
    initialize: function() {
      this.html(template);
    }
  };
});

what does it stand for?
Answer: text! is the prefix of a plugin of Require JS, called text. See its webpage here.
Basically, it loads the resource specified as text:
define(['text!./awesome.hbs'], function(template) {
  //template will be a text with the content of the 'awesome.hbs' file
});

Answer: This is an example of the 'text' plugin for requireJS:
https://github.com/requirejs/text
It's often used by developers to load template resources into their code but can also be used for general text file resources. The "text!" part tells requireJS to use the text plugin, the file name that follows is loaded in.
Comment: The reason for down voting? I posted this almost simultaneously with Hussein's answer. Strategic down vote?
Answer: this is used to require text (obviously ) so you can treat none js files as dependencies  , for example template files , which is also the most common use case  .

It is nice to build HTML using regular HTML tags, instead of building
  up DOM structures in script. However, there is no good way to embed
  HTML in a JavaScript file. The best that can be done is using a string
  of HTML, but that can be hard to manage, particularly for multi-line
  HTML. RequireJS has a plugin, text.js, that can help with this issue.
  It will automatically be loaded if the text! prefix is used for a
  dependency. See the text.js README for more information.

here is the link for the project
https://github.com/requirejs/text

text! within requireJS


Affine transformation matrix coefficients

Question: In an affine transformation $x \mapsto Ax+b$, $b$ represents the translation; but what does the matrix $A$ represent exactly? In a 2D example, $A$ is a $2\times 2$ matrix, but what does each term represent?
Suppose that given an affine transformation $\operatorname{Aff}_1$ I want to introduce another affine transformation $\operatorname{Aff}_2$ that is "half" the transformation $\operatorname{Aff}_1$. For the translation $b$, I just need to divide each coefficient by $2$, but what about the matrix $A$?
Answer: For $A \in GL(2, \mathbb{R})$, the map $x \mapsto Ax$ is an invertible linear transformation from $\mathbb{R}^2$ to itself. There are four types of such transformations:

rotations,
reflections,
expansions/compressions, and
shears.

So an affine transformation is a map which does one of the above four things, followed by a translation.
As for your second question, it depends what you mean by an affine transformation 'doing half' of another transformation. First of all, there is some sense in which you can 'do half' of some linear transformations (e.g. rotations - you can rotate by half the angle), but not others (e.g. reflections).
Furthermore, the translation by $b$ complicates matters. Let $f(x) = Ax + b$ be a given affine transformation and suppose $g(x) = Cx + d$ is the affine transformation which 'does half' of $f(x)$. What does this mean? Well, I'm going to take it to mean that if you do the affine transformation $g(x)$ twice, then you get $f(x)$. So we are trying to find $C \in GL(2, \mathbb{R})$ and $d \in \mathbb{R}^2$ such that $$Ax + b = f(x) = g(g(x)) = g(Cx + d) = C(Cx + d) + d = C^2x + (Cd + d).$$ That is, we want to find $C$ and $d$ such that $A = C^2$ and $b = Cd + d = (C+I)d$. Depending on what $A$ and $b$ are, there may be no such $C$ and $d$ (as is the case when $A$ defines a reflection).


Duplicar planilha

Question: Ola,tenho uma planilha que contem alguns dados importantes, gostaria de saber se existe alguma de duplicar esse planilha automaticamente, de forma que eu manipule os dados em uma planilha e quando clique em salvar ela ja salve um backup dela, sem que eu precise fazer as mudancas manualmente...
Answer: Na árvore de projeto de dois cliques em EstaPastaDeTrabalho. Em seguida, na parte superior na comboBox da esquerda selecione Workbook, é de se esperar que automaticamente apareça isso:
Private Sub Workbook_Open()

End Sub

Caso não apareça isso basta selecione no comboBox da direita a função Open. E acrescente a função como descrito a seguir.
Private Sub Workbook_Open()
    planilha_backup
End Sub

Crie um novo módulo e insira está função
Option Explicit
Option Private Module

Function planilha_backup()
    Dim str_nome_da_pasta_de_trabalho As String
    Dim str_caminho_da_pasta_de_trabalho As String
    Dim str_data_hora As String
    Dim diretorio As String
    str_data_hora = Replace(Date, "/", "-") & "_" & Hour(Now) & Minute(Now) & Second(Now) & "_"
    str_nome_da_pasta_de_trabalho = ActiveWorkbook.Name
    str_caminho_da_pasta_de_trabalho = ActiveWorkbook.Path
    diretorio = str_caminho_da_pasta_de_trabalho & "\" & "bkp_" & str_data_hora & str_nome_da_pasta_de_trabalho

    ActiveWorkbook.SaveAs Filename:= _
        diretorio, FileFormat:= _
        xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False

    str_nome_da_pasta_de_trabalho = ""
    str_caminho_da_pasta_de_trabalho = ""
    str_data_hora = ""
    diretorio = ""
End Function

Duplicar planilha


Load sidebar onOpen google Sheets

Question: I am trying to load the sidebar when the page opens.  I have important information that i was readily available for them to see.  How can i load the sidebar when page is opened?  I also could do onEdit if need be.
function onOpen(){

  var ui = SpreadsheetApp.getUi()
  .createAddonMenu()
  .addItem('Show sidebar', 'showSidebar')
  .addItem('Show dialog', 'showDialog')
  .addSeparator()
  .addToUi();

// Display sidebar if auto-sidebar is enabled
showSidebar();

SpreadsheetApp.getUi().createMenu('Information')
.addItem('Help', 'showPicker')
.addToUi();

SpreadsheetApp.getUi().createMenu('Changelog')
.addItem('Changelog', 'changeLog')
.addItem('Show sidebar', 'showSidebar')
.addToUi();

////Get user name and

var name = SpreadsheetApp.getActive().getSheetByName('Discovery Sheet');
var email = Session.getActiveUser().getEmail();
Logger.log(email);
name.getRange('a38').setValue(email);

 }

Or like this one?
function OnEdit() {

 var html = HtmlService.createHtmlOutputFromFile('Changelog')
  .setTitle('Changelog')
  .setWidth(300);
   SpreadsheetApp.getUi()
  .showSidebar(html);

}

Comment: Your code would have execute a couple of years ago but Google has decided to restrict the use of the automated sidebar display for security reasons... I find it also very annoying but they have the power ! ;) So from now on every user needs to have its own installed trigger ( that can be programmatically added). By the way, it will continuously generate error messages telling you that you don't have permission to call showSidebar... I believe Google had good reasons to do so ;)
Comment: Have you tried either? Note that there [are limits](https://developers.google.com/apps-script/guides/triggers/#restrictions) on what the functions that are bound to simple triggers can do. Also note, that `#javascript` is not the right tag when dealing with UI / code specific / exclusive to Google Apps Script.
Comment: I have tried these but they fail to run.
Comment: https://developers.google.com/apps-script/reference/base/session#getActiveUser()
Comment: I guess I don't understand why you posted that link.  All that does is get the user information.
Comment: Did you read the bits about simple triggers and accessing information about the current user from functions that run without authorization?
Comment: I did read that.  Its unclear to me though that a sidebar wouldn't load if it doesn't contain executables.
Answer: Try this:
function anOnOpen(){
  SpreadsheetApp.getUi().createMenu('My Tools')
  .addItem('Sidebar', 'loadSidebar')
  .addToUi();
  loadSidebar();
}

function loadSidebar(){
  var ui=HtmlService.createHtmlOutputFromFile('simplesidebar');
  SpreadsheetApp.getUi().showSidebar(ui);
}

You can add anything you want in the html with getElementById and innerHTML.  I often use the JQuery ready function to call and apps script which returns the desired html contents.  Or you can use an HTML Template. Personally, I never use templates.
Comment: See this bug report, the installable trigger will work for you but no one else... waiting for a fix as this used to work a few months ago.https://issuetracker.google.com/issues/69238694#comment7
Comment: Note for this `anOnOpen` to run, an installed trigger is required.
Comment: Its considered bad practice to open the sidebar or any dialogs on page open and is strongly discouraged in the documentation. I'd avoid doing this in future if possible.
Comment: Where is it discouraged?
Comment: True.  I don't feel compelled to do everything for the questioner.
Comment: [18-03-15 16:40:09:139 EDT] Execution failed: You do not have permission to call showSidebar (line 86, file "Code") [0.918 seconds total runtime]
Comment: This is really frustrating as its such a simple call that it shouldn't need permissions.

Load sidebar onOpen google Sheets


How to get labels from hclust result

Question: let's say i have a dataset like this
dt<-data.frame(id=1:4,X=sample(4),Y=sample(4))

and then i try to make a  hierarchical clustering using the below code
dis<-dist(dt[,-1])
clusters <- hclust(dis)
plot(clusters)

and it works well

The point is when i ask for
clusters$labels

it gives me NULL, meanwhile i expect to see the label of indivisuals in order like
1, 4, 2, 3

it is important to have them with the order that they are added in plot
Answer: You could use the following code:
# your data, I changed the id to characters to make it more clear
set.seed(1234) # for reproducibility
dt<-data.frame(id=c("A", "B", "C", "D"),X=sample(4),Y=sample(4))
dt

# your code, no labels
dis<-dist(dt[,-1])
clusters <- hclust(dis)
clusters$labels

# add labels, plot and check labels
clusters$labels <- dt$id
plot(clusters)

## labels in the order plotted
clusters$labels[clusters$order]
## [1] A D B C
## Levels: A B C D

Please let me know whether this is what you want.
Answer: Use cluster$order rather than labels if you happened to not have assigned the labels.
Infact you can see all the contents by using function called summary
clusters <- hclust(dis)
plot(clusters)
summary(clusters)
clusters$order

You can compare with the plot i received at my end, it is offcourse little different than yours
My outcome:
> clusters$order
[1] 4 1 2 3

Content of summary command:
> summary(clusters)
            Length Class  Mode
merge       6      -none- numeric
height      3      -none- numeric
order       4      -none- numeric
labels      0      -none- NULL
method      1      -none- character
call        2      -none- call
dist.method 1      -none- character

You can observe that since there is null value against labels, hence you are not getting the labels. To receive the labels you need to assign them first using clusters$labels <- c("A","B","C","D") or you can assign with the rownames, once your labels are assigned you will no longer see the numbers you will able to see the names/labels.
In my case I have not assigned any name hence receiving the numbers instead.
You can put the labels in the plot function itself as well.
From the documentation ?hclust

labels
  A character vector of labels for the leaves of the tree. By
  default the row names or row numbers of the original data are used. If
  labels = FALSE no labels at all are plotted.
Answer: Please make sure you use rownames(...) to ensure your data has labels
> rownames(dt) <- dt$id
> dt
id X Y
1  1 2 1
2  2 4 3
3  3 1 2
4  4 3 4
> dis<-dist(dt[,-1])
> clusters <- hclust(dis)
> str(clusters)
List of 7
$ merge      : int [1:3, 1:2] -1 -2 1 -3 -4 2
$ height     : num [1:3] 1.41 1.41 3.16
$ order      : int [1:4] 1 3 2 4
$ labels     : chr [1:4] "1" "2" "3" "4"
$ method     : chr "complete"
$ call       : language hclust(d = dis)
$ dist.method: chr "euclidean"
- attr(*, "class")= chr "hclust"
>

How to get labels from hclust result


How to deal with the messages block in Magento hole punching

Question: I am getting interested in how hole punching might work in magento inside a full page cache situation.  This is not directly related to the enterprise edition and how its full page cache and hole punching mechanism might work, just in general.
Due to the way that the messages block is generated by magento i am really very curious as to how to deal with the messages block in a hole punching situation?
Have any magento devs out there tackled this before and can maybe explain to me how this particular block can be hole punched?
Comment: See http://stackoverflow.com/questions/9120413/how-do-i-include-a-dynamic-block-in-the-product-page-with-full-page-caching-turn .  Also, your question may be too generalized, so don't be surprised if it gets closed.
Comment: i thought the question was actually very specific: how to deal with the core/messages block in a full page cache situation
Comment: "This is not directly related to the enterprise edition and how its full page cache and hole punching mechanism might work, just in general.' I've no problem with your question, but these days the diamond crew seem to be closing questions at will.
Answer: You will need to link a cache container to the core/messages block to be able to prevent the block from caching. To reach your goal you will need a basic module, or add this to one of your existing module, whichever is the best (read: more logical) place for you.
Within your_module/etc/ you will need to create cache.xml file:
<config>
    <placeholders>
        <your_module_messages>
            <block>core/messages</block>
            <placeholder>SYSTEM_MESSAGES</placeholder>
            <container>Your_Module_Model_PageCache_NoCache</container>
        </your_module_messages>
     </placeholders>
 </config>

The Your_Module_Model_PageCache_NoCache needs to be an extend of Enterprise_PageCache_Model_Container_Abstract and in that extend you need to overwrite the saveCache() method and directly return $this instead triggering the underlying $this->_saveCache(). Perhaps with more logic you can make this punch hole a bit smarter, but for now assume that you never know when there is a new messages, thus leaving the hole open at all times.
public function saveCache($blockContent)
{
    return $this;
}

The only thing left is to trigger Magento to load the core/messages block from within the whole. This you can accomplish by adding the following method to your class.
protected function _renderBlock()
{
    $block = $this->_placeholder->getAttribute('block');
    //$template = $this->_placeholder->getAttribute('template');

    $block = new $block;
    //$block->setTemplate($template);
    $block->setLayout(Mage::app()->getLayout());

    return $block->toHtml();
}

It will fetch the block information from the cache.xml file and return the output of the block. Since core/messages actually generated it's own HTML you don't need to provide a template. So might as well remove those commented lines from the code.
Hopefully this helps you with your task at hand!


Linked list compile time error

Question: In the code below I am having problems within the add_node function at compile time.
I am getting an error relating to the following line of code: struct *node pNode = (struct node*)malloc(sizeof(struct node))
Any suggestions would be greatly appreciated.
struct list
{
   struct node *head;
   int count;
};

struct node *add_node(struct list *pList, float coef, int expo)
{
    if (pList == NULL)
    {
        return NULL;
    }

    struct *node pNode = (struct node*)malloc(sizeof(struct node));

    if (node == NULL)
    {
         return NULL;
    }

    pNode->coef = coef;
    pNode->expo = expo;
    pNode->link = pList->head;

    pList->head = pNode;
    pList->count++;

    return pNode;
}

Comment: never cast malloc returns
Comment: *Always* state what error you get. "An error" may as well be "disk full -- press any key to continue".
Answer: Make this
struct *node pNode = (struct node*)malloc(sizeof(struct node));

to
struct node *pNode = (struct node*)malloc(sizeof(struct node));

Comment: Thanks this works but another problem has arisen in that in the following line; if ( node == NULL), the error states that node is undeclared
Comment: @user4225083 You need to do sanity check on `pNode` instead `node`.
Answer: you might wanna change the line to struct node * pNode = (struct node*)malloc(sizeof(struct node));
Answer: Change
if (node == NULL)

to
if (pNode == NULL)

Comment: I did this and it works, however a new error claims I have an undefined reference to main; collect2: ld returned 1 exit status
Comment: @user4225083: so the above is your *entire* program? C needs a `main` function. Guess it's time to go back to your study book.
Comment: you forgot about main function
Comment: Ok back to the books I go, thanks for the help guys.

Linked list compile time error


What does Include & Extend correspond to in Programming?

Question: Just as Generalization in UML corresponds to Inheritance, what do Include & Extend relationships correspond to in OOP?
I do realize that Generalization represents a 'is-a' relationship. Would Include represent 'has-a' relationship?
Answer: AFAIK, include used in Use Case diagrams. It shows dependency between specific use case and common use case.
Example:
Ask question on StackOverflow ----include----> Login to StackOverflow
Answer: There are no include or extend relationships in UML Class Diagrams. If you refer to Use Case Diagrams they have no direct representation on code level, as you do not implement a Use Case as a single artifact in your software.
Comment: Why no direct representation? A use case can be represented as a web service for example.
Answer: Includes means direct dependency, which means that an including use case requires an including use case. Extension means extra functionality that you can add to a use case at a specified point.
An example of include relation is when you include a class in java. You must have the class for your code to execute, but this doesn't mean that you always call the other class.
An example of extends are eclipse extension points, which let you define new functionality for the eclipse platform at specified points, but the platform is unaware of the extensions.


Can a 4-hole harmonica play this song?

Question: I have a 4-hole harmonica. It is too simple; so, I can play
simple songs only.
Now, I want to know: "Is there any way to play this song with my own harmonica?".
Comment: I'm voting to close this question as off-topic because it is too specific to be useful to other users.  I see you've asked about the range in another question, though, which is excellent.
Answer: There are a couple of problems. The harp is most likely diatonic, and has a major scale playable, with an octave - 8 notes- range. The song has a range of 10 notes, so the highest two COULD be played an octave lower, but it will sound strange. Another problem is that since it's diatonic, but the song is in a minor key, the bottom two notes in the song will be missing from the harp. This could give you all the other (higher) notes, but the lower two would have to be played an octave higher. Again, strange. Another problem is that , because it's in a minor key, the leading note is sharpened. You won't find this note on that harp. It won't matter what key it's transposed into, that note won't play.
Comment: @JacobSwanson - it's more usual to bend notes down, so, maybe the tonic could make it happen. But it's easier to bend when drawing, so on note 6 it could work! That just leaves the bottom two notes missing.
Comment: I think you can bend the note up though.
Comment: @0mf Try just looking up "bending a note on a harmonica"

Can a 4-hole harmonica play this song?


Issue with dell omsa packages on Centos 7

Question: I have a Dell 2950 with Centos 7 and Dell OMSA packages installed. When I try to update the server with "yum update" I have the following dependences issue:
Error: Package: dell_ie_rac_5-8.1.0-4.1.128.el7.x86_64 (@dell-omsa-indep)
       Requires: srvadmin-racadm5 = 8.1.0
       Removing: srvadmin-racadm5-8.1.0-4.1.128.el7.x86_64 (@dell-omsa-indep                                                                             )
           srvadmin-racadm5 = 8.1.0-4.1.128.el7
       Updated By: srvadmin-racadm5-8.3.0-1908.9058.el7.x86_64 (dell-omsa-in                                                                             dep)
           srvadmin-racadm5 = 8.3.0-1908.9058.el7
Error: Package: python-smbios-2.2.27-4.4.1.el7.x86_64 (@dell-omsa-indep)
           Requires: libsmbios = 2.2.27-4.4.1.el7
           Removing: libsmbios-2.2.27-4.4.1.el7.x86_64 (@dell-omsa-indep)
               libsmbios = 2.2.27-4.4.1.el7
           Updated By: libsmbios-2.2.27-1908.9058.el7.x86_64 (dell-omsa-indep)
               libsmbios = 2.2.27-1908.9058.el7
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest

What is the safer solution in this case? Ignore/Skip the dependences is not an option for me
Comment: Contact the repository maintainer. They appear to have broken something.
Comment: I'll try to write to the Dell support since the repository is maintained by them but I'm pretty sure that they will reply that everything is ok
Comment: Ha. This would not be the first time they'd broken their repo.
Comment: Nice to hear :D I wrote to them. I hope they will be fix quickly :)
Answer: It seems that Dell doesn't want to fix their repo issue so the only solution that I have found is that post (http://en.community.dell.com/support-forums/servers/f/177/t/19952237)
yum remove dell_ie_rac python-smbios
yum update


Maximum weight matching (MWM) for a predefined number of nodes

Question: I am given a weighted graph and want to find a set of edges such that every node is only incident to one edge and such that the sum of the selected edge weights is maximized. As far as I know this problem is generally referred to as maximum weight matching and there exist fast approximations for it: https://web.eecs.umich.edu/~pettie/papers/ApproxMWM-JACM.pdf
However, for my application it would be better if only a certain ratio of nodes is paired. It's more important for my application that the nodes that get paired have a high weight between them. Leaving some nodes unpaired is no big problem.
Currently, I sort the weights between nodes in descending order and always select the edge with the highest weight until I have paired a certain number of nodes. Of course I ensure that pairs of nodes are mutually exclusive. This is only a 1/2 approximation to the original problem and it's probably even worse for the modified problem.
Could you please suggest an algorithm for this issue or tell me how this problem is called?
Comment: The bipartite version is the [k-cardinality assignment problem](https://doi.org/10.1016/S0166-218X(97)00120-0). Is your graph bipartite?
Comment: Thanks. No it's not bipartite. It is even a complete graph.
Comment: How big is it? Are you open to external libraries (e.g., integer program solver)?
Comment: It has 20000 nodes. Sure I am open to everything. Speaking of "integer", I forgot to mention that all weights are integers.
Answer: Some thoughts.

The greedy algorithm for this problem is a 2-approximation. Imagine that, during the execution of the greedy algorithm, we keep score versus an optimal solution in the following manner. Every time we add an edge to the greedy solution, we delete the incident edges in the optimal solution, which I claim must have weight no greater than the greedy edge. If no edge would be deleted from the optimal solution, we delete the two heaviest edges instead, which also I claim must have weight no greater than the greedy edge. Since the greedy solution must have at least half as many edges as the optimal solution, I claim that there are no optimal edges left at the end, and hence greedy is a 2-approximation because we never deleted more than 2x weight with each greedy edge.
A complete 20,000-vertex graph is right on that line where I don't know whether integer programming would be a good idea. I think it's still worth a try because it's easy enough.
There are polynomial-time algorithms for computing the maximum-weight independent set in the intersection of two matroids (for this problem, the matching matroid and the uniform matroid whose bases have size equal to the size of the desired matching). I don't know if they would be practical.


Checkstyle for C#?

Question: I'm looking to find something along the lines of Checkstyle for Visual Studio.  I've recently started a new gig doing .NET work and realized that coding standards here are a bit lacking.  While I'm still a young guy and far from the most experienced developer I'm trying to lead by example and get things going in the right direction.
I loved the ability to use Checkstyle with Eclipse and examine code before reviews so I'd like to do the same thing with Visual Studio.  Anyone have any good suggestions?
Another thing I'd be somewhat interested in is a plug-in for SVN that disallows check-in until the main coding standards are met.  I do not want people checking in busted code that's going to wind up in a code review.
Any suggestions at this point would be great.
Comment: So. New at the job, fairly young and you want to set coding standards. You want to be careful with this. Older, more experienced developers will be put off if you don't handle it right. My suggestion: find an ally then sell the idea to them and go to your manager together. Also keep in mind that there is a local culture that you need to understand before you go changing it.
Comment: My suggestion: Give it up.  The simple fact is that companies that care about that sort of thing already have it in place.  Those that don't have it, don't have it because they don't care.  Now if, several months in, they're impressed with your code and they *ask* you to share ideas, then great.  Till then, the best policy is just to keep your head down and make sure your own work is good.
Comment: @jcollum - Excellent point. "Coding Standards" tend to turn into religious arguments that can sometimes be bitter. And often times the things people get the most picky about do absolutely nothing to improve the code, except in a subjective way. Like, do you put your `{` on a new line or not.
Comment: Fortunately, C# comes with a set of conventions that are the de facto standard.  Just use those and a lot of pointless debate is avoided.
Comment: @Nick:  It's because people can safely go at each others' throats without anyone actually being "wrong".

@PSU_Kardi:  As jcollum says, finding an ally is a way to start - your build engineer is a good ally because if he's on board he can quietly add the reports to a build and then when you broach the argument you can pull 6 months worth of data out your butt.

Personally, I wouldn't put this out as "setting standards" or even "leading by example" - in your position I'd start using it on my code and wait for someone to notice.
Comment: When going on a coding standard crusade against an existing code base, it can also be damaging in other ways. For instance, if someone goes in and changes the style, without the functionality, it can really hurt the ability to do diffs between different file revisions and pick out what *actually* changed.
Comment: Adding coding standards is never a bad idea. When a company grows, it become harder and harder to make a standard and you'll have more and more different code everywhere. As soon as possible is better. Even if it's just to use a code analysis tools that is already configured on what the company already does in it's code. It's going to help the new users. Also, other interesting pieces of information can be looked at from analysis tools.
Answer: Have you tried StyleCop?

http://code.msdn.microsoft.com/sourceanalysis

Note: This's been moved to https://github.com/StyleCop
Comment: thanks a lot, very useful - even though this answer is some time ago ;)
Answer: Take a look at resharper.
Comment: Please note that there are [ReSharper Command line tools](https://www.jetbrains.com/resharper/download/#section=resharper-clt) available as well which are for free
Answer: We use StyleCop to enforce our coding standards.  It is free and integrates nicely with Visual Studio
Comment: For the most part we use StyleCop's rules.  There are a few that we disable.  I have not tried it, but it is possible to write custom rules using the StyleCop SDK.  Here is a tutorial: http://www.lovethedot.net/2008/05/creating-custom-rules-for-microsoft.html
Comment: could you tell me if you use stylecop's rules or if you implemented your own set of rules?
what i don't like about stylecop is that its rules aren't configurable (like in resharper) and that it kind of forces its rules upon you.. unless you want to go through the trouble of changing and maintaining the set of rules described in c# code..
Answer: What you're looking for is called Static Code Analysis.
FxCop is one option.  I think Resharper can check this kind of thing as well.
Comment: I think you mean StyleCop..? FxCop only looks at IL-code (thus cannot check indentation, braces and so on), StyleCop looks at C# code.
Comment: Thanks for letting me know the proper term, I feel a bit silly at times not knowing the right name for stuff.
Comment: Isn't CheckStyle just for coding style? FxCop actually looks for errors and mistakes which clearly falls into static code analysis. But coding style is more token/whitespace analysis than dealing with actual code ...
Answer: Here are some of the great tools you can use
FxCop is a code analysis tool that checks .NET managed code assemblies for conformance to the Microsoft .NET Framework Design Guidelines

ReSharper is a refactoring and productivity plugin by JetBrains that extends native functionality of Microsoft Visual Studio .NET 2003, 2005 and 2008.

StyleCop is a free static code analysis tool from Microsoft that checks C# code for conformance to StyleCop's recommended coding styles and a subset of Microsoft's .NET Framework Design Guidelines
ref: http://blogs.msdn.com/fxcop/
Answer: Have you had a chance to review StyleCop
Answer: If you are looking for a long term supported version, I would recommend to look to Roselyn analyzers. They are the native support for Static Code Analysis with pre-configured rules, custom configs, and allow extensions.
According to the docs: ".NET compiler platform (Roslyn) analyzers inspect your C# or Visual Basic code for code quality and style issues."
https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/overview

Checkstyle for C#?


Connecting to STUN returned External IP address

Question: I am trying to connect to a webserver that is behind a NAT listening at port 4000.
On my webserver, using pystun (https://github.com/jtriley/pystun) and the command:
$ pystun -p 4000
I have a returned value of
NAT Type: Symmetric NAT
 External IP: <ip>
 External Port: 1024

But when I try to access it from http://:1024, I am not able to connet and its always stuck at waiting for response.
Is this the correct way of using STUN?
Comment: I suspect your STUN call only opens the port for UDP, not TCP.
Answer: Your NAT has opened port (punched hole) only for your STUN server as it has seen outgoing packet for STUN while you have run "pystun". But when you are trying from somewhere else to reach to your webserver, your packet is unknown to the NAT. So NAT is silently discarding all incoming packets.
Note that, event though you are getting an external port from NAT while you are communicating with STUN server, because of it's symmetric type, this port will change to some other random port while the 4 tuple (src-address, src-port, dst-sddress, dst-port) changes.


Combine two independent predictions of 55% and 65%

Question: Quant developer interview question:

There are two price prediction models, one with accuracy 55%, another with accuracy 65%, both predict price is gonna go up, what's the probability that price is gonna go up? Please provide detailed answer.

One can assume two predictions are independent.
Comment: I put [tag:self-study] tag here because this is a textbook-style problem copy-pasted from elsewhere. The policy of this forum is to provide "helpful hints".
Comment: How did you arrive at these estimates, logistic regression?  What sample size was used to fit the models?  Did you get the predictions by test on data not used for fitting?
Comment: With what probability do the models predict that the price will increase? This seems like a good place to care about model output probabilities and proper scoring rules. (Where are Harrell and Kolassa...?) I also would consider the probability that the asset increases in value. This is a different problem if the asset usually loses value but has the occasional major increase in value than if the asset gains and loses value with the same frequency.
Comment: i am not sure to understand why the calculation of this probability answers the question?
can somebody elaborate?
we are supposed to compute the following probability:
Probability(price is up/ model 1 and model 2 predict that the price is up)
Answer: A simple answer here.
We construct random variable X representing correctness of model 1. X=1 if model 1 is correct, 0 otherwise. Similarly we define Y for model 2.
Consider Pr(model 1 is correct and model 2 is correct|both are correct or both are wrong), since we know they give same prediction, thus we have this condition of both correct or both wrong.
It's easy to calculate the probability: $\frac{0.55*0.65}{0.55*0.65+0.45*0.35}=0.6942$.
Thus with 0.6942 probability, the price grows up.
Answer: This could be considered an example of aggregate data meta-analysis.
Before pooling the two estimates, you need to provide also the variability in such effect estimates with a standard error or equivalent.
Then you can simply perform pooling with fixed effect inverse variance weighting.


How to Automate the installation of Chef Agent in Nodes or Servers

Question: We are planning to provide cluster environment to our customers in cloud. We are planning to automate it Using Chef. Now there is doubt with Chef-client agent. When installing chef agent, we need to download the chef agent manually in each nodes. I have to automate the process that when customer needs a cluster environment, Chef-client agent should be installed automatically without any manual intervention. Is there any way to do that within the scope of Chef or we need to do it using Programming?
Comment: Yes, please, specify the method you plan to use to boot the instances. AWS AutoScaling maybe?
Comment: Not sure, what you mean. You can include chef in your image. This question is very broad..
Comment: When you bootstrap a node using Chef, it will attempt to download the Chef-client (assuming it has access to the Chef website)
Comment: A lot of people do not realise that "knife bootstrap" will install chef-client, if it's not already present. Various cloud plugins exist for knife that will additionally provision servers. Finally cloud-init (offered by manyy clouds) can also install chef client, see: http://cloudinit.readthedocs.org/en/latest/topics/examples.html#install-and-run-chef-recipes
Answer: You can bake Chef + a client config + the validator key into your disk image (AMI, etc). The hard part becomes assigning the run list for each node. This is usually handled by starting chef-client the first time via the provisioning system (eg. cloud-init on EC2) with the <code>-j</code> command line option and a JSON file with the desired run list derived from information from the cloud backplane.
Comment: I wouldn't condone baking keys into server images. Not only has it security considerations, it assumes the image will only be used to connect to a single chef server/org...
Comment: It's the simplest option with the validator key. Another option is to grab it from an IAM-protected S3 bucket but custom AMIs live on S3 so it's not really any different in terms of at-rest security in the end.
Comment: I would prefer that credentials be supplied at deploy time. (The credentials to access Chef server, or the creds used to access the S3 bucket containing that key). When baked into the image, you've hardcoded that image to a single chef server and lost control over who can connect to it. Finally rotating keys requires a rebuild of the dependent images.


View display nodes with taxonomy term found in URL

Question: Using Drupal 8
I have a working setup my problem is when I try to access a taxonomy term that is made up of two words.
Set up.

View : shows nodes of content type A
Has relationship (required) with a field in the content type that stores the taxonomy term (one or more terms need to be associated to each content type)
Has contextual filter (that uses previous relationship) to get the taxonomy term from the URL. The filter gets the default value from Raw value from URL with Path component: 2 , and it has Use path alias instead of internal because the URL has the taxonomy term name. It also has Specify validation criteria by Taxonomy term name by Transform dashes in URL to spaces in term name filter values so that fan-art can be correctly matched to taxonomy term fan art.

I have no problem with taxonomy terms made up of one word, it's the ones made up of two words that are giving me a headache, any ideas?
Comment: These are two different terms ?? fan and art
Comment: It's just one, it's called "Fan Art", but the url for it is fan-art, it's a single Taxonomy Term.
Comment: Try term id from url option instead
Comment: It works with that just fine, I just wanted to learn why it doesn't work with the other set up.
Answer: I gave up trying to understand why it doesn't work and resorted to using Has Taxonomy term ID instead.

The URL contains the taxonomy term ID so only a Contextual Filter is needed. In raw value the URL is taxonomy/term/[id] , so all that needs to be done is tell the Contextual Filter to Provide default value from Type Raw value from URL and Path Component 3. I also added a Specify validation criteria WhenThe Filter Value is available or a default is provided, of Validator Taxonomy term ID and chose the appropriate Vocabulary.
Answer: I'm not sure if this meets the requirements of your specific use case, but for anyone else who ends up here looking for something similar here it is: In the contextual filter select 'Name' instead of 'Taxonomy Term ID' and then check the box 'Specify validation criteria' and select 'Taxonomy term name' as your validator. Then check the box 'Transform dashes in URL to spaces in term name filter values'


How can I share Sibelius templates across devices?

Question: I'm using Sibelius Ultimate on Mac. In the latest version it is really easy to set up default templates by Exporting files as Manuscript Paper. It then stores these template files in a Manuscript Paper folder, and they are available to open in the Quick Start Menu.
However, I would like to be able to access these templates on more than one computer, so that I don't have to keep updating templates on each computer. How can I do this?
I tried putting an Alias to an iCloud file in the Manuscript Paper folder; Sibelius won't open using an alias from the Quick Start Menu.
I know I could just save a folder of template Sibelius files in iCloud to open when I need them, but I just wondered if there was a better way to do this, so that they are available in Quick Start.
Answer: You can specify your main Scores folder to be in a cloud-shared location.   I don't think it's practical to do this with a User folder, like the one Sibelius stores Manuscript Papers in.
But those Manuscript Paper files are only normal Sibelius files, placed in that particular location so that Quick Start will recognise them.  So keep your main Scores folder in iCloud.  When you create or modify a Manuscript Paper, immediately create a new score using it, and immediately save it under a suitable name into the shared folder.  You can then use it as a template on any computer that accesses that iCloud account.  For the extra convenience of having in in Quick Start, immediately Export: Manuscript Paper on THAT computer.
Not a completely transparent process.   But a lot easier than modifing a Manuscript Paper score individually on each computer.
Answer: You should be able to locate your Manuscript folder as follows. macOS: /Users/username/Library/Application Support/Avid/Sibelius. Find your specific manuscript papers, make copies and store them in the cloud, from where you will be able to access them from another device. Copy and paste them into your default folder on your second device, as above.
Comment: From the question: "I know I could just save a folder of template Sibelius files in iCloud to open when I need them, but I just wondered if there was a better way to do this, so that they are available in Quick Start."
Comment: If you copy and paste your new Manuscripts (from iCloud) onto your 2nd device in the same folder as the other Manuscript papers on your 1st device, they should show up in the QuickStart. @Aaron, I hope this helps?
Comment: I think the answer from @Laurence Payne is probably the easiest method.


4 different letters and 4 addressed envelopes.

Question: Question is : In how many ways can the letters be put into the envelopes, so that at least one letter goes to the correct address ?
Answer is 15.
All i could think of is : 4 envelop choices for each letter, so 4*4 = 16.
A little fertilizer for my withered grey-matter ?
Comment: Use the inclusion-exclusion formula.
Comment: You have to subtract the number of derangements of four objects from the $4!$ ways of placing one letter in each envelope.
Answer: $$4!-!4=24-9=15$$
${}{}{}{}{}$
Comment: What is !4? I have not seen this sign before.


Energy Distance and $L^2$ Convergence

Question: $\newcommand{\E}{\mathbb{E}}$

Question: If we have a sequence of $\mathbb{R}$-valued random variables $X_n$ which converge in the metric space of random variables defined by the energy distance to the $\mathbb{R}$-valued random variable $X$, i.e. $$D(X_n,X) \to 0$$ then is this equivalent to the sequence $X_n$ converging to $X$ in $L^2$, i.e. $$\mathbb{E}[(X_n - X)^2] \to 0?$$

My thinking is that $L^2$ convergence implies that $$\E X_n^2 - 2\E X_n X + \E X^2 \to 0$$ which looks similar to the formula of covariance, and thus makes me think that there might be a relationship with Brownian covariance and distance covariance.
Also energy distance is equal up to a constant factor to the Cramer distance (the formula for which looks like the definition of $L^2$ convergence) for real-valued random variables. This is fortuitous because I am interested primarily in the real-valued case.
Finally there seems like there might be a relationship between energy (in physics) going to zero and $L^2$ convergence, so if there is an analogous relationship between energy distance and $L^2$ convergence, that would explain why energy distance is called energy distance (Wikipedia doesn't explain the etymology of the name). I have asked questions about this relationship before on StackExchange here, here, and here.
Also it would be interesting too because then one could interpret least-squares regression as "energy-minimizing" regression. But my main goal is to argue that the $L^2$ convergence that one has in the definition of stochastic integrals (as opposed to more conventional almost sure convergence) is natural in the sense that it is equivalent pointwise convergence of the "energy difference" between the approximating processes and the stochastic integral to zero for each moment in time.
Answer: Connections/Dominance between distances is not that straightforward to evaluate. In particular, there does not seem to be an obvious connection between the energy distance and the $L^2$ distance. See:

On choosing and bounding probability metrics.
Comment: @William Google is your friend: https://www.math.hmc.edu/~su/papers.dir/metrics.pdf. Regarding the Energy distance, this is a very young distance: https://en.wikipedia.org/wiki/Energy_distance, so, a lot of opportunity for you to do some research.
Comment: This paper is a really good introduction to all of these topics that Wikipedia just lists but doesn't explain -- thank you for sending me to it!

Energy Distance and $L^2$ Convergence


Como conseguir "currentLocation" dentro de uma webview

Question: Tenho um app que roda uma webview e dentro dessa webview tem uma opção de obter a localização atual do usuário, que, por algum motivo (que eu desconheço) funciona perfeitamente no site no desktop & mobile, porém, dentro do App fica em looping infinito e não consegue achar a localização. Creio que seja algo relacionado as permissões, alguém pode ajudar?
Answer: A partir da API 23 (Android 6.0) é necessário solicitar as permissões em tempo de execução.
Veja se isso te ajuda:
https://developer.android.com/training/permissions/requesting.html?hl=pt-br


Is it possible to deduce that the limit $\lim_{x\to-\infty}\sum_{n=1}^\infty\lambda(n)\frac{x^n}{\Gamma(n)}$ is finite?

Question: Let $\lambda(n)$ for integers $n\geq 1$ the Liouville function, see its definition for example from this Wikipedia. And we denote with $\Gamma(n)$ the particular values of the gamma function over positive integers $n\geq 1$, thus it is $(n-1)!$.
We consider $$\lim_{x\to-\infty}\sum_{n=1}^\infty\lambda(n)\frac{x^n}{\Gamma(n)}.\tag{1}$$
(Notice that is the limit of previous series as $x$ tends to $-\infty$).

Question. Is it possible to deduce that $(1)$ is finite? Many thanks.
Comment: Let $f(x)=\sum_{n\geq 1}\lambda(n)\frac{(-1)^n x^n}{\Gamma(n)}$. We have
$$ g(s)= (\mathcal{L} f)(s) = \sum_{n\geq 1}\frac{n\lambda(n) (-1)^n}{s^{n+1}} $$
and if we manage to prove that $\lim_{s\to 0^+} g(s)<0$ we have that $f(x)\to 0$ as $x\to +\infty$, since $f$ decays like $e^{-\lambda x}$ for some $\lambda>0$. If there is something known about the partial sums of $n\lambda(n)$ or $n\lambda(n)(-1)^n$, this is a good moment for exploiting it through summation by parts. It does not look to be a simple problem, anyway.
Comment: I would also add that [this answer of Peter Humphries on MO](https://mathoverflow.net/a/14233/30521), together with my previous remark, points towards a positive answer to your conjecture, since it shows that $L(n)$ is predominantly negative.
Comment: I hope that my question has mathematical meaning. I would like if it is possible to deduce that our limit is finite, is infinite or well oscillates. Many thanks all users.
Comment: Many thanks, one more time my problem has no more context (and my thougths were that maybe could have a suitable answer for the question), but it is good have your reasonings that I am going to read. I hope that other users want to do feedback about the question @JackD'Aurizio
Comment: I promise a live goose as added prize for the first user solving this problem! (Not, it is a joke, in fact now I've no much money and each goose that I am  meeting doesn't know how to fly yet.)
Comment: I'm going to read the post @JackD'Aurizio
Answer: Definitely too long for a comment.
Let $L(n)=\sum_{m)=1}^{n}\lambda(m)$. Quoting Peter Humphries from MO:

As for somewhat elementary methods (in the sense of avoiding the Riemann zeta function) to show that $L(n)$ is "usually" of order $\sqrt{n}$, one can use the Lambert series
  $$\sum_{n=1}^{\infty}{\frac{\lambda(n)q^n}{1-q^n}} = \sum_{n=1}^{\infty}{q^{n^2}}.$$
  As
  $$\frac{q^n}{1+q^n} = \frac{q^n}{1-q^n} - 2\frac{q^{2n}}{1-q^{2n}},$$
  we have
  $$\sum_{n=1}^{\infty}{\frac{\lambda(n)}{q^{-n}+1}} = \sum_{n=1}^{\infty}{q^{n^2}} - 2\sum_{n=1}^{\infty}{q^{2n^2}}$$
  or equivalently, letting $q = e^{-\pi/x}$ and $\psi(x) = \sum_{n=1}^{\infty}{e^{-\pi xn^2}}$, where $x$ is large,
  $$\sum_{n=1}^{\infty}{\frac{\lambda(n)}{e^{n\pi/x}+1}} = \psi(1/x) - 2\psi(2/x)$$
  Now $\psi(x)$ satisfies the functional equation
  $$\frac{1+2\psi(x)}{1+2\psi(1/x)} = \frac{1}{\sqrt{x}},$$
  and so we can rewrite this as
  $$\sum_{n=1}^{\infty}{\frac{\lambda(n)}{e^{n\pi/x}+1}} = \frac{1-\sqrt{2}}{2}\sqrt{x} + \frac{1}{2} + (\psi(x)-2\psi(x/2))\sqrt{x}.$$
  For large $x$, the left-hand side "looks like" $L(x)$, whereas the right-hand side is dominated by the term $\frac{1-\sqrt{2}}{2}\sqrt{x}$. This also explains why $L(n)$ is predominantly negative, as $\frac{1-\sqrt{2}}{2}$ is negative.

Now comes my comment under the main thread (with a $\color{blue}{\text{blue}}$ addendum):

Let $f(x)=\sum_{n\geq 1}\lambda(n)\frac{(-1)^n x^n}{\Gamma(n)}$. We have
  $$ g(s)= (\mathcal{L} f)(s) = \sum_{n\geq 1}\frac{n\lambda(n) (-1)^n}{s^{n+1}} =\color{blue}{-\frac{d}{ds}\sum_{n\geq 1}\frac{\lambda(n)(-1)^n}{s^n}}$$
  and if we manage to prove that $\lim_{s\to 0^+} g(s)<0$ we have that $f(x)\to 0$ as $x\to +\infty$, since $f$ decays like $e^{-\lambda x}$ for some $\lambda>0$. If there is something known about the partial sums of $n\lambda(n)$ or $n\lambda(n)(-1)^n$, this is a good moment for exploiting it through summation by parts. It does not look to be a simple problem, anyway.

Not a simple problem, indeed, but to remark the connection between $\mathcal{L} f$ and the Jacobi $\Theta$ function/the Jacobi triple product is enlightening. We have
$$ \sum_{n\geq 1}\frac{\lambda(n)(-1)^n}{s^n} = -\sum_{\substack{n\geq 1\\ n\text{ odd}}}\left(\frac{\lambda(n)}{s^n}+\frac{\lambda(n)}{s^{2n}}-\frac{\lambda(n)}{s^{4n}}+\frac{\lambda(n)}{s^{8n}}-\ldots\right)$$
and by setting $s=e^{\pi/x}$ (for $x\to +\infty$) the behaviour of the RHS (and its derivative) in a right neighbourhood of $s=0$ can be studied through Humphries' functional equation. I still have to complete the the necessary estimations in full rigor, but this points towards an affirmative answer to your question.
Comment: You take great dedication in your answers, many thanks today I am going to study your answer and Humphries' result.


ServiceStack, Slowness on first Deserialization?

Question: I'm testing out alternate Deserialization methods in a C# application. I'm trying out ServiceStack (4.0.38) right now and I'm discovering some odd behavior. Here's my testing code:
<code>    public class BasicObject
    {
        public List<string> Stuff { get; set; }

        public BasicObject()
        {
            Stuff = new List<string>();
        }
    }

    private void CustomTesting()
    {
        var largeObject = new BasicObject();
        var mediumObject = new BasicObject();
        var smallObject = new BasicObject();
        //Populate this shiz
        for (int i = 0; i < 100000; i++)
        {
            if (i < 50000)
                mediumObject.Stuff.Add("HelloWorld");

            if (i < 2000)
                smallObject.Stuff.Add("HelloWorld");

            largeObject.Stuff.Add("HelloWorld");
        }

        //Serialize, save to disk
        using(var stream = new MemoryStream())
        {
            JsonSerializer.SerializeToStream<BasicObject>(largeObject, stream);
            File.WriteAllBytes("C:\\Temp\\Large", stream.ToArray());
        }
        using (var stream = new MemoryStream())
        {
            JsonSerializer.SerializeToStream<BasicObject>(mediumObject, stream);
            File.WriteAllBytes("C:\\Temp\\Medium", stream.ToArray());
        }
        using (var stream = new MemoryStream())
        {
            JsonSerializer.SerializeToStream<BasicObject>(smallObject, stream);
            File.WriteAllBytes("C:\\Temp\\Small", stream.ToArray());
        }

        var watch = new Stopwatch();

        using (var stream = new MemoryStream(File.ReadAllBytes("C:\\Temp\\Large")))
        {
            watch.Start();
            var test = JsonSerializer.DeserializeFromStream<BasicObject>(stream);
            watch.Stop();
        }
        var timeTakenLarge = watch.Elapsed.Milliseconds;
        watch.Restart();

        using (var stream = new MemoryStream(File.ReadAllBytes("C:\\Temp\\Medium")))
        {
            watch.Start();
            var test = JsonSerializer.DeserializeFromStream<BasicObject>(stream);
            watch.Stop();
        }
        var timeTakenMedium = watch.Elapsed.Milliseconds;
        watch.Restart();

        using (var stream = new MemoryStream(File.ReadAllBytes("C:\\Temp\\Small")))
        {
            watch.Start();
            var test = JsonSerializer.DeserializeFromStream<BasicObject>(stream);
            watch.Stop();
        }
        var timeTakenSmall = watch.Elapsed.Milliseconds;
        watch.Restart();

        Console.Clear();
        Console.WriteLine(string.Format("{0}  {1}  {2}", timeTakenLarge, timeTakenMedium, timeTakenSmall));
        Console.ReadKey();
    }
</code>
Pretty simple, take a basic object, populate it with 3 different ranges of data. Serialize it, save it to disk. Then later take the saved file in a memory stream and see how long it takes ServiceStack to deserialize. Here's my output (times in milliseconds)

Deserialization Order: Large Med Small
Display Order: Large Med Small
209  61  1
222  73  1
178  57  1
174  60  1

Deserialization Order: Small Med Large
Display Order: Large Med Small
145  48  66
128  72  63
100  58  79
98  55  57

Deserialization Order: Med Small Large
Display Order: Large Med Small
106  130  1
155  114  1
106  199  1
115  217  1

For some reason Which ever deserialization occurs first will be a bit slow. Why is this? Is ServiceStack maybe caching info about the object behind the scenes?
Answer: Most serializers are optimized for run-time performance where the first iteration will be slow due to creating and compiling all the required delegates containing optimal code-paths which are then cached and re-used for subsequent serialization of the cached types.


Using '#type"=>'container' to create a div wrapper around nested elements?

Question: From my reading a render array can define a wrapper div by using the '#type'=>'container'. I am inserting a render array in the page_alter hook function in the page_bottom region. It appears that the container type does not work in this case. The code below does not wrap the two #markupelements with the div wrapper but instead outputs the div then the content at the same level.
$page['page_bottom']["notices"] = array(
  '#type' => 'container',
  '#attributes' => array(
    'id' => array('notices'),
  ),
);

$page['page_bottom']["notices"]['notices-placeholder'] = array(
  '#suffix' => "
",
  '#prefix' => '
',
);

$page['page_bottom']["notices"]['notices-tab'] = array(
  '#markup' => '
NOTICES  10
',
);

What I want is the following.

NOTICES....

What I get is the following.

NOTICES....

--- Added
I did try #children earlier in the day and it didn't work as well. Before I left for the day I also tried with
$page['page_bottom']["notices"]['notices-placeholder'] = array(
    '#suffix' => "
",
    '#markup'=>"Empty String", // added to see what it would do
    '#prefix' => '
',
);

This resulted in a completely out of sync html with the #markup tag being outside the #prefix/#suffix. I don't have the results on me now to post but if you try it you will see the results for your self.
Comment: You have a bug in your code :) Your #suffix should be #prefix, and your #prefix should be #suffix. Currently you have `'#prefix' => ''`, so this closes your container. It becomes more clear if you use a different html tag for the prefix/suffix stuff, e.g. `''`. Then you would get ``.
Answer: I was able to obtain what you wanted using the following code.
  $page['page_bottom']["notices"] = array(
    '#type' => 'container',
    '#attributes' => array(
      'id' => array('notices'),
    ),
  );

  $page['page_bottom']["notices"]['notices-placeholder'] = array(
    '#type' => 'container',
    '#attributes' => array(
      'id' => array('notices-placeholder'),
    ),
  );

  $page['page_bottom']["notices"]['notices-tab'] = array(
    '#markup' => '
NOTICES  10
',
  );

The output I obtain using that code as implementation of hook_page_alter() is the following.

NOTICES  10

I tried using your code, and setting $page['page_bottom']["notices"]['#tree'] to TRUE, or setting $page['page_bottom']["notices"]['notices-placeholder']['#type'] to 'markup', but I always obtained the same result as you.
The only explanation I have is that, using your code, theme_container() (the function defined as theme wrapper for the "container" element) doesn't get any value for $element['#children']. That would explain why the container HTML output doesn't contain any children element, as the code executed by theme_container() is the following one.
  $element = $variables['element'];

  // Special handling for form elements.
  if (isset($element['#array_parents'])) {
    // Assign an html ID.
    if (!isset($element['#attributes']['id'])) {
      $element['#attributes']['id'] = $element['#id'];
    }
    // Add the 'form-wrapper' class.
    $element['#attributes']['class'][] = 'form-wrapper';
  }

  return '
' . $element['#children'] . '
';

References

system_element_info()
drupal_render_page()
Comment: Thanks for the info. I did try with #children as well with no luck. I also tried with the

$page['page_bottom']["notices"]['notices-placeholder'] = array(
  '#suffix' => "",
  '#prefix' => '',
);
Comment: The first snippet I shown works.
Answer: Change suffix and prefix
$page['page_bottom']["notices"]['notices-placeholder'] = array(
  '#prefix' => "",
  '#suffix' => '',
);
Comment: Your answer is correct. Perhaps express it in a bit more detail :)
Answer: you have to render the $page : return drupal_render($page)


What are the downsides of using IPv6 Multicast for majority of all communication including one-to-one?

Question: Given IPv6 Multicast allows for a sub-pub communication model, it seems like a no-brainer for the vast majority of communication, but its very rarely used beyond video streaming, and I'd like to know if this is because its only efficient for large groups or if its just because its not well understood and Unicast/Anycast are easier to implement?
Answer: Multicast is suitable for traffic where everyone receives same data at the same time. Majority of internet communication is not like that. For example, all web traffic is initiated by requests from users, and server replies to those requests.


Quickly select lines shortcut in eclipse

Question: Is there any shortcut in eclipse to select lines lets say from line 40 to line 620 without click and dragging the mouse from line 40 to line 620?
Answer: Click on the start position and then Shift+Click on the end position.
Comment: thanks but any other shortcut without even navigating to end position?
Answer: If the lines are surrounded by parentheses or braces, double-click to the right of the opening bracket or to the left of the closing bracket. This selects all lines between the braces.
Else you can use shift+up/down arrows to select multiple lines.


Display entity images with thumbnails and 1 large image

Question: I want to attach multiple images to custom entity (commerce product),
and display them as follow: 1 large image, and list of thumbnails, user can click on thumbnail thus changing large image.
I found and plan to use the library http://www.elevateweb.co.uk/image-zoom/examples#gallery-lightbox
So my steps:

create subtheme of bootstrap theme
add field "images" to the commerce product entity
write twig file to display images

Is it correct path? or maybe there is better solution? better library?
With image zoom, I need to get output like this

Comment: I would create custom field formatter instead.
Comment: Thanks, but i cant see whole architecture with custom formatter, can you help me - write basic steps with formatter?

1. I make formater plugin extends ImageFormatter
2. override viewElements function?
3. set $element['#theme'] to my own template name?
so i just get my own twig template in use.

why not just override base ImageFormatter-myfield.twig
Answer: <?php

/**
 * @file
 * Contains \Drupal\mymodule\Plugin\Field\FieldFormatter\SlickMyentityGalleryFormatter.
 */

namespace Drupal\mymodule\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\Html;

/**
 * @FieldFormatter(
 *   id = "slick_myentity_gallery",
 *   label = @Translation("Slick Myentity Gallery"),
 *   field_types = {
 *     "image"
 *   }
 * )
 */
class SlickMyentityGalleryFormatter extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
      'visible_slides' => 3,
      'image_style' => 'thumbnail',
      'arrows' => TRUE,
      'dots' => TRUE,
      'fade' => FALSE,
      'standalone_image' => TRUE,
      'standalone_location' => 'above',
      'standalone_style' => 'xlarge',
      'vertical' => FALSE,
      'lazy_load' => 'ondemand',
      'hide_single_navigator' => TRUE
    ] + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $element = parent::settingsForm($form, $form_state);
    $field_name = $this->fieldDefinition->getName();

    $image_style_entities = \Drupal::entityManager()
      ->getStorage('image_style')
      ->loadMultiple();

    $image_styles = array_map(function($image_style) {
      return $image_style->label();
    }, $image_style_entities);

    $image_styles = ['_original' => '- ' . $this->t('Original') . ' -'] + $image_styles;

    $element['visible_slides'] = [
      '#type' => 'number',
      '#title' => $this->t('Number of visible slides'),
      '#default_value' => $this->getSetting('visible_slides'),
      '#min' => 1,
      '#max' => 10,
      '#description' => $this->t('Number of images visible at once.')
    ];

    $element['image_style'] = [
      '#type' => 'select',
      '#title' => $this->t('Image style'),
      '#default_value' => $this->getSetting('image_style'),
      '#options' => $image_styles,
      '#description' => $this->t('Image style to display the images with.')
    ];

    $element['arrows'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Show arrows'),
      '#default_value' => $this->getSetting('arrows'),
      '#description' => $this->t('Display the navigation arrows.')
    ];

    $element['dots'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Paging'),
      '#default_value' => $this->getSetting('dots'),
      '#description' => $this->t('Display the paging dots.')
    ];

    $element['fade'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Fade'),
      '#default_value' => $this->getSetting('fade'),
      '#description' => $this->t('Fade between transitions.')
    ];

    $element['vertical'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Vertical slider'),
      '#default_value' => $this->getSetting('vertical'),
      '#description' => $this->t('Display slider vertically instead of horizontally.')
    ];

    $element['lazy_load'] = [
      '#type' => 'select',
      '#title' => $this->t('Lazy load'),
      '#options' => [
        'none' => '- ' . $this->t('None') . ' -',
        'ondemand' => $this->t('On demand'),
        'progressive' => $this->t('Progressive')
      ],
      '#default_value' => $this->getSetting('lazy_load'),
      '#description' => $this->t('Lazy load the images to increase page performance.')
    ];

    $element['standalone_image'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Standalone active image'),
      '#default_value' => $this->getSetting('standalone_image'),
      '#description' => $this->t('Display the active image separately.')
    ];

    $element['standalone_style'] = [
      '#type' => 'select',
      '#title' => $this->t('Standalone image style'),
      '#default_value' => $this->getSetting('standalone_style'),
      '#options' => $image_styles,
      '#description' => $this->t('Image style to display the standalone image with.'),
      '#states' => [
        'visible' => [
          "input[name=\"fields[$field_name][settings_edit_form][settings][standalone_image]\"]" => [
            'checked' => TRUE
          ]
        ]
      ]
    ];

    $element['standalone_location'] = [
      '#type' => 'select',
      '#title' => $this->t('Standalone image location'),
      '#default_value' => $this->getSetting('standalone_location'),
      '#options' => [
        'above' => $this->t('Above'),
        'below' => $this->t('Below'),
        'left' => $this->t('Left'),
        'right' => $this->t('Right')
      ],
      '#description' => $this->t('Display slider vertically instead of horizontally.'),
      '#states' => [
        'visible' => [
          "input[name=\"fields[$field_name][settings_edit_form][settings][standalone_image]\"]" => [
            'checked' => TRUE
          ]
        ]
      ]
    ];

    $element['hide_single_navigator'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Hide single item carousel'),
      '#default_value' => $this->getSetting('hide_single_navigator'),
      '#description' => $this->t('If standalone image is displayed and there is only one image, the carousel will be hidden.'),
      '#states' => [
        'visible' => [
          "input[name=\"fields[$field_name][settings_edit_form][settings][standalone_image]\"]" => [
            'checked' => TRUE
          ]
        ]
      ]
    ];

    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = parent::settingsSummary();

    if ($this->getSetting('standalone_image')) {
      $standalone_style = $this->getSetting('standalone_style');
      if ($standalone_style == '_original') {
        $summary[] = $this->t('Display standalone image without image style.');
      } else {
        $style = \Drupal::entityManager()->getStorage('image_style')->load($standalone_style);
        $summary[] = $this->t('Display standalone image with %style image style.', [
          '%style' => $style ? $style->label() : 'original'
        ]);
      }

      $location = $this->getSetting('standalone_location');
      $location_labels = [
        'above' => $this->t('above'),
        'below' => $this->t('below'),
        'left' => $this->t('left'),
        'right' => $this->t('right')
      ];
      $summary[] = $this->t('Standalone image position: %position.', [
        '%position' => $location_labels[$location]
      ]);

      if ($this->getSetting('hide_single_navigator')) {
        $summary[] = $this->t('Hide carousel with single image.');
      }
    }

    $image_style = $this->getSetting('image_style');
    if ($image_style == '_original') {
      $summary[] = $this->t('Display images without image style.');
    } else {
      $style = \Drupal::entityManager()->getStorage('image_style')->load($image_style);
      $summary[] = $this->t('Display images with %style image style.', [
        '%style' => $style ? $style->label() : 'original'
      ]);
    }

    if ($this->getSetting('vertical')) {
      $summary[] = $this->t('Display slider vertically.');
    }

    switch ($this->getSetting('lazy_load')) {
      case 'ondemand':  $summary[] = $this->t('Use on demand lazy loading.'); break;
      case 'progressive':  $summary[] = $this->t('Use progressive lazy loading.'); break;
    }

    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    // Skip if there are no items to display.
    if ($items->isEmpty()) {
      return [];
    }

    $standalone_html_id = Html::getUniqueId($items->getName() . '-standalone');
    $carousel_id = Html::getUniqueId($items->getName() . '-nav');
    $lazy_load = $this->getSetting('lazy_load');
    $use_lazy_load = $lazy_load != 'none';

    // Retrieve file IDs.
    $fids = [];
    foreach ($items->getIterator() AS $item) {
      $fids[] = $item->get('target_id')->getValue();
    }

    // Load files so we can get their URIs.
    $files = \Drupal::entityManager()->getStorage('file')->loadMultiple($fids);

    // Make a list of all URIs.
    $uris = array_map(function($file) {
      return $file->getFileUri();
    }, $files);

    // Set up the render element.
    $element = [
      '#attached' => [
        'library' => [
          'mymodule/slick_myentity_gallery'
        ]
      ]
    ];

    // Create carousel for the standalone image if needed.
    if ($this->getSetting('standalone_image')) {
      $element['#attributes']['class'][] = 'with-standalone';

      $element['standalone'] = [
        '#theme' => 'item_list',
        '#items' => [],
        '#weight' => 0,
        '#attributes' => [
          'id' => $standalone_html_id,
          'class' => [
            'slick-myentity-gallery',
            'slider-standalone',
            'location-' . $this->getSetting('standalone_location')
          ],
          'data-slick-settings' => json_encode([
            'slidesToShow' => 1,
            'slidesToScroll' => 1,
            'arrows' => FALSE,
            'fade' =>  TRUE,
            'asNavFor' => '#' . $carousel_id,
            'lazyLoad' => $lazy_load,
            'mobileFirst' => TRUE
          ])
        ]
      ];

      foreach ($uris AS $uri) {
        $element['standalone']['#items'][] = $this->getImageItem($uri, $this->getSetting('standalone_style'), $use_lazy_load);
      }
    }

    // Create the main image carousel.
    $element['carousel'] = [
      '#theme' => 'item_list',
      '#items' => [],
      '#weight' => 1,
      '#attributes' => [
        'id' => $carousel_id,
        'class' => [
          'slick-myentity-gallery',
          'slider-navigation',
          $this->getSetting('vertical') ? 'vertical' : 'horizontal'
        ],
        'data-slick-settings' => json_encode([
          'slidesToShow' => (int) $this->getSetting('visible_slides'),
          'slidesToScroll' => 1,
          'asNavFor' => '#' . $standalone_html_id,
          'dots' => (bool) $this->getSetting('dots'),
          'arrows' => (bool) $this->getSetting('arrows'),
          'fade' => (bool) $this->getSetting('fade'),
          'vertical' => (bool) $this->getSetting('vertical'),
          'verticalSwiping' => (bool) $this->getSetting('vertical'),
          'focusOnSelect' => TRUE,
          'lazyLoad' => $lazy_load,
          'mobileFirst' => TRUE,
          'rtl' => \Drupal::languageManager()->getCurrentLanguage()->getDirection() == 'rtl',
          'infinite' => FALSE
        ])
      ]
    ];

    foreach ($uris AS $uri) {
      $element['carousel']['#items'][] = $this->getImageItem($uri, $this->getSetting('image_style'), $use_lazy_load);
    }

    // Display the carouse first if the standalone image is visible and
    // is positioned below the carousel or to the right next to it.
    if ($this->getSetting('standalone_image') && in_array($this->getSetting('standalone_location'), ['below', 'right'])) {
      $element['carousel']['#weight'] = -1;
    }

    // Hide navigator if standalone image is displayed and there is only
    // one image.
    if ($this->getSetting('standalone_image') && $this->getSetting('hide_single_navigator') && $items->count() == 1) {
      unset($element['carousel']);
    }

    return [$element];
  }

  /**
   * Helper method to generate image for provided style
   * that takes the lazy load setting into account.
   *
   * @param string $uri
   *   The original image uri.
   * @param string $image_style
   *   The image style name.
   * @param bool $lazy_load
   *   If TRUE the lazy slick load image will be returned.
   *
   * @return array
   *   Renderable array for a single image.
   */
  function getImageItem($uri, $image_style, $lazy_load = FALSE) {
    if ($lazy_load) {
      $style = \Drupal::entityManager()
        ->getStorage('image_style')
        ->load($image_style);

      return [
        '#type' => 'inline_template',
        '#template' => '',
        '#context' => [
          'path' => $style ? $style->buildUrl($uri) : file_create_url($uri)
        ]
      ];
    } else {
      return [
        '#theme' => 'image_style',
        '#uri' => $uri,
        '#style_name' => $image_style
      ];
    }
  }

}

(function($) {

  Drupal.behaviors.slickMyentityGallery = {
    attach: function(context) {
      // Initialize the Slick Carousel on all appropriate elements.
      $('.slick-myentity-gallery[data-slick-settings]', context).once('slick-myentity-gallery-init').each(function() {
        var $this = $(this);
        var settings = $this.data('slick-settings');

        // Adjust behavior if this is a Field API field.
        var $fapi_items = $this.find('.field__item');
        if ($fapi_items.length != 0) {
          $fapi_items.parent().slick( settings );
        } else {
          $this.slick( settings );
        }
      });
    }
  }

})(jQuery);

Comment: Would you please provide full custom module?


About finding the closure of a set.

Question: I want to learn how should I find the closure of a set $S$. It's a long that I was not worked with topological concepts, and I am afraid if I am mistaken about some easy things. Here I will list some of the facts which will help me to solve my problems and pursue my purposes.
Suppose that a topological space $X$ is given, and let $R, S \subseteq X$ be two sets.

Is this true? The closure of $S$ is the union of $S$ with all limit points of $S$. (I think it should be the definition of the closure, or at least it should be equivalent to the definition, any other equivalent definitions are welcome.)
If $S$ is dense in $R$, then $R \subseteq \overline S$.
$\overline S$ is the largest set, in which $S$ is dense. (i.e. if $\overline S \subsetneq R'$, then any $x\in R'\backslash \overline S$ has a positive distance from $S$, therefore is not a limit point)

The next two points, are not related to the closure, but I have some doubts.

A function $f: X \rightarrow Y$ between two topological spaces is called continuous, iff for every open $V \subseteq Y$, $f^{-1}(V)$ is open in $X$. (I think this was a standard definition, any other equivalent definition are welcome.)
A function $f: X \rightarrow Y$ between two topological spaces, is continuous, iff for every close $V \subseteq Y$, $f^{-1}(V)$ is close in $X$.

My intuition says that, the first $4$ points are true. Am I right? If I am mistaken about these facts, please tell me, and if it is possible please give me a counter-example. Also, I think the last point is also equivalent to the $4^{th}$ point, because if a set is closed iff and only if its complement is open. Having this in mind it seems the last two points are equivalent to each other as the definition of a continuous function.
Any equivalent definitions to the $1^{st}$ point and $4^{th}$ point are welcome. Especially those equivalent definitions, which are useful for computing the closure. Using the first three points I am able to find the closure of some simple sets in $p$-adic topology.
Answer:
Yes, a set is "closed"if and only if it contains all of its limit points so taking the union of any set with its limit points gives the closure of the set.  (The closure of a set is also the intersection of all closed sets containing it.)

2.Yes, that is pretty much the definition of "dense".

Yes, again that follows directly from the definition of "dense".

The spelling is "continuous", not "continues".  But, yes, that is a standard definition of "continuous".

Yes, the fact that the inverse image of a closed set is closed is an alternate definition of "continuous
Answer: They are all correct. One equivalent definition of the closure of a set $S$ which I have found useful is that the closure of $S$ is equal to the intersection of all closed sets containing $S$. In other words, $\overline{S}$ is the smallest closed set containing $S$.

About finding the closure of a set.


Primary key for multiple columns?

Question: I have this MySQL Table, the PRIMARY KEY (ID).
ID  | COLOR   | SIZE
====================
| 1 |   RED   | 1  |
| 2 |   RED   | 2  |
| 3 |   RED   | 3  |
| 4 |   GREEN | 1  |
| 5 |   GREEN | 2  |
| 6 |   BLUE  | 1  |
===================

When i insert this row for example
INSERT INTO `test`(`COLOR`, `SIZE`) VALUES (RED',1);

i have a duplicate row
1, RED, 1
and
7, RED, 1
how to avoid this problem?
Thanks
Comment: add an unique constraints  on color
Comment: @scaisEdge `color` and `size`?
Comment: You need to define ` unique key` for `color` column
Comment: @JuanCarlosOropeza  correct  .. thanks
Comment: exactly why you mean with `how to avoid this problem`? because create an `UNIQUE` constraint will generate an error when trying to insert second `Red,1`, so will protect your db table to have duplicate values, but  so you have to handle those error somewhere.
Answer: You can use alter table
ALTER TABLE `test`
ADD UNIQUE (color, size)

Answer: Before you run this empty your table first or remove the duplicate row from your table than run it.
ALTER TABLE  `test` ADD UNIQUE (color, size)

Comment: I have  tried with
ALTER TABLE 'test
   ADD PRIMARY KEY ( `COLOR`,` size`) ;.
But there is an error.
your solution works. by adding " INSERT IGNORE INTO ".
Thanks

Primary key for multiple columns?


Drupal database loading slow

Question: I'm making a website (don't open in IE) where I use Ajax to load a view. I now want to use BOOST to cache the view as HTML.
These pages should be "BOOSTED":
http://www.spanjevakantiewinkel.nl/regio/ajax/8
http://www.spanjevakantiewinkel.nl/regio/ajax/9
...
Should I use JSON instead of my way to load the view? Any idea how?
The ID (8,9,...) is given by hovering a small image beneath the large header image. Then the view will be loaded, but always within the database, I want HTML pages made with BOOST.
function dynamic_regio_menu() {
  $items = array();

  $items['regio/ajax'] = array(
    'title' => 'Dynamic Regio',
    'page callback' => 'dynamic_regio_get_by_category_id',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
  );
  return $items;
}

function dynamic_regio_get_by_category_id($cat_id){
    $viewName = 'regio_submenu'; // The name of the view we are going to load

    $args = array($cat_id);  // Array of arguments we set for the view.
    $displayId = 'block'; // The display id of for the view.

    // Call the views_embed_view function to returned themed view output
    $html = views_embed_view($viewName, $displayId, $args);
    echo $html;
}

xhr = $.ajax({
  type: 'POST',
  url: '/regio/ajax/' + this.parentNode.getAttribute('tid'),
  success: updateData, dataType: 'html',
});

Comment: For starters, I would suggest using [hoverintent](http://drupal.org/project/hoverintent) to prevent all the aborted `POST` requests.
Comment: You've mentioned that you've enabled Boost in the comments, but make sure you've also enabled the caching of ajax requests in Boost too... (would have commented directly but I don't have enough rep *sadpanda*)
Comment: how did you set the caching on the view ? does the content change often ? does it save the cache every time (do you see the update cache for each request) ? Did you try "precaching" for some of the parameters ?
Comment: how do you load the view in your js ?
Comment: Hoverintent sounds like a good idea, but first I want to make it faster... The loading of the view is now in my question.
Comment: I installed the Boost module, and that made the site a lot faster. But boost doesn't make HTML pages for the module I made, so that is still slow. Any idea's?
Comment: You can enable JSON caching, but I don't use JSON, I get HTML from my module...
Comment: So what I'm looking for is this:
Use BOOST for

http://www.spanjevakantiewinkel.nl/regio/ajax/8
http://www.spanjevakantiewinkel.nl/regio/ajax/9
...

I changed my question...
Answer: I think the problem is how your views are cached - if you say it is sometimes slow, it is most probably because those times the cache is beeing saved.
If the content doesnt change often, you might just prolongue the interval. Another option is to use Views content cache.
But basically if you have enough visitors (and enough people hovering the images :), they will only wait from time to time ...
Comment: I changed my question. Using BOOST to make HTML pages from the URL's is what I'm looking for. Caching of the view is enabled, but I use ID's of regio's to change the result of the view. Also, I think BOOST is faster then everything else. Should I change the output of my Ajax request to JSON, and not direct HTML like I do now? Any idea how I can see if a page is loaded with BOOST or not?
Comment: I use my own module to link the VIEW with a URL. So views caching won't do anything I think? Maybe I should change my view? Is it possible to have let's say 10 pages for 1 view?

http://www.spanjevakantiewinkel.nl/regio/ajax/8
http://www.spanjevakantiewinkel.nl/regio/ajax/9
http://www.spanjevakantiewinkel.nl/regio/ajax/10
...
Comment: There was a snippet from the queries run when the view is beeing shown (did you delete it in the meantime ?) And from that it was clear that there was some cache beeing saved (update), i think it was even clear that it was the cache from views. So you should now check the settings of the caching on that view, and think about the data that is beeing shown - how often does it change and so on ... The best is the module i suggested - that will help you to only fill the cache once the data is changed.
Comment: boost saves stuff to fysical files, you should be able to see the files and thus determine what is beeing cached by boost. I dont think it is a big difference in this case whether you use json or html, i personally would stick with html.
Answer: The Query time is simply the time it took for the DB to send the result of the query to be returned.  The page execution takes into account all of the processing of those results.
This is why it's so important to have Caching enabled.
This may explain more of Views caching: Are views cached through the core caching mechanisms or should I be setting the caching directly in each view?
Answer: I am not sure if it can help or not but when I try to make ajax I have to call drupal_exit()
I don't want drupal to get all page element just this string
function dynamic_regio_get_by_category_id($cat_id){
    $viewName = 'regio_submenu'; // The name of the view we are going to load

    $args = array($cat_id);  // Array of arguments we set for the view.
    $displayId = 'block'; // The display id of for the view.

    // Call the views_embed_view function to returned themed view output
    $html = views_embed_view($viewName, $displayId, $args);
    echo $html;
    drupal_exit();
}

Answer: I would definitely advise to check if you have removed modules that are still enabled. This is a real performance killer because Drupal is searching for the module files.
The behavior that you describe looks like this issue.
Answer: OK, I know this is an old thread, however, I just went through quite a bit of trouble with this and thought I should post here so others will know what my problem was.
first and foremost, verify that your view is not trying to render every single node and comment in the content type if there is a lot of content! It will dismally slow the site doen even if you are using caching, etc. The problem only manifested itself after migrating 56000 or so comments onto 30000 nodes.
The pager count evidently counts nodes and comments and my view had a contextual filter for the logged in user that was not working as it should. Once I got it working, the views are fast and everything is good so I hope this helps someone down the road.

Drupal database loading slow


How to set checked properties false on checkbox array in js

Question: My chechkbox

<input class="alanlar" type="checkbox" disabled="" name="gunlukAlanlar[]" value="tarih" checked="" style="position: absolute; opacity: 0;">

                            Tarih

<input class="alanlar" type="checkbox" disabled="" name="gunlukAlanlar[]" value="saat" checked="" style="position: absolute; opacity: 0;">

                        Saat

<input class="alanlar" type="checkbox" disabled="" name="gunlukAlanlar[]" value="Order Adı" checked="" style="position: absolute; opacity: 0;">

                        Order Adı

JQuery Lib

Js Code
$("input[name='gunlukAlanlar[]']")[2].prop("checked", false);

But its not working.I'm want unchecked have index 2.But its not working.
Please review image
Comment: Sorry,I couldn't enter in a few houses due to internet access problems.I try now.But not fixed problem
Comment: I was updated my question.Please review new image
Comment: ok. I just adjusted my answer. See if that helps you.
Comment: Be more specific than "not working". What is happening? What isn't happening? What console errors do you get?
Comment: Not working again Kinglish.And not get console error.
Comment: $("input[name='gunlukAlanlar[]']")[2].prop("checked", false); I' trying again this.And error log
Comment: index.php?do=detayli_operasyon_raporu:943 Uncaught TypeError: $(...)[2].prop is not a function
    at GunlukFiltreVarsayilan (index.php?do=detayli_operasyon_raporu:943)
    at HTMLInputElement.onclick (index.php?do=detayli_operasyon_raporu:1190)
GunlukFiltreVarsayilan @ index.php?do=detayli_operasyon_raporu:943
onclick @ index.php?do=detayli_operasyon_raporu:1190
Comment: I want just this."Varsayılana Çek" is button with set "Model Adı" checkbox unchecked
Comment: I was updated checkbox html codes.Please review again.Kinglish is code another html file is working.But not working my project.Maybe not working for chechkbox html.Please review my friends
Answer: Instead of referencing an array index on a jQuery element collection (which doesn't work anyways) - stick with JQ and use .eq()
Also your code was setting an invisible checkbox (opacity: 0) to false (prop("checked", false);) - when they were all unchecked to begin with so ...
In this, I've set it so 'checked' checkboxes are visible. That is just a css class so it's easy to get rid of.

$("input[name='gunlukAlanlar[]']").eq(1).prop("checked", false);

<input class="alanlar" type="checkbox" name="gunlukAlanlar[]" id="gunlukAlanlar[]" checked value="saat" /> //index 0
<input class="alanlar" checked type="checkbox" name="gunlukAlanlar[]" id="gunlukAlanlar[]" value="modelii">//index 1
<input class="alanlar" checked type="checkbox" name="gunlukAlanlar[]" id="gunlukAlanlar[]" value="tarih">//index 2
<input class="alanlar" checked type="checkbox" name="gunlukAlanlar[]" id="gunlukAlanlar[]" value="musteri">//index 3


Decimal representation begins with $N$

Question:
Let $a \geq 2$ be a positive integer such that $\log_{10}a$ is irrational. Then for any positive integer $N$ there exist infinitely many powers $a^n$ of $a$ whose decimal representation begins with $N$.

I am not sure how to use the fact that $a^n$ begins with $N$. How should I prove this?
Answer: If $\log_{10}(a)\not\in\mathbb{Q}$, by setting $r_n=n\cdot\log_{10}(a)$ and considering the sequence
$$ r_n\pmod{1}$$
we have that such a sequence is dense in the interval $(0,1)$ by the Dirichlet's box principle. It follows that for infinite values of $n$
$$ r_n \in M_n+\left(\log_{10} 3,\;\log_{10} 4\right), \qquad M_n\in\mathbb{N}^* $$
holds, so $ 10^{r_n} = a^n $ lies between $3\cdot 10^{M_n}$ and $4\cdot 10^{M_n}$ and the first decimal digit of $a^n$ is $3$.
Obviously you may replace $3$ with any digit $\in\{1,2,3,4,5,6,7,8,9\}$ and the same argument still applies. Moreover, with a minor fix (by working with $\log_{100}$, $\log_{1000}$ and so on) we may also prove that the initial substring of the decimal representation can be any substring not starting with a zero.
Comment: (+1) Nice! I was just thinking about using $\log_{10}(a)\notin \mathbb{Q}$ too, you are fast.
Comment: Can you explain how $r_n$ is dense in $(0,1)$ using the pigeonhole principle?
Comment: @Puzzled417: http://math.stackexchange.com/questions/843763/a-dense-set-on-0-1
Comment: @Puzzled417 http://math.stackexchange.com/questions/903142/for-an-irrational-number-a-the-fractional-part-of-na-for-n-in-mathbb-n-is This has been on this site several times.
Comment: How do you get $r_n \in M_n+\left(\log_{10} 3,\;\log_{10} 4\right), \qquad M_n\in\mathbb{N}^* $?
Comment: @Puzzled417 That's the consequence of $r_n$ being dense in $(0,1)$.
Comment: But that means that $r_n$ could lie in like $(4,5)$, which isn't a subset of $(0,1)$.
Comment: @Puzzled417 $r_n$ is considered modulo $1$. That means you can consider $r_n$ as a **fractional part** of $n\log_{10}(a)$.
Comment: @i707107 Right, and how can the fractional part lie outside of $[0,1)$?
Comment: @Puzzled417 No, that does not happen. A fractional part always lies in $(0,1)$.
Comment: @Puzzled417 I see your point. Maybe I didn't understand $r_n$ correctly. It seems that $r_n$ is **exactly** equals to $n\log_{10}(a)$, and its fractional parts are dense in $(0,1)$.
Comment: @JackD'Aurizio Also, I think $n$ is supposed to be a positive integer? So how are you getting $10^{r_n} = a^n$?
Comment: @Puzzled417: $$ 10^{r_n} = 10^{n\cdot \log_{10}(a)} = a^n.$$

Decimal representation begins with $N$


Mozilla Browser (Meta) button issue on closed click popup

Question: i faced this issue may be someone else also find it difficult to read button text
Answer: This issue has been fixed and will be corrected in the next production build. The issue arose from not declaring a [disabled] color within Magento's Meta theme. Sorry about that.
Answer: Totally agree with you, it's happening on Chrome too.
That would be an easy CSS fix:
input[type="submit"][disabled], input[type="button"][disabled], button[disabled], .button[disabled], a.button[disabled], a.button[disabled]:visited, .btn[disabled], .btn[disabled]:visited, input[type="submit"]:disabled, input[type="button"]:disabled, button:disabled, .button:disabled, a.button:disabled, a.button:visited:disabled, .btn:disabled, .btn:visited:disabled, input._disabled[type="submit"], input._disabled[type="button"], button._disabled, .button._disabled, a.button._disabled, a.button._disabled:visited, .btn._disabled, .btn._disabled:visited {
    background-color: light-grey;
    border-color: transparent;
    color: #717171;
}

Rendered result:
Comment: @QaisarSatti Haha. I appreciate the help! :D
Comment: you make work easy for @Hynes


await api call responding after unmounting of component | vue.js

Question: I have an method(doSomething) which will be called on mounted state and also have a CTA to unmount the component. Before the await call finish if user unmount the component with back CTA, the controller is still coming back to unmounted component. How to abort  the response coming back to the component.
Vue Component:
doSomething(){
   let data = await someApiCall();
   console.log(data)
}

Store.js(vuex)
someApiCall(){
  axios.get("apicall").then(res => res);
}

Answer: Instead of abandoning, you could stop the 'unmount CTA' being clickable in the first place - until the doSomething() method has been completed its fetch.
export default {
  data() {
      return {
          isFetching: false,
      }
  },
  methods: {
      async doSomething() {
          this.isFetching = true
          let data = await someApiCall()
      },
      myUnmount() {
          // Do your unmount
      },
  },
  async mounted(){
      await this.doSomething()
      this.isFetching = false
  }
}

And then bind this to the CTA;
<button @click="myUnmount()" :disabled="isFetching">Unmount</button>