preciso inserir fotos automaticamente em uma planilha no Excel porem meu código VBA não funciona da forma que eu quero

Question: Bom, procurei uma solução para meu problema, (por muitas fotos de uma só vez e de forma organizada na planilha) no Youtube, fóruns e etc., mas a solução mais próxima foi essa a baixo, que originalmente preenchia por coluna, tentei editar o código para que pudesse executar da forma que eu preciso, mas ele simplesmente empilha tudo no canto direito da planilha.
 Private Sub Inseri_Click()
 Dim strFolder As String
 Dim strFileName As String
 Dim objPic As Picture
 Dim rngCell As Range

 Dim i As Integer

  strFolder = ThisWorkbook.Path & "\" 'diz o caminho das imagens
   If Right(strFolder, 1) <> "\" Then 'verificando se esta vazio
   strFolder = strFolder & "\"
   End If

   Set rngCell = Range("F2")

   strFileName = Dir(strFolder & "*.jpg", vbNormal)
    Do While Len(strFileName) > 0
    Set objPic = ActiveSheet.Pictures.Insert(strFolder & strFileName)
With objPic
.Left = rngCell.Left
.Top = rngCell.Top
.Height = rngCell.Height
.Placement = xlMoveAndSize
End With

If (i < 5) Then
Dim e As Integer
e = e + 1
Set rngCell = rngCell.Offset(0, e)
i = i + 1
Else
Set rngCell = rngCell.Offset(1, 0)
i = 0
End If
strFileName = Dir

 Loop
End Sub

Answer: O problema é o seguinte:
.Left = rngCell.Left
.Top = rngCell.Top

Todas as vezes que passa por ai coloca o valor Set rngCell = Range("F2").
Precisa de colocar uma variável e incrementar esse valor com um loop.
Exemplo:
 For i = 1 To 6 Step 1
      ActiveSheet.Pictures.Insert(caminho).Select
            With Selection
                .Left = Cells(i, 1).Left
                .Top = Cells(i, 1).Top
                .ShapeRange.LockAspectRatio = msoFalse
                If .ShapeRange.Height > Cells(i, 1).RowHeight Then
                    .ShapeRange.Height = Cells(i, 1).RowHeight
                End If
                If .ShapeRange.Width > range("A2").Width Then
                    .ShapeRange.Width = range("A2").Width
                End If
                .ShapeRange.Rotation = 0#

                .Left = (range("A2", "D2").Width - .ShapeRange.Width) / 2
                .Top = Cells(i, 1).Top + (Cells(i, 1).RowHeight - .ShapeRange.Height) / 2
            End With
   next


Cubic BSpline interpolation

Question: I'm trying to interpolate a curve using cubic bsplines, but I cannot get it to  exactly match the original curve. Could someone please give me some pointers. The original solution is from page #7 in here.
library(splines)
func <- function(x){return (sin(x)/(1+x*x))} # original curve
x1 <- seq(-4,4,length.out = 500) #domain is -4 to +4
f1vals <- func(x1)
k1 <- c(-7,-6,-5,-4,-3,-2,-1, 0, 1,2,3,4,5,6,7) # add 3 artificial knots at either ends
bb1 <- splineDesign(k1, x = x1, outer.ok = TRUE)

fit1 <- lm(f1vals ~ bb1)
curve(func, -4, 4)
lines(x1, fit1$fitted.values, lty = 2)

Dark line is the original curve, dotted is the interpolated. Why is it so different.
Answer: It's so different because you're not using an interpolation spline, but a regression spline. You're using lm to solve the overdetermined system with 500 rows and 11 columns. If you want to follow the approach in the link you provide, you don't want to do that. You want to use an interpolation spline. This means solving a determined system, with as many equations as unknowns, and a non-zero determinant.  Here it is:
library(splines)
func <- function(x){return (sin(x) / (1 + x * x))} # original curve
# a first level of approximation
k1 <- seq(-4, 4, len = 9)
f1vals <- func(k1)
spline1 <- interpSpline(k1, f1vals)
xpred <- seq(-4, 4, len = 500)
curve(func, -4, 4)
lines(predict(spline1, xpred), lty = 2, col = "red")
points(k1, f1vals, col = "blue")

As you can see, the spline interpolant (red dotted line) passes through the interpolation points (blue dots). Away from the interpolation points, the agreement with the interpolated function is worse, but still pretty good.
If we halve the spacing of the interpolation points, here's what happens:
# a second level of approximation
k2 <- seq(-4, 4, len = 17)
f2vals <- func(k2)
spline2 <- interpSpline(k2, f2vals)
lines(predict(spline2, xpred), lty = 2, col = "green")
points(k2, f2vals, col = "purple")

The new spline (green dotted line) is now extremely close to the original function. If you were to compute the maximum of the difference between the original function and the second spline approximation, you would see that it has became less than or equal to $\frac{1}{16}$ of the maximum difference using the first spline approximation.

Cubic BSpline interpolation


STM32f429ZI log the call stack without debugger

Question: I am using the Watch dog in my system. If it is not reloaded within 5 sec it will be triggered. I would like to see the list of code that is done prior to watchdog reset. With out the debugger connected can ) log the list of instruction in my code.
Comment: Welcome to Stack Overflow! Please [edit] your question to show [the code you have so far](http://whathaveyoutried.com).  You should include at least an outline (but preferably a [mcve]) of the code that you are having problems with, then we can try to help with the specific problem. You should also read [ask].
Comment: What operating system are you on? Why don't you try `ptrace` ? Also you will still need the debug symbols to identify the functions on the stack frame. If you don't want the debugger always connected, you can attach it *after* the watchdog triggers.
Comment: You can still add displays, like `print("Flag");` to know until where your code went before being stopped.
Comment: @Likhitha: This part has an early wake-up interrupt feature for the watchdog. You can use this to preserve a stack trace, along with other core state of intereset, in non-volatile memory prior to resetting. This is usually most easily performed grabbing the stack pointer and copying the next N bytes to an area of RAM marked not to be initialized across a reset. Then printing this through whatever channel is available after reset. Interpretation is the tricky bit and benefits from familiarity with machine code, comparing plausible return addresses against the map file is a good start though.
Answer: There are couple of ways of doing it:

Use serial debug output and grab the data using usart (another micro)
Buy USB->Serial converter and use one of the UARTs to output the data.
In extreme circumstances :) (eg when you do not have access to the pins) use (if avaiable) led(s) to flash out required information.
Answer: There is one simple, yet little bit expensive solution, to your problem. Cortex M4 core has support for tracing instructions. Therefore you need to check if the tracing signals are routed to the pins (needs to be large package > 100 pins), after startup enable tracing and just connect HW tracer, which will log every instuction the core has executed.


Eclipse can't resolve a maven-bundle-plugin produced dependency

Question: I made a bundle for a third-party lib with the maven-bundle-plugin as described here: http://git.eclipse.org/c/tycho/org.eclipse.tycho-demo.git/tree/itp02/build01/pomfirst-thirdparty/pom.xml.
I can build my third-party lib and use it in another eclipse-plugin project which is build by the tycho-maven-plugin and whose dependencies are resolved by the target-platform-configuration plugin. So far so good.
But my eclipse can't resolve this dependency.
Comment: Can you provide more details? Errors messages?
Answer: I think you are facing the problem explained in thread Eclipse support for pomDependencies=consider.
The suggested solution is:

You need to import pom-first projects into workspace, there is no
  integration between PDE workspace target platform and Tycho
  pomDependencies=consider feature.


How to set default font and size for the text buffer

Question: I just simply want to set a default font using GTK4, but the examples I found don't work.
This code below is what I used and it does absolutely nothing; it doesn't even give me an error. So I have no idea of what I might be doing wrong.
<code>#include <gtk/gtk.h>

static void activate(GtkApplication *app, gpointer user_data) {
    GtkWidget *window = gtk_application_window_new(app);
    gtk_window_set_title(GTK_WINDOW(window), "GTK4 Text Buffer Example");
    gtk_window_set_default_size(GTK_WINDOW(window), 800, 600);

    // Create a text buffer
    GtkTextBuffer *buffer = gtk_text_buffer_new(NULL);

    // Create a text view and set its buffer
    GtkWidget *text_view = gtk_text_view_new_with_buffer(buffer);

    // Set default font and size for the text buffer
    PangoFontDescription *font_desc = pango_font_description_from_string("Cantarell Italic Light 15");
    GtkTextTag *tag = gtk_text_buffer_create_tag(buffer, "default_tag", "font-desc", font_desc, NULL);
    g_object_set(tag, "font-desc", font_desc, NULL);
    pango_font_description_free(font_desc);

    // Create a scrolled window and add the text view
    GtkWidget *scrolled_window = gtk_scrolled_window_new();
    gtk_scrolled_window_set_child(GTK_SCROLLED_WINDOW(scrolled_window), text_view);

    gtk_window_set_child(GTK_WINDOW(window), scrolled_window);

    gtk_window_present(GTK_WINDOW(window));
    //gtk_widget_show(window);
}

int main(int argc, char **argv) {
    GtkApplication *app = gtk_application_new("org.gtk.example", G_APPLICATION_DEFAULT_FLAGS);
    g_signal_connect(app, "activate", G_CALLBACK(activate), NULL);
    int status = g_application_run(G_APPLICATION(app), argc, argv);
    g_object_unref(app);
    return status;
}
</code>
I want to set a default font and size to text in a text buffer using GTK4 in C.
Comment: What text should get the font settings that you made?
Comment: All the text in the text buffer.
Comment: You did not put any text in the text buffer.
Comment: @stark I guess what I wanted was that they text I would type in would be of that specified font, but it never is.
Answer: All types of configuration related to text visualization (font, size, color, etc.) are not made in the Textbuffer, they are made in the TextView. The TextBuffer stores data, how it will be displayed is up to the TextView. To choose these details, use a CSS class that affects the TextView in question or Pango to format the inserted text.
Comment: Thank you, I ended up doing that and it worked.


"Expressão ausente após operador unário '--'" ao tentar instalar o postgres pelo docker

Question: codigo:
docker run \
--name postgres \
-e POSTGRES_USER=spirit \
-e POSTGRES_DB=spiritSt \
-e 5432:5432 \
-d \
postgres

estava seguindo um tutorial e nele funcionou normal mas no meu pc estou com esse error:
No linha:2 caractere:3
+ --name postgres \
+   ~
Expressão ausente após operador unário '--'.
No linha:2 caractere:3
+ --name postgres \
+   ~~~~
Token 'name' inesperado na expressão ou instrução.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingExpressionAfterOperator

Answer: O \ para usar múltiplas linhas não funcione em powershell, troque ele por "acento grave", algo assim:
docker run `
--name postgres `
-e POSTGRES_USER=spirit `
-e POSTGRES_DB=spiritSt `
-e 5432:5432 `
-d `
postgres

E após isto basta digitar enter duas vezes.
PowerShell 5+
Se estiver usando PowerShell 5 ou superior e quiser digitar manualmente o comando e suas instruções então pode usar Shift+Enter a cada linha nova que desejar inserir
Leia mais em: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_line_editing?view=powershell-6


SOB rule for computing dual LP

Question: I wanted to have a fast rule for computing dual LP at hand.. I always seem to struggle to form the dual not in terms of the objective function or the coefficients of constraints but I am struggling to decide whether the constrains should be $\leq, \geq , = $ and also sign constraints..
I found this https://www.usna.edu/Users/math/dphillip/sa305.s12/sob.pdf
And it has this table :

I applied it to a couple of LP's and got the duals right . But then I stumbled on this one and I get it wrong:
The primal is
$$ \min 3x1 +x2 + x3 + x4$$
$$ \text{s.t } 3x1  -x2 -7x3 + x4 = -3 $$
$$ 3x1 - 4x3 + x4 = -1 $$
$$ x3 \leq 3 $$
$$x1, x2, x3, x4 \geq 0 $$

To compute the dual :
$$ \max -3y1 -y2 +3y3 $$
$$ \text{s.t } 3y1 + 3y2 \; ?\;  3 $$
$$ -y1 \; ?  \; $$
$$ -7y1 -4y2 + y3 \; ?\;   1 $$
$$ y1 + y2 \; ? \; 1 $$
$$ ? $$
So to my understanding, according to the rule , the type of constraints is defined by the sign constraint of the corresponding primal variable .. So since all of them are positive we introduce only $\leq $ constraints.
And the sign constraints are defined by the type of constraints in the primal . The $=$ constraints let $y1, y2$ to be free and the $\leq$ constraints is according to the pdf a "bizarre" one and it implies that $y3 \leq 0 $
$$ \max -3y1 -y2 +3y3 $$
$$ \text{s.t } 3y1 + 3y2 \; \leq  3 $$
$$ -y1  \leq 1$$
$$ -7y1 -4y2 + y3 \leq   1 $$
$$ y1 + y2 \leq 1 $$
$$ y3 \leq 0 $$
But by putting my LP into an online calculator my result seems to be wrong..
Can you help me work out my mistake ?
Comment: Any further questions?
Comment: @callculus42 so you are suggesting that the dual is not unique and mine is also correct ? because when I plugged into a calculator it had a different dual where for example $ y_3 \geq 0 $
Comment: No. I just say your dual is correct. You can make $y_3$ non-negative and change the signs of all terms with $y_3$. It's a kind of substitution. It doesn't change the nature of the Model.But your (direct) transformation  from primal to dual is fine.
Answer: In my view you are on the right track. The dual is
$$ \max\  -3y_1 -y_2 +3y_3 $$
$$ \textrm{s.t } 3y_1 + 3y_2 \leq  3$$
$$ -y_1  \leq 1$$
$$ -7y_1 -4y_2 + y_3\leq    1 $$
$$ y_1 + y_2 \leq 1 $$
The last (third) constraint of the primal min-problem is a $\leq$-constraint.Thus $y_3\leq 0$. I don't see any mistake in your model.
Remark:
I've calculated the optimal solutions with this calculator. The optimal solutions are
primal: $(x_1^*,x_2^*,x_3^*,x_4^*)=\left(0,\frac54, \frac{1}{4},0\right)$
dual: $(y_1^*,y_2^*y_3^*)=\left(-1,\frac32,0\right)$
In both cases the optimal value of the objective function is $\frac32$ and hence the strong duality theorem is satisfied.

SOB rule for computing dual LP


Overriding equals method not working on using object as key in hashmap?

Question: I have Overridden equals method of Person class comparing the name attribute of class and if they are equal returning back true from equals method.
When i am creating the instance of Person object and using it as key in hashmap, while retrieving using a new object with same name i am not able to retrieve back the associated value from hashMap.
Below is my
import java.util.HashMap;

import java.util.Map;
public class ToStringTest {
public static void main(String[] args) {

    Person person = new Person("Jack", "California");
    Map<Person,String> personsMap = new HashMap<>();
    personsMap.put(person,"MyCar");
   Person otherPerson = new Person("Jack", "California");
    System.out.println(personsMap.get(otherPerson));
}

}
class Person {
String name;
String city;

public Person(String name, String city) {
    this.name = name;
    this.city = city;
}

@Override
public String toString() {
    return "Name : " + this.name + ", City : " + this.city;
}

@Override
public boolean equals(Object o) {

    Person person = (Person) o;
    if(person.name.equals(this.name)){
        return true;
    }

    return false;
}

}
This is printing null while retrieving from using otherPerson object.
Could someone please explain this behavior.
Comment: don't forget about `hashcode` implementation
Answer: When you add new person in map personsMap.put(person,"MyCar"); first of all if key is not null the position where the element will be put is determined. It is determined by calling hashcode method for key. There are a few steps after but it doesn't matter for this example.
Since you don't override hashcode() your person and otherPerson will have different hashcode.
The same happens when you try to get value by some key. To find position where the element is, hashcode() will be invoked. But otherPerson has different hashcode and it will lead to position where is no item (null)
equals() is used when at the same position there are many elements (in list or tree structure). Then to find the right item they will be compared by equals() method
Comment: I tried overriding hasCode method for Person class and it worked. Able to retrieve the object from map using otherPerson object.Thanks


Coefficient estimated with a binary predictor $\in \{0,1\}$, but making predictions with values between $0$ and $1$ - is this OK?

Question: Let's say I have a variable $x_d$ that, in the estimation data, is a simple indicator ($x_d \in \left\{0,1\right\}$).  I estimate a coefficient for it, $\beta_d$, along with several other coefficients for variables that could be continuous, more dummies, etc.
Now someone wants to use these coefficients in a forecast. For their input data, they would like to treat $x_d$ not as an indicator, but rather as a continuous variable. That is, while the estimation data represented this quantity as an either/or, the forecast data represents it more as a matter of degree.  In this forecast data, I would hope that my colleague would constrain the value of $x_d$ between 0 and 1, but we have not yet discussed that.
Edit
$x_d$ describes whether a loan came from a very specific lender.  So in reality, the value really is only 0 or 1.  In the forecast, my colleague wants to treat that variable as a continuous measure of similarity to that lender, i.e. how much like that lender is a loan's source, with 0 meaning not at all, and 1 meaning the same lender.  Is it a bad thing to alter the meaning in that way?  I'm especially concerned about how it affects the meanings of the other coefficients, which were estimated alongside an indicator and are now being used alongside a continuous variable.
Are there any issues when a coefficient is estimated with an indicator/dummy, but then used in a forecast with a continuous variable?
Comment: Yes I think you should be concerned about this. Why are you using an estimated coefficient for another variable on a new variable?
Comment: after our discussion under Michael's answer, the true nature of the question was clarified for me and I've modified the title accordingly - I hope the change I've made was OK. If not, please modify it appropriately.
Comment: @whuber:  thanks for edit, that definitely should be part of the original question.
Answer: After clarification in a comment discussion, it appears that the question is about a situation where there is a linear model relating a continuous response variable $Y_i$ and a binary predictor $X_i \in \{0,1\}$, and the OP wants to know whether or not it is defensible to interpolate by plugging in values for $X_i$ that are $\in (0,1)$ and assuming everything is "OK". That answer is that this is only defensible if you assume linearity of $E(Y_i | X_i)$ over that interval.
To see why this is true, consider fitting these data with a simple regression model:
$$ Y_i = \beta_0 + \beta_1 X_i + \varepsilon_i $$
where $\varepsilon_i$ is a mean $0$ error term. Under this model, $E(Y_i | X_i = 1) = \beta_0 + \beta_1$ and $E(Y_i | X_i = 0) = \beta_0$. When you only use data such that each $X_i \in \{0,1\}$ to fit this model, the coefficient estimates will be exactly
$$ \hat \beta_0 = \overline{Y_0}$$
and
$$ \hat \beta_1 = \overline{Y_1} - \overline{Y_0}$$
where $\overline{Y_0}$ is the sample mean of the $Y_i$'s when $X_i = 0$ and $\overline{Y_1}$ is the sample mean of the $Y_i$'s when $X_i = 1$. Therefore, the estimated mean for any intermediate value of $X_i$, call it $x$, is
$$ \overline{Y_0} + (\overline{Y_1} - \overline{Y_0})x = \overline{Y_0}(1-x) + \overline{Y_1}x$$
That is, a function which linearly goes from $\overline{Y_0}$ to $\overline{Y_1}$ as $x$ moves from $0$ to $1$. If the true relationship is not this way, then the predictions made will be very wrong.
For example, suppose the true relationship was a step function:
$$E(Y_i | X_i) = \beta_0 + \beta_1 \mathcal{I}(X_i \geq 1/2) $$
where $\mathcal{I}(X_i \geq 1/2) = 1$ if $X_i \geq 1/2$ and 0 otherwise. This would be compatible with the linear model specified if all you observe are $X_i = 0,1$ but once you start to interpolate that linear relationship, you will get very wrong predictions. At $X_i = 1/2$, the true mean is $\beta_0 + \beta_1$ but the linear model's estimate would be $\beta_0 + \beta_1/2$ (Yikes!). Other examples can be given where the linear model is correct for the binary data, but makes this disagreement arbitrarily large once you interpolate.
Answer: Of course I agree with Macro here.  These are two entirely different models.  The coefficient for an indicator variable would bear no relation to what the coefficient should have been had you fit the model with a continuous variable.  If you have data on the continuous variable you would be better off fitting the model to that.  By dichotomizing the variable you throw out information in your data.
Comment: I think this reply may be a little too strong and perhaps loses a chance to focus on a key issue, which is model mis-specification. Take the toy example of regressing $y$ only on $x$ with $x$ ranging in $[0,1]$. In some ways it is *optimal* to design the data collection so half the $x$'s equal $0$ and the other half equal $1$: this minimizes the S.E. of the slope. We don't do this in practice because we need other values of $x$ to check possible non-linearity (model mis-specification). Absent such nonlinearity, the estimated parameters will be *excellent* for *all* $x$.
Comment: +1. While I don't entirely agree that "The coefficient for an indicator variable would bear no relation to what the coefficient should have been had you fit the model with a continuous variable" - there will be _some_ relation - but I think you could come up with examples where the coefficient on the raw variable and the coefficient on the discretized version are arbitrarily different to any pre-specified degree, which is, I think, what you meant.
Comment: I think it would be misuse of the model if you were to plug in values for $x$ that were not $0$ or $1$ and would require an explicit assumption of linearity over that interval.
Comment: @Macro I meant that they need not be very similar and it could be very bad to use one in place of the other going either way.  But particularly from the coefficient for the indicator variable to be used with the continuous one.
Comment: Agreed. The only time the two will agree is when the true effect of the continuous variable is a step function, which wouldn't be well approximated by a linear model, so, in that case, you might as well just use the discrete variable for prediction anyways.
Comment: @whuber Whise reply are you referring to?  Mine or Macros?  I am not sure why in your toy example the choice of equal numbers at only the extremes minimizes the SE of the slope. Since the extremes are high leverage points the slope would be very sensitive to outliers in the y values. I do appreciate your point about looking at intermediate value to be able to detect nonlinearities.
Comment: (Michael, this comment thread pertains to just one *reply*: yours. Comments are not replies.) I was thinking of [D-optimal designs](http://en.wikipedia.org/wiki/Optimal_design). The design I described is D-optimal (for one I.V.): it's a minimum-volume bounding ellipse. The extremes will not have high leverage when they are the only two values of $x$ and they are equally frequent in the dataset. The sensitivity to outliers is an interesting point: that goes hand-in-hand with the optimality and provides another reason to be cautious when fitting a model with only two distinct values of $x$.
Comment: @MichaelChernick, I'm guessing whuber is referring to the fact that, in linear regression with normal errors, the standard error is inversely related to the variance in the predictor, which is maximized when half are 0 and half are 1, in that example
Comment: @Macro.  I understand that.  Similarly central composite designs are optimal for certain multifactor ANOVAs.
Comment: @whuber it may be the jargon he to refer strictly to answers to the question as reply.  But in general reply just means an answer to a question.  Questions are posed in comments as well as in formal answers and so I was thinking that my discussion with Macro amounted to a give and take that included replies in the dictionary sense of the word.
Comment: @all: I should have described $x_d$ some more. In reality, $x_d$ isn't continuous:  it really is either 0 or 1.  It describes whether or not a loan came from a very specific lender. In the forecast, my colleague wants to treat that variable as a continuous measure of similarity to that lender, i.e. how much like that lender is a loan's source, with $0$ meaning not at all, and $1$ meaning the same lender. I have lots of concerns, including how this affects the meanings of the other coefficients, which were estimated alongside an indicator, but are now being used alongside a continuous variable.
Comment: @sparc_spread, if the variable takes on only the values $0$ and $1$, using it as an indicator or a continuous variable will give the same coefficient estimates.
Comment: @Macro: that's certainly true. I guess what I mean to say is, we estimated those coefficients in a world where something either was or was not true.  In the forecast, we're now saying that that thing could be just partially true.  It almost feels like the forecaster is saying, "remember all the zeros in the estimation data? Well, they actually should have been somewhere in the interval $[0,1)$."  Does this alter the meaning of the other coefficients?  Is it a misuse of the model?
Comment: @Macro: you make a strong case here that this is a misuse of the model, for I believe that an assumption of linearity for the continuous version of $x_d$ would be highly subjective indeed. Could you explain a bit why we would need to assume linearity here? Thanks.
Comment: @sparc_spread - sure. Please see my answer below.
Comment: Thanks everyone for the help here!  This thread plus the other one have really given me the insight needed to debate this issue intelligently with my teammates.


Finding the equivalence classes of a relation

Question: Define a relation on the set of all real numbers $x, y \in \mathbb{R}$:
$x ≃  y$  if  and only if $x − y \in \mathbb{Z}$
Prove that this is an equivalence relation, and find the equivalence class of the number $1/3$.
I proved that the relation is:
reflexive
$$x-x = 0 \in \mathbb{Z}$$
symmetric
$$x-y = y-x \in \mathbb{Z}$$
transitive
$$x-y \in \mathbb{Z}$$
$$y-z \in \mathbb{Z}$$
$$x-z \in \mathbb{Z}$$
Are these proofs enough?
I'm stuck on the step where I need to find the equivalence class.
Comment: Possible duplicate of [Finding the equivalence class of a relation](https://math.stackexchange.com/questions/225857/finding-the-equivalence-class-of-a-relation)
Answer: Opps, carefull: $$x-y\ne y-x$$
You should write: if $x\sim y$ then $x-y\in Z$ so $-(x-y) = y-x\in Z$ so $y\sim x$.
Also, if $x\sim y$ and $y\sim z$ then $x-y,y-z\in Z$, so $(x-y)+(y-z) \in Z$ so $x-z\in Z$ so $x\sim z$.

And equivance class is $$Z+{1\over 3} = \{...-{5\over 3},-{2\over 3},{1\over 3}, {4\over 3},{7\over 3},...\}$$
Comment: @ph-quiett Pay particular attention to the way this answer uses important _words_ telling what the easy algebra means. You put the algebra in your question but not the reasoning.
Answer: An equivalence class of an element $x$ is the set of all elements which are in relation $\sim$ with $x$. In your case $x=1/3$, so the equivalence class is the set of all elements $y$ such that $\frac{1}{3}-y = k \in \mathbb Z$. It follows that $y=\frac{1}{3}-k = l+\frac{1}{3}$, $l \in \mathbb Z$. Therefore, the equivalence class of $\frac{1}{3}$ is
$$\left[\frac{1}{3}\right]_\sim = \left\{k+\frac{1}{3} : k\in \mathbb Z\right\}$$
Described in common language, this is the set of all fractions with $3$ in the denominator and their numerator divided by $3$ gives the remainder $1$. Some of these numbers are $\frac{1}{3}, \frac{4}{3}, \frac{7}{3}, \cdots$


Send and Receive JSON with Java

Question: I'm trying to send and receive JSON using java GUI, but, i keep getting some errors (like, 500,405,403) with i use the http://localhost:8080/clienteWebService/test-resbeans.html Them I'm able to use normally, sending and receive JSON with any problems.
For this program that I'm trying to do I also get this error:
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: http://localhost:8080/ClienteWebService/webresources/Cadastro%20Cliente/Cliente/inserir
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1944)
at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1939)
at java.security.AccessController.doPrivileged(Native Method)

I don't know where is the mistake, I tried to make a direct POST request using http://localhost:8080/clienteWebService/webresources/Cadastro%20Cliente/Cliente/inserir
and them I receive the JSON, but, if I get the information with a jTextField doesn't run properly or at all.
This is the code:
    public static void Inserir () throws Exception {

    ConsumirWs1 http = new ConsumirWs1();
    Gson g = new Gson();
    Cliente u = new Cliente();
    Type ClienteType = new TypeToken<Cliente>() {
    }.getType();

    u.setCad_pes_nome(InterfaceConsu.jTextFieldNOME.getText());
    u.setCad_pes_cpf(InterfaceConsu.jFormattedTextFieldCPF.getText());
    u.setCad_pes_apelido(InterfaceConsu.jTextFieldAPELIDO.getText());
    SimpleDateFormat formatter  = new SimpleDateFormat ("dd-MM-yyyy");

                    java.util.Date utilDate = null;
                    try {
                        utilDate = formatter.parse(jFormattedTextFieldDATA.getText());
                    } catch (ParseException ex) {
                        Logger.getLogger(InterfaceConsu.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
    u.setCad_pes_data(sqlDate);

    String json = g.toJson(u, ClienteType);
    String url = "http://localhost:8080/clienteWebService/webresources/Cadastro%20Cliente/Cliente/inserir?";

    http.sendPost(url, json, "POST");

}

And them the code to send with the Webservice
private void sendPost(String url, String urlParameters, String method) throws Exception {

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    //add reuqest header
    con.setRequestMethod(method);
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    //String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
    // Send post request
    con.setDoOutput(true);
    try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
        wr.writeBytes(urlParameters);
        wr.flush();
    }

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    StringBuffer response;
    try (BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()))) {
        String inputLine;
        response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
    }

    //print result
    System.out.println(response.toString());

}

and if I try GET, I receive this error java.net.ProtocolException: Invalid HTTP method:
Answer: The problem was in the String url, here's the code and the format that i needed to make the request in the right link.
public void Inserir () throws Exception {
    InterfaceConsu2 IFC2 = new InterfaceConsu2();
    ConsumirWS2 http = new ConsumirWS2();
    Gson g = new GsonBuilder().setDateFormat("dd-MM-yyyy").create();
    Cliente2 u = new Cliente2();
    Type ClienteType = new TypeToken<Cliente2>() {
    }.getType();

    u.setCad_pes_nome(IFC2.jTextFieldNOME.getText());
    u.setCad_pes_cpf(IFC2.jFormattedTextFieldCPF.getText());
    u.setCad_pes_apelido(IFC2.jTextFieldAPELIDO.getText());
    SimpleDateFormat formatter  = new SimpleDateFormat ("dd-MM-yyyy");

                    java.util.Date utilDate = null;
                    try {
                        utilDate = formatter.parse(IFC2.jFormattedTextFieldDATA.getText());
                    } catch (ParseException ex) {
                        Logger.getLogger(InterfaceConsu2.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
    u.setCad_pes_data(sqlDate);

    String json = g.toJson(u, ClienteType);
    String url = "http://localhost:8080/clienteWebService/webresources/CadastroCliente/Cliente/inserir";
    System.out.println("63 consumir");
    System.out.println(json);

        http.sendPost(url, json, "POST");

}

I think there's few minor changes in the code, but this works with zero error
also, with is needed to send a parameter to a the webservice, here's another example that I made by myself figuring out how to do it, any other advice is welcome
u.setCad_pes_cpf(IFC2.jFormattedTextFieldCPF.getText());
    String url = "http://localhost:8080/clienteWebService/webresources/CadastroCliente/Cliente/get/" +u.getCad_pes_cpf();

In this one, after this i call a GET method

Send and Receive JSON with Java


having 2 different styles for ui-state-default and ui-selected

Question: at the moment, i am using the selectable JQUERY function

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

Item 7

but for some reason, when i select an element, the color will not change to bright orange but revert to the default gray of ui-state-default like below:

But if I go to the Chrome debugger and uncheck the background in ui-state-default in the style section, it works perfectly.

Is it because of this snippet:
var nodes = document.getElementById('selectable').getElementsByClassName('ui-widget-content');
      if (nodes.length > 0)
      {
        nodes[0].innerHTML = getSymbol();
        nodes[0].setAttribute("class", "ui-state-default");
      }

How do i go around this problem, such that when i click on the element of interest, the color will change like i specified in the


Função em JS para calcular idade em meses e anos

Question: Tenho essa função, porem quando roda o mês sempre está dando +12 meses, como se a pessoa já tivesse feito aniversário. Como poderia concertar?

let daysH = document.getElementById("date");
let monthH = document.getElementById("month");
let yearH = document.getElementById("year");

let showAge = document.getElementById("show-age");

const btn = document.getElementById("calc-btn");

var today = new Date();
let d = today.getDate();
var m = today.getMonth() + 1;
var y = today.getFullYear();
let maxDays = 0;
let monthNum = 1;

btn.addEventListener("click", (days, month, year) => {

  days = daysH.value;
  month = monthH.value;
  year = yearH.value;

  if (daysH.value == "" || monthH.value == "" || yearH.value == "") {
    return alert("Por favor, preencha seu dados")
  }

  // no else condition needed

  console.log(`Current Date : ${d} ${m} ${y}`);

  if (m == 1) { // janeiro
    maxDays = 31;
    monthNum = 1;
  } else if (m == 2) { // fevereiro
    maxDays = 28;
    monthNum = 2;
  } else if (m == 3) { // março
    maxDays = 31;
    monthNum = 3;
  } else if (m == 4) { // abril
    maxDays = 30;
    monthNum = 4;
  } else if (m == 5) { // maio
    maxDays = 31;
    monthNum = 5;
  } else if (m == 6) { // junho
    maxDays = 30;
    monthNum = 6;
  } else if (m == 7) { // julho
    maxDays = 31;
    monthNum = 7;
  } else if (m == 8) { // agosto
    maxDays = 31;
    monthNum = 8;
  } else if (m == 9) { // setembro
    maxDays = 30;
    monthNum = 9;
  } else if (m == 10) { // outubro
    maxDays = 31;
    monthNum = 10;
  } else if (m == 11) { // novembro
    maxDays = 30;
    monthNum = 11;
  } else { //dezembro
    maxDays = 31;
    monthNum = 12;
  }

  var ageYears = y - year;

  if (m <= month) {
    m = m + 12;
  }
  var ageMonths = m - month;
  var ageDays = (maxDays - d) + parseInt(days);

  console.log(`Sua Idade é ${ageYears} a , ${ageMonths} m and ${ageDays} d`);
  showAge.innerHTML = `Sua Idade é ${ageYears} a , ${ageMonths} m and ${ageDays} d`;
})

  Qual a data do seu nascimento?
  <input type="number" id="date" placeholder="data">
  <input type="number" id="month" placeholder="mês">
  <input type="number" id="year" placeholder="ano">

  <button id="calc-btn">Calculate Age</button>

Comment: então, eu preciso que calcule os meses e dias também
Comment: O Stack Overflow em Português [não é um fórum](https://pt.meta.stackoverflow.com/questions/2068/o-stack-overflow-em-portugu%c3%aas-%c3%a9-um-f%c3%b3rum), nós somos um site de perguntas e respostas. Não usem o campo de respostas para trocar comunicação. Ou [editem](https://pt.stackoverflow.com/posts/492606/edit) a pergunta acrescentando detalhes e esclarecimento ou usem o [chat](https://chat.stackexchange.com/rooms/new) para uma comunicação mais ativa.
Answer: Resolucao do problema.[EDITADO]
        let daysH = document.getElementById("date");
        let monthH = document.getElementById("month");
        let yearH = document.getElementById("year");

        let showAge = document.getElementById("show-age");

        const btn = document.getElementById("calc-btn");

        var today = new Date();
        let d = today.getDate();
        var m = today.getMonth() +1;
        var y = today.getFullYear();
        let maxDays = 0;
        let monthNum = 1;

        btn.addEventListener("click", (days, month, year) => {

            days = daysH.value;
            month = monthH.value;
            year = yearH.value;

            if (daysH.value == "" || monthH.value == "" || yearH.value == "") {
                return alert("Por favor, preencha seu dados")
            }

            // no else condition needed

            console.log(`Current Date : ${d} ${m} ${y}`);

            if (m == 1) { // janeiro
                maxDays = 31;
                monthNum = 1;
            }
            else if (m == 2) { // fevereiro
                maxDays = 28;
                monthNum = 2;
            }
            else if (m == 3) { // março
                maxDays = 31;
                monthNum = 3;
            }
            else if (m == 4) { // abril
                maxDays = 30;
                monthNum = 4;
            }
            else if (m == 5) { // maio
                maxDays = 31;
                monthNum = 5;
            }
            else if (m == 6) { // junho
                maxDays = 30;
                monthNum = 6;
            }
            else if (m == 7) { // julho
                maxDays = 31;
                monthNum = 7;
            }
            else if (m == 8) { // agosto
                maxDays = 31;
                monthNum = 8;
            }
            else if (m == 9) { // setembro
                maxDays = 30;
                monthNum = 9;
            }
            else if (m == 10) { // outubro
                maxDays = 31;
                monthNum = 10;
            }
            else if (m == 11) { // novembro
                maxDays = 30;
                monthNum = 11;
            }

            else { //dezembro
                maxDays = 31;
                monthNum = 12;
            }

            var ageYears = y - year;

            ageYears = ageYears - monthNum;

            // if (m <= month) {
            //     m = m + 12;
            // }

            var ageMonths = month - m;
            var ageDays = (maxDays - d) + parseInt(days);

            console.log(`Sua Idade é ${ageYears} a , ${ageMonths} m and ${ageDays} d`);
            showAge.innerHTML = `Sua Idade é ${ageYears} a , ${ageMonths} m and ${ageDays} d`;
        })

Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](https://chat.stackexchange.com/rooms/119172/discussion-on-answer-by-bruno-bafilli-funcao-em-js-para-calcular-idade-em-meses) ... para outras conversas, informais recomendo o chat oficial: https://chat.stackexchange.com/rooms/11910/estouro-de-pilha


Continuous and Discontinuous Functions - Variation of Dirichlet function

Question: Be $f: R \longrightarrow R $ a real function where:
$
f(x) =
\begin{cases}
x + 1,  & \text{if $x \in Q $} \\[2ex]
2, & \text{if $x \in R-Q$}
\end{cases}
$
Where the graph "jumps" among the two straight lines of the graph. There is just one point where both straight line are continuous, that is x = 1 and y = 2.
If we have an sequence $ (x_n) $ that converge to $\sigma $, then $(x_n) + 1 \longrightarrow \sigma + 1$ by rational values $(Q)$ and $(x_n) = 2 \longrightarrow 2 $ by irrational values $(R - Q)$. Then, the unique point of converge is $\sigma = 1$, where both straight lines are y = 2.
My question is for whats point's in the domain of $f$, $f$ is continious and discontinious?
Answer: Actually, $x=1$ is the only point of continuity. To see why, first let $x_0\in \Bbb Q^c$. Then there exist two sequences $$a_n=x_0+{1\over n}\to x_0\implies f(a_n)\to 2\\b_n={\lfloor nx_0\rfloor\over n}\to x_0\implies f(b_n)\to x_0+1$$since $x_0+1\ne 2$, continuity fails here.
Now let $x_0\in \Bbb Q-\{1\}$. Then by defining $$a_n=x_0+{1\over n}\\b_n=x_0+{\pi\over n}$$ we see again that $f(x)$ is not continuous in $x=x_0$ either in this case. So the conclusion is what we mention first.

More generally, the following function$$f(x)=\begin{cases}g(x)&,\quad x\in \Bbb Q\\h(x)&,\quad x\notin \Bbb Q\end{cases}$$is continuous in the roots of $g(x)=h(x)$.


Set that does not contain its supremum

Question: I am wondering, if a set does not contain its supremum, does this imply that the set is infinite? For example, say $A\subset\mathbb{R}$ has a supremum $a$ such that $a\notin A$. Does this imply the set is infinite? This tells us the set does not contain a maximum, but I am not sure about my other statement.
Comment: the open interval $0 < x < 1$ does not contain its supremum
Comment: Let's see, a finite set of reals does contain its maximum, so, yes
Comment: @WillJagy Then yes, if the set does not contain its supremum it is infinite.
Comment: It is true for you example but in general is false.
Answer: You can rephrase your question as "do finite sets contain their supremum?" which is indeed true, as the supremum of a finite set is its maximum element.
Comment: @Sam.  That is true only if the set is linearly ordered.

Set that does not contain its supremum


Passing variables to JS from theme folder .tpl files

Question: I use many template files in my modules via hook theme. In order to pass variable to JS files I use the method described here:
https://www.drupal.org/node/304258
in the .tpl.php files:
<code>$my_settings = array(
  'basePath' => $base_path,
  'animationEffect' => variable_get('effect', 'none')
);

drupal_add_js(array('myModule' => $my_settings), 'setting');
</code>
and then in the .js files:
<code>var basePath = Drupal.settings.myModule.basePath;
var effect = Drupal.settings.myModule.animationEffect;
</code>
For the first time (it seems) I'm trying to pass variables to JS from .tpl files located in my theme folder.
Suppose I have a content type called 'cars',  I craete a page-cars.tpl.php template file in my theme folder which automatically applies to all car pages. But in these tpl files I can't pass variables to JS using the method described above.
I tried switching 'myModule' to 'myTheme' but Drupal won't recognize it as a defined setting
As per Clive's instructions I added to the my_theme_preprocess_content_type(&$variables) function and it works! (thanks Clive)
Comment: Which part of the docs you read said you should put a call to `drupal_add_js()` in a template file? Or have you assumed? I only ask because if there are official docs telling you to use `drupal_add_js()` in a template file, they need to be changed ASAP. That code should be in a preprocess function, never a template file.
Comment: Been doing it this way for years now Clive... Probably a bad habit I developed unintentionally.
Comment: Bad indeed! It'll probably work in a lot of cases, but it breaks caching and can have unwanted effects (possibly like you're experiencing now). Try moving the logic to a preprocess function just to make sure that's not the problem
Answer: Take a look at the variable_set function. If my memory is correct, I used this to move variables between PHP and java script.
Comment: I don't think thats right, this sets drupal variables like site_name in the variables table and doesn't necessarily expose them to JS.


Defining an isomorphism that is an inverse of an non-invertible linear transformation?

Question: Let $T: V \to V$ be a linear mapping such that $B = \{v_1, ..., v_n\}$ is a basis for $V$ and $C = \{v_r , ..., v_n\}$ is a basis for $\operatorname{Ker}(T)$. Prove that there exists an isomorphism $S: V \to V$ such that $T\circ S \circ T = T$ by defining it.
Comment: Do you have any thoughts?
Comment: I tried defining S as the inverse of T strictly for the Range(T), I'm not sure if this is correct, but even so, I have no idea what to do about the Ker(T).
Answer: Since all the maps involved are linear, we just need to show that $TST(v_i) = T(v_i)$ for all $i$. Moreover, we can define the maps solely on the basis vectors. Note also that $T(V)$ is spanned by $v_1, \dots, v_{r-1}$.

Consider $v_1 = (1, 0), v_2 = (0, 1)$, and $C = \{ (0, 1) \}$. Let
$$T: v_1 \mapsto 2 v_1 \\ \ \ \ \  v_2 \mapsto 0
% apologies for the awful spacing hack here$$
Then we see that $S: v_1 \mapsto \frac{1}{2} v_1; v_2 \mapsto v_2$ works.

This highlights the general fact that we can set $S$ to be the identity on $\text{Ker}(T)$. Indeed, since we're applying $T$ after $S$, anything that $S$ somehow sends to the kernel will be killed by $T$. Therefore the only things we can allow $S$ to send to the kernel must already be in the kernel. To be totally concrete: if $u$ is in the kernel of $T$, then $TST(u) = TS(0) = 0$, while $T(u) = 0$. Conversely, if $S$ mapped anything non-kernel into the kernel of $T$, then $TST(v)$ would be zero for some $v$, despite $T(v)$ not being zero.

Now, what about the image? Let's write $T(v_1) = u_1$, and so on up to $u_{r-1} = T(v_{r-1})$. Then the $u_i$ form a basis of $\text{Im}(T)$ because there are enough of them to span, and they are linearly independent since the $v_i$ were.
We just need to determine $S$'s action on the $u_i$. Notice that $TST(v_i) = TS(u_i) = T(v_i)$, so what we want to do is set $S(u_i) = v_i$. Fortunately, we can do that!

Summary: Let $u_i$ be the basis of $\text{Im}(T)$ given by $T(v_i)$ for $i=1, \dots, r-1$. Then define $S$ by $S(u_i) = v_i$ for $i=1, \dots, r-1$, and extend linearly to define $S$ on $\text{Im}(T)$. Define $S(v_j) = v_j$ for $j \geq r$, and extend linearly to define $S$ on all of $V$.


RabbitMQ: Priority queue with changing priority

Question: I want to implement a priority work queue, in which the priority of a group of messages can change once they are in the queue. Since it is a work queue with variable processing time, the messages are not assigned using round-robin algorithm, but are pulled from the queue when a resource is free (using per-consumer limit).
I came up with 2 ideas for implementation:

Use priority queue from RabbitMQ, and when a request for priority change comes, read messages with this priority from the queue and re-send them with different priority. (I am not sure this is a good approach, given the O(n) complexity.)
Use several queues with distinct names for each group of messages, and use a separate queue to communicate the current priority list (ordered list of queue names) to workers. (Using this approach, I am not sure how to make the list of priorities "persistent", so that newly joined worker knows what is the current priority list.)

How would you implement it? Is RabbitMQ viable option for this use case?
Answer: your idea "priority of a message can change once they are in the queue" IMO is not possible with rabbitmq because rabbitmq only allows you to get messages from the head of a queue.
for example:

you have N queues each used for a different priority
each queue has 100+ messages
your idea requires you to reach into the middle of a queue to get a specific message but this is not possible with rabbitmq so the thought experiment stops here because you can only get messages at the head of a queue

your idea IMO would require using something else besides rabbitmq.
a quick and dirty idea that would work with rabbitmq now and is similar to your idea:

create one rabbitmq queue with N priorities
submit a message with priority x
if you need to change the priority to higher priority like priority y then you could send the same message again but with a new higher priority y
this would ensure the new message is processed faster
the side effect is that you may process the same request twice

you could fix the side effect in your design by having a some sort of database for synchronization to keep track of what jobs are completed and then this could avoid processing the job twice
there are many other details that would need to be addressed like keeping the original message around somehow outside of rabbitmq, concurrency, etc, etc,


How to mirror a GitHub repo using Github actions?

Question: I would like to know if there is a way to use GitHub Actions to automatically mirror changes from repoA to repoB.
Both would be private repositories.
The workflow would be like this: a commit would be pushed to a branch on repoA and then automatically the same commit would be sent to repoB as well.
I've seen posts on adding a remote repository, but would be interested to see how GitHub Actions can help to improve this.
Comment: As far as I know, it is not possible. However, why do you wanna do it?
Answer: You might consider a GitHub Action like Git Sync:

A GitHub Action for syncing between two independent repositories using force push.

You add use in it an SSH private key to access to your second repository
ssh_private_key: ${{ secrets.SSH_PRIVATE_KEY }}

(since you can create and store encrypted secrets in a workflow)


How do I add an [(ngModel)] and Datetime format to ionic V7 ion-datetime

Question: I am testing the ionic V7 ion-datetime I am able to bind the (ionChange) to an [(ngModel)] and format the change.  What I am trying to do is link the ion-datetime-button to an [(ngModel)] and format to YYYY-MM-DD.  is this possible.
html
    <ion-datetime-button datetime="TESTID"></ion-datetime-button>

    <ion-modal [keepContentsMounted]="true">
      <ng-template>
        <ion-datetime
          #popoverDateMain
          [showDefaultButtons]="true"
          id="TESTID"
          presentation="date"
          displayFormat="YYYY-MM-DD" // Does nothing
          min="{{minDateAvailable}}"
          max="{{today}}"
          (ionChange)="item.Input = formatDate(popoverDateMain.value)" // links to [(ngModel)]
        >
      </ion-datetime>

ts
import { format, parseISO } from 'date-fns';

formatDate(value: any) { return format(parseISO(value), 'yyyy-MM-dd'); }

getToday() {
   this.today = this.formatDate(new Date().toISOString())
   return this.today;
}

minDate(){
  this.min = new Date();
  this.min.setMonth( this.min.getMonth()-6)
  this.min = this.min.toISOString();
  this.minDateAvailable = this.formatDate(this.min);
  return this.minDateAvailable;
}

Answer: Maybe I'm missing something in what you're trying to achieve here, but it seems you're simply overthinking/overcomplicating it.
If you set ngModel directly to a string in the desired and supported format, it should just work.
Here's a bare-bones example that should get you going:
TS...
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';

@Component({
  selector: 'app-datepicker',
  templateUrl: './datepicker.page.html',
  styleUrls: ['./datepicker.page.scss'],
  standalone: true,
  imports: [IonicModule, CommonModule, FormsModule]
})
export class DatepickerPage {
  #date: string = '2023-04-20T12:00';
  get date(): string { return this.#date };
  set date(val: string) {
    this.#date = val;
    console.log(this.date);
  };

  constructor() { }
}

HTML...
<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>Date Picker Test</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-datetime-button datetime="datetime"></ion-datetime-button>

  <ion-modal [keepContentsMounted]="true">
    <ng-template>
      <ion-datetime
        id="datetime"
        [(ngModel)]="date"
      >
      </ion-datetime>
    </ng-template>
  </ion-modal>
</ion-content>

Here's some console output changing the date or time...
datepicker.page.ts:18 2023-04-06T12:00:00
datepicker.page.ts:18 2023-04-06T13:00:00

If I'm missing something please say and I can see about updating this.
Here's a repo with the code.
Comment: You are right I was way over thinking it and using the V6 format to much
Comment: The only real issue I seen is if you have multiple date times in the form
Comment: Multiple datetimes? What are you referring to?
Comment: Some forms can have multiple date entries.  Start date, end date, date due.  That's why I had the ionChange so I could use the same code across multiple form entries. Item.input is multiple ngModels from an question array
Comment: In that case the usual approach is to make it a component and reuse the code that way.
Comment: can anyone help me to fix this issue
https://stackoverflow.com/questions/77566749/how-to-hide-dial-pad-or-key-board-in-ion-datetime-ionic-capacitor


if H is a subgroup and N is a normal subgroup is H normal in HN?

Question: The title speaks for itself, I saw something that requires it but I can't seem to prove it, any help is appreciated!
I'm asking because of this comment which specify that from the second isomorphism theorem we know that $[HK:H]=[K:H\cap K]$ suggesting that $H\triangleleft HK$ when in the question we have that $K\triangleleft G$ and $H\le G$
Comment: Let $G$ be a group with a nonnormal subgroup $H$. Let $N=G$. Then $HN=G$ and $H$ is not normal in $HN$. Are you sure that this is what you want?
Comment: If you pick $N=G$ then it would mean that every subgroup is normal. Which is not true. So, there are plenty of counterexamples. Even with $N$ a proper subgroup of $G$. Try some small examples.
Comment: I'm asking because of [this](http://math.stackexchange.com/questions/148528/question-about-normal-subgroup-and-relatively-prime-index#comment342219_148528)
Comment: What do you don't understand about the proof? Make that clear to us please, so we can help.
Comment: Edit the link into your question. It is absurd to omit such information when you have it. What part exactly do you think requires this (false) result?
Comment: I think I clarified by your comments I now know that it's false just as I suspected but it's still not clear to me how it "adds up"
Answer: It appears to me that your core mistake is that you seem to think the 'index of' relation (denoted by the '[:]') is only applicable between a group and a normal subgroup.  Actually it is applicable between a group and any subgroup.


hook_node_access called more than once

Question: I have this very simple implementation of hook_node_access
function applx_node_access($node,$op,$account){
    drupal_set_message($node);
}

This returns
applx_application
forum
article
page
forum

And because of this i am not able to proceed further. I'm not sure why it prints the name of all bundles.
Answer: $node contains all the content-type in your application as value. So, you need to set your node access based on the $node value.
function hook_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;
  if($type == 'forum') {
    //set your permission based on $op value.
  }
}

Comment: Well, how do i go about figuring out which content-type a user is trying to access so i can set the node access?
Comment: Oh i see, its like an iteration. Thanks a lot man ;) You're a life(time) saver :)
Answer: It happens because the first parameter of hook_node_access() could be either:

A string containing the content type of the node
A node object

It is a string for the content type when a node doesn't exist yet, for example because it is going to be created.
In fact, the first line of node_node_access() (the implementation of that hook made from the Node module), is the following one.
$type = is_string($node) ? $node : $node->type;

Your code needs to check the type of the value passed as first argument, in a similar way.
The hook is invoked multiple times because Drupal is checking what content types should be shown in node/add for the currently logged-in user. In fact, your hook implementation is getting the machine names of the content type defined in that site.
Notice that, in Drupal 8, the first parameter of that hook is always an object implementing the NodeInterface interface, so it is not anymore necessary to check the type of the first parameter.

hook_node_access called more than once


Show that the property holds for the group homomorphism

Question: We have $(\mathbb{Q}^2,+)$ with the operation $(x,y)+(x',y')=(x+x',y+y')$. For $a\in \mathbb{Q}$ and $(x,y)\in \mathbb{Q}^2$ we have that $a\cdot (x,y)=(a\cdot x, a\cdot y)$.
Let $f:\mathbb{Q}^2\rightarrow \mathbb{Q}^2$ be a group homomorphism.
I want to show that $f(a\cdot (x,y))=a\cdot f(x,y)$ for all $a\in \mathbb{Z}$ and $(x,y)\in \mathbb{Q}^2$.
For that do we have to write $a(x,y)$ as an addition of each component a times to use the operation that's given?
$$$$
EDIT:
I have shown that $f(a\cdot (x,y))=a\cdot f(x,y)$ for all $a\in \mathbb{N}_0$. To show that it holds for $\mathbb{Z}$ we have to show that $f((−a)\cdot (x,y))=−a\cdot f(x,y)$, or not? But how?
Comment: is $a\in \mathbb{Q}$ or $\mathbb{Z}$? One time you say the former and another the latter?
Answer: I assume it is supposed to be the case that $a\in \mathbb{Z}$.  My advice would be to think of a small example and see if you can generalize $f(3\cdot (x,y))=f((x,y)+(x,y)+(x,y))=f(x,y)+f(x,y)+f(x,y)=3\cdot f(x,y)$.  What if it were $f((-3)\cdot (x,y))$?  Induction to prove it carefully.
Comment: Prove it first for $a \in {\mathbb Z}$. Let $f(\frac{1}{n}(a,b)) = (c,d)$. Then by the result for $a \in {\mathbb Z}$, $f(a,b) = (nc,nd)$, so $f(\frac{1}{n}(a,b))  = \frac{1}{n}f(a,b)$.
Comment: $0 = f(0) = f(a(x,y) + (-a)(x,y)) = f(a(x,y)) + f(-a(x,y))$.
Comment: It works also for $a \in {\mathbb Q}$.
Comment: So do we show by induction that it holds for every natural a and then that the negative values are symmetrical? What would be if a is rational?
Comment: How can we show that for $a\in \mathbb{Q}$ ? @DerekHolt
Comment: I have shown that $f(a\cdot (x,y))=a\cdot f(x,y)$ for all $a\in \mathbb{N}_0$. To show that it holds for $\mathbb{Z}$ we have to show that $f((-a_\cdot (x,y))=-a\cdot f(x,y)$, or not? But how? @DerekHolt
Comment: Do we have to show that again by induction or does this follow by $f(a\cdot (x,y))=a\cdot f(x,y), a\in \mathbb{N}_0$ ? @DerekHolt
Comment: Thank you!! :-)


scheduling backup_migrate with elysia cron

Question: I am looking at scheduling backup & migrate jobs with the elysia cron module. Can I ask how to call backup & migrate directly from the elysia script? Or should I be calling "drush bam"?
Comment: I don't think Elysia lets you choose the jobs to run when you invoke the script file. Personally I'd go with `drush bam` either way, it will always be slightly less overhead
Answer: It all depends on your preferences and situation.
Elysia is designed to work in environment when you can trigger Elysia every minute (or every five, or ten minutes, but regularly 24/7). In that environment it would be more convenient to simply schedule Backup and Migrate with Elysia. Just remember to keep what you set in Home > Administration > Configuration > System > Backup and Migrate > Schedules in sync with what you set in Home > Administration > Configuration > System > Cron > Settings.
Benefit of that solution is easily accessible status of a cron task, the fact that you can see with GUI how long it took and when it was last fired, without login to any other tools but your Drupal.
Problem is that if cron system gets delayed, you may lost next sheduled backup - it may be mere 23h 58m since last time Elysia fired BaM task, so BaM may decide it's too soon to take another "everyday" backup. It's common problem with one scheduler calling another. And if you will make Elysia to trigger BaM every 5 minutes, to make sure everyday backup will be triggered consistently, you will waste a lot of CPU power for nothing.
drush bam approach is more direct. Long story short, it's main pros is lack of problems described above, and main cons is lack of benefits described above. And it's slightly faster in execution overall, as one "layer" less is in use.


Android animated nested fragments

Question: I have an activity with a fragment A inside of it. The fragment A have nested fragment B inside of it. I'm switching B with C using following code:
<code>            getChildFragmentManager()
                .beginTransaction()
                .setCustomAnimations(R.anim.move_left_in, R.anim.move_left_out,R.anim.move_right_in, R.anim.move_right_out)
                .replace(R.id.container, fragmentC)
                .addToBackStack("nested")
                .commit();
</code>
after that Im doing
<code>        getChildFragmentManager().popBackStack();
</code>
what brings me back to fragment B.
After that I switch fragment A with fragment D using code
<code>        getSupportFragmentManager()
            .beginTransaction()
            .setCustomAnimations(R.anim.move_up_in, R.anim.move_up_out, R.anim.move_down_in, R.anim.move_down_out)
            .replace(R.id.fragment_holder, fragmentD)
            .addToBackStack("fragments")
            .commit();
</code>
and while that animation on A->D transaction is playing, the B plays animation of transaction C->B, and by poping backstack im getting same result, why?
Comment: What support libs version do you use?
Comment: I am not getting what you actually want. Can you elaborate a little bit on this part, "and while that animation on A->D transaction is playing, the B plays animation of transaction C->B, and by poping backstack im getting same result, why?"?
Answer: When you switch fragment A with fragment D.
The content within fragment A detach from its parent and then transaction A -> D takes place,
Since you have already set animation to your fragments, delay due to those animation is the reason you,see that left out animation in B first,
then A -> D animation.
Answer: Don't use the getChildFragmentManager(),
Use support fragmnetManager means use getSupportFragmentManager why?
Bcz of nested fragment
I hope your problem is solved with this solution. Thank you:)
Comment: Because I've also faced this problem while I'm doing animation with fragments, So, I just change it from child Manager to support manager so after that I get my results which I want.
Comment: you can check here https://developer.android.com/reference/android/app/FragmentTransaction.html#setCustomAnimations%28int,%20int,%20int,%20int%29
Comment: and what about lifecycle? What if you rotate device, is fragment inside fragment recreated properly?
Comment: you can check this , https://stackoverflow.com/questions/8474104/android-fragment-lifecycle-over-orientation-changes

Android animated nested fragments


Largest area with given perimeter, one straight edge

Question: A common example to introduce quadratic functions is to ask for a rectangle with the largest area when the perimeter is given and you are allowed to use one additional edge that does not count towards the perimeter ("Building a fence for an rectangular enclosure next to an existing wall").
What happens if you lift the "rectangular" limitation and allow arbitrarily shaped shapes?
I found out that a semicircle is better than the best rectangle, but I have no idea how to check for other shapes with curved boundaries.
So, the question is:
What is the largest possible area that one can get with a shape that has one straight edge and an otherwise arbitrarily shaped boundary of length $x$?
Comment: You are right about the semicircle enclosing max area. Look up "Queen Dido's problem" via google.
Comment: Try this other question on this site, and it's answers/links. https://math.stackexchange.com/questions/1358824/general-question-about-optimization?noredirect=1
Answer: This is a problem from antiquity calles "Dido's Problem" or "Dido's isoperimetric Problem", the solution is a semi-circle.
See for example here or here.
It's clear that the resulting shape has to be convex, because otherwise one can just flip an inside bulge to an outside bulge, thereby inclreasing the area but keeping the perimeter unchanged.  See here for a description.
Likewise, and under the assumption that the curve is smooth, when the curve has an inside angle of $\phi > 90°$ with the line, a portion of the curve can be flipped inside out such that the area increases, the length of the curve stays the same, and $\phi < 90°$ after the flip.  Thus $\phi\leqslant 90°$.
The technique used to solve the prolbem is calculus of variations, where the problem is stated a bit differently:  One assumes that the curve starts and ends at fixed points $a$ and $b$ of the line, and one then shows that the curve is part of a circular arc.


Calculating the parameters of a Beta distribution using the harmonic mean and variance

Question: Is there a similar way to this for calculating the $\alpha$ and $\beta$ parameters for a Beta distribution if I know the harmonic mean and variance that I want the distribution to have ($\alpha>1$ and $\beta>0$)?
$HM=\frac{\alpha-1}{\alpha+\beta-1}$
Example: harmonic mean = 0.25 and variance = 0.04 should yield $\alpha$ = 2 and $\beta$ = 3
As per JimB's comments below; is there a single solution if $\alpha > 1$ and $\beta > 1$?
Comment: One way: write $\alpha = 1 + \beta(h/(1-h))$ where $h$ is the harmonic mean.  Plug that into the equation for the variance and solve for $\beta.$
Answer: You are not guaranteed a single solution.
If you do the substitutions as suggested by whuber, you will end up having to solve a cubic expression for $\alpha$ or $\beta$ which with minor difficulty will lead to three pairs of solutions.
In your example, you will get $\alpha=1+\frac\beta 3$ and something like $$64\beta^3-33\beta^2-495\beta+54 =0$$
and solutions $$(3,2) \text{ and }\\ \left(\frac{9 \sqrt{41}+75}{128},\frac{27 \sqrt{41}-159}{128}\right) \text{ and } \\\left(\frac{-9 \sqrt{41}+75}{128},\frac{-27 \sqrt{41}-159}{128}\right)  $$
where you can reject the third pair as it has $0< \alpha<1$ and $\beta<0$.
The second pair with $\alpha \approx 1.036157172944497$ and $\beta\approx 0.1084715188334915$ appears to be a solution satisfying the conditions. It is a deeply strange solution as $61\%$ of the probability would be concentrated in the interval $[0.99,1]$ and less than $3\%$ below the harmonic mean, and this raises the question of whether the harmonic mean is an useful statistic for describing a Beta distributed sample.
This shows the probability densities of the two solutions - the first in blue and the second in red, with the harmonic mean as a vertical black line. It is the small but substantial probability of extremely small values using the second solution which brings its harmonic mean down, despite the vast bulk of the distribution being much higher (its pdf is unbounded near $1$).
Comment: @JimB The harmonic mean uses the reciprocal.  The reciprocal of a Beta distributed random variable is a  Beta-prime distributed random variable on $[1,\infty]$ with the parameters swapped.  In this case, the corresponding Beta-prime random variable has a mean of $\frac1{0.25}=4$ but in the case of the second solution would have an infinite variance, causing issues for the speed of convergence for the sample harmonic mean of the original Beta random variable with the second solution as parameters.
Comment: Just to play Devil's Advocate about the usefulness of the harmonic mean for describing a Beta distributed sample:  isn't it the use of the variance that results in potentially multiple solutions?  There is a unique solution when using the mean and the harmonic mean with the estimates of $\alpha$ and $\beta$ being $\frac{m(1-h)}{m-h}$ and $\frac{(1-h) (1-m)}{m-h}$, respectively.
Comment: Maybe a slight modification in my argument:  it appears to be the combination of the harmonic mean and the variance that causes the multiple solutions.  Using the combination of the variance and mean results in just a single solution.
Comment: @JimB I have added a chart for the densities of the two solutions which suggests to me that you can substantially manipulate the harmonic mean with small adjustments to the probability of extremely small values even if the bulk of the distribution is elsewhere. These adjustments would make minimal changes to the arithmetic mean and variance, so I would still say it is the nature of the harmonic mean which causes this.
Comment: I think I might not have been clear.  As you've mentioned there is no guarantee of a unique solution (although I think using the harmonic mean and variance always results in two legitimate solutions).  That should be enough to not use the harmonic mean *and* the variance as the moments in a method of moments estimator for $\alpha$ and $\beta$.  That one of the two solutions has an infinite variance for the harmonic mean would seem to be irrelevant.  Two solutions == bad.  Again, it is the combination of using the sample harmonic mean and sample variance that should be avoided.


understanding how shapes are combined in a CNN

Question: I've heard CNN's explained a few times as looking for simpler shapes like edges, and then gradually combining them into larger / more complex shapes at deeper levels. However, I'm having a tough time seeing how that could take place.
Say the first layer has 6 filters, detecting various sorts of edges. They output 6 of their own images, basically showing where those edges were detected.
The next layer has 8 filters which presumably could combine the output of the first layers into more complex shapes. HOWEVER, the problem I see is that to combine edges, what you really want is to see that edge 1 is connected to edge 2 is connected to edge 3, forming a triangle or something like that. But the filters in layer 2 could never do that, because they are still looking at the same location of each image simultaneously. They could only detect edges in the different images that are "on top" of each other.
See what I mean? How does this work?
Also, maybe related but maybe not: Is there an intuition for why we want smaller images but more filters as we go deeper in the network? What purpose does that serve?
Answer:
They output 6 of their own images, basically showing where those edges were detected.

That's not exactly like this. Convolutional filters (a.k.a. kernels) don't show where the edges are detected, they show what kinds of edges are most descriptive subject to the training images and the loss function. It just so happens that simple shapes such as edges and corners are very helpful for the future layers.

HOWEVER, the problem I see is that to combine edges, what you really want is to see that edge 1 is connected to edge 2 is connected to edge 3, forming a triangle or something like that.

Also not exactly like that. Each convolutional layer doesn't take the filters as input (the filters are usually small, e.g. 3x3), they take the training input image after applied the previous convolution and non-linearity (we can ignore downsampling, batch-normalization and other complications for this discussion). It is true that the convolutional layer is boosting the signal, where the filter has matched. Hence, the second layer will likely see higher values at the edges (enhanced by the first layer). But it's still the input image, which will probably have a lot of details and complex shapes in it.
In other words, it is possible to learn a triangle-like shape, even though the lower layer doesn't have filters exactly like triangle edges. Realistically, it could be a combination of different edges, enhanced by different filters. But, to be fair, many of the deeper layers' filters aren't easily interpretable to make any firm conclusions (see also this discussion on AI.SE).
Hope this clarifies the learning process inside a CNN.

Also, maybe related but maybe not: Is there an intuition for why we want smaller images but more filters as we go deeper in the network? What purpose does that serve?

If by images you mean filters, the latest tendency is to use small filters all the time: since VGGNet, 3x3 seems like a standard, Inception was the first network to apply asymmetrical 1x3 and 3x1 filters, now they are also very common.
But it is true that the number of filters usually increases in the deeper layers, because the earlier layers serve as feature extractors, so that the deeper layers learn more complex shapes. Increasing feature complexity naturally demands more filters for CNN to work better.
Comment: Maybe I can rephrase my question: It seems like to detect a more complex shape, you need to do two things: 1) combine smaller features, 2) detect whether the smaller features were combined in a meaningful way. It seems like a single filter couldn't do both of these things. So would you be depending on a series of 2 filters to do that? For example the first one just sums input features from a variety of channels. Then the second one looks at the result of that (now probably in fewer pixels) and assesses the overall shape.


Show $\int_{-\infty}^\infty\int_0^\infty \exp(\cos t-1-t^2) \cos(\sin t-t x)\,\mathrm dt\mathrm dx=\pi$

Question: I am tring to prove
$$
\int_{-\infty}^\infty\int_0^\infty \exp(\cos t-1-t^2) \cos(\sin t-t x)\,\mathrm dt\mathrm dx=\pi.
$$
Numerical integration in Mathematica (truncating the integration bounds on $x$ to $(-30,30)$ shows agreement with the conectured exact value of $\pi$.
Interchanging the order of integration is not applicable here because $\int_{-\infty}^\infty\cos(\sin t-tx)\,\mathrm dx$ does not converge.  I also do not see a useful $u$-substitution to simplify things.  I can write the entire integrand as a single (complicated) exponential function using $\cos(\sin t-tx)=\Re \exp(i(\sin t-tx))$ but this too has not produced any fruit. Also the exponential term $\exp(\cos t-t-t^2)$ is critical to the convergence of the integral so expanding it as a Taylor series and integration termwise won't work. Perhaps someone sees a path forward using complex methods.
Comment: Happy pi day :)
Comment: Whenever I see integrals involving cosines of sines, I think of [Bessel's integrals](https://en.wikipedia.org/wiki/Bessel_function#Bessel's_integrals) and the [Jacobi-Anger formula](https://en.m.wikipedia.org/wiki/Jacobi–Anger_expansion). So this integral may end up being the completeness relation for Bessel functions.
Answer: Let $I$ denote the integral. Then
\begin{align}
I
&= \frac{1}{2}\int_{-\infty}^{\infty}\int_{-\infty}^{\infty} \exp(\cos t - 1 - t^2) \cos(\sin t - t x) \, \mathrm{d}t\mathrm{d}x \tag{1} \\
&= \frac{1}{2} \int_{-\infty}^{\infty}\int_{-\infty}^{\infty} \exp(e^{it}-t^2-ixt-1) \, \mathrm{d}t\mathrm{d}x \tag{2} \\
&= \frac{1}{2} \int_{-\infty}^{\infty} \sum_{n=0}^{\infty} \frac{1}{n!} \int_{-\infty}^{\infty} e^{int}\exp(-t^2-ixt-1) \, \mathrm{d}t\mathrm{d}x \tag{3} \\
&= \frac{1}{2} \int_{-\infty}^{\infty} \left( \sum_{n=0}^{\infty} \frac{1}{n!} \sqrt{\pi} \, e^{-\frac{1}{4} (n-x)^2-1} \right) \mathrm{d}x \tag{4} \\
&= \frac{\sqrt{\pi}}{2e} \sum_{n=0}^{\infty} \frac{1}{n!} \int_{-\infty}^{\infty} e^{-\frac{1}{4} (n-x)^2} \mathrm{d}x \tag{5} \\
&= \frac{\sqrt{\pi}}{2e} \sum_{n=0}^{\infty} \frac{1}{n!} (2\sqrt{\pi}) \tag{6} \\
&= \pi.
\end{align}
Here are some explanations:

$\text{(3)}$ : Fubini's theorem is applicable:
$$ \int_{-\infty}^{\infty} \sum_{n=0}^{\infty} \left| \frac{e^{int}}{n!} \exp(-t^2-ixt-1) \right| \, \mathrm{d}t
= \int_{-\infty}^{\infty} \sum_{n=0}^{\infty} \frac{1}{n!} \exp(-t^2-1) \, \mathrm{d}t < \infty. $$

$\text{(4)}$, $\text{(6)}$ : We have
$$\int_{-\infty}^{\infty} e^{-a(x-z)^2} \, \mathrm{d}x = \sqrt{\frac{\pi}{a}}$$
for any $a > 0$ and $z \in \mathbb{C}$. Now, use this and complete the square of the exponent to conclude.

$\text{(5)}$ : Tonelli's theorem is applicable.


General questions on Cayley graphs

Question: In Graph Theory mainly in Cayley graphs there are four general questions " according to Audery Terras" : 'Suppose A is the adjacency operator of a connected regular (undirected)
graph $X$ of degree $k$ (without multiple edges). Let $spec(A)$ denote the spectrum
of $ A$, that is, the set of all eigenvalues of $A$. Let $d$ be the diameter of $X$ and $g$
be the girth.
Question 1. Is $X$ Ramanujan, that is, if $λ ∈spec(A)$, $|λ|≠k$ does $λ$ satisfy $|λ|≤ 2(k-1)^{1/2}$?
Question 2. Is $0∈  spec(A)$ or, equivalently, is $A$ invertible?
Question 3. Can we bound the diameter $d$?
Question 4. Can we bound the girth $g$?

As I am new in this field of mathematics, my question is: are there more important or maybe new questions that researcher can ask or for example analogue some questions?
Answer: Ramanujan graphs are important and interesting and, so far, all examples
are constructed as Cayley graphs. If you're interested in Ramanujan graphs,
then the problems that Audrey Terras lists are central. But Cayley graphs
appear all over graph theory and, when they do, raise questions not on her list.
One famous open problem is whether every Cayley graph has a Hamiltonian path.
(There are many variants, all of which are open.) In quantum information theory,
we would like to know which Cayley graphs admit perfect state transfer, even just
for Cayley graphs of abelian groups. There is
active work on the structure of the automorphism groups of Cayley graphs, particularly
circulants.

General questions on Cayley graphs


linq - list of string - order by letter only, and then by numbers

Question: For example :
this array:
a 2
a 10
a

should be after sort :
a
a 2
a 10

I try this, but it doesn't not work: the order is wrong.
 ...
.OrderBy(s => s.name)
.ThenBy(s => {
   var stringNumber = Regex.Match(s.name, @"\d+").Value;

   return string.IsNullOrEmpty(stringNumber)
     ? 0
     : int.Parse(stringNumber);
 });

Comment: What does "is not work" mean exactly? And do your `name`s always look like this: single character-space-number?
Comment: what is ur output
Comment: The problem is that you at first sort by the **whole string**, so `ThenBy` has no effect anymore, you need to `OrderBy` the letter only, `ThenBy` the number only.
Comment: Select into an anonymous type that splits the string into string and int? Then order by accordingly
Answer: I suggest extracting criterium explicitly: name and number groups in the regular expression:
  var list = new List<string>() {
    "a",
    "a 4",
    "b 1",
    "a 2",
    "a 11"
  };

  var result = list
    .Select(item => new {
         value = item,
         match = Regex.Match(item, @"^(?<name>.*?)\s*(?<number>[0-9]*)$"),
       })
    .OrderBy(item => item.match.Groups["name"].Value)
    .ThenBy(item => item.match.Groups["number"].Value.Length)
    .ThenBy(item => item.match.Groups["number"].Value)
    .Select(item => item.value);

Test:
Console.WriteLine(string.Join(Environment.NewLine, result));

Outcome:
a
a 2
a 4
a 11
b 1

Comment: Worth mentioning that the new tuple types can be used here.
Answer: Since you said "letter" I assume you want to only sort by the first character, then by the number.
So don't OrderBy the whole string, but by the letter only:
var result = list
          .OrderBy(s => s.FirstOrDefault()) // only first character
          .ThenBy(s =>
             {
                var stringNumber = Regex.Match(s.name, @"\d+").Value;
                return string.IsNullOrEmpty(stringNumber) ? 0 : int.Parse(stringNumber);
             })

Your code sorted by the whole string at first, so ThenBy had no effect anymore.
Answer: You could try something like that;
        var list = new List<string>()
        {
            "a ",
            "a 4",
            "b 1",
            "a 2"
        };

        int value = 0;

        list = list
          .Select(x => new {
             WholeString = x,
             StringPart = x.Split(' ')[0],
             IntPart = int.TryParse(x.Split(' ')[1], out value) ? value : 0
            })
          .OrderBy(x => x.StringPart)
          .ThenBy(x => x.IntPart)
          .Select(x => x.WholeString)
          .ToList();

Answer: var test = new[] {"a 2", "a 10", "a"};

var sorted = test.OrderBy(s => new string(s.Where(char.IsLetter).ToArray())).ThenBy(s =>
{
    var stringNumber = Regex.Match(s, @"\d+").Value;
    return string.IsNullOrEmpty(stringNumber) ? 0 : int.Parse(stringNumber);
});

This should sort by letters first, then by numbers.


how to make a custom filter in custom module?

Question: i am creating a custom module
**

form_example.module

**
<?php
function form_example_permission() {
  return array(
    'submit form_example' => array(
      'title' => t('Submit form_example'),
      'description' => t('Submit the form_example form'),
    ),
    'access form_example submissions' => array(
      'title' => t('Access form_example submissions'),
      'description' => t('Access the form_example submissions'),
    ),
  );
}
function form_example_menu() {
  $items = array();

  $items['form-example'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Employess Entry Form', //page title
    'description' => "A form to submit the employee's data.",
    'type' => MENU_NORMAL_ITEM,
    'access arguments' => array('submit form_example'),
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('form_example_form'),

      );

 $items['form-submissions'] = array(
    'title' => t('List'),
    'page callback' => 'form_example_submissions',
    'access callback' => TRUE,
    'access arguments' => array('access form_example submissions'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function form_example_form($form, &$form_state) {

$form['empcode'] = array(
  '#weight' => '0',
  '#required' => '1',
  '#type' => 'textfield',
  '#title' => t('Employee Code'),
);
$form['empname'] = array(
  '#weight' => '1',
  '#required' => '1',
  '#type' => 'textfield',
  '#title' => t('Employee Name'),
);
$form['empemail'] = array(
  '#weight' => '2',
  '#required' => '1',
  '#type' => 'textfield',
  '#title' => t('Employee Email'),
);
$form['empdesignation'] = array(
  '#weight' => '3',
  '#required' => '1',
  '#type' => 'textfield',
  '#title' => t('Employee Designation'),
);
$form['file'] = array(
  '#weight' => '4',
  '#type' => 'file',
  '#size' => '30',
  '#title' => t('Employee Photo'),
);
 $form['submit'] = array(
     '#weight' => '5',
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

return $form;

}

function form_example_form_validate($form, &$form_state) {
  /*if (!($form_state['values']['price'] > 0)){
    form_set_error('price', t('Price must be a positive number.'));
  }*/
 // print('
'.print_r($form_state['values'],1).'
');
  //die();
 $file = file_save_upload('file', array(
    'file_validate_is_image' => array(),
    'file_validate_extensions' => array('png gif jpg jpeg'),
  ));
  if ($file) {
    if ($file = file_move($file, 'public://')) {
      $form_state['values']['file'] = $file;
    }
    else {
      form_set_error('file', t('Failed to write the uploaded file the site\'s file folder.'));
    }
  }
  else {
    form_set_error('file', t('No file was uploaded.'));
  }
}

function form_example_form_submit($form, &$form_state) {
   $file=$form_state['values']['file'];
  unset($form_state['values']['file']);
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
 // drupal_set_message(t('The form has been submitted and the image has been saved, filename: @filename.', array('@filename' => $file->filename)));

 $fe_id = db_insert('form_example')
        ->fields(array(

          'empcode' => $form_state['values']['empcode'],
          'empname' => $form_state['values']['empname'],
          'empemail' => $form_state['values']['empemail'],
          'empdesignation' => $form_state['values']['empdesignation'],
          'empphoto' => $file->filename,
        ))
        ->execute();
        drupal_set_message(t('Successfully added'));

}
function form_example_theme($existing, $type, $theme, $path) {
  return array(
    'form_example_function' => array(
      'variables' => array('rows' => NULL),
    ),
    'form_example_template' => array(
      'variables' => array('rows' => NULL),
      'template' => 'form_example_template',
    ),

  );
}

/* view the form submissions*/
function form_example_submissions()
{
  $results =  db_query("Select * from {form_example}");
   $rows = array();
  foreach($results as $result)
  {
    $rows[] = array(
        $result->fe_id,
        $result->empcode,
        $result->empname,
        $result->empphoto,
        $result->empemail,
         $result->empdesignation,
      );

  }
  return theme('form_example_function',array('rows' => $rows));
}
/*function theme_form_example_function($variables)
{
  print_r($variables);
//$output ="
".print_r$variables."

";
/*  foreach ($variables as $result)
  {

    $output = "

".print_r($result)."

";
  }
return $output;
 $output = '';

    foreach($variables['rows'] as $row) {
        foreach($row as $values) {

          print_r($values);
         $output .= "Empcode: " . $values . "
 ";
         // $output .= "EmpName: " . $values[1] . "
";
        //$output .= "Emphot: " . $values[2] . "\n";
        }
    }
    return $output;

}*/
function theme_form_example_function($variables)
{
    $output = '';
print_r($variables);
    foreach($variables['rows'] as $row) {
      //  echo $path;
      // $output .= "Empcode: " . (isset($row[1]) ? $row[1] : "--") . " ";
      //  $output .= "EmpName: " . (isset($row[2]) ? $row[2] : "--") . " ";
      //  $output .= "Emphot: " . (isset($row[3]) ? $row[3] : "--") . "
";

$img_url = 'public://'.(isset($row[3]) ? $row[3] : "--");  // the orig image uri
$style = 'medium';  // or any other custom image style you've created via /admin/config/media/image-styles

     $output .= '

'.(isset($row[2]) ? $row[2] : "--") .'

Emp Code:

'.(isset($row[1]) ? $row[1] : "--") .'

'.(isset($row[4]) ? $row[4] : "--") .'

'.(isset($row[5]) ? $row[5] : "--") .'

';

    }

    return $output;
}

?>

I want to show only filters on form-submissions like below:

After filter the data screen will shown like below

i want to know how can i add these filter on page and search the
  result on database and shown on page
Answer: I am adding an example for this. Hope this will helps you.
function form_example_list(){
    $search_form =drupal_get_form('form_example_search_form');
    $content = '
'.drupal_render($search_form).'
';
    $content .= '

';

    $query = db_select('form_example', 'pd');
    if(isset($_GET['empname']) && $_GET['empname'] != ''){
        $query->condition('pd.empname', $_GET['empname'],'=');
    }
    if(!empty($_GET['empcode'])){
        $query->condition('pd.empcode', $_GET['empcode'],'=');
    }
    if(isset($_GET['empdesignation']) && $_GET['empdesignation'] != ''){
        $query->condition('pd.empdesignation', $_GET['empdesignation'],'=');
    }
    $query->fields('pd');
    //$table_sort = $query->extend('TableSort')->orderByHeader($header);
    //$pager = $table_sort->extend('PagerDefault')->limit(10);

    $result = $query->execute();
 return $content;
}
function form_example_search_form($form, &$form_state){

    $form['#method'] = 'get';
    $form['#token'] = FALSE;
    $form['#form_build_id'] = FALSE;
    $form['#form_id'] = FALSE;
    $form['empname'] = array(
        '#type' => 'textfield',
        '#title' => t('empname'),
        '#attributes' => array( 'maxlength' => '128', 'size'=> '30'),
        '#prefix' => '

',
        '#suffix' => '
',
        '#default_value' => isset($_GET['empname'])?$_GET['empname']:'',
    );
    $form['empcode'] = array(
        '#type' => 'textfield',
        '#title' => t('empcode'),
        '#attributes' => array( 'maxlength' => '128', 'size'=> '30'),
        '#prefix' => '

',
        '#suffix' => '
',
        '#default_value' => isset($_GET['empcode'])?$_GET['empcode']:'',
    );
    $form['empdesignation'] = array(
        '#type' => 'textfield',
        '#title' => t('empdesignation'),
        '#attributes' => array( 'maxlength' => '128', 'size'=> '30'),
        '#prefix' => '

',
        '#suffix' => '
',
        '#default_value' => isset($_GET['empdesignation'])?$_GET['empdesignation']:'',
    );
    //views-exposed-widget

    $form['submit'] = array(
        '#type' => 'submit',
        '#attributes' => array( 'name' => ''),
        '#prefix' => '
',
        '#suffix' => '

',
        '#value' => 'Apply',
     );

    return $form;
}

// Fetch data as per you requirement means you may need like operator. Depend on situations.
After getting the result you can design as per your requirement.
Comment: its give me error undefined header and one more thing how can i call through url, list function is call through url?
Comment: I have updated my answer. You do not need header because your result output is different from table. and yes you need to call through url.
Comment: thanks buddy its working fine now and i have to study it to learn it :)
Comment: @smaluition: can you please tell me how can i add pagination in it
Comment: refer http://drupal.stackexchange.com/questions/58950/how-do-i-paginate-results-with-db-query
Comment: buddy can you please tell me how can i add like operator instead of = in condition clause of query
Comment: Refer http://drupal.stackexchange.com/questions/112530/how-to-use-like-condition-in-db-select-query. if you search more you will get more.
Comment: i add the pagination its didn't show on the page but the result is shown as per limit but without showing pagination boxes user cann't go on next page. Please tell me what to do to show the pagination on that


How to scroll down  with the help of react-three-drei (Scroll-controls)

Question: I want my sphere bubble to be in center of my screen even if we scroll pages.
is there any way toh do this
here is sandbox of it
https://codesandbox.io/s/happy-paper-cvl4fy?file=/src/App.js
I searched serveral things but didnt found anything
Answer: Just take the Circular component out of the Scroll Wrapper and it should work!
Your code should be something like this
<code><ScrollControls pages={3}>
    <Scroll HTML>
        <Html />
    </Scroll>
    <Circularr />
</ScrollControls>
</code>
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Multinomial coefficients (general inequality).

Question: Fix $s, n$ in $\mathbb{N}.$ Let $n_1,..., n_s$ in $\mathbb{N}$ such that $n_k\geq 1.$ Set $N= \sum_{k=1}^sn_k.$ I want to prove that
$$\sum_{m_1+...+m_s=n}\prod_{k=1}^s(m_k+n_k)!\leq (n+N)!.$$
The simple case where $s=2$ is equivalent to prove that
$$\sum_{m=0}^n (m+n_1)!(n-m+n_2)! \leq (n+N)!.$$
This can be proven by induction on $n;$
\begin{eqnarray}\sum_{m=0}^{n+1} (m+n_1)!(n+1-m+n_2)! &\leq&   (n+1+n_1)!n_2! +(n+N)\sum_{m=0}^n (m+n_1)!(n-m+n_2)! \\
&\leq& (n+N)! +(n+N)(n+N)! \\
&=& (n+1+N)! \end{eqnarray}
Any hint for the general case $s\geq 2?!$
Comment: This doesn't seem to have anything (directly) to do with multinomial coefficients. Perhaps you could clarify the relationship?
Comment: (It also doesn't seem to have anything to do with abstract algebra.)
Comment: In fact, if you divide by the right hand member, you will get inside the sum the term $\binom{|M|+N}{m_1+n_1,...., m_s+n_s}^{-1},$ where $M = (m_1, ..., m_s).$
Answer: You can use induction on $s$: for any $m_s'\ge 0$,
$$
\sum_{m_s+m_{s+1} = m_s'} (m_s + n_s)!(m_{s+1}+n_{s+1})! \le (m_s' + n_s')!,
$$
where $n_s' = n_{s} + n_{s+1}$. Therefore,
$$
\sum_{m_1+...+m_{s+1}=n}\prod_{k=1}^{s+1}(m_k+n_k)! \\= \sum_{m_1+...+m_{s-1}+m_s'=n}\left(\prod_{k=1}^{s-1}(m_k+n_k)!\right)\sum_{m_s+m_{s+1} = m_s'} (m_s + n_s)!(m_{s+1}+n_{s+1})! \\\le \sum_{m_1+...+m_{s-1}+m_s'=n}\left(\prod_{k=1}^{s-1}(m_k+n_k)!\right) (m_s'+n_s')!
$$
etc.
Comment: Just to be sure that I got it, you used $\sum_{m_1+...+m_{s+1}= n} = \sum_{m_1+...m_{s-1}+m'_s =n} \sum_{m_s+m_{s+1} =m'_s }$ ?
Comment: @A.MONET, sure I did. I've elaborated a bit; check now.
Comment: Seems to be done ! Thank you a lot.
Answer: For any $\ell$ define the formal power series
$$F_\ell(x)=\ell!+(1+\ell)!x+(2+\ell)!x^2+(3+\ell)!x^3+\cdots.$$
In terms of this power series, the left and right sides of the inequality are
$$ \sum_{m_1+\cdots+m_s=n}\prod_{k=1}^s (m_k+n_k)!=[x^n]F_{n_1}(x)\times\cdots\times F_{n_s}(x)$$
and $$(n+n_1+\cdots+n_s)!=[x^n]F_{n_1+\cdots+n_s}(x) .$$
In the $s=2$ case, the OP already did all the hard work to show
$$ [x^n]F_{n_1}(x)\times F_{n_2}(x)\le[x^n]F_{n_1+n_2}(x).$$
The rest follows by combining partial sums with the next term, like this:
\begin{eqnarray*}
% \nonumber to remove numbering (before each equation)
  [x^n]F_{n_1}(x)\times\cdots\times F_{n_s}(x) &\le& [x^n]F_{n_1+n_2}(x)\times F_{n_3}(x)\times\cdots\times F_{n_s}(x) \\
    &\le& [x^n]F_{n_1+n_2+n_3}(x)\times F_{n_4}(x)\times\cdots\times F_{n_s}(x) \\
    &\vdots&\\
    &\le& [x^n]F_{n_1+\cdots+n_s}(x) .
\end{eqnarray*}
Comment: What does the term $[x^n]$ represent ? Maybe you mean the coefficient of $x^n$ and in which step did you use the assumption $n_k \geq1$?
Comment: Right, $[x^n]f(x)$ means the coefficient of $x^n$ in $f(x)$. Also, I didn't use $n_k\ge1$, although you might have in the $s=2$ case. The inequality might still hold with $n_k\ge0$.
Comment: Then, if you take, for example, $s=2$ and $n_1 =  n_s = 0,$ the left hand member will be $n! + (n-1)! + 2(n-2)! + .... +n!  > (n+0)!$
Comment: @A.MONET, I believe $n_k\ge 1$ in the OP. This answer is in essence the induction on $s$. I don't like the emphasis on generating functions, but I do like that it unveils why the induction argument works: because of the convolution structure of the left-hand side.
Comment: Sorry for this stupid question: What does OP abbreviate ?
Comment: I think OP is taken to mean either Original Post or Original Poser.
Comment: @zhoraster Your proof is actually based on the initial case $s=2,$ where the inductive inequalities require explicitly that $n_k \geq 1.$