linear regression model using R

Question: I am a novice in R but am trying to learn. I have a dataset in excel and i import it in R using:
stockPrice<-read.csv("C:/Users/Desktop/prova.csv", sep=";", header=T, check.names = FALSE, stringsAsFactors=FALSE)

and the result of the import is this. there are 100 rows and columns.
        1       2       3      4       5       6       7      8       9     10      11      12
1  -1,8669 -1,2096  1,0358 0,0239 -1,0284 -0,0259  0,8801 0,4778  1,1449 0,4397 -0,1530 -0,3123
2  -2,1469 -0,4331 -0,0891 1,3842 -1,4148  0,1138 -0,8275 0,5115 -1,2898 1,8105  0,8521 -1,4327
3  -1,8919 -0,6469 -0,4098 2,8243 -1,3704 -1,6783 -0,6159 1,2910 -1,4260 2,4720  0,5230 -1,6965
4  -0,7912  0,4075  0,1092 3,8167 -0,9085 -1,0804  0,4104 0,9577 -0,2531 1,1191  1,5688 -0,8727
5  -0,2726  0,1827  0,7973 3,3848  1,0666  1,1254 -1,4111 1,2030 -0,9559 1,7813  1,8331 -1,0933
6   0,0539 -0,8640  2,0607 3,4989  2,1625  0,5226 -1,3890 2,6475 -0,6684 0,4587  0,7694  0,3462
7   0,6813 -1,9639  0,1362 1,9797  2,8645 -0,1524 -1,2367 4,6739 -1,7459 2,2648  1,8341 -0,4107
8  -0,4228 -0,3357  0,1201 2,1603  4,2053 -0,3679 -0,5577 3,7251 -1,6288 2,0168  1,1571 -0,8601
9   0,3020 -0,0523  1,4912 2,6993  5,2069 -0,0497 -0,3139 3,2010 -1,1773 1,8993  0,3357 -3,4239
10 -0,0832  0,2051  2,2387 2,9303  6,1984  1,9706 -0,3759 2,7283 -2,1752 2,0772  0,3298 -4,3092

I just copy part of the dataset. each column is referred to an asset. Now, what am trying to do is to calculate a linear regression, for example, the first asset y will be column 1 row from 1 to 9 and x will be column 1 row from 2 to 10.And I have to do this for each asset.i just need the value of the coefficient.
Answer: One option is to loop through the columns with lapply, extract the x and 'y' and create a model with lm after removing the , and convert it to numeric type
out <- lapply(stockPrice, function(vec) {
                      vec <- as.numeric(sub(",", "", vec))
                      y <- vec[1:(length(vec)-1)]
                     x <- vec[2:length(vec)]
                     coef(lm(y ~ x))
                  }
    )

out[[1]]
#  (Intercept)             x
#-2798.4234922     0.8392437

If we want the slope, then rbind the list elements and extract the second column
do.call(rbind, out)[, 2]
#   1           2           3           4           5           6           7           8           9          10          11
# 0.83924375  0.21597272  0.21761992  0.95551414  0.86204662  0.10036499  0.02051160  0.84014384  0.01129873 -0.31601104  0.18362571
#        12
# 0.46161256

-checking in excel for first column output
-data

-output

In addition to the above, we can also make use of lmList from nlme after reshaping to 'long' format
library(dplyr)
library(tidyr)
library(nlme)
stockPrice %>%
    mutate_all(readr::parse_number) %>%
    pivot_longer(everything(), values_to = 'y') %>%
    group_by(name  = factor(name, levels = unique(name)))
    mutate(x = lead(y)) %>%
    ungroup %>%
    na.omit %>%
    lmList(y ~ x|name, data = .)
#Call:
#  Model: y ~ x | name
#   Data: .

#Coefficients:
#   (Intercept)           x
#1    -2798.423  0.83924375
#2    -4621.407  0.21597272
#3     4274.414  0.21761992
#4    -2009.506  0.95551414
#5    -5269.101  0.86204662
#6    -1814.797  0.10036499
#7    -5479.691  0.02051160
#8     1218.587  0.84014384
#9    -8747.104  0.01129873
#10   21429.645 -0.31601104
#11    7811.527  0.18362571
#12   -3786.098  0.46161256

#Degrees of freedom: 108 total; 84 residual
#Residual standard error: 8419.53

data
stockPrice <- structure(list(`1` = c("-1,8669", "-2,1469", "-1,8919", "-0,7912",
"-0,2726", "0,0539", "0,6813", "-0,4228", "0,3020", "-0,0832"
), `2` = c("-1,2096", "-0,4331", "-0,6469", "0,4075", "0,1827",
"-0,8640", "-1,9639", "-0,3357", "-0,0523", "0,2051"), `3` = c("1,0358",
"-0,0891", "-0,4098", "0,1092", "0,7973", "2,0607", "0,1362",
"0,1201", "1,4912", "2,2387"), `4` = c("0,0239", "1,3842", "2,8243",
"3,8167", "3,3848", "3,4989", "1,9797", "2,1603", "2,6993", "2,9303"
), `5` = c("-1,0284", "-1,4148", "-1,3704", "-0,9085", "1,0666",
"2,1625", "2,8645", "4,2053", "5,2069", "6,1984"), `6` = c("-0,0259",
"0,1138", "-1,6783", "-1,0804", "1,1254", "0,5226", "-0,1524",
"-0,3679", "-0,0497", "1,9706"), `7` = c("0,8801", "-0,8275",
"-0,6159", "0,4104", "-1,4111", "-1,3890", "-1,2367", "-0,5577",
"-0,3139", "-0,3759"), `8` = c("0,4778", "0,5115", "1,2910",
"0,9577", "1,2030", "2,6475", "4,6739", "3,7251", "3,2010", "2,7283"
), `9` = c("1,1449", "-1,2898", "-1,4260", "-0,2531", "-0,9559",
"-0,6684", "-1,7459", "-1,6288", "-1,1773", "-2,1752"), `10` = c("0,4397",
"1,8105", "2,4720", "1,1191", "1,7813", "0,4587", "2,2648", "2,0168",
"1,8993", "2,0772"), `11` = c("-0,1530", "0,8521", "0,5230",
"1,5688", "1,8331", "0,7694", "1,8341", "1,1571", "0,3357", "0,3298"
), `12` = c("-0,3123", "-1,4327", "-1,6965", "-0,8727", "-1,0933",
"0,3462", "-0,4107", "-0,8601", "-3,4239", "-4,3092")),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10"))

Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/203824/discussion-on-answer-by-akrun-linear-regression-model-using-r).
Answer: As an alternative to @akrun answer, you can use apply instead of lapply:
Using a fake example m
m <- data.frame(matrix(rnorm(100), ncol = 10, nrow = 10))

> head(m[1:3,1:3])
           X1        X2          X3
1 -0.81150290 0.3196615 -0.70848803
2  1.39105642 0.8232761  0.02241253
3 -0.01187938 0.9158422 -0.21934718

You can do:
coeff = apply(m, 2, function(x) lm(x[1:9] ~ x[2:10])$coefficients[2])

And get a vector with all coefficients calculated from each asset:
> coeff
         X1          X2          X3          X4          X5          X6
-0.19160847 -0.52686830  0.36973049  0.29217668 -0.70102686  0.22142335
         X7          X8          X9         X10
-0.13817910 -0.14292086  0.05105796 -0.22829763

BTW, when you open your dataset using read.table, you should add the argument dec = "," in order to not have to deal with non-numerical values. So something like:
stockPrice<-read.csv("C:/Users/Desktop/prova.csv", sep=";", header=T, check.names = FALSE, stringsAsFactors=FALSE, dec = ",")

Comment: have try it but the code isn't working for me. having NA value
Comment: Did you use `dec = ","` when opening your `stockPrice` dataframe ?

linear regression model using R


Get all Ipv6 Addresses from CIDR prefix?

Question: I found many information how to get all addresses from ipv4 cidr subnet, but nothing helpful for ipv6.
Have php any libaries to calculate that?
What i need is an array of all addresses from a ipv6 cidr subnet.
For example all addresses from this subnet 3FFA:FF2B:4D:A000::/51.
After that i want to do an nslookup on this addresses.
Comment: I think the title should be changed to mention IPv6, instead of IPv4.
Comment: oh thanks u are right!
Answer:
What i need is an array of all addresses from a ipv6 cidr

Actually, that probably isn't what you want.  The numbers of addresses involved can quickly grow to be unmanageable.  Holding them all in an array is going to require a huge amount of memory. (e.g. if you hold each address as a 128bit value
then for a /51 you would need around 2,000,000,000,000 TB of ram to hold that array).
What you really want is probably something that will generate the sequential addresses so that you can iterate over the addresses and perform some action on each; again this is not likely to be managable, as even if you are only taking 1ns to process each IP you are going to take millenia to actually iterate over all the addresses in a /51 (e.g. (1e-9 * 2**77)/(86400*365) = 4,791,848 years).


What's the recommended solution/technology to this use case?

Question: I'm building a website which offers 1 on 1 coaching on various topics. The coaching is done over the web ( video call, document upload, stuff like this ), and one of the most important things is that the client pays by the minute. My problem is the following: how will I know when a coaching session ends ( so that I can correctly bill the customer )?
I'm planning to store the coaching session in the db roughly like this:
  coach_id:integer
  client_id:integer
  created_at:datetime
  updated_at:datetime
  in_progress:boolean

At the session's end I will do a difference between updated_at and created_at, and get the length of the session.
Here are the potential problems I see:

coach loses internet access => in this case, the client will press a button on the website which will notify us that the session had a problem, and the session's updated_at will be updated, and in_progress will be set to false
client loses internet access => same workflow as if coach loses internet access
both lose internet access => this is the trickiest case. I am not sure how to notify the server that the session should be considered as finished. I am thinking of doing it via push, and have both the client's browser, and the coach's browser update the server every minute. Worst case scenario, the error would cause a difference of 1 minute to the bill, which is acceptable. The downside is that I think this could load the server a lot, and I don't know if this would still be a viable solution once we will have many users.

What do you think of this approach? In case it matters, the application will be built on Rails 3.2.
Comment: Why dont you look into HTML5 EventSource or WebSockets as possible means of detecting connectivity/loss of connection?
Comment: @PeterAronZentai, yes, but what if both persons lose connectivity? Who will notify the server?
Comment: At least in .NET (and I would guess in all server environments) it is possible to see if the client is still connected (tcp wise). EventSource/WebSockets helps you to establish an always open connection (as opposed to request/response connection with a short period of being connected) that you can monitor if its still operational/open.
Comment: @PeterAronZentai, I've also been thinking that the solution needs to be implemented at the websocket server.
Comment: I don't see any other reliable way...
Comment: I'm creating a demo app, to test how well this will work, and I will update the question once I'm done. In the meantime, perhaps you'd like to add your comments as an answer, so I could upvote them?
Answer: Why dont you look into HTML5 EventSource or WebSockets as possible means of detecting connectivity/loss of connection?
At least in .NET (and I would guess in all server environments) it is possible to see if the client is still connected (tcp wise). EventSource/WebSockets helps you to establish an always open connection (as opposed to request/response connection with a short period of being connected) that you can monitor if its still operational/open.
So essentialy the solution needs to be implemented at the websocket server.


Are ballroom dance competitions just for trophies only?

Question: I visited several dancesports web sites, such as the 2018 New England Dancesports Championships, and I only see entry fees mentioned.
There is no mention of any prizes. What are the prizes? Are dance competitions just for flowers and trophies?
Answer: The dance competition you linked to is an amateur competition. However, there are professional dance competitions with prize money, such as the United States Dance Championships.


Are there any classification systems that categorize music by mood?

Question: Recently I had the idea to categorize my digital music library with mood tags.
Thinking about these moods, I figured that it's not so easy to come up with a complete list that covers all possible emotional impressions.
Some example categories could be "happy", "sad", "mellow", "aggressive", "uplifting", "melancholic", "joyful", etc.
Are there any classification systems that categorize music by mood?  What are they based on?  Have you used them, and why?
Answer: Some very famous pieces of music have started with a mood description written on the sheet music by the composer.
Some other have become the perfect example of a given mood (Appassionata, Pathetic for Beethoven)
You could start with the MIREX vocabulary clusters

Cluster 1: passionate, rousing, confident, boisterous, rowdy
Cluster 2: rollicking, cheerful, fun, sweet, amiable/good natured
Cluster 3: literate, poignant, wistful, bittersweet, autumnal, brooding
Cluster 4: humorous, silly, campy, quirky, whimsical, witty, wry
Cluster 5: aggressive, fiery, tense/anxious, intense, volatile,visceral

Some people use research from psychologist about human moods such as Robert Thayer's (not restricted to music).
Classifiying music is a very active research subject, especially these days for commercial reasons. Every internet music platform wants to propose and sell tracks to their users by different recommendation systems. Classifying (if possible automatically) music tracks becomes a way to feed such a recommendation system.
If people work with clusters, it is because they encountered difficulties in predicting reliably appartenance of music to finer divisions.
To refine these mood clusters, what you can do is take all the adjectives in each cluster, their synonyms and try to see if you can either group some of them or draw limits between them based on simple concepts.
Companies like Pandora are known to have designed a multi-criteria classification of music pieces and song, constructed first by humans as the Music Genome Project. Their model is quite sophisticated and could be of great interest to a composer.
Other usual (commercial) suspects (without restricting themselves to mood classification or contiguity) are Last.frm, MusicBrainz, Spotify, Musicovery, Aupeo, Stereomood, ...  Members of these organizations sometimes write research articles about what they do. Many universities labs do research on this (US MIT, Sony, French IRCAM, ...). There are alternative systems, some based on color like Ghost.
Also if you want to have non standard descriptive phrase for music pieces, you can enjoy Satie's french humour, like in "Morceaux en forme de poire".
Answer: Just to add information, indian classical music is based on the concept of Raga ("color"), a hard to define concept because it doesn't exists in western music as it is, but we can say it's the melodic system used in ICM, the modal framework. Raga generates Bhavas ("moods") and these moods generate Rasa ("essence") and it's the essence of an emotion that the performed art generates. Thus, different ragas ("modes") invoke particular rasa (the essence of a emotion or mental state). One can say that raga is the colors which paint particular moods and the experience of the essence of a emotion on the listener's mind.
Answer: This company builds its business around defining the mood of music. It's important because their goal is to deliver a system which can help you tune the music to the mood you desire.
I don't know it they already have an English intro on their site, I couldn't find it. But maybe that is because I get automatically relocated to the Dutch one.
Anyway, maybe their way of categorizing music according to mood can give you some ideas.
EDIT: From what I could gather on this list, they have following classes:
Comfortable, dynamic, intense, intimate, mystical and relaxing. Each of these is then further subdivided according to genre.
Answer: Yeah, that's called genre.
More specifically, genres tend to draw their boundaries at mood shifts, and often newer subgenres will have mood/emotion as part of their name.
I love using this particular photo as evidence.

Others have made me aware that many genres are named differently, and I must now backtrack a bit and offer that genres, at their basis (bases? basises?), get their names from differences in the sound of the music, but I'll stick to my original point that at least some genres do use emotional feel as a weak qualifier.
Comment: I can't say this helps. If a genre, let's say 'singer-songwriter', can include songs that are both very happy and very sad, then it seems like there is only a very weak correlation between genre and mood.
Comment: While a agree that certain genres correlate with specific moods (there's hardly a cheerful death metal song), I think classifying moods by genre is pigeonholing too much.
Comment: I totally agree with that, but there's at least some tendencies along genre lines, and allowing for no inferences is too weak to be useful, in my opinion. Sure, one could argue that genres can have any mood they want, but that doesn't really help anyone understand the differences between genres, or moods, for that matter.


Error applying patch with Git

Question: I have read different SE posts and Drupal.org posts about applying patches using git but I am getting an error message whenever I try any of the following methods. the error is:

error: modules/callbacks.inc: No such file or directory

I tried:
curl https://www.drupal.org/files/issues/op_update_should_be_create-2807275-2.patch | git apply -
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   668  100   668    0     0   2278      0 --:--:-- --:--:-- --:--:--  2279
error: modules/callbacks.inc: No such file or directory

Also, I downloaded the patch into Drupal root and tried:
git apply -v op_update_should_be_create-2807275-2.patch

The backstory:
I was getting the following errors on my website, which I found this discussion explaining that it was because of Entity API, and I was trying to apply the patch in #2.

Notice: Undefined property: stdClass::$custom in
  block_block_list_alter() (line 794 of
  /Applications/AMPPS/www/example/docroot/modules/block/block.module).
  Notice: Undefined property: stdClass::$visibility in
  block_block_list_alter() (line 807 of
  /Applications/AMPPS/www/example/docroot/modules/block/block.module).
  Notice: Undefined property: stdClass::$pages in
  block_block_list_alter() (line 817 of
  /Applications/AMPPS/www/example/docroot/modules/block/block.module).

This is my first time trying to apply a patch.
Answer: Place op_update_should_be_create-2807275-2.patch into the module folder, in this case being the sites/all/modules/entity folder.
Then in your terminal cd (change directory) into the module folder.
cd /var/www/drupal/sites/all/modules/entity
then
git apply -v op_update_should_be_create-2807275-2.patch
In the discussion, Fago has commited this patch (2 months ago), but into the 7.x-.1.x only.

So I assume you're trying to patch the stable version, 7.x-1.8.
If you use/download the latest dev (7.x-1.x-dev) version, it will already have the patch.
Note: The rule of thumb, is to use the Stable version rather than the Dev version.
Comment: @Christia you misunderstood. The 1.8 version does not have the patch yet (as the commit was made 2 months ago to the 1.x, the 1.8 was released 5 months ago, which means it does not have the patch, so you need to apply the patch to the 1.8.
Comment: Thanks for the comments. I check and I am already on 1.8 version. So I guess that means that this patch isn't the answer I need.
Comment: I counted the months wrong, 1.8 was released 7 months ago, but yeah you get my point `:)`

Error applying patch with Git


Multiple Antidifferentiation

Question: Suppose that I have the following:
$$p(x)=\sum_{k=0}^n{c_kx^k}$$
$$q_M(x)=\sum_{k=0}^n{c_k\frac{x^{k+M}}{(k+M)_M}}$$
where $(k+M)_M=(k+M)(k+M-1)...(k+1)$ is the falling factorial.  I think it is clear that if we take the $M$-th derivative on $x$, the following is true
$$\frac{d^M}{dx^M}q_M(x)=p(x)$$
Suppose though that I am interested in a mapping $I:\mathbb{Q}_n[x]\rightarrow \mathbb{Q}_{n+M}[x]$ such that $I(p(x))=q_M(x)$.  THe main issue I think with the Integration operator, which would normally handle this antidifferentiation, does not yield a singlular result due to the differentiaion operation being onto only.  Clearly, I think, $q_M$ is an $n$-dimensional object but it is embedded (is this the right term...) in a higher $n+M$ dimensional space so integration $p(x)$ would yield an extra term, the constant of variation, every time the antidifferentiation would occur.
My question is; is there a way around this?  Is there a way of integrating polynomials so that we can neglect that term.  Or, probably a better way of stating the problem as above; can we find a mapping $I$ from $\mathbb{Q}_n[x]$ to $\mathbb{Q}_{n+M}[x]$ such that $Ip(x)=q_M(x)$ without just defining it from the onset and using such tools as integration multiple times?  Is there a way, perhaps, using definite integration and picking specific bounds multiple times that would negate the constant of variation once we integrated?
Answer: Sure: use the definite integration operator.
$$
J(p)(x) = \int_0^x p(t) dt
$$
for $p$ any polynomial. This can be written out as a linear map in terms of the coefficients of $p$ (the matrix form is just a superdiagonal matrix).
Comment: Assuming you list your coefficients starting with the constant and working up to highest order, for quadratic-to-cubic integration, it's just $\begin{bmatrix} 0 & 0 & 0 & 0 \\ 0 & 0 & \frac{1}{2} & 0 \\ 0 & 0 & 0 & \frac{1}{3}\end{bmatrix}$.
Comment: So for multiple integrations just continue using different dummy variables?  $$\int_0^x \int_0^{x_1} \int_0^{x_2} p(x_3}dx_3 dx_2 dx_1$$
Comment: For multiple integrations, iterate the operator $J$, yes.That's pretty much what your formula for $q_M$ above does already. In particular, it converts the constant function $x \mapsto 0$ into $x \mapsto 0$ after $M$ integrations...which is fine, because $M$ differentiations will turn it back into..$x \mapsto 0$.
Comment: Okay.  That seems to work.  I tried to edit my post so that I could show an example, but I feel pretty confident that I understand.  Thank you.
Comment: Out of curiosity, what would the superdiagonal matrix form look like?

Multiple Antidifferentiation


changed position buttons in dynamic layout

Question: I have this XML.I want to include dynamic buttons in the linearlayoutUp of the XML code with the Java code, and I want that this buttons appear in horizontal position, any idea to hanged vertical to horizontal
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFCCCCCC"
android:orientation="vertical"
tools:context=".MainActivity" >

<LinearLayout
    android:id="@+id/linearlayoutUp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

     <ScrollView
  android:id="@+id/scrollView1"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:scrollbars="vertical" >

         </ScrollView>

</LinearLayout>

<com.example.nuevo.ControladorView
    android:id="@+id/drawing"
    android:layout_width="match_parent"
    android:layout_height="0dip"
    android:layout_marginBottom="3dp"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginTop="3dp"
    android:layout_weight="0.83" />

<LinearLayout
    android:id="@+id/linearlayoutDown"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

</LinearLayout>

</LinearLayout>

Comment: what are you trying to do with the second `LinearLayout` and `ScrollView`?
Comment: that linear is the area to create the buttons. the number of buttons could be high so I introduce the scrollView inside the layout4
Comment: hey! I delete the scroll ant it works,but i want to include the scroll, how I can do it? thanks thanks!
Answer: If you want to use a ScrollView, you put it around the Layout. Also, you should use a HorizontalScrollView since your list is horizontal.
Try this:
<HorizontalScrollView
  android:id="@+id/scrollView1"
  android:layout_width="match_parent"
  android:layout_height="wrap_content" >

    <LinearLayout
        android:id="@+id/linearlayoutUp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
    </LinearLayout>
</HorizontalScrollView>

Comment: I would like to do two buttons one up and one down and the functionality for all the same, wiht a tableLayout instead linear??
Comment: I have a XML file with a canvas and two linear layout, one up of the canvas and the other at the bottom. I want to have four buttons at the top and the other at the bottom, when I clicked one, (play button) I would like that this linear changed the buttons

thanks


Python - Programa de analise numeros

Question: Vamos lá! Estou tentando fazer um exercício de um programa, onde o usuário irá dar a quantidade de numeros que ele deseja para serem verificados, quais são os números, e se ele quer o maior ou menor, número entre eles.
PROBLEMA: Não estou conseguindo fazer com que o input dado no escolhaUser seja lido para uma tomada de decisão do programa;
print ('------------------------------------------------------------')
print ('               PROGRAMA Avaliação numero                    ')
print ('------------------------------------------------------------')

quantidade_num = input ('Quantos serão os números a serem avaliados? ')
lista_numero = []

i = 1
while i <= int (quantidade_num):
    numero_input = input ('Número #' + str(i) + ' ')
    lista_numero.append(numero_input)
    i += 1

escolhaUser = input('Quer o menor ou o maior número? ')

if escolhaUser == 'maior':
    escolhaUser = True
else:
    escolhaUser = False

def maior(colecao):
    maior_item = colecao[0]
    for item in lista_numero:
        if item > maior_item:
            maior_item = item
    return maior_item

def menor(colecao):
    menor_item = colecao[0]
    for item in lista_numero:
        if item < menor_item:
            menor_item = item
    return menor_item

if escolhaUser == True:
    decisao = maior(lista_numero)
else:
    decisao = menor(lista_numero)

print (str(decisao(lista_numero)))

TypeError: 'str' object is no callable
Comment: A pergunta é formatada com [markdown](https://pt.stackoverflow.com/editing-help).
Comment: Onde está `print(str(decisao(lista_numero)))` troque por `print(decisao)`
Comment: Outra coisa o python possui a funções nativas [`min()`](https://docs.python.org/pt-br/3/library/functions.html#min) e [`max()`](https://docs.python.org/pt-br/3/library/functions.html#max) que tornam desnecessárias suas funções `maior()` e `menor()`.
Answer: Basta você alterar a 'última linha do código' que seu problema será resolvido.
troque
print(str(decisao(lista_numero)))

por:
print(decisao)

Pronto!
É um simples problema de sintaxe. Você não criou o método decisao para chamá-lo através da forma decisao(). Você apenas criou a opção decisao e já indicou através dos if no seu programa qual será a decisão do user se vai ser o "maior" ou "menor"

Python - Programa de analise numeros


How to pass two or more arguments to a Button command?

Question: I'd like to pass 2 variable arguments in a function to be assigned to a Button command. These variables change within a for loop that also creates the buttons.
Mostly inspired by some of the top answers here and here, here are my fail attempts at trying to solve this problem based on what I read:
I tried using partial:
self.dct[(i, j)] = Button(command=partial(self.on_click, i, j))

Another try:
self.dct[(i, j)] = Button(command=partial(partial(self.on_click, i), j))

And another:
self.dct[(i, j)] = Button(command=partial(self.on_click, [i, j]))

.. Guess what?
tup = [i, j]
self.dct[(i, j)] = Button(command=partial(self.on_click, tup))

And then, lambda:
self.dct[(i, j)] = Button(command=lambda i=i, j=j: self.on_click(i, j))

Here's my code:
import tkinter as tk

from functools import partial

class Board(tk.Frame):
    board = None
    images = None
    tile = None

    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.tile = {}
        for i in range(10):
            for j in range(10):
                self.tile[(i, j)]['btn_obj'] = tk.Button(self.board, command=partial(partial(self.on_click, i), j))

    def on_click(self, i, j):
        print("X: {}, Y:{}".format(j, i))

partial always causes an error like this:
TypeError: on_click() takes 2 positional arguments but 3 were given

It's always mismatched number of arguments.
Meanwhile, lambda gets the wrong value of the variables, causing something of an error in tkinter's part.
Comment: Why do you think the `lambda` doesn't work? It looks correct to me.
Answer: The lambda in your question should work:
tk.Button(self.board, command=lambda i=i, j=j: self.on_click(i,j))

This binds the value i and j as the default values for the lambda parameters.
Personally I prefer lambda over partial, mainly because I don't have to import the functools module. If you wish to use partial, it should look like your first example:
tk.Button(self, command=partial(self.on_click, i, j))

In both cases, on_click will be passed the correct value for i and j based on their values when the button is created.
Here is an example based on your code, but with some unnecessary code removed for clarity:
import tkinter as tk
from functools import partial

class Board(tk.Frame):
    def __init__(self, parent, method):
        tk.Frame.__init__(self, parent, bd=2, relief="sunken")
        for i in range(10):
            for j in range(10):
                if method == "lambda":
                    button = tk.Button(self, command=lambda i=i, j=j: self.on_click(i,j))
                else:
                    button = tk.Button(self, command=partial(self.on_click, i, j))
                button.grid(row=i, column=j)

    def on_click(self, i, j):
        print("X: {}, Y:{}".format(j, i))

root = tk.Tk()
board1 = Board(root, method="lambda")
board2 = Board(root, method="partial")
board1.pack(side="top", fill="both", expand=True)
board2.pack(side="top", fill="both", expand=True)
root.mainloop()

Comment: How would I do this with the `bind()` method? I did something like this: `button.bind("", partial(self.on_enter, i, j))` but this error shows up again: `TypeError: on_enter() takes 3 positional arguments but 4 were given`
Comment: @mashedpotatoes: that's a different question, but the technique is precisely the same. You simply have to account for the extra argument sent by tkinter. Here's an example: https://stackoverflow.com/a/28996754/7432


Show Covergence, Integral

Question: $$\int_{0}^{1} \frac{e^x}{x^6+x} dx$$
This how i approached the problem:
1st Step : Using partial fractions.
$$e^x = A(x^5+1)+Bx^2+Cx$$
Now can i solve for $$Cx = e^x$$ and get $$C=e^{-ln(x)+x}$$
I want to understand if these are special kind of problem while, i dont think $$x^6+x)$$ is a polynomial that i could just factor. If someone has time and Energy to show me how it is done. Would highly appreciate it.
Comment: It's not useful to do integration by parts when the numerator is $e^x$.
Comment: $C=e^{x-\ln(x)}$, not $e^{\ln(x)-x}$
Comment: the integral is not convergent
Comment: Can i show convergence of it easily without calculating all the bits?
Comment: In a neighborhood of $0$ the integrand behaves like ${1\over x}\notin L^1(0,\varepsilon)$
Answer: Notice that $$\frac{e^{x}}{x^{6}+x}\geq \frac{1}{x^{6}+x}\geq \frac{1}{2x}$$ for all $x\in [0,1]$
Since the integrand is non-negative on $[0,1]$, the integral diverges by simple comparison with $$\int_{0}^{1}{\frac{dx}{2x}}$$
Comment: Is that all i have to show to say it converges?
Comment: Well, the argument actually shows quite the opposite. Your integral diverges
Comment: ok sorry i meant diverges, how about showing it with an upper bound and a lower bound how would that fit in here? Using Riemann.
Answer: Here's an argument by partial fractions. We can write:
$$\frac{e^x}{x^6+x} = \frac{-x^4e^x}{x^5+1} +\frac{e^x-1}{x} + \frac{1}{x}$$
The first term on the right side is continuous and hence integrable on $[0,1]$. The second term can be made continuous by defining it as $1$ at $x=0$ and hence is also integrable on $[0,1]$.
Thus $$\int_0^1 \frac{e^x}{x^6+x}\,dx$$ converges if and only if $$\int_0^1\frac{dx}{x}$$ converges. It doesn't.
Answer: HINT: use that for all real $x$ : $$e^{x}\geq x+1$$

Show Covergence, Integral


For loop is not executing as expected, sequence matters so can't use set() here

Question: I used a for loop to remove the duplicates in a list from the left side. For example, [3,4,4,3,6,3] should be [4,6,3]. And also the sequence cannot be changed, that's why I cannot use a set here. If I use set() here, the result would be [3,4,6].
def solve(arr):
    for i in arr:
        if i in arr[arr.index(i)+1:]:
            arr.remove(i)
    return arr

solve([1,2,1,2,1,2,3])

It should return [1,2,3]. Instead, I got [2,1,2,3]. I viewed the visualized execution of the code, and it seems when python got to the item '2' the second time, meaning when the arr is mutated to be [2,1,2,3], it just suddenly stopped iteration from the for loop and returned the list as it is. When it should detect there is still another '2' in the list. Please help
Comment: Rule #1: Don't remove item from list while iterating over it, it's like cutting off tree branch on which you sit.
Comment: ... You could use `set()` if order of elements in result does not matter.
Comment: ...and if you don't want to use `set` (which is really the simplest solution here) then iterate over your list but don't remove anything from it. Instead, create a new list and add items to to it.
Comment: Sorry I forgot to say that the sequence does matter, which is why I couldn't use set() here. And I agree that changing a list while iterating over it is not good practice, but I just want to understand why the last iteration is not being executed.
Answer: You can use set for this:
a  = [1,2,1,2,1,2,3]
b = set(a)

Then b will be:
{1,2,3}

Answer: You can try this way:
def solve(arr):
    another_arr = []
    for i in arr:
        if i in another_arr:
            another_arr.remove(i)
            another_arr.append(i)
        else:
            another_arr.append(i)
    return another_arr

print(solve([1, 2, 1, 2, 1, 2, 3]))


How to include .filter function in my data filtering component

Question: I got my data fetched, but I need to filter them based on the letter they include (typical live search), but I am not sure how and where to include the function
I am thinking the function would look something like this:
this.filteredResults = res.results.filter(filteredResults =>
              filteredResults.toLowerCase().includes(this.result.toLowerCase())
            );

And this is my data fetch using axios
 methods: {
    onChange() {
      axios
        .get("myURL")
        .then((response) => {
          this.filteredResults = response.data;
        })
        .catch((error) => {
          console.log(error);
          this.errors = true;
        })
        .finally(() => console.log("Data successfully loaded"));
      this.filterResults();
      this.modal = true;
    },

filterResults() {
          this.filteredResults = this.results.filter((result) => {
            return result.toLowerCase().includes(this.search.toLowerCase()) > -1;
          });
        },

    setResult(filteredResult) {
      this.search = filteredResult;
      this.modal = false;
    },
  },

  watch: {
    results: function(val, oldValue) {
      if (val.length !== oldValue.length) {
        this.filteredResults = val;
      }
    },
  },

Current output is showing whole list of data when start typing, but filtering does not work what so ever - no errors anywhere detected, when some item is clicked this is output in input (see image)

What is the right way to use .filter in Vue?
Answer: methods: {
    onChange() {
      axios
        .get("myURL")
        .then((response) => {
        this.filteredresults=FilterOnInput((response.data,document.getelementById("IdOfTheInput").value)

        })
        .catch((error) => {
          console.log(error);
          this.errors = true;
        })
        .finally(() => console.log("Data successfully loaded"));
      this.modal = true;
    },

//new !!
  FilterOnInput(list, inputFilter) {
  let filteredList = [];
  for (let i = 0; i < list.length; i++) {
    let name = list[i].Name; //if given returns are objects
    if (name.toUpperCase().includes(inputFilter.toUpperCase())) {
      filteredList.push(list[i]);
    }
  }
  if (inputFilter.length === 0) {
    filteredList = list;
  }
  return filteredList;
}

This getelementById("IdOfTheInput").value is only needed when working with id if you use a v-model, just put the name of the variable you use.
Comment: Thank you for the answer, but isnt there a simplier method how to implement it? I am just trying to learn Vue and want to know the basic functions before I'll dig into it and find other solutions
Comment: the awnser of omerS works the same, just not using the store getter, u can use the store in the computed instead of the "methods" doesn't really matters how you do it. i just showed you the "vuex" way of using store and his possibilities :)
Comment: Sure, I appreciate it :) I used `computed: {
    filtered() {
      return this.results.filter((filteredResults) =>
        filteredResults.toLowerCase().includes(this.result.toLowerCase())
      );
    },
  },` but unfortunately it still not working, is it used right ?
Comment: [here is sandbox link @tony19 (https://codesandbox.io/s/agitated-architecture-91tj6?file=/src/components/HelloWorld.vue:943-971)
Comment: i will edit my response so that you have a good awnser gimmi a sec


Checkbox not displays on chrome

Question: I cannot make chrome display correctly the checkboxes generated with the CakePHP form helper.
Labels are OK, but not checkbox can be seen, nor the value can be changed.
In the other web browsers it works OK.
Please see the attached screenshot.
Ideas ?
Comment: That's a pure CSS problem and not related to CakePHP. It might be a good idea to show what the inspector shows for the CSS or paste your whole CSS related to the checkboxes.
Comment: Post a [mcve] in your question please
Answer: Found it.  It was, of course, a css problem.  I've defined height: 100% for input fields.  It seems that chrome handles this in a different way than other browsers do.
Removing that line, makes chrome display checkboxes ok.
Regards.
Facundo.

Checkbox not displays on chrome


kdump issues - not saving memory dump / network issues

Question: I have a VMWare VM on an ESX host that has LVM partitions.  I've configured kdump with very basic configuration - ext /dev/mapper/logical-volume-name and path /data/crash.  When I force a system crash, it loads the kdump kernel and it shows the logical volumes, loads them and shows that it is saving the memory dump, and takes about 30 seconds to export about 2.5GB, which is normal.  The problem is, when it reboots, it comes back up, but no network connectivity (can't get out, and can't get in via network), however, all network services are running and a simple reboot (no crash) fixes this.  Additionally, another issue - the vmcore memory dump saved was not actually saved.  I've tested this on a VM on VirtualBox and this works running a CentOS equivalant of the RHEL server that is currently in production that is currently having these kdump issues.
Any ideas or things I should look in to?
Answer: I spoke to one of the developers for KDump and confirmed that this is a known bug.  At this time, I cannot make any changes to production, but have a very suspicious idea that either the kernel needs to be upgraded and/or something between the VM and the VM Host need looked into.

from    Eric W. Biederman
to  Drew Decker
cc  firstname.lastname@example.com,
email@example.com,
email@example.com,
firstname.lastname@example.com
date    Tue, Jan 25, 2011 at 1:50 PM
subject Re: KDump Question/Issues (Need a developer's eyes)

That does sound like a bug in the RHEL kernel interacting with VMware.

The fact that the reboot doesn't reset the hardware is frankly scary.

At this point any RHEL kernel is old and has not been updated by the
many many bug fixes that have happened between when they branched off
linus's tree and the present, and presumably comes with a support
contract by people that are paid to help you, and understand those
details, so I recommend you talk to the fine people at Red Hat.  They
should be able to help.

Usually problems like this come down to driver issues of some sort, not
issues in the actual kexec on panic infrastructure.  Although in this
case I would also suspect how the kdump kernel is calling reboot.

Good luck to you,
Eric


Como guardar texto em arquivo, XML ou TXT ou HTML?

Question: Eu estou a desenvolver um programa em C# e gostaria de saber como guardar o texto de uma RichTextBox em formato .xml ou .html ou .txt.
Comment: Você já tem algum código desenvolvido para colocar na sua pergunta?
Comment: Não mas postei essa pergunta pois eu sou iniciante e então eu não sei fazer isso.
Answer: A pergunta não dá detalhes mas a forma mais simples de fazer isto é usando o WriteAllText():
File.WriteAllText(caminhoCompletoDoArquivo, seuRichTextBox.Text);

Este método é pronto para o que deseja. Como o próprio nome diz ele escreve um texto no arquivo especificado em caminhoCompletoDoArquivo) não precisa ser uma variável, pode ser um texto com o caminho do arquivo, ex.: "c:\minhaApp\xml.txt") e ele pegará o conteúdo a ser gravado diretamente o controle através da propriedade Text do objeto seuRichTextBox.
Para ler:
var texto = File.ReadAllText(caminhoCompletoDoArquivo);

Coloquei no GitHub para referência futura.
Documentação do ReadAllText().
Evidentemente que os dados em formato XML e HTML devem estar em ordem. A gravação não garante nada. Estes métodos só fazer a gravação de um texto sem saber o que ele significa e se está certo.


Divide case by population

Question: In the table2 dataset from the tidyr package, we have:
  country  year       type      count
         <chr> <int>      <chr>      <int>
 1 Afghanistan  1999      cases        745
 2 Afghanistan  1999 population   19987071
 3 Afghanistan  2000      cases       2666
 4 Afghanistan  2000 population   20595360
 5      Brazil  1999      cases      37737
 6      Brazil  1999 population  172006362
 7      Brazil  2000      cases      80488
 8      Brazil  2000 population  174504898
 9       China  1999      cases     212258
10       China  1999 population 1272915272
11       China  2000      cases     213766
12       China  2000 population 1280428583

How do I code this so that I can divide the type cases by the type population and then multiply by 10000. (Yes, this is a question from R for Data Science by Hadley Wickham.)
I've thought of:
sum_1 <- vector()
for (i,j in 1:nrow(table2)) {
  if (i %% 2 != 0) {
    sum_1 <- (table2[i] / table2[j]) * 10000

Comment: What is the expected result suppose to look like?
Comment: @RomanLuštrik the resulting dataset should be a tibble with a new column (rate) and ideally, have values computed by dividing counts for cases by counts for populations and multiplied by 10000 grouped by each country for each year.
Comment: @RomanLuštrik is this confusing you? :)
Answer: Assuming that there are only 2 values for 'type' for each 'country', 'year', then after grouping by 'country', 'year', arrange by 'type' (in case the order is different) and divide the first value of 'count' with the last value of 'count' to create the 'newcol'
library(dplyr)
table2 %>%
    group_by(country, year) %>%
    arrange(country, year, type) %>%
    mutate(newcol = 10000*first(count)/last(count))

If we need only a summarised output, replace mutate with summarise

If there are other values in type in addition to 'cases' and 'population', then we subset the 'count' based on logical index
table2 %>%
   group_by(country, year) %>%
   mutate(newcol = 10000*count[type=="cases"]/count[type=="population"])

Here, also the assumption is that there is only a single 'cases' and 'population' per each 'country', 'year'
Comment: @JasonJoonWooBaik  It is the `group_by` which makes sure that we use only the 'count' values from that particular 'country' and 'year'
Comment: Thanks!!! This works fabulously. However, I don't understand what part of your code enables me to calculate the rate for each year and country.

Divide case by population


Laplace transform of a resonant second-order ODE

Question: I'm trying to solve the following ODE with the Laplace transform $y'' + y = \cos \omega t$ with initial conditions $y(0)=y'(0)=0$.
I get $Y(s) = \frac{s}{(s^2 + 1)^2}$ but then, I don't know how to compute the inverse transformation. Decomposing this fraction into partial fractions does not help in this specific case, which seems to involve resonance. How would you use the inverse Laplace transform to get the final solution? Thank you for your help!
Answer: Source: Inverse Laplace Transform partial fraction $\frac{\omega ^{2}}{\left ( s^{2}+\omega ^{2} \right )( s^{2}+\omega ^{2} )}$
By taking the derivative $\frac{d}{d \omega} \mathcal{L}(\cos \omega t) = \mathcal{L}(- t \sin \omega t) = \frac{d}{d \omega} \frac{s}{s^2 + \omega^2} = - \frac{2 \omega s}{(s^2 + \omega^2)^2}$. The derivative commutes with the Laplace transform in this case since we derive w.r.t. $\omega$ while the Laplace transform integrates w.r.t. $t$.
Finally, fix $\omega=1$, so we obtain $\mathcal{L}(t \sin t) = \frac{2s}{(s^2+1)^2}$ and then $y(t) = \frac{1}{2} t \sin t$.
Comment: After writing the question, Stack Exchange recommended looking at some existing questions and I found the one that I cited as the source. I completed the exercise and then I hesitated to remove it, but then I read this [link](https://stackoverflow.blog/2011/07/01/its-ok-to-ask-and-answer-your-own-questions/?_ga=2.53439528.1446735456.1709907132-2099619096.1708809681) so I decided to post it anyway in case it can help someone else. I'm ok to remove it if you think it is not useful.
Comment: Why did you ask for help if you already knew how to solve the problem?


Navegar entre diferentes pilhas em React Native com react-navigation

Question:
Objetivo: Navegar da screen LoginScreen para screen MainScreen

Codigo das rotas em routes.js:
const AuthenticationNavigator  = createStackNavigator({
    Login: {
      screen: LoginScreen,
      navigationOptions: {
        title: 'Login',
        headerShown: false, //desabilita a barra do topo
      },
    },
    Register: {
      screen: RegisterScreen,
      navigationOptions: {
        title: 'Cadastro',
      },
    },
  }, {
    initialRouteName: 'Login',
    defaultNavigationOptions: {
      headerTitleAlign: 'center',
      headerTintColor: '#FFF',
      headerStyle: {
        backgroundColor: '#121212',
      },
    }
})

const MainNavigator = createStackNavigator({
  Main: {
    screen: MainScreen,
    navigationOptions: {
      title: 'Main',
      headerShown: false,
    },
  },
}, {
  initialRouteName: 'Main',
  defaultNavigationOptions: {
    headerTitleAlign: 'center',
    headerTintColor: '#FFF',
    headerStyle: {
      backgroundColor: '#121212',
    },
  }
})

const AppNavigator = createSwitchNavigator({
  /*
   * Rather than being rendered by a screen component, the
   * AuthenticationNavigator is a screen component
   */
  Auth: AuthenticationNavigator,
  Home: MainNavigator,
}, {
  initialRouteName: 'Auth'}
);

const AppContainer = createAppContainer(AppNavigator);
export default AppContainer

Como estou tentando usar no arquivo App.js
render() {
    if (!this.state.isAuthenticationReady) {
      return (
        {}
      );
    } else {
      return (
        <>
          <StatusBar barStyle="light-content" backgroundColor="#121212" />
          {this.state.isAuthenticated ? <AppContainer /> : <AppContainer />}
        </>
      );
    }
  }

Como eu uso o AppContainer no meu arquivo principal App.js? E como faço para navegar entre as Screens das diferentes stacks?
Answer: O createAppContainer você vai utilizar apenas uma vez. Dentro do seu AppContainer, você pode ter dentro um StackNavigator, e dentro dele, cada elemento pode ser um componente (como no seu exemplo), ou um outro Stack.
Um outro exemplo seria você ter dentro do seu AppContainer um TabNavigator, e cada item ser um Stack.
Sendo assim, para funcionar a navegação entre telas, o seu AppContainer deve ter um Stack com os componentes Login, Register e Main. Ele ficaria da seguinte forma.
export const Intro = createAppContainer(
  createStackNavigator({
    Login: {
      screen: Login,
      navigationOptions: {
        title: 'Login',
        headerShown: false, //desabilita a barra do topo
      },
    },
    Register: {
      screen: Register,
      navigationOptions: {
        title: 'Cadastro',
      },
    },
    Main: {
      screen: Main,
      navigationOptions: {
        title: 'Main',
        headerShown: false,
      },
    },
  },{
    initialRouteName: 'Login',
    defaultNavigationOptions: {
      headerTitleAlign: 'center',
      headerTintColor: '#FFF',
      headerStyle: {
        backgroundColor: '#121212',
      },
    }
  })
);

Dentro de Login, para navegar para Main, você pode fazer o seguinte
this.props.navigation.navigate("Main");

Cada componente de sua rota recebe uma props chamada "navigation", que vai permitir a navegação entre telas.  Se você criar um botão em sua página login e adicionar este código, deve funcionar.  Essa props apenas se aplica aos componentes da rota, os componentes abaixo por padrão não recebem esta props.
Aqui tem mais informações:
https://reactnavigation.org/docs/en/common-mistakes.html
https://reactnavigation.org/docs/en/navigation-prop.html
https://reactnavigation.org/docs/en/connecting-navigation-prop.html
Comment: Mas eu queria separar em duas Stacks, uma de autenticação e outra da Main, onde vou adicionar mais funcionalidades, tentei fazendo o createSwitchNavigator, mas estou tento problemas, vou atualizar o codigo como esta atualmente


How do I set the page title from view result (same as the view result)

Question: I have set up a View that shows a random page from the site filtered according to node types and uses the Global : Random (asc) sort criteria. It displays only one result per page and a fresh page is shown every time the page is refreshed.
I want to set the view's page title to be same as the node displayed. I am doing this using javascript right now, but would prefer a PHP alternative that I could either use in the template or the views setting directly.
Setting the page title using javascript isn't SEO friendly.
I am using the latest version of Drupal 6 with the latest stable release of Views 3.
The results of print_r($view->result, true) (as requested) are :
Array
(
    [0] => stdClass Object
        (
            [_random] => 0.00171253550957193
            [radioactivity_node_1_s_energy] => 3
            [node_title] => <Title of the node being displayed>
            [nid] => 393
        )

)

Answer: Inside a views template, you could call drupal_set_title() with whatever you want out of the $view->result array.  You can put a drupal_set_message('
' . print_r($view->result, true) . '
'); or its equivalent in there to see what you have to work with.
In Style Settings, just click on Theme Information, and choose one, I'd suggest modifying the Style Output one because you could also change $title in there as well.
ADDITIONS DUE TO COMMENTS:
No, views will not set this for you, I thought that's what you were asking.
In your views template for the view in question, you need to dig into your row result to get the value you want and then call drupal_set_title() with that.  Calling it with a null value only returns the existing title, if any.
For example, if you put the print_r() of your result in there, you will see what values you have to work with, and then you use them with this to set the title.
Let's say you have something like this:
[0] => stdClass Object
    (
        [node_title] => Sirens
        [nid] => 240
        [_random] => 0.000554758124570137
    )

which is the view result from a view I just put together that randomly returns node titles, you would do something like this in your template:
$title=check_plain($view->result[0]->node_title);
drupal_set_title($title);

You could also put this in a pre_render() hook like so:
function YOURMODULE_views_pre_render(&$view) {

  if ($view->name==NAMEOFYOURVIEW) { // && $view->current_display == 'page' if needed
    $title=check_plain($view->result[0]->node_title);
    drupal_set_title($title);
  }

}

But either way, since I don't know exactly what your view row looks like, I can't tell you precisely what $view->result[0]......  you need.
Also, all of this is assuming your theme behaves nicely with the $head_title variable as well.
Comment: I tried adding `` and `` in the style output template, separately in different attempts. None of the approaches worked.
Comment: what did you set `$title` to?
Comment: I did not set it to anything. Isn't that set by the View?
Comment: I did whatever you mentioned here, and it works, except it's still not changing the document title. I thought `drupal_set_title()` does the same. Can the `pre_render()` hook be added to my theme's template.php?
Comment: I've only used the pre_render() hook within a module, and a quick test here didn't work by naming it MYTHEME_views_pre_render() and putting it in my template.php file, so if you don't have a custom module, putting the code in your views template looks to be the only way to go.  I would put a `$title='foobarbaz'; set_drupal_title($title);` or something in there to make sure your template is being called as all of the above worked here.  Also, if you want to edit your question with a print_r() of your `$view->result`, that would help out as well.
Comment: Yeah, I tried adding it to my template.php file too, didn't work. I have added the result of the `print_r()` you requested in my question, take a look. It's not much different from yours, except I have also used the radioactivity module to help sort the results obtained from the view in a descending order. Please remember that only one node is displayed per page.
Comment: Also, could you tell me what do you mean by `Also, all of this is assuming your theme behaves nicely with the $head_title variable as well.`
Comment: This is a case of "it should work" as you have your title is in there similarly.  So, you have to make sure that your view template is correct, it should be named something like `views-view-unformatted--VIEWNAME.tpl.php` (assuming unformatted is your row style, insert whatever here if otherwise) and that Views is seeing it...
Comment: $head_title is the variable that is put inside ` ... ` in the page `` by most themes.
Comment: I have a custom theme (Zen subtheme, actually) that does have `$head_title` in the title tag.
The template filename is also correct, I copy-pasted it form the theming infomation field and then using the rescan template files button. The filename appears in bold over there, so I assume it's correct and the view sees it.
Comment: The node title is getting set, but the document/page title isn't.


Android Navigation Component has lag when navigating through NavigationDrawer

Question: I am updating my app to Navigation Architecture Components and I see that it has a lag replacing fragments which is visible in the NavigationDrawer that does not close smoothly.
Until now, I was following this approach:
https://vikrammnit.wordpress.com/2016/03/28/facing-navigation-drawer-item-onclick-lag/
So I navigate in onDrawerClosed instead than in onNavigationItemSelected to avoid the glitch.
This has been a very common issue, but it is back again. Using the Navigation Component, it is laggy again and I don't see a way to have it implemented in onDrawerClosed.
These are some older answers prior to Navigation Component
Navigation Drawer lag on Android
DrawerLayout's item click - When is the right time to replace fragment?
Thank you very much.
Comment: Unfortunately, I've hit the same problem. The only workaround I came up with was to make the Fragment wait a bit before loading its contents, but that's far from ideal. I wish there was a better way to solve this...
Comment: Can you public code and xml?
Comment: I dont know how it was in 2019, but using the Navigation version 2.4.1 you can overwrite `onDrawerClosed` and put the fragment navigation logic using `NavController` class and `.navigate(..)` method. All as per my knowledge.
Answer: I'm tackling this issue as I write this answer. After some testing, I concluded that code I'm executing in fragment right after its created (like initializing RecyclerView adapter and populating it with data, or configuring UI) is causing the drawer to lag as its all happening simultaneously.
Now the best idea I got is similar to some older solutions that rely on onDrawerClosed. We delay the execution of our code in fragment until the drawer has closed. The layout of the fragment will become visible before the drawer is closed, so it will still look fast and responsive.
Note that I'm also using navigation component.
First, we are going to create an interface and implement it fragments.
interface StartFragmentListener {
    fun configureFragment()
}

In activity setup DrawerListener like:
private fun configureDrawerStateListener(){
    psMainNavDrawerLayout.addDrawerListener(object: DrawerLayout.DrawerListener{
        override fun onDrawerStateChanged(newState: Int) {}
        override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}
        override fun onDrawerOpened(drawerView: View) {}

        override fun onDrawerClosed(drawerView: View) {
            notifyDrawerClosed()
        }

    })
}

To notify a fragment that the drawer has been closed and it can do operations that cause lag:
private fun notifyDrawerClosed(){
    val currentFragment =
            supportFragmentManager.findFragmentById(R.id.psMainNavHostFragment)
                    ?.childFragmentManager?.primaryNavigationFragment

    if(currentFragment is StartFragmentListenr && currentFragment != null)
        currentFragment.configureFragment()

}

In case you are not navigating to the fragment from the drawer (for example pressing back button) you also need to notify fragment to do its things. We will implement FragmentLifecycleCallbacksListener:
private fun setupFragmentLifecycleCallbacksListener(){
    supportFragmentManager.findFragmentById(R.id.psMainNavHostFragment)
            ?.childFragmentManager?.registerFragmentLifecycleCallbacks(object : FragmentManager.FragmentLifecycleCallbacks() {

        override fun onFragmentActivityCreated(fm: FragmentManager, f: Fragment, savedInstanceState: Bundle?) {
            super.onFragmentActivityCreated(fm, f, savedInstanceState)

            if (!psMainNavDrawerLayout.isDrawerOpen(GravityCompat.START)) {
                if (f is StartFragmentListener)
                    f.configureFragment()
            }

        }
    }, true)
}

In fragment:
class MyFragment: Fragment(), MyActivity.StartFragmentListener {
    private var shouldConfigureUI = true
    ...

    override fun onDetach() {
        super.onDetach()
        shouldConfigureUI = true
    }

    override fun configureFragment() {
        if(shouldConfigureUI){
            shouldConfigureUI = false
            //do your things here, like configuring UI, getting data from VM etc...
            configureUI()
        }
    }
}

A similar solution could be implemented with a shared view model.
Comment: No, this solution will handle it. BackStackListener will register every fragment change in host fragment, but it will only call configureFragment() if drawer was closed when fragment was changed - indicating that we navigated to that fragment outside the drawer.
Comment: Ah! You're right. Amazing :) Good thinking. I'll test it today.
Comment: I've tested your solution, and man, that's a huge improvement in performance, thank you! As for the potential bug, a flag might solve the issue, but I'm also unsure if it can really happen.
Comment: @Mauker it has to be done, I missed it. I will update it now, thank you.
Comment: What if it's also possible to navigate to the fragment outside from the drawer? I would have to call the `configureFragment()` "by hand" right?
Comment: I found a problem with BackStackListener, there is a case when it wont register fragment change. When i pop up backstack when navigating so the destination fragment will be only fragment on backstack, BackStackListener wont be called. I will edit my answer to handle this :)
Comment: As for your edit, shouldn't we reset the variable once the fragment has been detached?
Comment: Great solutions
Comment: When you have tapped on outside the drawer then drawer closes. But I wanted the drawer to be closed smoothly on item selected. I have solved this by adding shouldConfigureUI = true in onViewCreated and shouldConfigureUI = false after configuring UI.
Comment: Unfortunately, this clever approach did not help me. Drawer still lagged and I have not noticed any performance improvement. Looks like in my case initializing RecyclerView adapter and populating it with data and configuring UI are not as "heavy" operations as creating and inflating a View.
Comment: Try experimenting, disable displaying and loading data for some performance test, is your layout loading some heavy images etc? Maybe you could even add layout elements after the drawer is closed and initially only display root layout and maybe progress bar. @MichaelZur
Comment: The heaviest in my layout is a nested Google Maps fragment as . I thought the map loading starts afer I run `.getMapAsync()`, but turns out no. So, indeed, I might add it dynamically using your method. However, overwriting `onDrawerClose` works for me now. I might consider migrating to your method later again and then I will follow up on performance. @UrosKekovic
Answer: Avoid the lag caused while changing Fragment / Activity onNavigationItemSelected- Android
Navigation Drawer is the most common option used in the applications, when we have more than five options then we go towards the navigation menu.
I have seen in many applications that when we change the option from the navigation menu, we observe that it lags, some people on StackOverflow recommended that use Handler like the below code:
private void openDrawerActivity(final Class className) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                ProjectUtils.genericIntent(NewDrawer.this, className, null, false);
            }
        }, 200);
    }

But in the above code, it's still not smooth & I thought why we add handler may be there is another solution after so much R&D, what I figure it out that we need to change the fragment/activity when the drawer is going to be close. let's see with the implementation.
For more details with solution kindly go through https://android.jlelse.eu/avoid-the-lag-caused-while-changing-fragment-activity-onnavigationitemselected-android-28bcb2528ad8. It really help and useful.
Hope you find better solutions in it!
Comment: This question is about the Navigation Component Library
Comment: Instead of using postDelayed, isn't there any onTransitionDone function or like ?


how to create azure data factory project in vs2017?

Question: how to create azure data factory in vs 2017?
I dont have vs2015, what can i do?
I checked for online template but cant find one.
similar questions is : Azure Data Factory project with Visual Studio 2017
but it does not have answer.
Comment: Possible duplicate of [Azure Data Factory project with Visual Studio 2017](https://stackoverflow.com/questions/43001227/azure-data-factory-project-with-visual-studio-2017)
Answer: There is currently no template for creating data factories using VS 2017.  The best you can do is install Visual Studio 2015 and then install the data factory tools
Comment: You can add your vote to the UserVoice issue for this [here](https://feedback.azure.com/forums/270578-data-factory/suggestions/18773008-support-adf-projects-in-visual-studio-2017)


Is it a subspace or not?

Question: Is $$\mathscr{S_1}=\lbrace(a,b,c)\in\mathbb{R}^3:a^3=b^3\rbrace$$ subspace of R^3?
my try:: $a^3=b^3\iff a=b$ in $\mathbb{R}$. So $\mathscr{S_1}=\lbrace(a,a,c)\in\mathbb{R}^3\rbrace$ this is a plane going through the origin so it is a subspace
Is $$\mathscr{S_2}=\lbrace(a,b,c)\in\mathbb{C}^3:a^3=b^3\rbrace$$ subspace of C^3?
my try:: $a^3=b^3\iff a=b$ or $a=(-b+\sqrt{-3b^2})/2=b*\rho_1$ or $a=(-b-\sqrt{-3b^2})/2=b*\rho_2$ where $\rho_1=\frac{-1+\sqrt{-3}}2$ and $\rho_2=\frac{-1-\sqrt{-3}}2$ .... at the end i get it is a subspace, is my try right? if not why not?
Comment: For the complex, no. You should find not closed under addition. The first is a subspace. A proof using algebra language is probably  required, though I like your geometric viewpoint.
Comment: The second will not be a subspace; that "or" changes things significantly.
Comment: The reason that the first one works is that $x \mapsto x^3$ is injective on the reals, so $a^3 = b^3$ **iff** $a=b$. This suggests a possible way to obtain a counterexample.
Comment: @Timbuc both are closed under scalar multiplication, your example is false
Comment: @copper.hat What i don't understand is the or. So can i choose for example $a=b$ in $\mathscr{S_2}$ and $a=b*\rho_1$ in $\mathscr{S_2}$ and add them? (then it is obvious)
Comment: Well, I think it is easier to guess & verify here. Choose $a=1$ and find all complex $b$s such that $b^3=1$. This will give, say, $(1,b,0)$ and $(1,\bar{b},0)$. Then see if $(2, b+\bar{b},0)$ lies in the set.
Comment: @copper.hat okay, i was more thinking of $(-b*\rho_1,-b,-c)$ , $(b*\rho_2,b,c)$ then their sum $(b(\rho_2-\rho_1),0,0)$ which isn't there
Comment: Whatever works. A better take on my example would be the difference $(0,b-\bar{b},0)$, but I always figure out the best solution afterwards :-).
Comment: right, thanks to you all!
Answer: Hint
Look at the axioms. Obviously $0\in\mathcal S_2$ and $\lambda x\in\mathcal S_2$ for $\lambda\in\mathbb C$ and $x\in \mathcal S_2$. What will blow up is that
$$x,y\in\mathcal S_2 \not\Rightarrow x+y\in\mathcal S_2$$
Try to find a counter-example for that, it's not hard ;)
Comment: What i don't understand is the or. So can i choose for example $a=b$ in $\mathscr{S_2}$ and $a=b*\rho_1$ in $\mathscr{S_2}$ and add them? (then it is obvious)
Comment: @user211273 Yes, you can even take concrete values such as $(1,1,0) + (\omega_3,1,0) \notin \mathcal S_2$.

Is it a subspace or not?


How to get text before the title?

Question: I suppose this is something about theming, but I haven't found a way to do this. I'm using the Pixtures Reloaded subtheme of Adaptive Themes.
I have a group of pages that need to have the structure:

     Pretitle
     Title
     Subtitle
     Body

that should come out looking like this:

A true story:
               The Amazing Thing
              And Why it's Amazing
This is the story of...

The title and subtitle are centered.
When I create a "Basic page", I have to specify a title for the page, and that title is displayed at the top-left of the page. I tried two ways to get something to be shown before the title.
First I defined a block called "Pretitle" and placed it in the theme's region called "Secondary content", which in the "Block region demonstration" is shown as being above the title. But when I displayed the page, the pretitle was exhibited under a big banner that said "Pretitle". That's not okay.
Next, I deleted that and defined a text field called "Pretitle" and placed that above the title in the Field Manager. When I displayed the page, the pretitle appeared at the very bottom of the page, under a line that said "Pretitle:". Again, not okay.
Aside from not seeing how to get a line of text to appear before the title (without a banner saying that it's a pretitle), I also have not a seen a way to get the title to be centered horizontally on the page.
I'm guessing this problem is because there's something really simple about composing pages in Drupal that I don't know about. Can you tell me what I'm missing?
Please don't give an answer that requires writing my own module because I'm not nearly ready to do that yet.
Thank you.
Answer: to center the title: find the appropriate css file, and change:
.title, #page-title
{
...
}

to include
.title, #page-title
{
  text-align:center;
}

It could be listed as either the class title, or id, depending on the theme. This is basic CSS.
to include the other fields:
1) you can alter the page.tpl.php file for theme, but if modules are out,  I assume most any php is out, so this is probably not suitable.
2) reassign your block if it otherwise worked, but in the block set up, change the Block Title to <none>
Comment: Thank you Geoff. In (2), deleting the contents of the block title worked. Re the first part, I didn't find ".title, #page-title", but I did find "h1#page-title {padding: 0; margin: 0 0 0.46em;}" in "sites\all\themes\pixture_reloaded\css\pixture_reloaded.css". I added "text-align:center;" there, but that didn't have any effect that I saw. However, looking around in that CSS file, I found something on Extensions, so I went back to the theme settings and found "Extensions > Title Styles", which allowed me to set the title alignment. So I got both parts of the problem solved. Thank you.
Comment: ok - you could have added the css to the end of file since it wasn't already there. An easy way to find it is to use Developer tools in either Firefox or Chrome - it would allow you to narrow down what css needs to change, and on what line in what file it is being assigned

How to get text before the title?


scala case class too many fields

Question: I am trying to define one case class with 1000 fields in scala REPL 2.11.8.  The case class definition is like:
case class Step2_Class(
   `Response` : String,
   `D1` : String,
   `D2` : String,
   `D3` : String,
   `D4` : String,
    //......,
   `D999` : String,
   `D1000` : String)

And the REPL is waiting for response. After about 1 hour, following stack overflow exception is thrown out.
java.lang.StackOverflowError
    at scala.reflect.internal.Trees$class.traverseComponents$1(Trees.scala:1294)
    at scala.reflect.internal.Trees$class.itraverse(Trees.scala:1330)
    at scala.reflect.internal.SymbolTable.itraverse(SymbolTable.scala:16)
    at scala.reflect.internal.SymbolTable.itraverse(SymbolTable.scala:16)
    at scala.reflect.api.Trees$Traverser.traverse(Trees.scala:2475)
    at scala.reflect.internal.Positions$DefaultPosAssigner.traverse(Positions.scala:288)
    at scala.reflect.internal.Positions$DefaultPosAssigner.traverse(Positions.scala:282)
    at scala.reflect.internal.Trees$class.traverseComponents$1(Trees.scala:1283)
    at scala.reflect.internal.Trees$class.itraverse(Trees.scala:1330)

Do you have any ideas? Does scala not support such case? Are there any work-arounds?
Comment: Why do you need a class with 1000 fields?
Comment: Have you considered doing this instead: `case class Step2_Class(response: String, theDs: List[String])`?
Comment: Such class seems meaningless
Comment: You have too many fields alright. But the error is probably caused by an infinite loop, not the amount of fields.
Comment: If the fields are named `D1` to `D1000` why not use an array instead?
Comment: Oo use a vector, array, list, map, what ever don't put 1000 string in a class!
Comment: The input is one CSV file which is the input of one PMML model (Random Forest). In our system, we are trying to parse the CSV file into one case class, and pass through to downstream components (PMML engine) to handle it.
Comment: @Guy I don't know anything about java but in compile language you can stack overflow because you allocate a very big variable on the stack.
Comment: @Stargateur If the problem was in creating new `Step2_Class` object it wouldn't fail after an hour.
Comment: A good hint in the question is this line in the stack trace: scala.reflect.internal.Trees$class.itraverse(Trees.scala:1330). This is called twice, which tells us that your doing something recursive. This in itself is not strange, but even if you do not do infinite recursion, if you're traversing a big data set recursively, without taking care to make your functions tail recursive, you might get this problem. How big is the csv you're using as input? Does your code work properly if you use a smaller csv?
Comment: if  you define in a scala file, does it compile? just to understand if it's a REPL specific problem
Comment: @pedrorijo91 both fails
Answer: It seems that the error is not related to the number of fields.
You said that it breaks after some time. Are you sure that you haven't a recursive function without a return condition? The StackOverFlow infact is a runtime error.

Thrown when a stack overflow occurs because an application recurses too deeply.

If the problem is related to the number of fields it appears at compile time.
While the problem is not related to the number of fields it is a very bad idea to create a code with 1000 parameters, or a class with 1000 fields. As you can imagine there is no real difference between D1 and D15 and D1000, so why don't use an array called D?
Comment: What you are missing is that the compiler _itself_ can throw a runtime exception, including `StackOverflowError`, and judging from `scala.reflect.internal.Trees` in the stack trace that's what happens (a macro call could also lead to that).
Answer: Until recently there was a limit of 22 fields in a case class. So it isn't surprising if the compiler (or REPL itself) fails to gracefully handle 1000 fields. You can try to give it more memory (and stack memory in particular) by setting JAVA_OPTS (-Xss for stack overflow in particular), e.g.
JAVA_OPTS="$JAVA_OPTS -Xss8M" scala

but you'd have to guess how much, it wouldn't help much with speed (unless it's mostly stuck garbage collecting, which is quite possible), and it could fail with more fields.

scala case class too many fields


Comunicação HC-06 com android

Question: Olá, sou leigo no assunto e gostaria de saber como fazer, se possível, uma transferência de dados via bluetooth do Android para o módulo HC-06 do arduino utilizando o próprio pareamento do celular. Ou seja, como manipular apenas a programação de funções de envio/leitura de dados no Android e no Arduino para estabelecer a comunicação.
Pesquisei um pouco sobre o assunto e encontrei apenas projetos muito robustos ou envolvendo aplicativos prontos, que não são interessantes no momento.
Se puderem me ensinar, indicar algum tutorial ou fazer uma recomendação ficaria muito grato.
Answer: Podes ler o o que é recebido pelo módulo HC-06, com o Arduíno, como uma entrada de série normal. Um exemplo do código (para ler e escrever) pode ser este:
<code>#include <SoftwareSerial.h>

// Define os pinos para comunicação de série (RX, TX)
// Pinos 6 e 7 neste caso
SoftwareSerial MinhaSerial(6,7);
String command = "";

void setup()
{
  // Inicia a comunicação de série com o PC
  Serial.begin(115200);
  Serial.println("Digite os comandos AT :");
  // Inicia a comunicação de série com o módulo BT (portas 6 e 7)
  MinhaSerial.begin(9600);
}

void loop()
{
  // Se o módulo BT tiver bytes para ler
  if (MinhaSerial.available())
  {
    // Enquanto o módulo BT tiver bytes para ler
    while(MinhaSerial.available())
    {
      // Acrescentar os bytes lidos à variável "comando"
      comando += (char)MinhaSerial.read();
    }

    // Deixando o módulo de ter bytes para ler
    // Imprimir a variável "comando" para a interface de série ligada ao PC
    Serial.println(comando);
    // Fazer reset à variável "comando"
    comando = "";
  }

  // Se a interface do PC tiver bytes para ler
  if (Serial.available())
  {
    // Esperar 10ms
    delay(10);
    // Escrever para o módulo BT o que é recebido do PC
    MinhaSerial.write(Serial.read());
  }
}
</code>
O Arduíno terá de ter 2 interfaces em série, uma para se ligar ao PC e outra ao módulo Bluetooth. Este exemplo foi retirado daqui.
Para poderes comunicar com um telemóvel android aconselho-te primeiro a utilizar uma aplicação que funcione como um terminar Bluetooth, como por exemplo a Bluetooth Terminal.
Depois de conseguires verificar que existe de facto comunicação entre o Arduíno e o android é que deverás (se assim o desejares) criar uma aplicação tua, por exemplo recorrendo ao cordova/Phonegap/Phonegap Build e ao plugin BluetoothSerial para ler os dados BT na tua app.
Desta forma, se souberes programação web (JS, HTML e CSS) não precisas programar nativamente em android, o que poderá ser bom para quem está a começar.

Comunicação HC-06 com android


Typescript copy signature of function parameter

Question: I try to create a function that takes a function as argument and returns a function with the same signature.
This looks like this:
function create<TCreator extends (...args: any) => any>(creator: TCreator) {
  return (...params: Parameters<TCreator>) => creator(params);
}

And I use it like this:
const created = create((a: string, b: string) => ({
  a,
  b
}));

When I look at the type of the created variable, the return type is any instead of { a: string, b: string}:
const created: (a: string, b: string) => any

Any idea how I could fix that?
Answer: TypeScript doesn't know that the input function type is in any way related to the function type being returned, so you'll not only have to capture the parameter types (which you have done correctly!), but also the return type, something like this:
function create<TCreator extends (...args: any[]) => any>(creator: TCreator) {
  return (...params: Parameters<TCreator>): ReturnType<TCreator> => creator(params);
}

Two adjustments:

change the ...args type from any -> any[]
specify the return type of the new function using ReturnType<TCreator> type (requires TypeScript 2.8 or later)


Retain Cycle in Swift delegate

Question: I have a UIViewController and in it a UIToolbar. They get instantiated from a storyboard.
I made a custom class for my UIToolbar. Based on some logic I do or do not show buttons on it.
The UIViewController needs to take action when some of the buttons are tapped.
For this I created a delegate protocol in the UIToolbar.
Currently, when I dismiss the view, it is kept in memory. Further investigation revealed my delegate created a retain cycle.
In Objective-C, we would simply define delegates as weak. However, I am using Swift, and it does not allow me to define delegate variable as weak:
weak var navigationDelegate: MainToolBarDelegate?
// 'weak' cannot be applied to non-class type 'MainToolBarDelegate'

When I dismiss the view controller, I set self.toolBar.navigationDelegate = nil and the memory gets cleared. But it feels wrong!
Why do I get the retain cycle and why can I not simply define the delegate as weak?
Comment: Is your NavigationDelegate a protocol (as opposed to a [class-only protocol](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html#//apple_ref/doc/uid/TP40014097-CH25-ID281)?) If it's just a standard protocol, there's no guarantee that your actual object will be a class instance rather than a structure, hence "Cannot be applied to non-class type"; if it could be a structure or an enum, then it can't be `weak`, as it might not be a reference type.
Answer: weak references only apply to classes, not structs or enums, which are value types. But protocols by default can apply to any of those types.
Define your MainToolBarDelegate as a class-only protocol:
protocol MainToolBarDelegate: AnyObject {

}

Then you'll be able to declare your delegate as weak.
Comment: @user2363025 `class` means any class, and `NSObjectProtocol` means anything that conforms to this protocol. I would use `class` unless you have a specific reason to use `NSObjectProtocol`.
Comment: do you know if there is any difference between using : class or : NSObjectProtocol

Retain Cycle in Swift delegate


A 3/3 figured bass

Question: I am working on my homework and encountered this that I cannot understand and the teacher did not talk about this. What does the 3/3 mean?
Answer: Typically, a root-position triad has nothing in the figured bass; if the text is really specific, it will provide "5 3" as the figures. But in this case, they've taken it one step further: they clarify that two pitches will be a third above the bass.
This is because of the voice leading from the prior chord. Since the prior chord is a V65, that means that the chordal seventh, D♭, will need to resolve down by step to C. And since the soprano moves from B♭ up to C, this means that two separates voices will be on C, and thus the uncommon "3 3" figured bass.
Nevertheless, this is still a root-position triad, so there is also an implied "5" in these figures. In other words, in addition to the two thirds (C) above the bass, there will also be a fifth (E♭).
Comment: Yes, this is definitely in root position. If it were first inversion, there would some kind of 6 mentioned somewhere in the figures for this chord.

A 3/3 figured bass