How do I bundle the C source in a Raku distribution that uses NativeCall?

Question: I'm writing Raku bindings to a C library, but rather than require the users of the Raku code to install the C library on their own, I'd like to bundle the C code as part of the distribution (it's not such a widely distributed library).
I've read about a distribution's %?RESOURCES, and that seems like it would be useful. But I'm hazy on the specifics of how to apply it for this.
Can I bundle the C source code in the distribution, and specify some way for it to get compiled as part of the installation (eg. with zef)? Or would I need to bundle precompiled versions of the library, and get the code to choose the right one depending on the platform?
Or is this simply impossible, and I should just give users instructions on how to install the library separately?
Answer: It's possible, and there exists a module LibraryMake to ease the process.
For an example of a module using it, see Digest::SHA1::Native.


How to show a function is locally C^1 implies globally C1?

Question: Actually there is a series problem like
f(x)=sum(n=1 to ∞)[sin(nx^2)/1+n^3], the question was whether f(x) is C^1 or not.
This question has already answered, but a big issue of mine is I can't find any hint from those. There were told
It is enough to show f(x) is C^1 locally and hence it follows globally. But how?
I'm also aware of the the theorem
Rudin page 152 Theorem 7.17: Suppose  a sequence of functions, differentiable on [a, b] and such that {fn}  converges for some point  on [a,b]. If  {f'n}  converges uniformly on [a,b], then {fn} converges uniformly on [a,b] to f and lim(f'n)=f',for all a<= x<=b
But I don't know how it follows from this theorem.
Please help me find it out. Thanks in advance.
Answer: $f\in C^{1}$ means $f$ is differentiable and its derivative is continuous. This is same as saying that $f$ is differentiable at each point and its derivative is continuous at each point. To prove this fix a point $x$. If you know that $f$ is a $C^{1}$ function in some interval around $x$ then $f'$ is continuous at $x$ so we are done.


Setting a string from one destination to another

Question: I want to include the string "oldSummary" in the second richtextbox, however all of the summary's functionality belongs to a streamRead after opening a file. Is there a way for that when btn1 button is clicked, it will display the oldSummary string? At the moment it's blank due to it's global string set to "" but I want it to display the oldSummary string set in the mnuOpen button.
string oldSummary = "";
private void mnuOpen_Click(object sender, EventArgs e)
{

    //Load up file code which I remove for this example but goes here…

    //Add data from text file to rich text box
    richTextBox1.LoadFile(Chosen_File, RichTextBoxStreamType.PlainText);

    //Read lines of text in text file
    string textLine = "";
    int lineCount = 0;

    System.IO.StreamReader txtReader;
    txtReader = new System.IO.StreamReader(Chosen_File);

    do
    {
        textLine = textLine + txtReader.ReadLine() + " ";
        lineCount++;
    }
    //Read line until there is no more characters
    while (txtReader.Peek() != -1);

    //seperate certain characters in order to find words
    char[] seperator = (" " + nl).ToCharArray();

    //number of words, characters and include extra line breaks variable
    int numberOfWords = textLine.Split(seperator, StringSplitOptions.RemoveEmptyEntries).Length;

    int numberOfChar = textLine.Length - lineCount;

    string divider = "------------------------";

    //Unprocessed Summary
    string oldSummary = "Word Count: " + numberOfWords + "Characters Count: " + numberOfChar + divider;

    txtReader.Close();
}

private void btn1_Click(object sender, EventArgs e)
{
    string wholeText = "";
    string copyText = richTextBox1.Text;
    wholeText = oldSummary + copyText;
    richTextBox2.Text = wholeText;
}

Comment: A correct indentation of your code could help a lot to understand what's going on here
Comment: I have corrected the indentetion of your code, but some rogue close braces have to be removed, please check
Answer: If you want to use the global variable oldSummary then do not redeclare one with the same name inside the menu open event handler, just use the global one
//Unprocessed Summary
oldSummary = "Word Count: " + numberOfWords + "Characters Count: " + numberOfChar + divider;

Answer: Try replacing:
string oldSummary = "Word Count: " + numberOfWords + "Characters Count: " + numberOfChar + divider;

with:
oldSummary = "Word Count: " + numberOfWords + "Characters Count: " + numberOfChar + divider;

so that you assign the value to the class field used in btn1_Click.
Comment: unbelievable, spent hours trying to figure it out. Thanks


cannot start mysql 5.1 windows service under normal user account

Question: MySQL 5.1 service can start under Local System account or Administrator User account.
But MySQL 5.1 service cannot start under normal user account.
It gives:
Error 1067:The process terminated unexpectedly.

What could be the issue?
Answer: The most important thing is giving security permissions to normal user on MySQL Data folder.
Here is another simple way to solve the problem.

Create a new user group. eg. MySQL_Admins
Create a new user. eg. Mysql_user
Add Mysql_user under MySQL_Admins group.
Add following security permissions to MySQL_Admins on MySQL Data folder (you can find it in my.ini file)
Windows XP
datadir="C:/Documents and Settings/All Users/Application Data/MySQL/MySQL Server 5.1/data"
Windows Server 2008
datadir="C:/ProgramData/MySQL/MySQL Server 5.1/data"
a. Read & execute
b. List folder contents
c. Read
d. Write
Chage Log On as properties for MySQL Service to Mysql_user.
MySQL Service > Properties > Log On > This account > Select Mysql_user
Start MySQL Service
Comment: Can only one user be assigned the "Log On" property of the MySQL Service? Or can multiple users be assigned this?
Answer: To startMySQL service under normal user account,
user must have permission to start that service.
User should be at least Standard User.
Restricted user doesn't have sufficient permission to start service.
I  can solve doing following steps:

Create a new user group. eg. MySQL_Admins
Create a new user. eg. Mysql_user
Add Mysql_user under MySQL_Admins group.
Edit registry key permission
a. Give 'Full Control' Permission to MySQL_Admins Group for
    HKLM\SYSTEM\CurrentControlSet\Services\MySQL
b. Give 'Full Control' Permission to MySQL_Admins Group for
    HKLM\SYSTEM\CurrentControlSet\Services
c. Give 'Full Control' Permission to MySQL_Admins Group for
    HKLM\SOFTWARE\MySQL AB
Add following file security permission to MySQL_Admins Group on
C:\Program Files\MySQL\MySQL Server 5.1(MySQL Installation Path)
a. Read & execute
b. List folder contents
c. Read
Add Full control security permission to MySQL_Admins Group on MySQL Data Directory
(You can find in my.ini file)
Windows XP
datadir="C:/Documents and Settings/All Users/Application Data/MySQL/"
Windows Server 2008
datadir="C:/ProgramData/MySQL"
Chage Log On as properties for MySQL Service to Mysql_user.
MySQL Service > Properties > Log On > This account > Select Mysql_user
Log Off Admin account
After Log On again, MySQL Service will be started under Mysql_user User Name.
Answer: First step will be to check the permissions: Does the user you want to run MySQL have all the necessary access rights?
Comment: Which are "run as service".


The geometric interpretation of quaternion and Octanion

Question: Can anybody give me any useful link for the history of quaternion? The quaternion and Octanion are constructed but why other do not exist? What is the geometric interpretation of a quaternion?
Comment: See http://mathworld.wolfram.com/Quaternion.html
Comment: Other(bilinear associative operation without zero divisors) do not exist(besides usual, complex, quaternion and octanion multiplications), because of the arguments coming from the characteristic classes. It could be a quite strong and technical machinery depending on your background.
Answer: In the case of complex space we have two real perpendicular axex while in the case of Quaternion we have 2 complex axes and a quaternion is constructed basically by the multiplication of 2 complex numbers. Similarly octanions are constructed from quaternions. But geometrically it has been proved that no further such extension is possible.


How to change a views block ID attribute to use it as anchor

Question: I have a views block with id=block-views-block-services-block-1 which I used in the menu link.
The menu link is now shown as https://example.com/gb/#block-views-block-services-block-1
As you can see it's really not looking nice with long hyphend words. Is there any easy way to change it to something like this https://example.com/gb/#services
I read an answer for Drupal 7 where we need to edit template.php to change the ID. But in Drupal 8 it seems that template.php is replaced with twig.html. I'm not very sure as I'm new to Drupal.
Could anyone please explain few steps on how to do it?
Answer: you should place this function in your themes/YOURTHEME/YOURTHEME.theme file:
function YOURTHEME_preprocess_block(&$variables) {
  dump($variables);
}

and you will see the name of your block. You have to look for block_html_id. Based on your description the value of the block_html_id will be block-views-block-services-block-1.
Then you can simply owerdefine it this way:
function YOURTHEME_preprocess_block(&$variables) {
  if ($variables['block_html_id'] == "block-views-block-services-block-1") {
    $variables['block_html_id'] = "services";
  }
}

Or you can create a custom module and you can put this function there too. In that case you have to replace the YOURTHEME to the name of the custom module.
Comment: I cannot get this to work in Bootstrap theme. I have cleared cache several times, but the ID never changes.

function bootstrap_mytheme_preprocess_block(&$variables) {
  if ($variables['block_html_id'] == "block-views-block-homeblocks-block-1") {
    $variables['block_html_id'] = "about";
  }
}
Comment: Are you sure that this `bootstrap_mytheme_preprocess_block` function is called? What do you see if you dump the `$variables` before the condition?


Filtro no dplyr com restrição pelo valor máximo de variável do db gapminder

Question: Estou fazendo o filtro no df gapminder, gerando um df vazio quando utilizo a variável gdpPercap:
library(gapminder) # versão 0.2.0

library(dplyr)  # versão 0.7.2

gapminder %>%
  filter(year == 2007, gdpPercap==max(gdpPercap))

# A tibble: 0 x 6

# ... with 6 variables: country <fctr>, continent <fctr>, year <int>, lifeExp <dbl>, pop <int>, gdpPercap <dbl>

Se eu altero a variável da consulta, aparece o resultado esperado
gapminder %>%
  filter(year == 2007, pop==max(pop))

# A tibble: 1 x 6

# country continent  year lifeExp   pop      gdpPercap

#1   China      Asia  2007  72.961 1318683096  4959.115

Seria um bug do dplyr? Estou usando RStudio (Version 1.0.143) e MRO (3.3.3).
Answer: O resultado está correto. O comando
gapminder %>%
  filter(year == 2007, gdpPercap==max(gdpPercap))

vai te retornar todas as linhas do data frame gapminder que ocorreram no year de 2007 e cujo gdpPercap seja igual ao máximo valor de gdpPercap. Acontece que nenhum país satisfaz esta condição. Veja o seguinte:
gapminder %>%
  group_by(year) %>%
  summarise(max(gdpPercap))
# A tibble: 12 x 2
    year `max(gdpPercap)`
   <int>            <dbl>
 1  1952        108382.35
 2  1957        113523.13
 3  1962         95458.11
 4  1967         80894.88
 5  1972        109347.87
 6  1977         59265.48
 7  1982         33693.18
 8  1987         31540.97
 9  1992         34932.92
10  1997         41283.16
11  2002         44683.98
12  2007         49357.19

O valor máximo de gdpPercap ocorreu em 1957. Assim, não faz sentido perguntar quais países obtiveram este valor em 2007. Perceba que o comando abaixo, com o ano de 1957, retorna um resultado não-vazio:
gapminder %>%
  filter(year == 1957, gdpPercap==max(gdpPercap))
# A tibble: 1 x 6
  country continent  year lifeExp    pop gdpPercap
   <fctr>    <fctr> <int>   <dbl>  <int>     <dbl>
1  Kuwait      Asia  1957  58.033 212846  113523.1

Se o tu objetivo era encontrar o país com maior gdpPercap em 2007, tu deve primeiro agrupar os dados de acordo com o ano:
gapminder %>%
  group_by(year) %>%
  filter(year==2007, gdpPercap==max(gdpPercap))
# A tibble: 1 x 6
# Groups:   year [1]
  country continent  year lifeExp     pop gdpPercap
   <fctr>    <fctr> <int>   <dbl>   <int>     <dbl>
1  Norway    Europe  2007  80.196 4627926  49357.19


How to find out if there is any correlation between a yes/no question and Likert scale data?

Question: I have used a survey to research willingness to pay regarding virtual goods in videogames. For this, I have asked the respondents a couple of questions via Likert scale, to get their opinions on certain statements. I then asked them if they had ever purchased virtual goods before.
In this case, I want to see if satisfaction with the game leads to a higher likeliness of purchasing virtual goods. How would I go about testing this statistically? My first idea was to convert my Likert data to numerical values, E. G. from strongly disagree = 1 to strongly agree = 5. However I can't seem to find which type of test I should use to then see if there is any correlation between a higher satisfaction value and buying virtual goods.
Answer: Strongly disagree to strongly agree is ordinal data. There is a large set of methods to use with ordinal data: spearman correlation or Kendall's tau may be the most prominent ones.
Answer: You could use logistic regression. If you represent your likert, that is ordinal, predictor with numerical codes $1,2, \dotsc$, then use also a quadratic term to represent possible nonlinearity in the effects, or maybe even with a spline.
For an example with a monotone spline, see Looking for function to fit sigmoid-like curve.  For some other ideas see How do you estimate correlations between ordinal and binary data in SPSS? and specifically Correlations between continuous and categorical (nominal) variables.
Comment: The problem I'm struggling with is that when I look at any of the tests online, people are always using two numeric variables. How would I go about calculating the Spearman coefficient for example, with Yes/No data?
Comment: You shouldn't use Spearman, read also https://stats.stackexchange.com/questions/102778/correlations-between-continuous-and-categorical-nominal-variables
Comment: The spearman correlation function in base R is corrected for this, no?
Comment: Surely this is answering the inverse question: are people more likely to be satisfied with the game if they are willing to spend money in it?


Exact copy of machine code runs 50% slower than the original function

Question: I've been experimenting a bit with execution from RAM and flash memory on embedded systems. For rapid prototyping and testing I'm currently using an Arduino Due (SAM3X8E ARM Cortex-M3). As far as I can see, the Arduino runtime and bootloader should make no difference here.
Here is the issue: I have a function (calc) which is written in ARM Thumb Assembly. calc calculates a number and returns it. (>1s runtime for the given input) Now I manually extracted the assembled machine code of that function and put it as raw bytes into another function. Both functions are confirmed to reside in flash memory (Address 0x80149 and 0x8017D, right next to each other). This has been confirmed both via disassembly and
a runtime check.
void setup() {
  Serial.begin(115200);
  timeFnc(calc);
  timeFnc(calc2);
}

void timeFnc(int (*functionPtr)(void)) {
  unsigned long time1 = micros();

  int res = (*functionPtr)();

  unsigned long time2 = micros();
  Serial.print("Address: ");
  Serial.print((unsigned int)functionPtr);
  Serial.print(" Res: ");
  Serial.print(res);
  Serial.print(": ");
  Serial.print(time2-time1);
  Serial.println("us");

}

int calc() {
   asm volatile(
      "movs r1, #33 \n\t"
      "push {r1,r4,r5,lr} \n\t"
      "bl .in \n\t"
      "pop {r1,r4,r5,lr} \n\t"
      "bx lr \n\t"

      ".in: \n\t"
      "movs r5,#1 \n\t"
      "subs r1, r1, #1 \n\t"
      "cmp r1, #2 \n\t"
      "blo .lblb \n\t"
      "movs r5,#1 \n\t"

      ".lbla: \n\t"
      "push {r1, r5, lr} \n\t"
      "bl .in \n\t"
      "pop {r1, r5, lr} \n\t"
      "adds r5,r0 \n\t"
      "subs r1,#2 \n\t"
      "cmp r1,#1 \n\t"
      "bhi .lbla \n\t"
      ".lblb: \n\t"
      "movs r0,r5 \n\t"
      "bx lr \n\t"
      ::
   ); //redundant auto generated bx lr, aware of that
}

int calc2() {
  asm volatile(
    ".word  0xB5322121 \n\t"
    ".word  0xF803F000 \n\t"
    ".word  0x4032E8BD \n\t"
    ".word  0x25014770 \n\t"

    ".word  0x29023901 \n\t"
    ".word  0x800BF0C0 \n\t"
    ".word  0xB5222501 \n\t"
    ".word  0xFFF7F7FF \n\t"
    ".word  0x4022E8BD \n\t"
    ".word  0x3902182D \n\t"
    ".word  0xF63F2901 \n\t"
    ".word  0x0028AFF6 \n\t"
    ".word  0x47704770 \n\t"
  );
}

void loop() {

}

Output of the above program on the Arduino Due target is:
Address: 524617 Res: 3524578: 1338254us
Address: 524669 Res: 3524578: 2058819us

So we confirm the results to be equal and the address during runtime to be as expected. Execution of the manually entered machine code function is 50% slower.
Disassembly with arm-none-eabi-objdump further confirms the respective addresses, flash memory residency and equality of the machine code (Note endianness and byte grouping!):
00080148 <_Z4calcv>:
   80148:   2121        movs    r1, #33 ; 0x21
   8014a:   b532        push    {r1, r4, r5, lr}
   8014c:   f000 f803   bl  80156 <.in>
   80150:   e8bd 4032   ldmia.w sp!, {r1, r4, r5, lr}
   80154:   4770        bx  lr

00080156 <.in>:
   80156:   2501        movs    r5, #1
   80158:   3901        subs    r1, #1
   8015a:   2902        cmp r1, #2
   8015c:   f0c0 800b   bcc.w   80176 <.lblb>
   80160:   2501        movs    r5, #1

00080162 <.lbla>:
   80162:   b522        push    {r1, r5, lr}
   80164:   f7ff fff7   bl  80156 <.in>
   80168:   e8bd 4022   ldmia.w sp!, {r1, r5, lr}
   8016c:   182d        adds    r5, r5, r0
   8016e:   3902        subs    r1, #2
   80170:   2901        cmp r1, #1
   80172:   f63f aff6   bhi.w   80162 <.lbla>

00080176 <.lblb>:
   80176:   0028        movs    r0, r5
   80178:   4770        bx  lr
}
   8017a:   4770        bx  lr

0008017c <_Z5calc2v>:
   8017c:   b5322121    .word   0xb5322121
   80180:   f803f000    .word   0xf803f000
   80184:   4032e8bd    .word   0x4032e8bd
   80188:   25014770    .word   0x25014770
   8018c:   29023901    .word   0x29023901
   80190:   800bf0c0    .word   0x800bf0c0
   80194:   b5222501    .word   0xb5222501
   80198:   fff7f7ff    .word   0xfff7f7ff
   8019c:   4022e8bd    .word   0x4022e8bd
   801a0:   3902182d    .word   0x3902182d
   801a4:   f63f2901    .word   0xf63f2901
   801a8:   0028aff6    .word   0x0028aff6
   801ac:   47704770    .word   0x47704770
}
   801b0:   4770        bx  lr
    ...

We can further confirm the analogously used calling convention:
00080234 <setup>:
void setup() {
   80234:   b508        push    {r3, lr}
  Serial.begin(115200);
   80236:   4806        ldr r0, [pc, #24]   ; (80250 <setup+0x1c>)
   80238:   f44f 31e1   mov.w   r1, #115200 ; 0x1c200
   8023c:   f000 fcb4   bl  80ba8 <_ZN9UARTClass5beginEm>
  timeFnc(calc);
   80240:   4804        ldr r0, [pc, #16]   ; (80254 <setup+0x20>)
   80242:   f7ff ffb7   bl  801b4 <_Z7timeFncPFivE>
}
   80246:   e8bd 4008   ldmia.w sp!, {r3, lr}
  timeFnc(calc2);
   8024a:   4803        ldr r0, [pc, #12]   ; (80258 <setup+0x24>)
   8024c:   f7ff bfb2   b.w 801b4 <_Z7timeFncPFivE>
   80250:   200705cc    .word   0x200705cc
   80254:   00080149    .word   0x00080149
   80258:   0008017d    .word   0x0008017d

I can rule out this being due to some kind of speculative fetch (which the Cortex-M3 seemingly has!) or interrupts. (EDIT: NOPE, I can't. Probably some kind of prefetch) Changing the order of execution or adding function calls in between does not change the result. What could be the culprit here?

EDIT:
After changing the alignment of the machine code function (insert nops as a prologue) I get the following results:
+16bit for calc2:
Address: 524617 Res: 3524578: 1102257us
Address: 524669 Res: 3524578: 1846968us

+32bit for calc2:
Address: 524617 Res: 3524578: 1102257us
Address: 524669 Res: 3524578: 1535424us

+48bit for calc2:
Address: 524617 Res: 3524578: 1102155us
Address: 524669 Res: 3524578: 1413180us

+64bit for calc2:
Address: 524617 Res: 3524578: 1102155us
Address: 524669 Res: 3524578: 1346606us

+80bit for calc2:
Address: 524617 Res: 3524578: 1102145us
Address: 524669 Res: 3524578: 1180105us

EDIT2:
Only running calc:
Address: 524617 Res: 3524578: 1102155us

Only running calc2:
Address: 524617 Res: 3524578: 1102257us

Changing the order:
Address: 524669 Res: 3524578: 1554160us
Address: 524617 Res: 3524578: 1102211us

EDIT3:
Adding .p2align 4 before label .in for calc only, separate execution:
Address: 524625 Res: 3524578: 1413185us

Both as in original benchmark:
Address: 524625 Res: 3524578: 1413185us
Address: 524689 Res: 3524578: 1535424us

EDIT4: Reversing the position in flash completely changes the outcome. -> Linear prefetch?
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/203402/discussion-on-question-by-fscheidl-exact-copy-of-machine-code-runs-50-slower-th).
Answer: The speed of code execution from flash depends on the number of wait cycles and code alignment for each branch target. In this and similar processors, like STM32F103, flash needs 3 wait cycles when the core runs at the highest frequency. This means each taken branch may take between 2 and 5 cycles, which might affect total run time.
To compensate for FLASH slowness, these processors have a wide FLASH bus and a fetch buffer. SAM3X has a pair of 128-bit instruction buffers, which seem to be populated in a prefetch pattern [1].
To optimize a tight loop, try to fit into a 32-byte code block and align it at 16-byte boundary (or better 32, just in case). Also, it could be a good idea to check if FLASH parameters are set up correctly, i.e. prefetch is enabled and bus width is set to 128 bit, in this MCU. Copying code to RAM may be an option, but it's a pain and can actually slow things down, compared to properly working fetch buffers.
[1] http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf, page 294, Figures 18-2, 18-3.


Relation with one content type to other

Question: How can I give relation once content type to other. Eg If I have a product and the product sub items. I need to make a product content and a product_sub_item content type. Also need to select the product while creating the sub item. How to achieve this relation
Answer: Check out the module "References". It allows you to create a field where you can reference on other content types and nodes.
Answer: In addition, you might also want to take a look at the module Relation which looks to have a brighter future in terms of active maintenance and integration with other Drupal contribs. Another module that will come handy is Rules.
For both modules there are good introductory screencasts available by Johan Falk on http://dev.nodeone.se/sv
Answer: I discuss some of the different options available here: http://drupal.org/node/1293792#comment-5275780
This discussion is particularly relevant if you care about back-references.  For your use case, perhaps references & cnr would give the best user experience.
Answer: Using node_references cck module we can achive this. In manage fields need to create a new field and select the type node reference and the parent type to be referenced
Comment: When you ask a question, you should specify whether you mean Drupal 6 or Drupal 7.  This answer is for Drupal 6; the other answers above all presumed Drupal 7.

Relation with one content type to other


Dados não estão sendo carregados na Tabela

Question: Boa Tarde,
Gostaria de saber como posso fazer minha lista de registros ser carregada na tabela no mesmo momento que o gráfico é carregado por AJAX, porque atualmente no meu model mostra que tem registros porém não aparecem na tabela(View), segue as cods/imgs para ajudar na compreensão.
EX:
Controller:
<code>    private DBConnection banco = new DBConnection();

    // GET: TotalSMS

    public ActionResult Index()
    {

        #region "URL"
        var e = this.RouteData.Values;

        string controllerName = (string)e["controller"];
        string actionName = (string)e["action"];

        ViewBag.Message = controllerName;
        ViewBag.Acao = actionName;

        ListaCampanhas();
        #endregion

        var codCampanha = TempData["codCampanha"];

        if (codCampanha == null)
        {
            return View(banco.Database.SqlQuery<QtdSmsEnviadoPorMes>("SP_CARREGA_GRAFICO_SMS @IDCampanha", new SqlParameter("@IDCampanha", '0')).ToList());
        }
        else
        {
            return View(TempData["_list"]);
        }
    }

    public JsonResult GetDados(int campanhaSelecionada)
    {

        TempData["codCampanha"] = campanhaSelecionada;
        var result = banco.Database.SqlQuery<QtdSmsEnviadoPorMes>("SP_CARREGA_GRAFICO_SMS @IDCampanha", new SqlParameter("@IDCampanha", campanhaSelecionada)).ToList();
        TempData["_list"] = result;

        return Json(result);
    }
</code>
Class:
<code>public class QtdSmsEnviadoPorMes
{

    [Key]
    public int QtdEnviados { get; set; }
    public int QtdConfirmados { get; set; }
    public int QtdNaoConfirmados { get; set; }
    public int QtdNaoRecebidos { get; set; }
    public int MES { get; set; }
    public int ANO { get; set; }

}
</code>
SCRIPT:
<code>//Primeiro Load
$("#campanhaTotalSmsEnv").val('');
//Apos a alteração de Campanha
$("#campanhaTotalSmsEnv").change(function () {

    var campanhaSelecionada = $("#campanhaTotalSmsEnv option:selected").val();

    $.ajax({
        dataType: "json",
        type: "POST",
        url: "/TotalSMS/GetDados",
        data: { campanhaSelecionada: campanhaSelecionada },
        success: function (dados) {

            $(dados).each(function (i) {

                var chart = new Chart(ctx, {
                    // The type of chart we want to create
                    type: 'line',

                    // The data for our dataset
                    data: {
                        labels: ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"],
                        datasets:
                        [

                            {
                                label: "Enviado",
                                backgroundColor: 'transparent',
                                //backgroundColor: 'rgb(255, 99, 132)',
                                borderColor: 'rgb(75, 192,192)',
                                borderWidth: 3,
                                data: [
                                    dados[0].QtdEnviados, dados[1].QtdEnviados, dados[2].QtdEnviados, dados[3].QtdEnviados, dados[4].QtdEnviados,
                                    dados[5].QtdEnviados, dados[6].QtdEnviados, dados[7].QtdEnviados, dados[8].QtdEnviados, dados[9].QtdEnviados,
                                    dados[10].QtdEnviados, dados[11].QtdEnviados
                                ],
                            }, {
                                label: "Confirmado",
                                backgroundColor: 'transparent',
                                //backgroundColor: 'rgb(255, 99, 132)',
                                borderColor: 'rgb(54, 162, 235)',
                                borderWidth: 3,

                                data: [
                                    dados[0].QtdConfirmados, dados[1].QtdConfirmados, dados[2].QtdConfirmados, dados[3].QtdConfirmados, dados[4].QtdConfirmados,
                                    dados[5].QtdConfirmados, dados[6].QtdConfirmados, dados[7].QtdConfirmados, dados[8].QtdConfirmados, dados[9].QtdConfirmados,
                                    dados[10].QtdConfirmados, dados[11].QtdConfirmados
                                ],
                            },
                            {
                                label: "Não Confirmado",
                                backgroundColor: 'transparent',
                                //backgroundColor: 'rgb(255, 205, 86,0.3)',
                                borderColor: 'rgb(255, 205, 86)',// rgb(201, 203, 207)
                                borderWidth: 3,
                                data: [
                                    dados[0].QtdNaoConfirmados, dados[1].QtdNaoConfirmados, dados[2].QtdNaoConfirmados, dados[3].QtdNaoConfirmados, dados[4].QtdNaoConfirmados,
                                    dados[5].QtdNaoConfirmados, dados[6].QtdNaoConfirmados, dados[7].QtdNaoConfirmados, dados[8].QtdNaoConfirmados, dados[9].QtdNaoConfirmados,
                                    dados[10].QtdNaoConfirmados, dados[11].QtdNaoConfirmados
                                ],
                            },
                            {
                                label: "Não Recebida",
                                backgroundColor: 'transparent',
                                //backgroundColor: 'rgb(255, 99, 132,0.3)',
                                borderColor: 'rgb(255, 99, 132)', //rgb(228, 33, 33)
                                borderWidth: 3,
                                data: [
                                    dados[0].QtdNaoRecebidos, dados[1].QtdNaoRecebidos, dados[2].QtdNaoRecebidos, dados[3].QtdNaoRecebidos, dados[4].QtdNaoRecebidos,
                                    dados[5].QtdNaoRecebidos, dados[6].QtdNaoRecebidos, dados[7].QtdNaoRecebidos, dados[8].QtdNaoRecebidos, dados[9].QtdNaoRecebidos,
                                    dados[10].QtdNaoRecebidos, dados[11].QtdNaoRecebidos
                                ],
                            },

                        ]
                    },

                    // Configuration options go here
                    options: {
                        title: {
                            display: true,
                            fontSize: 20,
                            text: "Mês"
                        }
                    }
                });

            });
        }
    });

});
</code>
IMGS:
O Usuário selecionará o tipo da campanha, após selecionar automaticamente tenho que carregar o gráfico e carregar a tabela baseado no resultado da procedure em cima daquela campanha.
Porém atualmente, apenas o gráfico esta sendo carregado.
as informações são passadas para o Model porém não mostra nada !

Model:
Comment: Qual é o nome desse plugin mesmo que vc tá usando?
Comment: @sam é o charts.js
Comment: Essa tabela faz parte do plugin ou apenas os gráficos? Tipo, vc está criando a tabela por conta própria ou ela é criada pelo plugin juntamente com os gráficos?
Comment: São Separados, um Método pra cada @sam
Comment: Se não me falha a memória o TempData[""] é apagado logo após ser lido...
Comment: @LeandroAngelo Oque você me sugere a fazer ?
Comment: Você poderia utilizar ViewModels ou ViewBags
Answer: Cara, olhando seu código o que me parece é que o seu gráfico é carregado dinamicamente com AJAX porém a sua tabela abaixo segue o fluxo normal do mvc. O ideal era carregar os dois da mesma forma, os dois com AJAX ou os dois com o fluxo normal do mvc indo no servidor e voltando.


Github não esta registrando contributions

Question: Estou com o seguinte problema com o Github, ele não esta registrando minhas contributions apesar de que no repositório mostra que as atualizações estão sendo realizadas sem nenhum problema.Alguem sabe o que pode ser?Atualmente estou usando o visual code.

Comment: Você está realizando esses commits em um branche, ou no repositório master?
Comment: No repositório master.
Comment: Só para confirmar, posta seu github aí.
Porém acredito que possam haver duas possibilidades, seu repositório é privado e você não ativou a opção 'Include private contributions on my profile', nas configurações da sua conta do GitHub.
Ou o e-mail que você está utilizando para commitar não está associado a sua conta do GitHub.
Comment: Meu Git  //github.com/Richar2
Comment: Mas o estranho e que um repositório que estava fazendo os registros normalmente também parou.
Answer: Rode esse comando no terminal git config --global user.name e veja se está aparecendo 'Richard' ou 'Richar2', se aparecer 'Richard', rode o seguinte comando git config --global user.name "Richar2" e depois tente commitar algo novamente, e veja se está contabilizando suas contribuições.
O motivo disso é que os seus últimos commits vieram com o nome de usuário Richard, porém seu nome no GitHub está como Richar2, e quando os mesmos estão diferentes, os commits realizados não são considerados seus.
Caso isso não resolva seu problema, também confira seu email git config --global user.email e veja se o e-mail configurado é o mesmo que você tem vinculado a sua conta do github, caso não for, rode o seguinte comando git config --global user.email seuemailaqui. (Mas acredito que o e-mail já está correto)
Comment: Valeu mesmo Marcelolx ! O problema era no nome mesmo.
Comment: Show de bola! :)


Cannot use angular material datepicker

Question: I try to use angular material datepicker.
The component html file where I try to use it:
<mat-form-field appearance="fill">
    <mat-label>Choose a date</mat-label>
    <input matInput [matDatepicker]="picker">
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

app.module.ts file:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { DashboardComponent } from './components/pages/dashboard/dashboard.component';
import { AppRoutingModule } from './app-routing.module';
import { NavComponent } from './components/pages/dashboard/nav/nav.component';
import { DefaultComponent } from './components/pages/dashboard/default/default.component';
import { ChartComponent } from './components/pages/dashboard/chart/chart.component';
import { UploadComponent } from './components/pages/dashboard/upload/upload.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ReactiveFormsModule } from '@angular/forms';
import { MatDatepickerModule } from '@angular/material/datepicker';

@NgModule({
  declarations: [
    AppComponent,
    DashboardComponent,
    NavComponent,
    DefaultComponent,
    ChartComponent,
    UploadComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    ReactiveFormsModule,
    MatDatepickerModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

The error I get: error NG8001: 'mat-form-field' is not a known element.
But, as the angular material datepicker doucumentation states, I only need to import:
import { MatDatepickerModule } from '@angular/material/datepicker'; as I did.
edit:
After fixing imports,
I get no errors, but also don't get it work.
All I see is:

marked by arrow - is the place where the datepicker is placed. But I cant see it work. why?
Answer: You need below modules also
import { FormGroup, FormControl, FormsModule, ReactiveFormsModule } from '@angular/forms';

Comment: Error: `Appears in the NgModule.imports of AppModule, but
could not be resolved to an NgModule class.`
Comment: After reset `ng serve` it worked. But no fully. Look at edit.
Answer: You have wrapped the date picker in a <mat-form-field>, you must also import
import { MatFormFieldModule } from '@angular/material/form-field';

and add it to your imports array,
as seen here in the full example of the snippet you have copied and pasted.
https://stackblitz.com/angular/vnydardxnkq?file=src%2Fmain.ts
Comment: Got error: `ERROR in node_modules/@angular/material/form-field/form-field-module.d.ts:8:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class.`
Comment: After reset ng serve it worked. But no fully. Look at edit.

Cannot use angular material datepicker


Master method - polynomially and asymptotically comparison

Question: This might be a trivial question but want to ensure that I had sound understanding.
In the master method, when we try to solve recurrences, we typically compare two functions (asymptotically and polynomially) to determine which case of the master method is applicable.
For example, comparing $f(n)=n$ with $g(n)=n\log n$, we can say that $g(n)$ is asymptotically larger than $f(n)$, but the polynomial relation between the two functions cannot be determined because the ratio between the two functions is $\log n$ (which less than polynomial).
How about comparing $f_1(n)=n$ with $g_1(n)=n+\log n$? I expect $f_1(n)$ and $g_1(n)$ to be equal (asymptotically and polynomially) because $g_1(n) \in O(n)$. Right?
Answer: It depends on how you define asymptotic equivalence, but assuming the standard definition, which is that $f \sim g$ if $\lim_{n \to \infty} \frac{f}{g} = 1,$ then we have at once that $n \sim n + \log n$, since $\lim_{n \to \infty} \frac{n + \log n}{n} = \lim_{n \to \infty} 1 + \frac{\log n}{n} = 1$.
Indeed, this limit of the ratio ($1$) turns out to be a polynomial, so they are also polynomially equivalent per your definition.


How to use NSCursor to display custom cursor

Question: I am trying to use custom cursor in my game using nscursor.  I use following code

//While initializing openglview
    mCustomCursor = [[NSCursor alloc] initWithImage:image hotSpot:NSZeroPoint];
    [image release];
[mCustomCursor set]

I am setting cursor rect in resetcursorrect method

- (void)resetCursorRects
{

    [self  addCursorRect:currentViewPortRect cursor:[NSCursor currentCursor]];

}

Custom cursor appears, It is not consistent, at times it switches back to system cursor (for alerts), some times it comes back and sometime not. It is  so confusing. I am not sure if I should use 'setOnMouseEntered', 'pop'. What is the standard way to use nscursor and change it dynamically.
Answer: You're changing the cursor to the current cursor, which isn't changing it at all. To display your own custom cursor, you must pass your custom cursor when creating the cursor rect.
Comment: @shakthi: You generally shouldn't, and the same goes for `-[NSCursor set]`. When using a cursor rect, you don't need to and shouldn't change the cursor manually—that's what the cursor rect is for. Don't pass `currentCursor` to `addCursorRect:cursor:`; the point of adding a cursor rect is to change the cursor when the user passes over it—changing the current cursor to the current cursor makes no sense. Just add the cursor rect with your custom cursor.
Comment: Agreed, But when should I use [NSCursor pop] ,[NSCursor push]? If I used [NSCursor push] can I use ` [self  addCursorRect:currentViewPortRect cursor:[NSCursor currentCursor]];`
Comment: Thanks a LOT. I was struggling for a week to make it straight.
Comment: '@'Peter:How can I change cursor efficiently when user presses mouse button change it back when he releases? Right now I am calling  '[[view window] invalidateCursorRectsForView:view];'. It works fine but is it the right method?
Comment: @shakthi: No; I'm not sure why you want to do that, but assuming you have a good reason, that's actually a case in which to use push and pop.
Comment: Its actually a game. I need to implement drag and drop of some objects. I want to use the openHandCursor before picking, the closeHandCursor while dragging and again  the openHandCursor after dropping.
Comment: @shakthi: Yup, sounds good. Use a cursor rect for the open-hand, and push the closed hand when the drag begins and pop it when it ends.
Comment: Cursor rect method is not working when I have nested cursor rects. Moment  I added nested rect and moved the (mouse) cursor from inner most cursor rect to the outer rect it changes to system cursor. The behavior will correct when I move the cursor out of the screen and then inside.


Problema na instalação do AngularJs

Question: Estou com problema para instalar o AngularJs, mas tenho quase certeza que o que esta errado é o caminho do src e onde coloco os arquivos do angular (em qual pasta).
Se possível, informe;

Quais os arquivos do Angular eu preciso?
Em qual pasta eu coloco os arquivos do angular?
Qual é o caminho que descrevo no src?
Comment: Qual versão do Angular você está tenta do usar?
Comment: Seja bem-vindo ao StackOverflow em Português. Uma boa prática para iniciarmos uma discussão saudável é ler o [Guia de Como Perguntar](http://pt.stackoverflow.com/help/asking). Comece seguindo estas recomendações, principalmente sabendo quais os tipos de perguntas deve fazer, como criar um exemplo mínimo que seja completo e verificável e até mesmo o que fazer quando alguém te responder.
Answer: O único arquivo necessário é o angular.js ou o angular.min.js. Se você estiver usando o arquivo do CDN ficará assim:

Se você estiver usando o arquivo que baixou da página oficial você precisa coloca-lo em algum local onde seja possível acessá-lo externamente. Digamos que você coloque na raiz do seu projeto, então a importação ficará assim:

Problema na instalação do AngularJs


Automate installation of msodbcsql with puppet

Question: To install msodbcsql that comes with mssql-tools that are needed to use the PHP Microsoft SQL Driver for Linux the following command is needed
sudo ACCEPT_EULA=Y apt-get install mssql-tools

However when installing this with Puppet, this fails, the puppet code currently used
package { 'mssql-tools'      : ensure => latest, }

But this returns an error:
ERROR: The EULA was not accepted. Installation aborted.

What would be needed so Puppet can successfully install this package.
I already tried setting a environment variable before calling the package command.
Exec { environment => [ "ACCEPT_EULA=Y" ] }

Microsoft's installation instructions are here:
https://blogs.msdn.microsoft.com/sqlnativeclient/2017/02/04/odbc-driver-13-1-for-linux-released/
And this is the driverpage:
https://www.microsoft.com/en-us/sql-server/developer-get-started/php/ubuntu/
Comment: When doing sudo apt-get install mssql-tools a ncurses window pops up with two boxes, Yes and No, the default selected is No. So I don't know how to use the responsefile from package to correctly select the Yes field and press enter, backspace tab and the arrow keys can put the selected field on yes.
Answer: It appears that this is a feature that was requested; Run the package entity with an environment value.
But since there is a feature freeze this will not be implemented in puppet 4.x (https://projects.puppetlabs.com/issues/6400)
The workaround is to not use the package entity but the exec entity:
exec { "/usr/bin/apt-get -yq install msodbcsql":
  environment => "ACCEPT_EULA=Y",
  unless => "/usr/bin/dpkg -l msodbcsql | tail -1 | grep ^ii",
}

Where unless is used to make it idempotent to not run if the package is already installed.
Disadvantage of this method is that this only works when using apt-get if you would want this to work on other systems as well you should provide an $osfamily with if statement to use the correct package manager.


"Rigorous" definition of Cartesian coordinates

Question: I, like most, first learned about Cartesian coordinates very early on in my educational career, and so the most instructional way to think about them was that you place down some perpendicular lines and measure the perpendicular distance from each line to get your coordinates; in other words, an operational definition. Now that I'm much farther along in my education, though, I wonder whether or not there's another, more "rigorous" way to define Cartesian coordinates, perhaps using the idea of a coordinate system as a mapping? Or is my question a bit pointless, since we already have the operational definition?
Comment: One can treat $\Bbb R^n$ as the $n$-fold Cartesian product of the sets $\Bbb R$. This might be what you're looking for.
Comment: Perhaps you should write down a list of properties you want Cartesian coordinates to have, and then it'll be easier to give the concept you're looking for.
Comment: *Or* one can treat $\mathbb R^n$ as the set of functions from $n = \{0,1,\dotsc,n-1\}$ (i.e. the von Neumann definition of ordinals) to $\mathbb R$ under coordinate-wise addition. Of course that would be right at home in the classic book "[Mathematics Made Difficult](https://en.wikipedia.org/wiki/Mathematics_Made_Difficult)".
Comment: Perhaps! But unfortunately, I'm still not entirely sure how to specify Cartesian coordinates as distinct from, say, spherical coordinates, or indeed any other coordinate system, even in higher dimensions. Cartesian coordinates come from an orthonormal basis, for instance, but I'm not sure how one might encode that into a rigorous definition.
Comment: @EtaZetaTheta So, did you find what you wanted? If not, you should post that set of criteria in the question itself; if so, you should write up your conclusion, and accept your own answer.
Comment: @Mike Very true, I've started doing so and I think that might be what I needed! Thank you, I would give you reputation if I could!
Answer: One formalization of the intuitive notion of a coordinate system is the rigorous notion of a chart on a manifold. This formalizes the notion of a local coordinate system, where our coordinates aren't globally well-defined and only make sense in some particular region; this is the notion of coordinates one needs to use in physics to understand, for example, relativity. If you want to get perpendicular lines and so forth into the game your manifold needs to be a Riemannian manifold.
Answer: I'm also surprised not to find any definition of Cartesian coordinate, so let's suggest this (personal and most simple) definition:

A cartesian coordinate on a Euclidean space E (finite dimensional $\mathbb{R}$ vector space, with a scalar product) is a "global chart" = Euclidean space isomorphism = isometry from $E$ to $\mathbb{R}^n$
Answer: If you're thinking about manifolds, it's most useful to think about how you can write the metric for the coordinate system: if it can be written as g_ab = diag(+/- 1, +/-1 , ...) then you're in Cartesians. That immediately give you the line element, in the positive case being the familiar Pythagorean addition of ds^2 = dx^2 + dy^2 + ... . The negative case is important in pseudo-Euclidian manifolds.
Answer: Based on my experience superimposing Cartesian coordinate systems on a multitude of practical problems, these are the key elements in the process:
1) Units.  The coordinate numerics appeal to physical distances, so you must choose what physical distance your coordinate unit represents (and use the same units in all dimensions).
2) Origin.  You have to pin down the location for your origin.
3) Axes directions. You have to choose axis reference directions.
a) For a 2D system, you have to choose the + x-axis based on some reference beacon or marker.  The +y-axis will be 90 deg. CCW from the + x-axis.
b) For a 3D system, you have to choose 2 out of the 3 axis directions. The 3rd axis will depend on choice of the first two.  To follow convention, the 3 axes must be mutually orthogonal, and obey the right-hand rule:
<code> x_dir  x  y_dir  --> z_dir
</code>
Where x_dir and y_dir are axis direction vectors [ 1, 0, 0 ]  and [0, 1, 0 ]
and z_dir is [ 0, 0, 1 ] and "x" is the right-handed 3D vector cross product.
Before you can define a mapping, you must have some kind of reference coordinate system (to express the mapping in).
Answer: In most (all ?) French mathematics books, Cartesian frames are defined as follows, e.g.  in 'Affine Geometry' (Cagnac, Ramis, Commeau) - [my translation] : "A Cartesian frame is defined in space by a point O (called origin), and by three independant vectors, i, j, k ; that is three non-vanishing vectors, such that their representatives originating in O be carried by the edges of a trihedron."
Similarly, one can refer to  a parallelogram in 2D.
Therefore, in France (Descartes country of origin), orthonogonal and orthonormal coordinates are only special cases of "Cartesian coordinates". I am not suggesting that the French education is more right in this matter  than the American one. I am only emphasizing the fact that when dealing with this topic, it is worth having this in mind.
An other source  for this fact is simply given by https://fr.wikipedia.org/wiki/Coordonn%C3%A9es_cart%C3%A9siennes as compared to https://en.wikipedia.org/wiki/Cartesian_coordinate_system
I  imagine that other countries where the French mathematical culture has been influent may also use the same  definition for Cartesian coordinates.


Limit row items to 1 as per the GROUP BY result in Views 3.x

Question: I'm trying to limit row items to 1 as per the GROUP BY result in Views 3.x, below is the view which I've created but I'm missing the key part from that, below is the exported code of my view.
<code>$view = new view();
$view->name = 'position';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Position';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Position';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['grouping'] = array(
  0 => array(
    'field' => 'field_home_page_anchor_position',
    'rendered' => 1,
    'rendered_strip' => 0,
  ),
);
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
  'field_home_page_anchor_position' => 'field_home_page_anchor_position',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'field_home_page_anchor_position' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Home Page Anchor Position */
$handler->display->display_options['fields']['field_home_page_anchor_position']['id'] = 'field_home_page_anchor_position';
$handler->display->display_options['fields']['field_home_page_anchor_position']['table'] = 'field_data_field_home_page_anchor_position';
$handler->display->display_options['fields']['field_home_page_anchor_position']['field'] = 'field_home_page_anchor_position';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Sort criterion: Content: Home Page Anchor Position (field_home_page_anchor_position) */
$handler->display->display_options['sorts']['field_home_page_anchor_position_value']['id'] = 'field_home_page_anchor_position_value';
$handler->display->display_options['sorts']['field_home_page_anchor_position_value']['table'] = 'field_data_field_home_page_anchor_position';
$handler->display->display_options['sorts']['field_home_page_anchor_position_value']['field'] = 'field_home_page_anchor_position_value';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'news_story' => 'news_story',
);
/* Filter criterion: Content: Home Page Anchor Position (field_home_page_anchor_position) */
$handler->display->display_options['filters']['field_home_page_anchor_position_value']['id'] = 'field_home_page_anchor_position_value';
$handler->display->display_options['filters']['field_home_page_anchor_position_value']['table'] = 'field_data_field_home_page_anchor_position';
$handler->display->display_options['filters']['field_home_page_anchor_position_value']['field'] = 'field_home_page_anchor_position_value';
$handler->display->display_options['filters']['field_home_page_anchor_position_value']['operator'] = 'not empty';
$handler->display->display_options['filters']['field_home_page_anchor_position_value']['value'] = array(
  'min' => '',
  'max' => '',
  'value' => '',
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');
$translatables['position'] = array(
  t('Master'),
  t('Position'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Home Page Anchor Position'),
  t('Block'),
);
</code>
SQL query generated by View is:
<code>SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created, field_data_field_home_page_anchor_position.field_home_page_anchor_position_value AS field_data_field_home_page_anchor_position_field_home_page_a, 'node' AS field_data_field_home_page_anchor_position_node_entity_type
FROM
{node} node
LEFT JOIN {field_data_field_home_page_anchor_position} field_data_field_home_page_anchor_position ON node.nid = field_data_field_home_page_anchor_position.entity_id AND (field_data_field_home_page_anchor_position.entity_type = 'node' AND field_data_field_home_page_anchor_position.deleted = '0')
WHERE (( (node.status = '1') AND (node.type IN  ('news_story')) AND (field_data_field_home_page_anchor_position.field_home_page_anchor_position_value IS NOT NULL ) ))
ORDER BY node_created DESC, field_data_field_home_page_anchor_position_field_home_page_a ASC
</code>
Answer: Don't know if I understood the question, but if you want to group the results in views, in the view edit page, in Advanced >> Other >> Use aggregation you can select the Aggregate option for the display. After that, each filed will have an Aggregation settings link for your to select the aggregation options you need to generate the group by part of your SQL query.


What is so great about 7?

Question: I'm going to write down my problem verbatim:

Write down the integers from $1$ to $50$ in rows of $10$ numbers each.
  Mark out $1$, and then cross out all multiples of $2$ greater than $2$
  (i.e., cross out, $4, 6, 8, . . . ). 3$ is not crossed out, so cross
  out all multiples of $3$ greater than $3$ (i.e., cross out $6, 9, 12, . . . )$.
  Find the next number $f$ after $3$ which is not crossed out.
  This is the next prime. Cross out all non-unary multiples of $f$.
  Continue in this way until you get to the end of the list, and the
  numbers which haven't been crossed out are the primes less than $50$.
  Notice that the last sequence of multiples you crossed off while doing
  this were multiples of $7$.
What's special about $7$ in this list?
If, instead of using just the numbers from $1$ to $50$ you had used
  the numbers from $1$ to $1000$, what's the smallest composite number
  that would not have been crossed off after crossing off the multiples
  of $7$?
Comment: Which multiple of $7$ was the last (only) one you erased? Is that a coincidence?
Comment: Well, 7,8,9. So it's pretty great.
Answer: $7$ is the largest integer less than the square root of $50$.
Comment: @variancemaster My guess would be $121$. $11$ is the next prime after $7$, so I think $11\times 11 = 121$ is the smallest composite not expressible as a multiple of some prime less than or equal to $7$.
Comment: Okay and what would happen if, instead of using just the numbers from 1 to 50 I use the numbers from 1 to 1000. What would be the smallest composite number that would not have been crossed off after crossing off the multiples of 7?
Comment: What does non-unary multiples of f mean
Comment: Why didn't you start out by asking what the terms mean? - I'm not a native english speaker, and I don't remember having seen the word "non-unary" before, but knowing Eratosthenes' sieve, I'm pretty sure it just means that the other factor has to be greater than 1.
Comment: It has nothing to do with $7$. When finding primes from $2$ to $N$, you only go up to $\sqrt{N}$.
Comment: @Eff Okay, I get that. But, what is the answer to my second question?
Answer: It is known that a composite integer $a$ has a prime divisor $p$ that satisfies the inequality $p\leq a$. If you let $a=50$, then it will have prime divisor $p$ that is less than or equal to $\sqrt{50}$.The greatest among possible p's is 7. Thus in employing the Sieve you will just cross out the multiples of prime $p$ 2,3,5 and lastly multiples of 7. The numbers that are not cross out are the primes from 1 to 50 which are 2,3,5,7,11,13,17,19,23,29,31,37,41,43 and 47. The special in 7 is that it is the greatest prime that you need to cross out its multiple.
Comment: Thanks, and is 121 correct for the second part of the question. If so, what is the reasoining behind it.
Comment: Do you know what non-unary means?
Comment: Where have you heard of that word? And to answer your question 121 is correct.
Comment: In the question it says "Cross out all non-unary multiples of f"
Comment: for the explanation that 121, I agree with Scott
Comment: Sorry for the non-unary word but im not familiar with it.
Answer: First, write down each number like you told me to do:
$\begin{array}{cccccccccc}
1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10\\
11 & 12 & 13 & 14 & 15 & 16 & 17 & 18 & 19 & 20\\
21 & 22 & 23 & 24 & 25 & 26 & 27 & 28 & 29 & 30\\
31 & 32 & 33 & 34 & 35 & 36 & 37 & 38 & 39 & 40\\
41 & 42 & 43 & 44 & 45 & 46 & 47 & 48 & 49 & 50
\end{array}$
Now cross out $1$ and multiples of $2$ greater than $2$:
$\begin{array}{cccccccccc}
\not1 & 2 & 3 & \not4 & 5 & \not6 & 7 & \not8 & 9 & \not10\\
11 & \not12 & 13 & \not14 & 15 & \not16 & 17 & \not18 & 19 & \not20\\
21 & \not22 & 23 & \not24 & 25 & \not26 & 27 & \not28 & 29 & \not30\\
31 & \not32 & 33 & \not34 & 35 & \not36 & 37 & \not38 & 39 & \not40\\
41 & \not42 & 43 & \not44 & 45 & \not46 & 47 & \not48 & 49 & \not50
\end{array}$
Now cross out multiples of $3$ greater than $3$:
$\begin{array}{cccccccccc}
\not1 & 2 & 3 & \not4 & 5 & \not6 & 7 & \not8 & \not9 & \not10\\
11 & \not12 & 13 & \not14 & \not15 & \not16 & 17 & \not18 & 19 & \not20\\
\not21 & \not22 & 23 & \not24 & 25 & \not26 & \not27 & \not28 & 29 & \not30\\
31 & \not32 & \not33 & \not34 & 35 & \not36 & 37 & \not38 & \not39 & \not40\\
41 & \not42 & 43 & \not44 & \not45 & \not46 & 47 & \not48 & 49 & \not50
\end{array}$
The next not-crossed out number is $5$, which is then $f$.  Cross out all the non-unary numbers of that:
$\begin{array}{cccccccccc}
\not1 & 2 & 3 & \not4 & 5 & \not6 & 7 & \not8 & \not9 & \not10\\
11 & \not12 & 13 & \not14 & \not15 & \not16 & 17 & \not18 & 19 & \not20\\
\not21 & \not22 & 23 & \not24 & \not25 & \not26 & \not27 & \not28 & 29 & \not30\\
31 & \not32 & \not33 & \not34 & \not35 & \not36 & 37 & \not38 & \not39 & \not40\\
41 & \not42 & 43 & \not44 & \not45 & \not46 & 47 & \not48 & 49 & \not50
\end{array}$
As you just saw, $49$ is not crossed out, so that's the smallest composite number of the group that hasn't been crossed out, plus it's $7^2$.
Comment: ReliableMathBoy: I've tried to improve alignment in your post. (Feel free to revert the edit, if you don't like the new version.) You can find more about using tables/arrays in some post on meta. For example [here](http://meta.math.stackexchange.com/questions/6734/how-can-i-put-a-table-here) or [here](http://meta.math.stackexchange.com/questions/4240/how-do-i-insert-a-table-when-asking-a-question) and in other posts shown there among linked questions.
Comment: Well, at least there's a great job of aligning :)

What is so great about 7?


"Ut" and "La" notation on horn and cornet instruments in orchestral score?

Question: I'm looking at an orchestral score from the late 1800's (well, OK, it's "The Mikado" by Arthur Sullivan).
In the portion of the score that I am looking at, the non-transposing instruments all have no key signature (a key of C-Major, I presume).
For the "Horn in F" part, he has no key signature, but the notation "Ut" above the staff.
For the "Cornet in B-flat" part, he has an E-flat key signature (three flats) and the notation "La" above the staff.
Here's an image:

I know both the Horn in F and the Cornet in B-flat are transposing instruments, but I'm not entirely sure what he's trying to represent here.
Could someone please explain what "Ut" and "La" mean in this context, and what is the meaning of the seemingly-odd key signatures for these instruments?
Answer: The issue is your assumption that the horn and trumpet are in fact in F and B-flat. Trumpets can be pitched in a variety of keys, and horn historically has played in one harmonic series or another without the use of valves, but by using crooks to pitch the instrument in one key or another.
In this case, the horn part is written in C and the trumpet part is written in A. Modern-day players reading this music would need to transpose to the key of the instrument they have, or use an instrument with the matching key. Modern-day horn players are VERY adept at this kind of transposition as the classic horn parts come in a wide variety of keys, and professional trumpet players will typically have a few different instruments on hand; but if the trumpet player doesn't have an A trumpet, he or she should be comfortable doing the half-step transposition to B-flat.
More likely in this particular case, however, is that only the public-domain score you are looking at has the odd-transposition brass parts -- the individual instrument parts you'd rent to perform The Mikado would almost surely be available in the more typical transpositions of F and B-Flat.
The syllables of Ut and La here come from traditional fixed-do solfege as seen historically in European classical music. Wikipedia

The key signature issue can be explained as follows: The key of the piece is C Major (or A minor -- but that's moot here), so for the trumpet playing in A to sound up a minor third in C (sounding), the written key needs to move from C up a minor third to Eb, which is a key signature of 3 flats.
Comment: Just to historical note: in the 19th century British cornets were often made with a transposing device to switch between B flat and A. This fell out of use because the A setting was notoriously out of tune. Sullivan has a little joke in the song "Young Man, Despair" in "Mikado," with cornets in A playing a solo imitating the Titipu Town Band (in which Namki-Poo played second trombone) as N-P's intended wife-to-be is married off to the Lord High Executioner. The joke is lost in most modern performances using in-tune trumpets not out-of-tune cornets.
Comment: Fixed-do is not historical, it's the National norm in Belgium, and is far from dead throughout the Continent. They seem not to want to know about modality...
Comment: Pulling out the tuning slide of a Bb trumpet could be used to lower the open notes a semitone. But the intonation of any note that then needed a valve to be depressed would be spoilt because the lengths of tubing for the valve crooks are based on the length of the open instrument. I own a D/Eb trumpet which has interchangeable tuning slides - when you change the main tuning slide for D or Eb you also have to fit the corresponding pair of 1st and 3rd valve slides too so the intonation stays correct.
Comment: Thank you! Being a piano guy, this is all new to me and very interesting.  I found a discussion on a trumpet web forum where the Mikado was being discussed.  Apparently it was (or still is) common to score a trumpet part in A; and not only can a good trumpeter transpose from A to B-flat, as you said, another possible option is to pull out the tuning slide to "bend" the A trumpet to a B-flat.  Live and learn!


Images can be load in Phalcon

Question: My images are not loaded with Phalcon Framework.
Maybe because the .htaccess file. I don't know.
The framework return this error:

"ImgController handler class cannot be loaded", when access http://domain.com/img/tiger.jpg

The route "http://domain.com/projects/update/1" is OK.
My .htaccess files below.
#/.htaccess
<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule ^$ public/    [L]
    RewriteRule (.*) public/$1 [L]
</IfModule>

#/public/.htaccess
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L]
</IfModule>

What's worng ?
Thanks anyway.
Answer: It appears to be a routing problem, especially if something works and something isn't. Phalcon digests the uri, finds a route, but cannot dispatch the ImgController. Check that the naming is correct, that your have the correctly named controller (ImgController not ImageController), that it has the correct namespace. If doesn't help, add your routing configuration details and your ImgController and where it is located.
Comment: Ian, in the URL (http://domain.com/img/tiger.jpg) 'img' is the path name that the images are.
The ImgController does exists.
Comment: Do I understood correctly that both the file `/img/tiger.jpg` exist and ImgController exist?
Comment: I just want show a image in the img tag, like this: . The image path is /public/img
But, the framework returns that error: ImgController handler class cannot be loaded.
Comment: Are you running Apache? Did you try using [server configuration](http://docs.phalconphp.com/en/latest/reference/apache.html) instead of .htaccess?
Comment: Ian, i was stupid.
i had a error in my images path.
My fault! Sorry.

Images can be load in Phalcon


Show that if $f$ is integrable on $[a,b]$, then $|f|$ is also integrable.

Question: The problem suggests doing it by showing that $U(P,|f|) - L(P,|f|) \le U(P,f)-L(P,f)$ for some partition $P$.  I can get the other steps after that, but I've tried proving this inequality on my own and multiple tutors at my university couldn't figure it out using the material in my book.  Every time I've attempted it on my own, I've gotten the arrow in the opposite direction.  Doesn't $\displaystyle\sup_{i \in [x_{i-1},x_i]} |f(x)| \ge \displaystyle\sup_{i \in [x_{i-1},x_i]} f(x)$ hold?
Note that my class is using a pretty simplified Analysis (question 5.5.2a) book that doesn't cover metric spaces or Lebesgue integrals.  Everything is Riemann and we show a function is Riemann integrable if and only if its upper and lower Darboux integrals are equal.
Comment: Hint: how do the suprema and infima of $|f|$ compare to those of $f$?
Comment: Aren't both greater for |f|?
Comment: I guess I should rephrase: the differences in the suprema and infima of $f$ are greater than or equal to those of $|f|$. Can you see why? You can do it by cases (where both are positive, one is positive and one is negative and both are negative).
Comment: Both are positive is a trivial case.  If both are negative, then inf(|f|) = sup(f).  If one is positive and one is negative, then either -inf(f)=sup(|f|), inf(f) = sup(-|f|) (I think.)
Comment: I think that if $\inf(f) \lt 0$ then $\sup(|f|) = -\inf(f)$ and if $\sup(f) \lt 0$ then $\inf(|f|) = -sup(f)$
Answer: It is enough to show that if $I$ is any subinterval of $[a,b]$, then
$$\sup_I\vert f\vert-\inf_I\vert f\vert\leq \sup_I f-\inf_I f\, . $$
If this is done then, given any partition $P$, apply this inequality to each interval $I$ of the partition, multiply by $\vert I\vert$ and and then sum everything to get $U(P,\vert f\vert)-L(P,\vert f\vert)\leq U(P,f)-L(P,f)$.
So let us fix the interval $I$. One may distinguish 3 cases.

If $\inf_I f\geq 0$, then $f\geq 0$ on $I$ so $\inf_I \vert f\vert=\inf_I f$ and $\sup_I\vert f\vert =\sup_I f$ and hence $\sup_I\vert f\vert-\inf_I\vert f\vert= \sup_I f-\inf_I f$.

If $\sup_I f\leq 0$, then $f\leq 0$ on $I$, so $\inf_I \vert f\vert=-\sup_I f$ and $\sup_I\vert f\vert =-\inf_I f$ and hence $\sup_I\vert f\vert-\inf_I\vert f\vert= \sup_I f-\inf_I f$ again.

If $\inf_I f<0<\sup_I f$, then we have either $\sup_I\vert f\vert=\sup_I f$, in which case $\sup_I\vert f\vert-\inf_I\vert f\vert\leq \sup_I\vert f\vert=\sup_I f<\sup_I f-\inf_I f$; or $\sup_I \vert f\vert=-\inf_I f$, in which case $\sup_I\vert f\vert-\inf_I\vert f\vert\leq -\inf_I f< \sup_I f-\inf_I f$.
Comment: This spells out precisely what I left for the OP to work out for himself.  Oh, well...
Comment: Yes, I saw your answer just after posting mine...
Comment: This is pretty much what I was trying to figure out and not coming close to (since I wasn't sure how in-depth my professor wanted me to go), but thanks!  I can do the rest on my own now.
Answer: I can propose the following very own proof. :-) Since $f$ is (properly) Riemann integrable on $[a,b]$, $f$ is bounded on $[a,b]$. By Lebesgue theorem, a bounded function $f$ on a segment is Riemann integrable iff the set $D(f)$ of the discontinuity points of $f$ has the Lebesgue measure $0$. Since the function $|\cdot|$ is continuous, $D(|f|)\subset D(f)$. Thus $0\le\mu(D(|f|))\le \mu(D(f))\le 0$ and again by Lebesgue thereom, the function $|f|$ is Riemann integrable on $[a,b]$.
Comment: I wish I was allowed to use that, but we're explicitly forbidden from using anything directly outside our book.  That means no Lebesque theorem, unfortunately.
Answer: Recall Darboux's Criterion: $f: [a,b] \rightarrow \mathbb{R}$ is Riemann(-Darboux) integrable iff for all $\epsilon > 0$, there is a partition $\mathcal{P} = \{a = x_0 < x_1 < \ldots < x_n = b\}$ of $[a,b]$ such that
$$\omega(f,\mathcal{P}) = \sum_{i=0}^{n-1} \left(\sup(f,[x_i,x_{i+1}])-\inf(f,[x_i,x_{i+1}]) \right) (x_{i+1} - x_{i}) < \epsilon.$$
The quantity
$\omega(f,[x_i,x_{i+1}]) = \left(\sup(f,[x_i,x_{i+1}])-\inf(f,[x_i,x_{i+1}] \right)$
is sometimes called the oscillation of $f$ on the (sub)interval $[x_i,x_{i+1}]$, since it measures the difference between the largest and smallest values.  I claim that for any function $f: I \rightarrow \mathbb{R}$, taking the absolute value does not increase the oscillation: $\omega(|f|,I) \leq \omega(f,I)$.  This is a simple argument that I leave to you: note that this argument also underlies the proof that if $f$ is continuous, so is $|f|$.  The result follows from this by applying Darboux's Criterion twice.
Some comments:

As Alex Ravsky says in his answer, we can actually "reduce" the problem to $f$ continuous at $a$ $\implies$ $|f|$ continuous at $a$ using the (Riemann-)Lebesgue criterion that $f: [a,b] \rightarrow \mathbb{R}$ is Riemann integrable iff it is bounded and its set of discontinuities has measure zero.  This is overkill.

The result is a special case of another useful result which is usually presented in undergraduate analysis courses: if $f: [a,b] \rightarrow [c,d]$ is Riemann integrable and $\varphi: [c,d] \rightarrow \mathbb{R}$ is continuous, then $\varphi \circ f$ is Riemann integrable.  Applying this with $\varphi(x)= |x|$ we get the result.  For a proof, see Theorem 8.17 of these notes.  This result can be applied, for instance, to show that the product of two Riemann integrable functions is Riemann integrable.

The proof of the theorem referred to above is not so easy.  However, it becomes much easier if $\varphi$ is not just continuous but Lipschitz, i.e., if there is a constant $C$ such that $|\varphi(x)-\varphi(y)| \leq C|x-y|$ for all $x,y \in [c,d]$.  This simpler case is proved separately as Theorem 8.20 in the above notes, and the proof comes down to observing that for Lipschitz $\varphi$, $\omega(\varphi \circ f, I) \leq C \omega(f,I)$.  Note that the absolute value function is Lipschitz with $C = 1$, and this is exactly what we observed above.


Discord.js | You can only bulk delete messages that are under 14 days old

Question: if there's messages over 14 days old and some that aren't 14 days old it does not delete the messages that aren't 14 days old and it sends an error is there a way to delete the messages that are not over 14 days old and leave the ones that are over 14 days old if you can't then can you help me make it stop sending an error and make it send a message saying "You can only bulk delete messages that are under 14 days old." in the channel instead of it showing a error in the console thanks.
const { Message } = require("discord.js");
const Client = require("../structures/Client");
module.exports = {
  name: `clear`,
  /**
   * @param {Client} client
   * @param {Message} message
   * @param {String[]} args
   */
  run: async (client, message, args) => {

    const msg = message;
    var amt = parseInt(args[0], 10);

    if(message.member.hasPermission(['MANAGE_MESSAGES'])) {
      if(!amt) {
        msg.channel.send(client.embed({ description: `${msg.author.username}! Please specify a amount of messages to delete`}));
      } else {
        if(amt > 100) {
          return message.channel.send(client.embed({ description: `You can only clear minimum of 100 messages per command` }))
        } else {
          if(amt == 100) {
            msg.channel.bulkDelete(amt);
            msg.channel.send(client.embed({ description: `${msg.author.username}! You cleared ${amt} messages`})).then(m => { m.delete({ timeout: 3000 }); }).catch(err => { console.log(err); })
          } else {
            msg.channel.bulkDelete(amt + 1);
            msg.channel.send(client.embed({ description: `${msg.author.username}! You cleared ${amt} messages`})).then(m => { m.delete({ timeout: 3000 }); }).catch(err => { console.log(err); })
          }
        }
      }
    } else {
      if(message.member.hasPermission(['ADMINISTRATOR'])) {
        if(!amt) {
          msg.channel.send(client.embed({ description: `${msg.author.username}! Please specify a amount of messages to delete`}));
        } else {
          if(amt > 100) {
            return message.channel.send(client.embed({ description: `You can only clear minimum of 100 messages per command` }))
          } else {
            if(amt == 100) {
              msg.channel.bulkDelete(amt);
              msg.channel.send(client.embed({ description: `${msg.author.username}! You cleared ${amt} messages`})).then(m => { m.delete({ timeout: 3000 }); }).catch(err => { console.log(err); })
            } else {
              msg.channel.bulkDelete(amt + 1);
              msg.channel.send(client.embed({ description: `${msg.author.username}! You cleared ${amt} messages`})).then(m => { m.delete({ timeout: 3000 }); }).catch(err => { console.log(err); })
            }
          }
        }
      } else {
        msg.channel.send(client.embed({ description: `${msg.author.username}! You do not have permission to run that command.`}));
      }
    }

  },
  timeout: 1500
}

Answer: The messages that are bulk deletable in the Discord API are messages less than 14 days old. That is an API limitation, not the library limitation.
The library can filter out messages older than 14 days, like so.
message.channel.bulkDelete(number, true);
You need to set the filterOld parameter to true to automatically filter out old messages and not throw an error.


Call to a member function label() on null after saving a node with a taxonomy term

Question: I create nodes, which have a taxonomy field, like this:
$node = Node::create([
  'type' => 'article',
  'status' => 1,
  'title' => 'Some title',
  ...
  'field_taxonomy' => [1, 2, 3],
]);
$node->save();

The nodes are saved and can be displayed. But the views, which should display articles with selected taxonomy terms, return the following error message:
Error: Call to a member function label() on null in Drupal\taxonomy\Plugin\views\field\TaxonomyIndexTid->preRender() (Line 149 in /var/www/html/core/modules/taxonomy/src/Plugin/views/field/TaxonomyIndexTid.php)
#0 /var/www/html/core/modules/views/src/ViewExecutable.php(1503): Drupal\taxonomy\Plugin\views\field\TaxonomyIndexTid->preRender(Array)
#1 /var/www/html/core/modules/views/src/Plugin/views/display/Page.php(183): Drupal\views\ViewExecutable->render()
#2 /var/www/html/core/modules/views/src/ViewExecutable.php(1630): Drupal\views\Plugin\views\display\Page->execute()
#3 /var/www/html/core/modules/views/src/Element/View.php(77): Drupal\views\ViewExecutable->executeDisplay('alle', Array)
#4 [internal function]: Drupal\views\Element\View::preRenderViewElement(Array)
#5 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(378): call_user_func(Array, Array)
#6 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(195): Drupal\Core\Render\Renderer->doRender(Array, false)
#7 /var/www/html/core/lib/Drupal/Core/Render/MainContent/HtmlRenderer.php(226): Drupal\Core\Render\Renderer->render(Array, false)
#8 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(582): Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}()
#9 /var/www/html/core/lib/Drupal/Core/Render/MainContent/HtmlRenderer.php(227): Drupal\Core\Render\Renderer->executeInRenderContext(Object(Drupal\Core\Render\RenderContext), Object(Closure))
#10 /var/www/html/core/lib/Drupal/Core/Render/MainContent/HtmlRenderer.php(117): Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array, Object(Symfony\Component\HttpFoundation\Request), Object(Drupal\Core\Routing\CurrentRouteMatch))
#11 /var/www/html/core/lib/Drupal/Core/EventSubscriber/MainContentViewSubscriber.php(90): Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object(Symfony\Component\HttpFoundation\Request), Object(Drupal\Core\Routing\CurrentRouteMatch))
#12 [internal function]: Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object(Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent), 'kernel.view', Object(Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher))
#13 /var/www/html/core/lib/Drupal/Component/EventDispatcher/ContainerAwareEventDispatcher.php(111): call_user_func(Array, Object(Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent), 'kernel.view', Object(Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher))
#14 /var/www/html/vendor/symfony/http-kernel/HttpKernel.php(156): Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object(Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent))
#15 /var/www/html/vendor/symfony/http-kernel/HttpKernel.php(68): Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1)
#16 /var/www/html/core/lib/Drupal/Core/StackMiddleware/Session.php(57): Symfony\Component\HttpKernel\HttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#17 /var/www/html/core/lib/Drupal/Core/StackMiddleware/KernelPreHandle.php(47): Drupal\Core\StackMiddleware\Session->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#18 /var/www/html/core/modules/page_cache/src/StackMiddleware/PageCache.php(99): Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#19 /var/www/html/core/modules/page_cache/src/StackMiddleware/PageCache.php(78): Drupal\page_cache\StackMiddleware\PageCache->pass(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#20 /var/www/html/modules/jsonapi/src/StackMiddleware/FormatSetter.php(51): Drupal\page_cache\StackMiddleware\PageCache->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#21 /var/www/html/core/lib/Drupal/Core/StackMiddleware/ReverseProxyMiddleware.php(47): Drupal\jsonapi\StackMiddleware\FormatSetter->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#22 /var/www/html/core/lib/Drupal/Core/StackMiddleware/NegotiationMiddleware.php(52): Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#23 /var/www/html/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#24 /var/www/html/core/lib/Drupal/Core/DrupalKernel.php(669): Stack\StackedHttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#25 /var/www/html/index.php(19): Drupal\Core\DrupalKernel->handle(Object(Symfony\Component\HttpFoundation\Request))
#26 {main}.

If I manually open the editing form for every of the new nodes and save the node (without changing anything), then the error message disappear and the views display correct content. Resaving all new articles in a bulk operation or clearing all caches do not solve the issue.
The line 149 in /core/modules/taxonomy/src/Plugin/views/field/TaxonomyIndexTid.php looks like:
127 public function preRender(&$values) {
128     $vocabularies = $this->vocabularyStorage->loadMultiple();
...
144     foreach ($result as $node_nid => $data) {
145         foreach ($data as $tid => $term) {
...
149             $this->items[$node_nid][$tid]['vocabulary'] = $vocabularies[$term->bundle()]->label();
...
            }
        }
    }

Comment: Seems that you are adding a taxonomy term ids that don't exist.
Comment: No. If a term does not exist, then it is created. The code here is simplified...
Comment: @AntonínSlejška What's version of drupal? Maybe have problem with publish and unpublish of term. And let ensure term exist first.
Comment: @Jonh There is Drupal 8.6. It is a good idea. I will try it. Thanks.
Answer: I believe it has to do with how you are trying to assign values to the field.
I think you want:
$node = Node::create([
  'type' => 'article',
  'status' => 1,
  'title' => 'Some title',
]);

$node->set('field_taxonomy', [1, 2, 3]);
$node->save();

Comment: Both examples should work the same - I suspect it's because `target_id` is missing from the array
Comment: Also, probably want to ensure the terms exist first.
Comment: Thanks Kevin. I have tried this approach, but it did not solve the issue. Both approaches return in my case exactly the same results.
Comment: line 149 has two method calls, first `$term->bundle()` and then `$vocabulary->label()`. So the term exists, but the bundle is NULL or not existing.


strpos() está encerrando o while quando verdadeiro

Question: Faço um loop de uma consulta. Verifico se o valor de cada registro contém dentro de uma string qualquer (no caso $mensagem). O problema é que, quando o valor é encontrado, nesse caso dentro do ELSE, o while é encerrado por algum motivo. Eu preciso que a verificação continue a ser feita em todos os registros, até o fim dos registros.
$query = "select id, id_usuario texto from palavra";
$result = mysql_query($query);
while($palavras = mysql_fetch_array($result)) {
   $valor = $palavras["texto"];
   $iduser = $palavras["id_usuario"];

   if(!strpos(strtolower($mensagem), strtolower($valor))) {
      echo " não.
";
   } else {
      echo " sim.
";

     $query = "select nome from usuario where id = $iduser";
     $result = mysql_query($query);
     $user_dados = mysql_fetch_row($result);

   }

}

Se tiro a consulta interna, o loop continua normal, como esperado. Mas preciso da consulta.
Comment: O loop precisa continuar, e não parar após achar a primeira ocorrência.
Comment: Seu código parece ter um problema mas ele não encerra o while, qual é o código real do else? o ideal é usar operador `===` para fazer a comparação
Comment: @rray Testei aqui e dessa forma o loop continua normal. Vou editar o código, o "else" tem mais coisas...
Comment: Eu entendi agora haha xD para quebrar um loop use o `break`
Comment: @rray Você estava certo, a ideia é fazer continuar mesmo, e não parar o loop. Arrumei lá.
Comment: Tbm vou alterar minha resposta ...
Comment: Calma ai, vc acertou o código mas o texto da pergunta não com os últimos comentários, pode editar a pergunta e clarificar.
Comment: Ok, o show continua :D
Comment: coloque: `$result = mysql_query($query) or die(mysql_error())` deve ter um erro na segunda consulta e no while por causa do reaproveitamento de `$result`
Comment: @rray vc matou a charada! O reaproveitamento do $result está com problema. A consulta interna alterei para $result2 e funcionou, o loop continuou.
Comment: Parece que nem leu e nem tentou o que passei na minha resposta, se tivesse testado o `ini_set` e o `error_reporting` teria chegado ao problema, pois como eu disse na resposta `provavelmente é algum erro no uso de mysql_fetch_array ou na sua query ou outra coisa próxima a isto`.
Comment: @GuilhermeNascimento Eu usei seus comandos para mostrar o erro. Não me retornou nenhum erro. Não era questão de erro ou sintaxe, mas de programação, basicamente sobrescrevendo a variável $result. Obrigado.
Comment: @DanielAccorsi ok entendi =)
Answer: O problema parece acontecer na segunda consulta devido ao reaproveitamento da variável $result na segunda consulta mude ela de nome.
Para evitar falsos positivos com a função strpos() use o operador === assim ele compara o valor e o tipo. Sem ele se a string for encontrada na posição zero seu código será desviado para o bloco else de forma errada.
$query = "select id, id_usuario texto from palavra";
$result = mysql_query($query); //<--- primeira ocorrência

//aqui na segunda 'volta' do while $result já pode ser false ou não devolver as chaves texto e id_usuario
while($palavras = mysql_fetch_array($result)) {
   $valor = $palavras["texto"];

   if(strpos(strtolower($mensagem), strtolower($valor)) === false) {
      echo " não.
";
   } else {

      $query = "select nome from usuario where id = $iduser";
      $result = mysql_query($query); //reatribução indevida.
      $user_dados = mysql_fetch_row($result);
   }

}

Answer: Deve ser uma exception e os erros estão desligados por isto você não notou, ligue os erros do PHP, quando estiver em desenvolvimento, em produção uso ini_set('display_errors', '0');, provavelmente é algum erro no uso de mysql_fetch_array ou na sua query ou outra coisa próxima a isto.
Outro problema que pode ter ocorrido foi com a variável $mensagem, verifique se ela existe e se está no mesmo "escopo" do script que você citou.
Faça assim em desenvolvimento, coloque no topo do seu arquivo:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL|E_STRICT);

Outra coisa strpos só retorna false se não encontrar nada, se fizer isto por exemplo:
strpos('abc', 'a');

Ele vai retornar zero e como ! considera tanto 0, quanto false quanto NULL quanto '' (string vazia) então deve se usar assim:
   if (strpos(strtolower($mensagem), strtolower($valor)) === false) {
        echo " não.
";
   } else {
        echo " sim.
";

        $query = "select nome from usuario where id = $iduser";
        $result = mysql_query($query);
        $user_dados = mysql_fetch_row($result);
   }

Notei que usou strtolower, mas isso é dispensável se usar assim stripos:
   if (stripos($mensagem, $valor) === false) {
        echo " não.
";
   } else {
        echo " sim.
";

        $query = "select nome from usuario where id = $iduser";
        $result = mysql_query($query);
        $user_dados = mysql_fetch_row($result);
   }

Outra coisa importante é não usar mais a API antiga do PHP pra mysql, prefira PDO ou mysqli, leia:

Diferença entre as funções mysql_connect() e mysqli_connect() em php
Comment: Nem eu sei o que está certo, vc viu esse [comentario](http://pt.stackoverflow.com/questions/131333/strpos-est%C3%A1-encerrando-o-while-quando-verdadeiro#comment273264_131333) ? O.o
Answer: Seu problema se deve ao fato do nosso amigo PHP interpretar o "0" da mesma forma que o "false". Então quando ele acha a substring no inicio da String ele retorna 0 (que o php também entende como false).
altere seu código para:
while($palavras = mysql_fetch_array($result)) {
   $valor = $palavras["texto"];

   if(strpos(strtolower($mensagem), strtolower($valor)) === false) {
      echo " não.
";
   } else {
      echo " sim.
";
   }

}

Isso mesmo com 3 "===".
Comment: Não foi o mesmo que eu respondi?
Comment: É sim, quando eu comecei a responder você ainda não tinha postado, vi agora. :D


Joining a window domain - DNS resolve

Question: My computer is joined to a Window domain named "acme.local".
However when I login into the computer, I only specify

acme\username --> notice ".local" is not specified

and not

acme.local\username

But I am still able to login, why ?
I would believe acme.local will resolve to a DomainController's IP, but how does "acme" itself get resolved ?
Is the resolution done via NetBios or DNS when speciying "acme\username"?
If it is done via DNS and my primary DNS suffix is acme.local , wouldn't specifying acme alone, result in the system attempting to resolve acme.acme.local instead ?
Answer: The answer to your question is not related to DNS.
When you create an Active Directory domain, amongst other things, you need to specify the domain name and the domain NetBIOS name. The domain name is the FQDN of your domain (acme.local). The domain NetBIOS name is by default (and usually never changed) the first part of your FQDN (acme) and also referred to as the pre-2000 domain name or legacy domain name.
When you log on to a machine with a domain user account, you can either

user the User Principal Name (UPN): email@example.com,
the down-level logon name: ACME\user
just the user name (SAM Account Name): user

Regardless of what method you chose for authentication, the computer is always sending the username to the domain controller of the currently joined domain (which is resolved by DNS). From comments: If you pull down the drop down for the local computer you do not authenticate against the domain.
The down-level logon name is derived from the NetBIOS name. If you chose acme, the downlevel logon name is ACME (which in reality is case-insensitive).
If you omit the down-level logon name, Windows always authenticated towards a domain controller of the currently joined domain.
(For the record: You can add multiple UPN suffixes per domain.)
Edit:
You can use nbtstat -n to find the NetBIOS domain name of the currently joined domain.
I found some sources:

https://msdn.microsoft.com/en-us/library/windows/desktop/aa380525%28v=vs.85%29.aspx#down_level_logon_name
Comment: It will always authenticate against the selected domain. If you pull down the drop down for the local computer you do not authenticate against the domain.
Comment: great I think this now encompasses the complete answer. +1
Comment: @Daniel thanks for the reply.  As you mentioned "no matter which method for authentication is chosen, the computer is always sending the username to the DC of the currently joined domain" --> how does the computer find the DC ?  to add-on, if we specify acme/username when we logon, what happen in the background actually, does the system use NETBIOs to find the DC ?

Joining a window domain - DNS resolve


Query to find an average weighted price

Question: I have a table in Oracle with multiple rows per a given part.  Each row has a quantity and a price associated with it.  There is also a total quantity that the set of rows for a given part adds up to.  Below is a sample of the data.  What I need is to get the average weighted price for the part.  For example if a quantity of 100 of a part has a price of 1 and a quantity of 50 has a price of 2 the weighted average price is 1.33333333
PART   TOTAL_QTY  QTY   PRICE_PER
----------------------------------
part1  317        244   27
part1  317        40    53.85
part1  317        33    24.15

Ideas?
Answer: Try this:
SELECT part, SUM(qty*price_per)/SUM(qty)
  FROM <YOUR_TABLE>
GROUP BY part

Comment: Guess you don't need the TOTAL_QTY field anymore. It blatantly violates the unicity data principle - each piece of data must appear only once.
Answer: create a user defined aggregate function to calculate the weighted average:
CREATE OR REPLACE TYPE WEIGHTED_AVG_O AS OBJECT (
  sum_of_weights NUMBER,
  sum_of_weights_times_value NUMBER,

  STATIC FUNCTION ODCIAGGREGATEINITIALIZE(cs_ctx IN OUT WEIGHTED_AVG_O) RETURN NUMBER,
  MEMBER FUNCTION ODCIAGGREGATEITERATE   (self IN OUT WEIGHTED_AVG_O, value IN WEIGHTED_AVG_O) RETURN NUMBER,
  MEMBER FUNCTION ODCIAGGREGATEMERGE     (self IN OUT WEIGHTED_AVG_O, ctx2 IN OUT WEIGHTED_AVG_O) RETURN NUMBER,
  MEMBER FUNCTION ODCIAGGREGATETERMINATE (self IN OUT WEIGHTED_AVG_O, returnvalue OUT NUMBER, flags IN NUMBER) RETURN NUMBER
);
/

CREATE OR REPLACE TYPE BODY WEIGHTED_AVG_O
AS

  STATIC FUNCTION ODCIAGGREGATEINITIALIZE(cs_ctx IN OUT WEIGHTED_AVG_O) RETURN NUMBER
  IS
  BEGIN
    cs_ctx := WEIGHTED_AVG_O(0, 0);
    RETURN odciconst.success;
  END;

  MEMBER FUNCTION ODCIAGGREGATEITERATE   (self IN OUT WEIGHTED_AVG_O, value IN WEIGHTED_AVG_O) RETURN NUMBER
  IS
  BEGIN
    self.sum_of_weights := self.sum_of_weights + value.sum_of_weights;
    self.sum_of_weights_times_value := self.sum_of_weights_times_value + value.sum_of_weights * value.sum_of_weights_times_value;
    RETURN odciconst.success;
  END;

  MEMBER FUNCTION ODCIAGGREGATEMERGE     (self IN OUT WEIGHTED_AVG_O, ctx2 IN OUT WEIGHTED_AVG_O) RETURN NUMBER
  IS
  BEGIN
    RETURN odciconst.success;
  END;

  MEMBER FUNCTION ODCIAGGREGATETERMINATE (self IN OUT WEIGHTED_AVG_O, returnvalue OUT NUMBER, flags IN NUMBER) RETURN NUMBER
  IS
  BEGIN
    IF sum_of_weights = 0 THEN
      returnvalue := NULL;
    ELSE
      returnvalue := sum_of_weights_times_value / sum_of_weights;
    END IF;
    RETURN odciconst.success;
  END;

END;
/

CREATE OR REPLACE FUNCTION WEIGHTED_AVG (input WEIGHTED_AVG_O)
   RETURN NUMBER PARALLEL_ENABLE
   AGGREGATE USING WEIGHTED_AVG_O;
/

query with your data:
SELECT part, WEIGHTED_AVG(WEIGHTED_AVG_O(qty, price_per))
  FROM <YOUR_TABLE>
 GROUP BY part;

Query to find an average weighted price


Flask: two servers supporting WS and HTTP protocols

Question: I would like to run two servers in parallel when my application starts, one for HTTP requests, one for websockets (using python-sockio). I already have a python back-end which starts an HTTP-based server with Flask. However, every time I start the first server, it seems like it is blocking the thread which in turn, causes my second server not to initialize at all. Since I'm using Flask, is there a Flask-way to do this?
Comment: Can you describe which websocket server you're referring to?
Comment: Have you considered `flask-socketio` instead of using `python-socketio` directly. Flask-SocketIo is wrapper around python-socketio. Same creator.
Answer: you can try to run the two servers on 2 different ports like so
flask run --host 0.0.0.0 --port 5000

flask run --host 0.0.0.0 --port 5001

If I did a terrible job explaining try and look at this thread Python - How to run multiple flask apps from same client machine
Answer: Sounds like an XY problem. Your app can serve both websockets and HTTP. Here's a code example taken from Miguel Grinberg's Flask-Socketio example:
from flask import Flask, render_template
from flask_socketio import SocketIO, emit

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

@app.route('/')
def index():
    return render_template('index.html')

@socketio.on('my event')
def test_message(message):
    emit('my response', {'data': 'got it!'})

if __name__ == '__main__':
    socketio.run(app)