Tkinter dynamic "iframe" won't scroll

Question: I wrote a bit of code, and I can't, for the life of me figure out why it doesn't work. I'm trying to make a frame with a scrollbar with dynamic contents, but for some reason, the scrollbar won't scroll.
import scrolledframe
from Tkinter import *

class app(Tk):
    def __init__(self, parent):
        Tk.__init__(self, parent)
        self.parent=parent
        self.initialize()
        populateinterior(self.sframe.interior)
    def initialize(self):
        self.grid()
        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(0,weight=1)
        self.resizable(True,True)
        self.sframe = scrolledframe.VerticalScrolledFrame(self)
        self.sframe.grid()

def OnButtonClick():
        appinstance.sframe.interior.buttons.append(Button(appinstance.sframe.interior, text=u'Click meh!',command=OnButtonClick))
        appinstance.sframe.interior.buttons[-1].grid(row=len(appinstance.sframe.interior.buttons)+1,column=0)
def populateinterior(self):
        self.grid()
        self.buttons=[]

        self.buttons.append(Button(self, text=u'Click meh!',command=OnButtonClick))
        self.buttons[-1].grid(row=len(self.buttons)+1,column=0)

if __name__=="__main__":
    appinstance=app(None)
    appinstance.title("All dem appz belong to meh")
    appinstance.mainloop()

scrolledframe is not something I wrote myself, but here it is anyways:
from Tkinter import *
class VerticalScrolledFrame(Frame):
    """A pure Tkinter scrollable frame that actually works!

    * Use the 'interior' attribute to place widgets inside the scrollable frame
    * Construct and pack/place/grid normally
    * This frame only allows vertical scrolling

    Assuming this is Public domain, but it's from here: http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame

    """
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)

        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = Scrollbar(self, orient=VERTICAL)
        vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
        canvas = Canvas(self, bd=0, highlightthickness=0,
                        yscrollcommand=vscrollbar.set)
        canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
        vscrollbar.config(command=canvas.yview)

        # reset the view
        canvas.xview_moveto(0)
        canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it
        self.interior = interior = Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior,
                                           anchor=NW)

        # track changes to the canvas and frame width and sync them,
        # also updating the scrollbar
        def _configure_interior(event):
            # update the scrollbars to match the size of the inner frame
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion="0 0 %s %s" % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the canvas's width to fit the inner frame
                canvas.config(width=interior.winfo_reqwidth())
        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the inner frame's width to fill the canvas
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
        canvas.bind('<Configure>', _configure_canvas)

        return

Any clues?
(I know it's ugly code, but it's just a proof of concept)
Comment: I noticed the scrollbar itself scrolls, but the buttons do not, maybe you are not adding the buttons where you think you are?
Answer: The problem is the first line in populateinterior:
def populateinterior(self):
    self.grid()
    ...

self in this context is the interior widget to the scrolled frame. You are calling grid on it, which you shouldn't be doing. The interior frame must not be packed, placed or gridded inside the canvas. Instead, it has to be a canvas object that is created with the canvas method create_window (which is handled by the VerticalScrolledFrame class). When you call grid on the interior frame, you are breaking the bond between the canvas and the frame.
Comment: Well look at that. Thanks :)

Tkinter dynamic "iframe" won't scroll


How to interact with elements of the tab opened with GM_openInTab

Question: I am opening a new tab using GM_openInTab inside my tampermonkey script, but I am not able to interact with the elements of this new tab using my code.
I simply want to click a button in the newly opened tab as soon as it opens and close it instantly.
Thanks in advance!
Answer: You have to run your script on the URL of the new tab you are opening as well (add an additional @include on top), you could make a distinction at the beginning of the script, like this:
if (location.href == oldurl){
  //open new tab
} else if (location.href == newurl){
  //click button, close
}


How to replace the value of the text element in svg from jquery

Question: I am creating an svg tool for the constructing a building , i had created a room ( with the  rect tool ) and grouped it and now want to place the name for that room eg : "Office" for the first time the text placed inside the rect , but for the next time i have to replace the name already exit inside the text element .
Below is my code
    var svgns = 'http://www.w3.org/2000/svg';
    var ex_x=70;
    var ex_y=30;

    var hidden = parseInt($("#svg_group_osiz_1").val());
    var gethide_curtselid=$("#hide_curtselid").val();
    var gethide_curtselid12=$("#hide_curtdrawx_id").val();
    var gethide_curtselid13=$("#hide_curtdrawy_id").val();

    var x=parseInt(gethide_curtselid12) + parseInt(ex_x);
    var y=parseInt(gethide_curtselid13) + parseInt(ex_y);

    var text = document.createElementNS(svgns, 'text');

    text.setAttributeNS(null, 'x', x);
    text.setAttributeNS(null, 'y', y);
    text.setAttributeNS(null, 'fill', '#343938');
    text.setAttributeNS(null, 'text-anchor', 'middle');
    text.textContent =room_name;

    var html =$( "#"+gethide_curtselid ).html();

    if(html.contains("</text>"))
    {
        var start_string=html.indexOf("<text");
        var end_string  =   html.indexOf("</text>");
        end_string      =   end_string+7;
        remove_string   =   html.substring(start_string,end_string);
        var content_replaced = html.replace(remove_string,"");

        $( "#"+gethide_curtselid ).html(content_replaced);
        var replaced_html =$( "#"+gethide_curtselid ).html();

    }

    $( "#"+gethide_curtselid ).append(text);

Here i had find whether the text is already present in the group and replace it as empty and again append the text, But it do-sent work. Can any one guide
Comment: `But it do-sent work` - _but it doesn't work_? (I'd type `I` in all capitals, just as `SVG`.)
Answer: Try setting an id for the textNode
var text = document.createElementNS(svgns, 'text');
text.setAttributeNS(null, 'x', x);
text.setAttributeNS(null, 'y', y);
text.setAttributeNS(null, 'fill', '#343938');
text.setAttributeNS(null, 'text-anchor', 'middle');
text.setAttributeNS(null, 'id', 'roomName');
text.textContent =room_name;

Then you can manipulate it using js like
document.getElementById('roomName').textContent = "new text";

Answer: I am suspecting that you are having a problem with Internet Explorer.  This is because the JQuery html() method returns "undefined" when applied to <text> elements inside of an <svg> container.  JQuery html() will work in Chrome but not in Internet Explorer.  Use JQuery text() method instead, it does not return the whole inner HTML of the element, just the text but that should not be an issue for text in an SVG.
<svg width="200px" height="200px">
<text x="50%" y="50%" fill="#AAA">Some text</text>
</svg>

Chrome:
> $("svg text").html()
"Some text"

IE11:
$("svg text").html()
undefined

This works on both Chrome and IE:
> $("svg text").text()
"Some text"

Answer: You already use jQuery, take more advantage of it.
var ex_x=70;
var ex_y=30;

var hidden = parseInt($("#svg_group_osiz_1").val());
var gethide_curtselid=$("#hide_curtselid").val();
var gethide_curtselid12=$("#hide_curtdrawx_id").val();
var gethide_curtselid13=$("#hide_curtdrawy_id").val();

var x=parseInt(gethide_curtselid12) + parseInt(ex_x);
var y=parseInt(gethide_curtselid13) + parseInt(ex_y);

// find existing text element
var $parent = $( "#"+gethide_curtselid );
var $text = $parent.find('text');

// if there is no <text>, create a <text> element with fixed value attributes
// and append it to $parent.
if ($text.length == 0) {
   $text = $('<text fill="#343938" text-anchor="middle" />').appendTo($parent);
}

// set attributes and text content.
$text.text( room_name ).attr( {x: x, y: y} );

Comment: This will not work.  SVG elements have a different namespace from HTML, and you can't use jQuery to create them like that.


If $F\subset\bigcup_{n=1}^\infty U_n$ then $F\subset U_n$?

Question:
Let $U_n$ be open sets in $\Bbb R^d$ such that $U_{n}\subset U_{n+1}$ for $n\geq 1$. If $F\subset\Bbb R^d$ is a closed set such that $F\subset\bigcup_{n=1}^\infty U_n$, then $F\subset U_n$ for some large $n$?

If the ambient space is compact, $\Bbb S^d$ for example, then the statement is clear. But I wonder if this is true for non-compact ambient space.
Comment: $U_n = (-n, n), F = \mathbb{R}$?
Comment: Well, I won't delete the post
Answer: No, take $U_n=B_n(0)$ and $F=\mathbb{R}^d$.
Comment: Thanks. I was too lazy.


Qual é o modo certo de se conectar com o banco de dados MySQLi

Question: tenho uma dúvida que tem me trazido diversas incompatibilidades. Com a evolução do PHP e Mysql, surgiram versões mais recentes, desta forma o Mysqli. Eis ai que reside meu problema, gostaria de saber qual é meio correto de conectar.
Com o Mysql era:
$con = mysql_connect("localhost","root","");

E com o Mysqli ?
$mysqli = new mysqli("localhost","root","","nome-tabela");

ou
$mysqli = mysqli_connect("localhost","root","");

Quando, olho no manual PHP, está uma abordagem mais orientada a objetos, mas nunca tinha visto deste modo.
Comment: Ambas funcionam bem. Vai do seu estilo de uso. Eu particularmente gosto do modelo funcional, mas é apenas uma questão de gosto e contexto, a funcionalidade é idêntica. E o bom é que a mysqli é muito parecida com a mysql, então a migração de uma pra outra é bem simples (até por ser especializada em MySQL, qualquer alternativa é inferior)
Comment: Já considerou usar o PDO? mysql_ são funções depreciadas do PHP.
Answer: Não existe uma maneira certa, tanto o estilo orientado a objetos e o procedural servem para um determinado caso.
Em projetos novos de preferencia ao estilo OO é mais prático por que não é necessario passar a variável de conexão para outros métodos como o query(), fetch_all() etc.
<?php
//Estilo orientado a objetos
$mysqli = new mysqli("localhost", "user","password","database");
$res = $mysqli->query("SELECT * FROM tabela");
$itens = $res->fetch_all(MYSQLI_ASSOC);

No caso de um sistema já escrito a migração das funções mysql_* deve ser troca pelo estilo procedural do mysqli pois acarreta menos impacto na mudança o que muda é ordem dos parâmetros e a obrigatóriedade de passar a conexão nas funções.
<?php
//Estilo procedural
$mysqli = mysqli_connect('localhost', 'usuario', 'senha', 'database');
$res = mysqli_query($mysqli, 'SELECT * FROM tabela');
$itens = mysqli_fetch_all($res, MYSQLI_ASSOC);

Answer: $link = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link));

Eu uso dessa forma.
Answer: Se quiser testar a conexão e exibir uma mensagem com botão Ok
$con = mysqli_connect("localhost", "root", "", "dbname");

if(!$con){
  die("Falha na conexao: " . mysqli_connect_error());
}else{
  echo "
  ";
}

Answer: Usando o mysqli OO em um singleton. Retorna a conexão que só é criada se for utilizada. Evita ficar passando variável por todo o código. Evita muito código.
function db(): mysqli
{
    static $db;
    $db OR $db = new mysqli('localhost', 'usuario', 'senha', 'database');
    return $db;
}

echo db()->query('SELECT 1+1 AS `soma`')->fetch_object()->soma;


Will this inequality stay preserved if I take $\log$ on both sides? EDIT: Also, can someone please try and help me work towards a solution?

Question: I am trying to solved this inequality for $k$.
$x^{2k}<\varepsilon\cdot k^k$
Here $k\in\mathbb{N}$ and $x,\varepsilon$ are fixed such that $x,\varepsilon\in\mathbb{R}$ and $\varepsilon>0$. I was thinking about taking $\log_\varepsilon$ on both sides but I am not sure about whether this will preserve the inequality or not? Moreover, I cannot really think of any other way to isolate $k$ other than to consider logarithms.
EDIT: Can someone suggest a solution?
Also if possible, could someone tell me what are the conditions for when the inequalities are preserved under logarithms and what are the properties that need to be satisfied by the base? EDIT: Got the answer for this! Thank you!
Comment: It's possible to show that if the function you're using is strictly monotonically increasing (which the logarithm is), it will preserve inequalities. If it's strictly monotonically decreasing, it will reverse the inequality. If it's neither, you will destroy the inequality.
Comment: If $\varepsilon>1$, the inequality will be preserved— but if $0<\varepsilon<1$, the inequality will be reversed.
Comment: @AdrianKeister and Mercy King : Thank you for your comments. So does that mean the value of $x$ makes no difference and does not have an impact on how the inequality will be upon taking the logarithm?

EDIT : Also, what about $\varepsilon=1$? Do you just deal with that as a special case?
Comment: Rather than take $\log_{\varepsilon},$ I would just do $\ln$ of both sides.
Comment: @MercyKing: I think the conditions on the variables present would make that an impossibility, right? The LHS is non-negative, and $k^k>0$ for all $k\in\mathbb{N}$, so $\varepsilon<0$ would make the inequality a contradiction.
Comment: @AdrianKeister I tried doing it with $\log_{10}$ but got stuck. If you could show me how to do the algebra maybe? EDIT : I got to the point where I have $k<\frac{\log_{10}\varepsilon}{\log_{10}x^2/k}$
Answer: Suppose $0 < a < c$ and $b = 1$.  The $b^k = 1$ for all $k$ and defining $\log_1$ makes no sense. So you can't use logarithms base $1$.  (Duh....)
If $b > 1$ then for every $x > 0$ there is some $k = \log_b x$ so that $b^k = x$.
Notice that if $0 < x < 1$ then $k =\log_b x < 0$.  If $x = 1$ then $k = \log_b x = 0$.  And if $x > 1$ then $k=\log_b x > 0$.
Now if we are given that $a,c$ are positive then notice:
$a < c \iff 1 < \frac ca \iff \log_b \frac ca > 0 \iff \log_b c - \log_b a > 0 \iff \log_b a < \log_b c$.
So if $b > 1$ then you can "take the logs of both sides" to perserve inequality.
If $0 < b < 1$ then we still have for every $x > 0$ there is some $k = \log_b x$ so that $b^k = x$.
If this is not as intuitively obvious note if $0 < b < 1$ then $M = \frac 1b > 0$ and there is $j = \log_M x$ so that $M^j = x$.  So $(\frac 1b)^{j} = b^{-j} = x$ so $k =  \log_b x = -j = -\log_M x$.  So it is true.
We get "double negatives" but...
If $x > 1$ then $b^k = x> 1\implies k =\log_b x < 0$.  Of $x = 1$ then $b^k = x=1\implies k = \log_b x = 0$ and if $0 < x < 1$ then $0<b^k = x< 1\implies k = \log_b x > 0$.
And again if $a,c$ are positive and $a < c\iff 1 < \frac ca\iff \log_b \frac ca <0 \iff \log_b c - \log_b a <0 \iff \log_b a > \log_b c$.
So....
Upshot.  You can take logs of both sides to preserve inequality if the base is more than $1$.  You can take logs of both sides to reverse inequality if the base is less that $1$.  And if the base is $1$ you can't do anything.
Answer: Because the log function (to a base greater than $1$) is monotonically increasing, you can take the log of both sides.  You still won't get a clean answer for $k$ given $x,\varepsilon$  If we make it an equality to find the minimum $k$ we can look at it as $$\left(\frac {x^2}k\right)^k=\varepsilon$$
If $\varepsilon$ is a small positive number as it usually is, we can see that $k$ must be greater than $x^2$.  If $x^2$ is reasonably large, $k$ will not be much larger because the power will be so high.  If $x=10, \varepsilon=10^{-6}$ we have $k \approx 113$
Comment: Could you use the Lambert $W$ function here? Looks like you might, but I'm not sure $W$ is monotonic; you might lose the inequality.
Comment: From your equation, Mathematica yields $k=-\ln(\varepsilon)/W(-\ln(\varepsilon)/x^2).$
Comment: @AdrianKeister:  Mathematica says so, but I haven't understood the W function to say one way or the other.
Answer: Choosing $k=\max \left( \lceil x^2\rceil+1,\ \lceil\frac{x^2}{\varepsilon}\rceil \right)$ works. Thanks to everyone for their suggestions.
Answer: Since $\ln$ is increasing,  we have
$$
2k\ln(|x|)<k\varepsilon\ln(k)
$$
i.e
$$
\frac{2k\ln(|x|)}{k\varepsilon}=2\varepsilon^{-1}\ln(|x|)<\ln(k)
$$
Hence
$$
k>|x|^{2/\varepsilon}
$$


expanders and random graphs

Question: I have seen in many places the quote: "Random graphs are good expanders".
The only prof I could find to this sentence is regarding b-partite graphs, for example the proof in here
I want to prove that the probability of a random graph being an expander goes to 1 as n (number of vertx) goes to infinity.
Can anyone address me to such a proof?
Answer: Take a look at this survey paper by Hoory, Linial and Wigderson.
Suppose that $G$ is a $d$ regular graph, and let $\lambda_{2}(G)$ be the second largest eigenvalue, so that $\lambda_1(G)=d$.  Then Cheegers inequality for graphs states that $$\frac{d-\lambda_2(G)}{2}\leq h(G)\leq \sqrt{2d(d-\lambda_2(G)},$$ where $h(G)$ is the edge expansion constant.  This means that the smaller $\lambda_2(G)$ is, the better the expander.  Alon and Boppanna proved that for any $d$-regular graph, as the number of vertices $n\rightarrow\infty$, we have that $$\lambda_2(G)\geq 2\sqrt{d-1}\left(1-o(1)\right).$$  That is, $2\sqrt{d-1}$ is a lower bound for the second largest eigenvalue.  Alon also conjectured that the random graph is in some sense the best possible expander, and that for the random graph, with probability going to $1$ as the number of vertices go to infinity, we have that $$\lambda_2(G)\leq 2\sqrt{d-1}+\epsilon.$$  This was proven by Joel Friedman in $2004$, and the $118$ page paper can be found here.
Comment: Thanks for your answer!What about non-regular graphs? can I prove it for such graphs also?

expanders and random graphs


Bijections and disjoint sets by finite summation

Question: Suppose $X$ is finite and $f:X\rightarrow\mathbb{R}$ a function. Let $g:Y\rightarrow X$ be a bijection. Then $$\sum_{x\in X} f(x) =\sum_{y\in Y} f(g(y))$$ That is what I first want to prove. The second statement: If $X$ and $Y$ are finite and disjoint and $f:X\cup Y\rightarrow\Bbb{R}$ a function then:
$$\sum_{z\in X\cup Y} f(z) = \sum_{x\in X} f(x) + \sum_{y\in Y} f(y)$$
These statements are intuitive right, but what must I do to prove this in general and with great accuracy? Can someone help me? Solutions/Hints and remarks are welcome. :)
Comment: Is the second one actually a set question?
Answer: You have to go back to the defintion of the sum and its compact notation $\Sigma$.
On is given here: http://en.wikipedia.org/wiki/Summation#Formal_definition for indices in $\mathbb{N}$. You can extend it to an other finite set (that by definition is in bijection with a segment of $\mathbb{N}$) using your first equality (that now comes trivially from the definition!).
The other one is just a matter of defining mappings between segements of $\mathbb{N}$ and $X$, $Y$, and $X\cup Y$.
Answer: $ \text {First one:  }$
$\text {Because g is a bijection, $\forall$ x $\in X, \exists y \in Y$ s.t. g(y) = x}$
$\text {and $\forall y_1, y_2 \in Y, g(y_1)=g(y_2)\iff y_1=y_2 $}$
$\text {Thus $\sum_{y\in Y}{f(g(y))} = \sum_{x\in X}{f(x)}$}$


Iterate through columns to generate separate plots in python

Question: I would like my code to iterate through columns to make one plot for each column. I have the below code to draw plot for one column, but I do not know how to use this code to loop through other columns and generate plots for all columns. Any idea?
Here's my code:
import seaborn as sns

sns.set()
fig, ax = plt.subplots()
sns.set(style="ticks")
sns.boxplot(x='Location', y='Height [cm]', data=df)
sns.despine(offset=10, trim=True)
fig.set_size_inches(22,14)
plt.savefig('Height.pdf', bbox_inches='tight')

This is what my data looks like:
Location            Height          Length       Width
A                    150             95           18
A                    148             122          25
A                    162             127          16
B                    155             146          32
B                    148             112          21
B                    154             108          30
C                    160             127          22
C                    148             138          36
C                    159             142          28

Answer: Simply putting your code inside a loop and changing the column name and plot name each time should do it (from a quick test it worked for me and I have 3 PDFs saved in my working directory):
import matplotlib.pyplot as plt
import seaborn as sns

for column in df.columns[1:]:  # Loop over all columns except 'Location'
    sns.set()
    fig, ax = plt.subplots()
    sns.set(style="ticks")
    sns.boxplot(x='Location', y=column, data=df)  # column is chosen here
    sns.despine(offset=10, trim=True)
    fig.set_size_inches(22,14)
    plt.savefig('{}.pdf'.format(column), bbox_inches='tight')  # filename chosen here

Answer: To plot only a specific list of columns
Make a list of columns that you want to plot
then iterate over the list
Here I am plotting a regression plot , Length vs Height and Width vs Height,
In a loop  .
import matplotlib.pyplot as plt

import seaborn as sns
lst = [ "Length"  , "Width" ]
for i in lst:
    sns.lmplot(x = 'Height', y = i , data = df ) # df is your dataframe


Karabiner-Elements Ctrl + Left Click to Left Click doesn't work

Question: Using Mac OS Catalina and on Mac OS a Ctrl + Left click = Right click. This is very annoying however I found a post that showed how Karabiner-Elements could fix this. I imported the rule and it is enabled, however it still doesn't work and Ctrl + left Click still = Right Click. Any help to get this working would be appreciated.
Update: opened event viewer and found that left clicks and right click don't show up, is this supposed to happen or do I need to enable Karabiner reading mouse in settings somehow?
Comment: got it fixed, because i'm using a usb mouse it didn't automatically enable as a device so i just had to enable it and it worked
Comment: Install older version
Comment: but Karabiner-Elements 13.1.0 is for Catalina 10.15.6 or later and I'm on Catalina 10.15.6
Comment: I have BigSur and Catalina before and version 13 is not working on my machine
Comment: so would downloading an old version even work? is it worth giving it a try?
Comment: Yeah in my case that was helping
Comment: ok, Ill give it a try
Comment: can you import the Ctrl + Left click to Left click please and tell me if it works for you
Comment: The older versions do not work, just tried
Comment: I can see there's something called Mouse keys in keys panel, have you tried it ? On my machine it's empty
Answer: I think using an older version of Karabiner-Elements is a bad ideal. If you're using a mouse, then you need to turn on the corresponding device to make it continue to work. Karabiner-Elements Preferences -> Devices -> Basic configuration and enable the mouse, which is useful for me when use IDEA for source code tracking


Incremental loads in Sqoop

Question: I have a table in Teradata which is loaded with new data on daily basis.
I need to import this data to Hive. I'm trying to use Sqoop but how should I do incremental load using Sqoop?
I checked incremental load options available in Sqoop
--check-col

This options expects only numeric and unique data whereas my Teradata table is not having such column
I'm using date  column inn --spli-by
How can I do incremental imports to Hive in this case?
Please suggest
Answer: If you use --incremental lastmodified mode then your --check-column is a timestamp that does not need to be numeric or unique.
See: Sqoop incremental imports.
Comment: Hey Thanks...I want to load daily data that is coming into my TD table using sqoop , data is not getting updated..it is just appending a newly data to Hive table , will --incremental lastmodified work in this case?
Comment: Yes, in many cases you can merge incremental loads using `sqoop merge`: see https://sqoop.apache.org/docs/1.4.1-incubating/SqoopUserGuide.html#_literal_sqoop_merge_literal.
Comment: hi thanks for your reply..--incremental appen is working for me
Comment: How can i reset value of --last-value in case of corrupt data coming into hive and need to be deleted then reload
Comment: I'm glad it worked. Please accept the answer if it worked for you.
Comment: I have another problem if you can suggest something..if --last-value is 23rd then it will load data for 24 .but if I'm running on 23rd morning then 24th morning will it load data of 23rd evening? If not what will be solution?
Answer: use one more "--append " command after the check column so that , the new data will not be replaced and you can see it saves in a new file in hdfs without replacing the old file.

Incremental loads in Sqoop


Resize view while ActionBar slide up animation is running

Question: I have an ImageView inside an activity and when the user clicks on it, I animate the view height so it becomes fullscreen (other views are just become hidden below the bottom of the screen).
However once the animation is finished I hide the actionbar (using getSupportActionBar().hide()) so I then need to resize my ImageView just a little bigger again to take the full screen again.
In the parent View I tried overriding both onMeasure and onLayout to get the size available while the actionbar slides off the screen, but it does not work, I only get the new size at the end of the actionbar animation + when I set the height of the view and request layout it does not layout again (so I can still see the other views at the bottom of the screen).
Answer: Make the ActionBar an overlay by calling requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY) before calling setContentView() in your activity. Then when you run your animation, the full-screen size of the ImageView will go behind the ActionBar.
You might have to mess with the timing of when to hide the ActionBar if you don't want the ImageView to be seen behind it at all before you hide, but that can be done relatively easily with a Thread or AsyncTask.
Comment: Thank you for your answer. The problem is I don't want the ActionBar to be in overlay mode.
Comment: Or is it possible to make the ActionBar switch from non-overlay to overlay mode programatically while the activity is already launched?
Comment: Not that I know of. You have to set the feature before calling `setContentView`.


Generate numbers that increase at decreasing level

Question: Currently I need to generate 100 increasing numbers between 10 and 280. The increase should be at decreasing level. Here is an example of some numbers that could be in the series:

10, 20, 29, ... , 277.8, 279, 280

I really have no idea how to do this, the numbers don't really matter, the important thing is that the first value is 10 and the last value is 280. The other 98 numbers should increase at a decreasing level.
Comment: What have you tried? What is the problem?
Comment: Find a mathematical function first I would say that given x=1 results in 10, and x=100 results in 280.  Then implement that in code.  Ask here again if you need help with your code.
Comment: My problem is to find such a mathematical function, to implement it is no problem, but I can't think of a suitable function.
Answer: A very simple example would be the following:
public class Main {

    public static void main(String[] args) {
        double start = 10;
        double end = 280;
        int numberOfNumbers = 100;

        double[] list = new double[numberOfNumbers];
        list[numberOfNumbers - 1] = end;

        for (int i = 2; i < numberOfNumbers; ++i) {
            list[numberOfNumbers - i] = list[numberOfNumbers - (i - 1)] - (1.0/(numberOfNumbers - i));
        }

        list[0] = start;

        System.out.println(Arrays.toString(list));
    }
}

Output would be something like
10, 274.83272349246164, 275.83272349246164, ..., 279.97948664001683, 279.98979591836735, 280
If you have numbers not that far apart, you need to choose a function that converges faster to 0 than 1/n like 1/(n^2) or 1/(2*n)
Answer: maybe something like this:
    double[] result = new double[100];
    result[0] = start;
    result[99] = 280;

    for (int i = 1; i < 99; i++) {
        result[i] = result[i - 1] + (280 - result[i - 1]) / 21.0;
    }

result:
[10.0, 22.857142857142858, 35.102040816326536, 46.76384839650146, 57.870331806191864, 68.44793505351606, 78.52184290811053, 88.11604086486717, 97.25337225225445, 105.95559262119471, 114.24342154399497, 122.13659194666188, 129.65389709205894, 136.81323532577042, 143.63165269120992, 150.12538351543802, 156.30988906232193, 162.19989434506851, 167.80942318577954, 173.15183160550433, 178.23983962428983, 183.0855615469427, 187.7005348066121, 192.09574743486866, 196.28166422368443, 200.26825164160422, 204.0650015634326, 207.6809538699358, 211.12471797136743, 214.4044933060642, 217.5280888629183, 220.50294177420793, 223.33613502305516, 226.0344143076716, 228.60420410254437, 231.05162295480417, 233.38249805219445, 235.60237909732805, 237.71655152126482, 239.73004906787125, 241.647665778925, 243.4739674085, 245.2133022938095, 246.86981170839002, 248.44743972227621, 249.94994259264402, 251.38089770728, 252.74371210217143, 254.0416305734966, 255.2777434033301, 256.4549937174572, 257.5761844928164, 258.64398523125374, 259.66093831547977, 260.6294650623617, 261.5518714879635, 262.4303537980605, 263.26700361720043, 264.0638129687623, 264.82267901786884, 265.5454085884465, 266.23372246518716, 266.8892594906544, 267.5135804672899, 268.1081718736094, 268.67444940343756, 269.2137613366072, 269.7273917491497, 270.2165635706188, 270.68244149582745, 271.1261347579309, 271.54869976945804, 271.9511426375791, 272.33442155959915, 272.69944910438016, 273.04709438512396, 273.3781851286895, 273.69350964637096, 273.9938187108295, 274.2798273436471, 274.5522165177592, 274.81163477881825, 275.0586997893507, 275.29399979938165, 275.51809504703016, 275.73151909240966, 275.9347800880092, 276.1283619885802, 276.3127257034097, 276.4883101937235, 276.65553351783194, 276.8147938265066, 276.9664703109587, 277.11092410567494, 277.2484991482618, 277.3795229983446, 277.50430761747106, 277.6231501118772, 277.736333439883, 280.0]
Comment: But then the end is not with decreasing increment `result[99] - result[98] > result[98] - result[97]`
Comment: As I wrote: 2 bay be to small. Using 43 gives distinct numbers. and changing the array type to a floating point type make it smoother.


Find the equation for the isoline given

Question: I don't really understand the question, it's probably really simple but I don't really get it right know

A linear function   of two variables has the equation
  $f(x,y)=10x+20y$
  a)    Find the equation for the isoline given by
  $f(x,y)=80$
Answer: Just draw
$$
f(x,y) = 80 \iff \\
10 x + 20 y = 80 \iff \\
y = - \frac{1}{2} x + 4
$$
That line goes through $(0,4)$ and $(8,0)$.
Comment: Ahhhhhh get it now! Thanks a lot!!!!

Find the equation for the isoline given


Is an E augmented triad the same as a C inverted augmented triad?

Question: I know that a C augmented triad is C, E, G♯ and an E augmented triad is E, G♯, B♯. However, I think we can replace the B♯ in the E augmented triad by its enharmonic equivalent, a C. Is it appropriate to treat a C inverted augmented triad (i.e. E, G♯, C) as an E augmented triad in a song, or should B♯ be used instead of C?
Specifically, if the we start with an E major triad and then augment the B, should we get a B♯?
Comment: (For an analogy: Yes, the two triads "sound the same." So do the words "horse" and "hoarse." But it isn't okay to just write "I have a horse throat," unless you actually mean that you have in your possession a trachea from a horse. You choose a spelling based on contextual function and intent.)
Comment: This is basically a question about why we choose one enharmonic spelling over another, based on context. The short answer is "you choose the right one," but I suspect you have some misunderstanding about that. It might help if you edit to tell more about why you currently think you would choose one or the other. (Basically, it should *not* depend on which note is "on the bottom," but on the overall context—the other chords around it and where everything is going.)
Comment: Thanks for the edit. Yes: assuming that EM was the right triad in the first place, then if the melody raises the B, then B# is the right spelling because this is still "an E chord that had something done to it."
Comment: There's just one more answer that you haven't yet chosen as your favourite..!
Comment: And that answer isn't nearly good enough compared to yours and John's.
Answer: The answer to your final question is yes. Correct enharmonic spellings aside, an augmented triad that is inverted (not "transposed" like you said) twice produces two other augmented triads. The means E+ G#+ and C+ are all augmented triads that use the same notes. When you throw correct enharmonic spelling into the mix, an augmented triad should have a 1,3 and +5. That means using every other letter for the chord tones. That gives you:
E+ = E G# B#
Ab+ = Ab C E (more practical than G#+ but G# can be used)
C+ = C E G#
When thinking of an augmented triad think of a major triad and raise the 5th a half step but keep the same letter. Flat becomes natural, natural becomes sharp, sharp becomes double sharp.
Comment: @mathlander Let's hope it doesn't come to that!
Comment: Ah, I forgot about Ab+..!
Comment: And double sharp becomes triple sharp.
Comment: And double flat becomes flat.
Answer: The inversions of an augmented triad are symmetrical, meaning the relative intervals of each inversion are the same, at least enharmonically.
C E G# is two major thirds stacked.
But, technically, E G# C is not two stacked major thirds. It is a major third and a diminished fourth, which enharmonically is the same as a major third.
E G# C is not an E augmented triad, E G# B# is an E augmented triad.
When you get into chord spellings and enharmonic equivalence, you should not just say it's all the same. The more obvious case is the German augmented sixth chord being enharmonically the same as a root position dominant seventh chord, but functionally the chord or very different. The former is a pre-dominant chord, while the later is a dominant chord.
We can make the same observation about augmented triads. Look at the harmonic context. If, for example, you were in the key of F major, and the chord was C E G#moving to an F major triad, you would call the first chord a C augmented triad, rooted on the dominant, a chord acting as a dominant. You don't then willy-nilly, say that chord is the same as an E augmented triad or G# augmented triad.

Specifically, if the we start with an E major triad and then augment the B, should we get a B♯?

Yes. An augmented triad has an augmented fifth above the root.
If you are thinking B# is enharmonically C, and then respell the chord to E G# C, and then call it an E augmented triad, instead of a C augmented triad, you're just misspelling chords.
It isn't really clear what the "problem" is. Is it a notation issue, an analysis issue? Part of the problem is asking about "sameness." That isn't a musical term. Enharmonic equivalency is the musical term. If the question is just general, I would say: spell chords correctly, and enharmonic equivalents are not necessarily the same in the sense of harmonic function.
Answer: Very similar to the diminished triads that use the same notes, but often with different names.
The augmented triad uses a root, major third and augmented fifth. Hence C aug = C E G♯, while E aug uses E G♯ B♯. C and B♯ being *enharmonic. But let's not forget the third use of those very same notes - G♯ aug - G♯ B♯ Dx. In fact each augmented triad has three incarnations.
So, why call the same pile of notes 3 different names? It will basically depend on its situation in the scheme of things. In key C, playing C>C+>F, it has to be C augmented, whereas in key E, playing E>E+>A it makes more sense to call it E+.
Not necessarily those triads in those keys, but that's where they are found most. And, as such, their roots will reflect their names, and just like root position of any triad sounds strongest, it's the same with augmenteds.
Augmented chords, in my experience, are used in the way described above far more than any other, so for that reason, this is my explanation.
Comment: You've had 3 answers within a couple of minutes! Please wait until other parts of the world wake up and offer their answers before choosing what you like best!!
Answer: Yes, an augmented triad is symmetrical, a pile of major 3rd intervals that add up to an octave. (In the same way that a dim7 is a symmetrical pile of minor 3rds.)
There's no transposing involved in your question.   Maybe a choice of enharmonic spellings.  E+ is properly spelled E, G♯, B♯.  In some circumstances it may be acceptable to spell it E, G♯, C, or even E, A♭, C.  It may also be debatable whether it's harmonic function is C+, G♯+ or C+.  Symmetrical chords are often used specifically BECAUSE of their ambiguity.
Answer: A B♯ is only inequivalent to a C in theoretical contexts of analysis. For instance, in the context of C♯ minor, you probably want to think of the "C" note of the harmonic minor scale as a "B♯" because it fits better within the theory of scales and triads. Disregarding any of the contexts of harmonic analysis, C+, E+, and G♯+ (A♭+) augmented triads are all the same chord, just inversions of each other.
Interesting note: The augmented triad divides an octave into three even parts. Therefore there are 12 / 3 = 4 unique augmented triads. A fully diminished 7th chord divides an octave into four even parts. There are 12 / 4 = 3 unique fully diminished 7th chords.
Answer: Each augmented triad has three enharmonically equivalent versions. Taking the case of C augmented, one has

C - E - G#
E - G# - B#
G# - B# - Dx

The importance of how the chord is spelled relates to the context in which it's used. For example, a common chord progression is I - I+ - vi, which in the key of E would be E - Eaug - C#m. By spelling the E augmented chord E - G# - B#, the performer is cued into the larger harmonic context. Spelling the augmented chord E - G# - C, would suggest, perhaps, a key change.
In harmonically ambiguous contexts, or sometimes just for readability, an augmented chord will be intentionally "misspelled", but these are special cases.
Comment: @phoog There's no reason to complicate the issue by introducing flats. It adds nothing to the answer the OP is looking for.
Comment: There are more than three ways to spell the example triad.


Partial differential equation in terms of hyperbolic functions.

Question: I am not sure of how to go about obtain the $g\left(y\right)$ in terms of a hyperbolic function. The partial differential equation I am dealing with is
Find an infinite series representation for the solution to the equilibrium problem:
$$u_{xx}+u_{yy}=0:0<x<a, 0<y<b$$
$$u_{x}\left(0,y\right)=u_{x}=0:0<y<b$$
$$u\left(x,0\right)=f\left(x\right), u\left(x,b\right)=0:0<x<a$$
I have to solve this using separation of variables, and I have to find the solution of $y$ in terms of a hyperbolic function. What I've gotten for my separation of variables is (the book I go by makes the right side as $-\lambda$ instead of just $\lambda$, so I have followed it for consistency):
$$\frac{p^{\prime\prime}\left(x\right)}{p\left(x\right)}=\frac{-g^{\prime\prime}\left(y\right)}{g\left(y\right)}=-\lambda$$
For $\lambda>0$, I've gotten that $\lambda_{n}=\frac{n^2\pi^2}{a^2}$, $p_{n}\left(x\right)=\cos\left(\frac{n\pi x}{a}\right)$. For $g\left(y\right)$,
$$g\left(y\right)=c_{1}e^{\frac{-n\pi y}{a}}+c_{2}e^{\frac{n\pi y}{a}}$$
How do I go about converting $g\left(y\right)$ into terms of a hyperbolic function? My textbook says that $$g_{n}\left(y\right)=c_{n}\sinh\left(\frac{n\pi y}{a}\right)+d_{n}\cosh\left(\frac{n\pi y}{a}\right)$$ but I am not sure how they got to this.
Answer: Hint: $e^x = \cosh x + \sinh x$, $e^{-x} = \cosh x - \sinh x$.


How does Bach harmonise chromatics?

Question:
The top line is soprano and the bottom line is bass. Is there supposed to be some sort of harmonic function used by Bach by the use of C#?
The key signature is Bb Major, though this passage could also either be F Major or G Minor.
Comment: With "used by Bach" do you mean "according to the rules for four-part harmony". Also: it would help if we'd know in what key this fragment is written?
Comment: We do not have all the context, but it could be a [secondary dominant](https://en.wikipedia.org/wiki/Secondary_chord#Dominant): A7/C# resolving to D or Dmin.
Comment: The C♯ is implying probably A7 or C♯ diminished inbetween the first bar's C major or a minor and the second's predominant function chord. What do you mean "Is there supposed to be some sort of function used by Bach"? Do you mean "what is the function of the chromatic note C♯ here"?
Answer: This isn't really a matter of Bach 'harmonising a chromatic'.  The melody doubtless came first.  He's harmonising it WITH a chromatic.
A sharpened chromatic note will generally have the function of a leading note, the third of a dominant type chord.  In this case the C# seems to be the third of A7, the dominant of D minor (assuming no key signature).
Maybe the music continues in D minor for a bit, in which case we could call a modulation.  I suspect however that it's a very fleeting tonicisation of D, not worthy of that label.  The chromatic note is just being chromatic.  Adding colour between a pair of diatonic chords rather than leading us somewhere new.
Answer: In this instance, it being Bach and the C# is in the bass, I would guess that this chord would be a first-inversion A7 leading into a D major or minor chord. I doubt that it is a C# dim because in Bach-style chorale writing that chord would normally be in 1st inversion to avoid undesirable parallel movement. If the chord is a fully-diminished 7th, the inversion doesn't matter but that chord really came into use later than Bach.
In any voicing, the leading tone is normally followed by the tonic by half-step. In a secondary dominance like this one, the C# is acting like a leading tone into the D, so these chromatic movements are usually by half-step. Bach could have chosen a different voicing, but no matter what voice in which the C# was placed, it would be followed by D since it is "tonicizing" that chord. In this instance, the chromatic movement makes for quite a nice bass line.

How does Bach harmonise chromatics?


Hard drive throttling?

Question: You're copying a lot of stuff in same time and computer performance just dies. Try for example to copy 10+ ISO images same time.
There's QoS in networking, affinities and priorities in CPUs, but is there anything for hard drives to throttle I/O queues? Virtual filesystems? OS drivers?
Of course you can go around with this with for example

Making list of files to copy and running script which copies files one by one
Using software like TeraCopy

Windows and GNU/Linux solutions are welcome.
Answer: For Linux there's ionice, Windows has IO priorities since quite some time, but at least since Vista it's also fully available in a sane implementation for Workstations.
Answer: At a lower level, Linux (and I assume Windows, and *BSD, and everything else in serious use) has an IO scheduler that tries to balance the best overall utilization of each device with providing good service to each process. Linux's current default scheduler is known as Completely Fair Queueing, with the current generally available alternatives being called Anticipatory and Deadline.
On a somewhat related note, the program iotop is useful for monitoring and examining what's going on in a system under heavy IO load.
Answer: ionice only works with the CFQ scheduler, which is usually the default. If you are using another scheduler or if ionice isn't doing the job for you, you might want to periodically pause execution to let your io buffers flush. Here is a script we use for that:
<code>#!/bin/sh

# Throttles the execution of a process by stoping it after every second of
# execution time
#
# Usage: io_nice <sleeptime> <pid>
# Where "sleeptime" is the number of seconds of sleep for each second of runtime
#       and "pid" is the process ID of the process to throttle

PID=$2
SLEEPTIME=$1

while [ true ]; do
    kill -s STOP $PID &> /dev/null|| exit 0
    sleep $SLEEPTIME
    kill -s CONT $PID &> /dev/null || exit 0
    sleep 1
done
</code>
Answer: Interestingly, there's been recent talk about implementing QoS for block devices on LKML.
There's a nice write up on the ever excellent LWN.net: Block device bio throttling support [V3]
Answer: on Linux ionice let's you prioritize IO, but falls somewhat short.  there's dm-ioband which should be a lot more powerful; but i still don't feel comfortable with the docs....

Hard drive throttling?


Consulta MySql com PHP

Question: Estou fazendo uma consulta no MySql para retornar a quantidade de pedidos que não foram entregues.
Para ver os que foram entregues eu faço:
$result = mysql_query("SELECT operacional FROM `pedidos` WHERE `status` = 'ENTREGA REALIZADA'");

Entretanto, existem alguns pedidos que o status é: ENTREGA REALIZADA EM 20/10/2017 ou até mesmo ENTREGA REALIZADA EM 20/11/2017 - ou seja, as datas variam.
E além disso, eu preciso pegar os que não foram entregues. Como posso fazer pra receber apenas os itens que não tem esse texto de "ENTREGA REALIZADA"? Pois este espaço nunca fica em branco, sempre haverá algo como SAÍDA PRA LISTA ou ENTRADA NA UNIDADE, entre outros...
Existe algo como:
$result = mysql_query("SELECT operacional FROM `pedidos` WHERE `status` != 'ENTREGA REALIZADA'");

Comment: SQL ainda está na minha lista para estudos aprofundados, mas fazer algo como `status not like "ENTREGA REALIZADA%`  funcionaria?
Comment: O problema do código original na verdade é que uma violação ao [1NF](https://en.wikipedia.org/wiki/First_normal_form). Você está usando dois dados distintos em uma mesma coluna. A melhor opção seria ter `status` e `data`, dessa forma não teria problema, cada serve para uma coisa e apenas salva uma informação. Como também dito pelo @Alisson Acioli você pode usar campos numéricos (TINYINT) para diminuir o espaço utilizado e tornar o indexes mais eficientes, uma outra opção (talvez não a melhor) é usar o [ENUM](https://dev.mysql.com/doc/refman/5.7/en/enum.html).
Comment: Lembrando que as funções mysql_* estão obsoletas e foram removidas no php 7. Recomenda-se usar mysqli_* ou PDO
Comment: Pessoal, fiz da seguinte forma: criei uma nova coluna no DB, "ativo" sendo ela do tipo INT, se for 0 o php lê e faz a atualização, se for 1 ele pula... funcionou!
Comment: Pedro, sinta-se a vontade em elaborar uma resposta e postá-la aqui como solução. Não é má conduta fazer isso, na verdade, até é bem apoiado desde que bem feito. Leia mais em [Responder sua própria pergunta](https://pt.meta.stackoverflow.com/questions/422/responder-sua-pr%C3%B3pria-pergunta).
Comment: Muito obrigado pessoal, vocês me ajudaram bastante, o fato de precisar fazer toda essa complicação é porque as informações vem pro meu banco através de um webservice, só após isso eu consigo manipular... Todos me ajudaram bastante! Forte abraço!
Answer: Amigo uma dica que dou a você é nunca usar texto em campos do tipo status. Ao invés disso, você poderia resolver isso de maneira fácil usando o campo status como INT. Fazendo algo assim:
0 = Não Realizado
1 = Entrega Realizada
2 = Saída para Lista
3 = Entrada na únidade

E na questão da entrega realizada ter data, você poderia criar mais um campo na tabela chamado (por exemplo) de data_status e sempre que o status for 1 você atualiza essa coluna e coloca a data.
Caso queira poderia também criar uma tabela separada só com status para consulta, algo com a estrutura assim:
id
id_status
nome_status

Assim você poderá evitar problemas futuros.
Com o seu caso acima
Poderia testar os seguintes comando e ver qual se encaixa melhor:
$result = mysql_query("SELECT operacional FROM `pedidos` WHERE `status` LIKE '%ENTREGA REALIZADA'");

$result = mysql_query("SELECT operacional FROM `pedidos` WHERE `status` LIKE '%ENTREGA REALIZADA%'"); //Talvez dê problemas no futuro caso tenha frases muito parecida no campo status

$result = mysql_query("SELECT operacional FROM `pedidos` WHERE `status` LIKE 'ENTREGA REALIZADA%'");

Mas faça como falei no começo do post, é melhor, você evitará problemas e dores de cabeças futuros.
Lembrando como o Anderson Carlos Woss citou, use a função mysqli_ pois todas mysql_ estão obsoletas nas novas versões do PHP.
Comment: Como [comentado](https://pt.stackoverflow.com/questions/202595/consulta-mysql-com-php#comment415152_202595), talvez seja interessante adaptar a solução para `mysqli_*` ou pelo menos colocar o aviso que as funções `mysql_*` estão obsoletas.
Answer: Obrigado à todos! Confesso que solucionaram meu problema e aprendi uma função que ainda não conhecia.
Para este problema eu resolvi criar uma tabela "Ativo" para saber se o pedido entra ou não na operação (que é receber a atualização de dados):

Se for 0 ele recebe a atualização quando a rotina acontecer, se for 1 ele pula este pedido.
Caso o pedido que recebeu as informações tenha como Status -> ENTREGA REALIZADA o ativo muda para 1:

Acho que assim fica mais seguro!
Forte abraço e obrigado pelas informações, foram de grande importância!

Consulta MySql com PHP


How to remove last result from a foreach() result

Question: I have some PHP code that grabs data from JSON. The code retruns all the usernames, including the current username to display. My question is, how would I only allow it so that it only shows the recent usernames and not the current?
I am using the Minecraft API for this and the JSON code I am getting can be found here.

Note that _scrunch is the current username.

Here's my code that displays the names:
// Save the uuid
$uuid = $json->id;

// Get the history (using $json->uuid)
$content = file_get_contents('https://api.mojang.com/user/profiles/' . urlencode($uuid) . '/names');

// Decode it
$json = json_decode($content);

$names = array(); // Create a new array

foreach ($json as $name) {
    $input = $name->name;

    if (!empty($name->changedToAt)) {
        // Convert to YYYY-MM-DD HH:MM:SS format
        //do

       // $input .= ' (changed at ' . $time . ')';
    }

    $names[] = $input; // Add each "name" value to our array "names"

}

and to display it
<?php echo implode(', ', $names) ;?>

Any help would be great! Thanks!
Comment: You can use [`array_pop()`](http://php.net/array_pop) before the foreach loop, to remove the last name.
Comment: You can remove last element after your foreloop ends
Comment: Is current user always last or is it the one with changedToAt?
Answer: If you're looking to remove the last element of the array, array_pop() should do the trick. Then your foreach loop will look over all the elements except the last one.
$array = [1, 2, 3]; // sample array
$last = array_pop($array); // remove last element of array and store it into a variable => $array = [1, 2]
// do stuff
foreach($array as $element) {
  ...
}
array_push($array, $last); // push the element to the back of the array => $array = [1, 2, 3]

Comment: Ah I see, I never knew about `array_pop`! The other answer helped me greatly because I knew what he meant and how to incorporate it, I am fairly knew to PHP! Thanks for the answer, I'm sure many will find it helpful! :)
Comment: Some other very useful functions when working with ordered arrays are array_shift() and array_unshift(). They do the opposite of push and pop, the remove and add to the beginning of array.
Answer: In your loop, just check and exclude if it's the user's name:
foreach ($json as $name) {
    $input = $name->name;
    if ($input != _scrunch) {

        if (!empty($name->changedToAt)) {
            // Convert to YYYY-MM-DD HH:MM:SS format
            //do

           // $input .= ' (changed at ' . $time . ')';
        }

        $names[] = $input; // Add each "name" value to our array "names"

    }
}

Comment: Ah yes! This seemed to work, easy and simple. Thanks for the answer!
Answer: Simply count the amount of data returned in the array through the count function, and then rank each item within the foreach loop by doing $foo ++;
// Save the uuid
$uuid = $json->id;

// Get the history (using $json->uuid)
$content = file_get_contents('https://api.mojang.com/user/profiles/' . urlencode($uuid) . '/names');

// Decode it
$json = json_decode($content);
$total = count($json); // This counts the amount of items returned
$rank = 0; // Declaring the rank for future use in the foreach loop
$names = array(); // Create a new array

foreach ($json as $name) {
    $rank ++;
    $input = $name->name;
    if ($rank == $total){
    // Do something if this is the last row

    }
    if (!empty($name->changedToAt)) {
        // Convert to YYYY-MM-DD HH:MM:SS format
        //do

       // $input .= ' (changed at ' . $time . ')';
    }

    $names[] = $input; // Add each "name" value to our array "names"

}


EntityQuery PHP issue when assigning the query to a variable

Question: I am very confused about this behavior of EntityQuery, or maybe I am just missing something basic about PHP.
Here is the query I am working with:
$entity_query_points1 = \Drupal::entityQuery($entity_type_id)
  ->condition($entity_type->getKey('bundle'), $entity_type_bundle)
  ->condition($entity_type->getKey('uid'), $uid)
  ->condition('field_int_points', 1, '=');
return $entity_query_points1;

This is fine.
But if this query returns no results, I wanted to immediately execute another query.  So I made a switch statement and wrote code like this:
$entity_query_points1 = \Drupal::entityQuery($entity_type_id)
  ->condition($entity_type->getKey('bundle'), $entity_type_bundle)
  ->condition($entity_type->getKey('uid'), $uid)
  ->condition('field_int_points', 1, '=');
$entity_query = $entity_query_points1;
$count = $entity_query->count()->execute();
if ($count >= 1) {
  return $entity_query_points1;
}

This fails with a WSOD (I am using this code with the JSON:API Resources module):
TypeError: Argument 2 passed to Drupal\jsonapi_resources\Resource\EntityQueryResourceBase::loadResourceObjectsByEntityIds() must be of the type array, string given, called in /app/web/modules/contrib/jsonapi_resources/src/Resource/EntityQueryResourceBase.php on line 97 in Drupal\jsonapi_resources\Resource\EntityQueryResourceBase->loadResourceObjectsByEntityIds() (line 125 of modules/contrib/jsonapi_resources/src/Resource/EntityQueryResourceBase.php).

If I use the following code, it works (query resolved correctly, no WSOD):
$entity_query_points1 = \Drupal::entityQuery($entity_type_id)
  ->condition($entity_type->getKey('bundle'), $entity_type_bundle)
  ->condition($entity_type->getKey('uid'), $uid)
  ->condition('field_int_points', 1, '=');
$entity_query = $entity_query_points1;
$count = $entity_query->count()->execute();
if ($count >= 1) {
  $entity_query_score1 = \Drupal::entityQuery($entity_type_id)
    ->condition($entity_type->getKey('bundle'), $entity_type_bundle)
    ->condition($entity_type->getKey('uid'), $uid)
    ->condition('field_int_points', 1, '=');
  return $entity_query_points1;
}

But... why?  I executed the count on $entity_query, but I have to redefine $entity_query_score1 to return the query as expected.  I know having to redefine the query means I have screwed up somehow, but I don't know what my mistake is.
Comment: Curious to see what happens if you use `$entity_query = clone $entity_query_points1;` because objects might behave different I think
Comment: @baikho Adding `clone` works; then I no longer need to redefine the query.
Answer: Objects work differently than regular variables in PHP. They are "assigned by reference", generally speaking. The Objects and References page in the PHP manual goes into some detail about this. Basically, your = is not working as you expect. $entity_query and $entity_query_points1 are "the same object".
As noted by @baikho in the comments, you'll need to use clone to achieve what you're trying to do.
$entity_query = clone $entity_query_points1;


Retaining earliest instances of duplicate entries from a table

Question: We have a situation where duplicate entries have crept into our table with more than 60 million entries (duplicate here implies that all fields, except the AUTO_INCREMENT index field have the same value).  We suspect that there are about 2 million duplicate entries in the table.  We would like to delete these duplicate entries such that the earliest instances of the duplicate entries are retained.
Let me explain with an illustrative table:
CREATE TABLE people
(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(40) NOT NULL DEFAULT '',
age INT NOT NULL DEFAULT 0,
phrase VARCHAR(40) NOT NULL DEFAULT '',
PRIMARY KEY (id)
);

INSERT INTO people(name, age, phrase) VALUES ('John Doe', 25, 'qwert'), ('William Smith', 19, 'yuiop'),
('Peter Jones', 19, 'yuiop'), ('Ronnie Arbuckle', 32, 'asdfg'), ('Ronnie Arbuckle', 32, 'asdfg'),
('Mary Evans', 18, 'hjklp'), ('Mary Evans', 18, 'hjklpd'), ('John Doe', 25, 'qwert');

SELECT * FROM people;
+----+-----------------+-----+--------+
| id | name            | age | phrase |
+----+-----------------+-----+--------+
|  1 | John Doe        |  25 | qwert  |
|  2 | William Smith   |  19 | yuiop  |
|  3 | Peter Jones     |  19 | yuiop  |
|  4 | Ronnie Arbuckle |  32 | asdfg  |
|  5 | Ronnie Arbuckle |  32 | asdfg  |
|  6 | Mary Evans      |  18 | hjklp  |
|  7 | Mary Evans      |  18 | hjklpd |
|  8 | John Doe        |  25 | qwert  |
+----+-----------------+-----+--------+

We would like to remove duplicate entries so that we get the following output:
SELECT * FROM people;
+----+-----------------+-----+--------+
| id | name            | age | phrase |
+----+-----------------+-----+--------+
|  1 | John Doe        |  25 | qwert  |
|  2 | William Smith   |  19 | yuiop  |
|  3 | Peter Jones     |  19 | yuiop  |
|  4 | Ronnie Arbuckle |  32 | asdfg  |
|  6 | Mary Evans      |  18 | hjklp  |
|  7 | Mary Evans      |  18 | hjklpd |
+----+-----------------+-----+--------+

On smaller sized tables the following approach would work:
CREATE TABLE people_uniq LIKE people;

INSERT INTO people_uniq SELECT * FROM people GROUP BY name, age, phrase;

DROP TABLE people;

RENAME TABLE people_uniq TO people;

SELECT * FROM people;
+----+-----------------+-----+--------+
| id | name            | age | phrase |
+----+-----------------+-----+--------+
|  1 | John Doe        |  25 | qwert  |
|  2 | William Smith   |  19 | yuiop  |
|  3 | Peter Jones     |  19 | yuiop  |
|  4 | Ronnie Arbuckle |  32 | asdfg  |
|  6 | Mary Evans      |  18 | hjklp  |
|  7 | Mary Evans      |  18 | hjklpd |
+----+-----------------+-----+--------+

Kindly suggest a solution that would scale to a table with tens of millions of entries and many more columns.  We are using MySQL version 5.6.49.
Comment: If you first create an index on `name, age, phrase`, wouldn't that speed up the `SELECT * FROM people GROUP BY name, age, phrase`? Also, you wrote _"We would like to delete these duplicate entries such that the earliest instances of the duplicate entries are retained"_ but the example for smaller sized tables will not necessarily retain the earliest instances of dupes. Is that really a necessary constraint?
Answer: why not deleting duplicates?
DELETE FROM people
where id in (
SELECT MAX(id)
FROM people
GROUP BY name, age, phrase
HAVING count(*) > 1
)

if it still takes too much time  , you can do it in batch
Comment: Right , my bad .
Comment: The table have no indices other than primary. Your query will execute infinitely long on OP's table.
Comment: index would not be helpful here since he needs to group by all the columns , actually having no index help with delete operation.


How To Limit User Quota Bandwidth to 10Gb/day

Question: I have been trying to figure this out:
I am creating a filehosting site with PHP and I would like to know how to limit user to 10Gb of bandwidth per day, so that they can download - just like RapidShare, until their session is expired. They will be then credited back with 25Gb.
What type of cap can I use to monitor their session of downloading (including resuming) their file?
I know I have to do something with chunk data, or the total chunks completed, and then I can calculate their total chunks.
Comment: This question is too localized and would not be useful to a large amount of other people. It also lacks understanding of punctuation and formatting.
Comment: i speak french sorry for bad english
Comment: This is NOT a PHP question, it is a server question. I think you need to go learn how your server actually works before you start a file hosting service, and you should probably learn how to type while you're at it.
Comment: Exact duplicate of [Bandwidth Monitor ](http://serverfault.com/questions/153123/bandwidth-monitor)
Answer: If you want to create a file hosting site which has a limit like this, I'd thing you'll need a specific PHP script to serve the files to download, like incrediman says. If you're not too new to PHP and Web Development, I encourage you to check out this article as well: http://onlamp.com/pub/a/php/2000/09/15/php_mysql.html
In the end the central idea, however, is that end users would always visit the same script (let's say you named it 'download.php') and you'd use something like a query string to dynamically choose what content is served. So to download a filelike 'lenna.jpg' they'd visit a URL similar to "www.yoursite.ex/download.php?file=lenna.jpg ".
Since in doing this, you'll have centralized the downloading in one place/script (this is called the Information Expert Pattern/Principle) you also have a central place to log how much a user has downloaded during their session (PHP has built in support for simplistic session information... see http://php.net/manual/en/features.sessions.php) and a central place to block them once they've downloaded enough.
Comment: Good edit Farseeker.
Comment: its something like this, http://www.rapidshare.com/faq5.html i have my code here you can see it and review it for me please check to see how i improve the coding thanks.  http://pastebin.ca/M2c6Cyj8 password ddd
Answer: You could store the users' session IDs in a database along with an amount of data they've downloaded. Each time they download a file, check that their current_usage + size_of_file < 100mb. If it is, allow the download, otherwise present them with an error. Each day reset everyone's current_usage to 0.
Comment: This will be a problem if they pause/resume, as it will be a brand new request, even if they only downloaded 10Mb of a 100Mb file, it will show up as 200Mb consumed
Comment: its something like this, http://www.rapidshare.com/faq5.html i have my code here you can see it and review it for me please check to see how i improve the coding thanks.  http://pastebin.ca/M2c6Cyj8 password ddd
Answer: Also, you should know that you can use php to initiate a download, which is what you should be doing if you want to be tracking downloads. If you simply link to the file, that won't work. So use the script to initiate the download, and increment their downloaded count that way.
More info on using a script to initiate a download: http://www.ryboe.com/tutorials/php-headers-force-download
Comment: thank you guys i have understand how to create that its creating a counter code of how much downloads per day/user but this is the scary part, if a user was to download the file and to stop it i want to record how much bytes the user used of downloading the file, if the user resume the file i can count how much they left off and deduct it form there traffic balance, i want to understand the amount of chunks sent to the user.
Comment: its something like this, http://www.rapidshare.com/faq5.html i have my code here you can see it and review it for me please check to see how i improve the coding thanks.  http://pastebin.ca/M2c6Cyj8 password ddd


how to integrate $\frac1{2-3x^2}\,dx$

Question: How do we evaluate
$$\int\frac{dx}{2-3x^2}$$
Comment: What is the domain of x?
Comment: Parentheses, please. It is not clear in the title that the $3x^2$ belongs in the denominator, though it is from context.
Comment: It is an indefinite integral, @Priyatham : what do we care about its domain?
Comment: I am sorry, I was thinking of some sine substitution (which is not required here).
Answer: Hints:
$$2-3x^2=\left(\sqrt2-\sqrt3x\right)\left(\sqrt2+\sqrt3x\right)\implies$$
$$\frac1{2-3x^2}=\frac1{2\sqrt2}\left(\frac1{\sqrt2-\sqrt3x}+\frac1{\sqrt2+\sqrt3x}\right)\implies\;\ldots$$
Comment: Nice, thanks...

how to integrate $\frac1{2-3x^2}\,dx$


Custom domain mapping to web application

Question: We are creating a SAAS base application, where every company get its own subdomain. But if the company wants to configure another domain with our application, they can do that.
e.g. I am a company registered with the application www.saas.com, i got the subdomain company.saas.com, now i want to point my company.com domain to the company.saas.com, so how we can achieve this?
i know it can be done using Cname but is there a way to dynamic update Cname?
Answer: This depends entirely on how your application performs the hostname detection. E.g. if it runs on HTTPS, you'll need to add a virtual host on your web server. We could deduce, based on that you currently use subdomain.saas.example.com and the software is able to detect that, that this should be possible. You'll just use the same method for hostname identification than with the current solution.
On DNS level you should use an A record pointing to the same IP address. That's because using a CNAME record only causes another DNS lookup for the company.saas.example.com IN A record and it doesn't cause any change in the hostname detected, so you wouldn't get any benefit from using it; i.e. it's not a shortcut for preventing configuration of this hostname detection method.
If you wish to use CNAME (for example if the IP address for *.saas.example.com may change without acknowledging the customer), you should advice using a subdomain, e.g. saas.example.net instead of example.net. This is because when using a CNAME record you are not able to use any other records on the same hostname. With the domain name itself this means you lose the ability to add MX, TXT, NS etc. records. That would prevent using the same domain for email etc.
Comment: What kind of server configuration i need? Do i need dedicated server or it can work on shared hosting as well?

I am using apache and codeigniter/php.
Comment: Share your Apache configuration for `*.saas.example.com` by adding it to your question. Then, I may help you to add an example virtual host for a custom domain. If the domain isn't always a direct match against the subdomain, you'll need to add one new virtual host for every single domain. But if you can sell a SaaS solution to a company, the effort:benefit rate in that would still be excellent.
Comment: I am not sure how i can check Apache configuration. I am on shared hosting. Do you think we need dedicated server ?
Comment: If you can't access Apache configuration, you'll need to ask for an addition every time a new domain appears. (Possibly you can do this via some web control panel, but they are off-topic here.) Therefore, a dedicated server (or VPS) would be ideal for this.
Comment: So if i have dedicated server, how should i create virtual host?
Comment: Basically you'll add a new `` section with `ServerName saas.example.net`. It can contain the same settings than a `company.saas.example.com` or be a redirect, depending how your software does the recognition. See [`VirtualHost` Examples](https://httpd.apache.org/docs/2.4/vhosts/examples.html). In some distributions virtual hosts are separate files in `/etc/apache2/sites-available/`, enabled with command `a2ensite`.
Comment: I need a dynamic solution. i dont want to update that file regularly. is that possible?
Comment: If you need to add these regularly and many, [mod_macro](https://httpd.apache.org/docs/2.4/mod/mod_macro.html) will help you. You'll just create one `...` and then add simple lines e.g. `Use SaasDomain company saas.example.net`, depending on the macro you have defined. As the domains will be custom, some manual work will always be needed. This is for minimizing that work.
Comment: alright thanks a lot.
So as per our converstation here are things we need:-
1)- Dedicated server or vps
2)- Virtual host
3)- And customers will point their domain name to our host. so i will give them Domain name servers.
4)- is there any cname involved?

Can you correct above?
Comment: That's a suitable procedure. My answer already has these two cases: don't use `CNAME` for `example.net`; you may use it for `saas.example.net`, but it's not necessary. Otherwise, I think my answer has all what is needed. The details may cause another question, later, and it is recommended to add distinct question if you have problems with the implementation. Until then, read the linked documentation and try to configure it by yourself – ask a question, when you have a delimited problem (and add what you have tried so far to solve it). Good luck!
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/60881/discussion-between-naveen-and-esa-jokinen).
Answer: You can use RewriteRule's to redirect requests to a specific DocumentRoot and you can add the rule's dynamic to a .htaccess file.
It would be better to add virtualhosts to Apache's config files but then you have to restart Apache after every change.
.htaccess:
RewriteEngine On

RewriteCond %{HTTP_HOST} (clientone.saas.example.com)
RewriteRule ^(.*)$ /clientonefolder/$1 [R=301,L]

RewriteCond %{HTTP_HOST} (clienttwo.saas.example.com)
RewriteRule ^(.*)$ /clienttwofolder/$1 [R=301,L]

Comment: What would add the new domain into `ServerAlias`, if the site isn't the default virtual host? Restarting Apache isn't necessary either; you can restart gracefully or reload.


nth root algorithm: value of initial guess?

Question: I wonder what value one would choose to maximize efficiency to make an initial guess for the nth root algorithm (supplementary constraint: only with the five operations: +, -, *, /, % (integer modulo)) presented here on wikipedia: http://en.wikipedia.org/wiki/Nth_root_algorithm
Answer: You want to be as close as possible, so it depends on how you get the number to take the $n^{\text{th}}$ root of.  If it is a floating point computer number, you have an exponent, so divide it by $n$.  In mathematical theory, no number is better than any other.  But in real life numbers tend to be around $1$ in magnitude, so without other information I would start there.


Sprinter but now want to take part in marathon

Question: I was a sprinter who used to run 100, 200 metres races, but now I'm training myself to improve my stamina and run long distance races.
I run on a treadmill 1 km everyday. Will a treadmill help me increase my stamina or do I have to choose an open field/road?
Also, I have completed 1 km in 4:05 minutes, is it good enough if I'm preparing for a 10 km race? Half and full marathon is a distant dream as of now. Also, I want to run marathons as a personal achievement only.
I'm open for any valuable suggestions.
Comment: regarding the treadmill, see the fitness stack exchange post http://fitness.stackexchange.com/questions/40/is-there-any-benefit-of-real-running-outdoors-vs-running-on-a-treadmill-in-gym?rq=1
Comment: I respectively disagree.  The name of the forum is Sports and running in marathons is a competitive sport.   The question was on how to play this particular sport.
Comment: Hi, welcome to Sports.SE.  Unfortunately, this isn't a post that is appropriate here; we're all about *competitive* sports, so questions about running are focused on competitive running (olympic marathon questions and such).  Training is appropriate on [fitness.se], as you've already been directed to.
Comment: I'm voting to leave closed, as there are no concerns in this question specific to competitive running. Questions about running a specific distance in general are more about fitness.
Answer: In a nutshell, the trick to longer distance races is to train at those distances.  To run a 10 k race, work your way up to 8 or 9 k regularly before your race.  The same holds true for longer distance races.  To successfully run a half-marathon, train so that your training runs have increased to 15 to 18 k in month or so before the race.  When training for marathons, the longest training run is about 40 km.  That run takes place four to six weeks before the race.  Most training plans take into account the fact that most of us have jobs.  Distances are between 5 and 15 k during the week with the long run (working up to 40 k) on the weekend.
Speed doesn't play a whole lot into it except in learning how to regulate it.  Consistency in pacing is more important.
Being outside is great, but unless your race is hilly training on a treadmill is fine especially for the weekday runs.  Make use of the incline.
I really, really like Hal Higdon. Here's his beginner novice plan for a marathon.  You can see how the distances increase.  The plans for more advanced runners presume you are already running substantially longer distances.
http://www.halhigdon.com/training/51137/Marathon-Novice-1-Training-Program
And good luck.
Comment: After reading the article I realised that I can gradually increase my pace. I lose my pace after 1 km and I'm all tongue out! The article is awesome, so is your wonderful advice!


How to make a IP Address Connecting to your DNS Server use another DNS Server with Conditions

Question: As you can see, the Title is quite a mouthful but i don't exactly know what to call it but what it is..
PC1 (External):PC2 (Local):

IP: 22.214.171.124
DNS: 126.96.36.199

IP: 220.127.116.11
DNS: 188.8.131.52

Restricted DNS:

IP: 188.8.131.52

Unrestricted DNS:

IP: 22.214.171.124

I need PC1 & PC2 to both connect to Restricted DNS Server and have a switch between them without actually changing PC1 or PC2's settings nor are either of them on active directory nor will they be.
So in a sense, Restricted DNS Server will be told that PC1's IP is cool and should use Unrestricted DNS Server (Via Forward or firewall or filter or something???) and if say PC2 (even if it's local) Not cool, keeps it in Restricted DNS Server.
Both Should be able to use it same time, if that makes sense?
*Some short answers

Blocking Method via other means (No, it's not intended for blocking
like that)
Single DNS Server? (Not sure what i want to do is possible this
way..)
Firewall Rules? (Cool, will likely be part of this to make it work,
but how would it interact with the DNS Server?)

*Equipment/OS

I have 2 Mikrotiks available
I have 2 Windows Servers Available
I have Ability to install linux on both.

As long as i can set it up the way i was hoping for, Windows/Linux/Mikrotik which ever works. Thanks.. its quite the headache..
Answer: Sounds like you want DNS Views. Google the term "DNS Split Horizon". You should be able to create "Access Control Lists" and then grant access to restricted/unrestricted "views" in a product like Bind on linux.
I use roughly the following on one of our amazon instances:
acl internal {
        172.31.32.0/20;
        127.0.0.1/8;
        localhost;
};
view "amazon-internal-view" {
        match-clients { internal; };
        zone "." IN {
                type hint;
                file "named.ca";
...
};
view "external-view" {
        zone "example.com" IN {
                type master;
                file "zones/example.com.ext";
        };
};

Comment: Yes this is what i've been looking for, or at least similair.. however implementing it, is what i am struggling with..

If i had a example on how to setup what i am looking for it would help a lot...
Comment: I remember there was a post in forum.mikrotik.com with proper Layer 7 filters on how to achieve DNS Split Horizon or Conditional DNS Forwarding. Unfortunately I cannot remember on which thread it was and a quick search didn't show anything useful. You may want to check the MikroTik forum or even better ask there since the regulars will surely remember the relevant thread.
Comment: @Paul Editted with an example from one of our amazon instances. good luck.
Answer: Many pieces of software can do this. I'm not familiar with Mikrotik, but I have used BIND for this on Linux. You can find an overview here.
Windows Server 2016 also has the ability to do it, though I believe the configuration for the particular feature you're looking for is via PowerShell only. Find an overview here.
I have done DNS views on Cisco IOS routers (!) as well, so if you have one of those around, you could use it too. One limitation, however, is that the TTL on all records is set to 10 seconds, with no way to override it, so I would not advise that.


Close default SSH Port On Centos

Question: I have been getting 1000s of failed logins per hour over the past few weeks and I'm sure 99% of them are from bots. I have installed fail2ban and I've been blocking some subnets, but i have also decided to change the port i use for SSH. It's only me using the server, so Its a simple change to get rid of a lot of bot requests.
I have made the change and everything is working fine. I want to now block port 22. I have checked firewalld and there was never a rule for port 22, which makes me wonder how it worked in the first place. Something must have been in place to make sure that port 22 requests were not blocked. How do I disable this and completely lock down port 22?
Comment: Port 22 is already closed if you changed the port.
Comment: The firewall was allowing ssh requests to port 22 before, there must be a rule somewhere?
Comment: Firewall emulates nearly the same when no daemons listening on port 22. When noone listens it's completely unnecessary to emulate that noone listen on it.
Comment: You should change the topic by: **How to block requests to port 22?**
Answer: From your earlier question I see you are using CentOS 6. The /etc/sysconfig/iptables file will contain the state of your IPv4 firewall when it is first loaded. This may be different from the running state of your firewall, especially if you have been adding arbitrary rules. You can save the current state of your firewall with the command
service iptables save

which will overwrite /etc/sysconfig/iptables (it may be prudent to make a backup first).
Under normal circumstances you will find a line like this
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT

which allows connections to port 22. Simply delete the line and then save the file. When you are back at the command line run the command
service iptables reload

This will ensure that the saved firewall state and the running firewall state are the same. This works because the default firewall on CentOS 6 has a blanket REJECT rule at the end of the INPUT chain.
If you do not want to rely on the blanket REJECT then change the line to
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j DROP

save and restart as above.
Note though that what @ipor says is true. If you have moved sshd to a different port then it is effectively closed as nothing is listening.
Comment: I am using centos6, but I have installed firewalld to handle the firewall. When I dump all rules I only have 5 open ports all of which must stay open. 22 is not one of those ports. I tried to drop it anyway, but it said it doesn't exist.
Comment: Then what is the problem you are trying to solve ?
Comment: > `I have installed firewalld` how did you do that. I didn't think firewalld was supported on C6.
Comment: its available from one of the main repos i believe. yum install firewalld. I think its just installed by default on centos 7.
Comment: It's not in any of the official CentOS repos or EPEL.
Answer: Use below IPtable rules to block the port 22 in firewall level after login as root.
block ssh over eth0 (nic card) from outside to system.

iptables -F
service iptables save
iptables -A INPUT -i eth0 -p tcp --dport 22 -j DROP
iptables -A OUTPUT -o eth0 -p tcp --sport 22 -j DROP
service iptables save

So it will keep iptable state for ever. (remember there are lot way to block unwanted request, you can select which one want to use it in your env. as per your requirement since anyone can do the "googling".)
Comment: On a standard CentOS system the INPUT chain is terminated with a blanket REJECT all rule, there is also a rule that allows traffic on port 22. Your rules will have no effect as tehy will be Added to the end of the chain after the REJECT rule.
Comment: Regarding the update: Why are you destroying the complete firewall state ?
Comment: read and understand the requirement fully, dont provide a generic reply

Close default SSH Port On Centos


shiny throws error while loading excel files when csv file is supposed to be loaded

Question: I have designed a tool using shiny which ask user to upload either a csv or xlsx file designed through radiobutton. Now there are four conditions

He chooses csv and uploads a csv file, which is correct
choose xlsx and uploads a xlsx file, also correct
choose csv and uploads an xlsx file, this is incorrect
choose xlsx and uploads csv file also incorrect

Now for point 3 and 4, i check if there is any mismatch and if it is then warn user to reload correct file type. However point 4 is not getting detected and the tools through its own error.
ui code
library(shiny)
library(xlsx)
library(tools)
shinyUI(fluidPage(
titlePanel("fileinput"),
sidebarLayout(
sidebarPanel(
  radioButtons("filetype", "Select file type",choices=c("csv file","xlsx file")),
  fileInput("file1","upload",accept = c("text/csv","text/comma-separated-values,text/plain",".csv",".xlsx",".xls"))

  ),
  mainPanel(
  uiOutput("Image_Data")
  )
  )
  )
  )

server code
shinyServer(function(input, output) {
# loading data
data <- reactive({
if(input$filetype=="xlsx file"){
  inFile <- input$file1
  if (is.null(inFile))
    return(NULL)
  a<-read.xlsx(inFile$datapath, sheetIndex=1,header =TRUE)
  as.data.frame(a)
  }else{
  inFile <- input$file1
  if (is.null(inFile))
    return(NULL)
  a<-read.csv(inFile$datapath,header =TRUE,stringsAsFactors = TRUE)
  as.data.frame(a)
  }})
# info of the file
output$about_file<-renderTable({
input$file1})
# to display data
output$display <- renderDataTable({
data()})
# passing to UI finally
output$Image_Data<-renderUI({
if(is.null(data())){
h1("forecasting tool")
}
else if(input$filetype=="csv file" & input$file1$type != "text/csv"){
sprintf("reload correct file type")}
else if(input$filetype=="xlsx file" & input$file1$type !=
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"){
  sprintf("reload correct file type")}
  else if(input$filetype=="xlsx file" & input$file1$type !=
                                             "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"){
sprintf("reload correct file type")
}else{
tabsetPanel(tabPanel("DATA",dataTableOutput("display")),
           tabPanel("aboufile", tableOutput("about_file")))
  }})})

I do have java 64 bit installed which is required to work with excel file in r.
Comment: Would it not be easier to bring the file name in as a text string and check the extension, then load based on the extension?
Answer: Your problem is that you are reading the file before you check for datatyp. Try to check the file ending before you read the files.
for example you could check if a file is an excel file with something like this
regexpr("\\.xlsx",input$file1) != -1

Comment: @ Bertil  else if(input$filetype=="xlsx file" & input$file1$type !=
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"){
  sprintf("reload correct file type")} has been replaced with else if(regexpr("\\.xlsx",input$file1$type) != -1){sprintf("reload correct file type")} but still throwing same error as earlier.
Answer: Sorry it was a basic lack of RnD from my end.
Issue is not with shiny but read.xlsx.
read.xlsx will not load any other file type other than xlsx and therefore throws error whereas read.csv will not throw any error(it gives warning) and load other type(xlsx) although the loaded file becomes irrelevant post loading.
what i did was just used tryCatch function and modified else if accordingly.
Below is the corrected code of server.r
shinyServer(function(input, output) {
# loading data
data <- reactive({
if(input$filetype=="xlsx file"){
  inFile <- input$file1
  if (is.null(inFile))
    return(NULL)
  a<-tryCatch(read.xlsx(inFile$datapath, sheetIndex=1,header =TRUE),error = function(e) return("wrong"))
  as.data.frame(a)
}else{
  inFile <- input$file1
  if (is.null(inFile))
    return(NULL)
  a<-read.csv(inFile$datapath,header =TRUE,stringsAsFactors = TRUE)
  as.data.frame(a)
}})
# info of the file
 output$about_file<-renderTable({
          input$file1})
 # to display data
 output$display <- renderDataTable({
 data()})
# passing to UI finally
output$Image_Data<-renderUI({
if(is.null(data())){
  h1("forecasting tool")
}else if(input$filetype =="csv file" & input$file1$type != "text/csv"){

  h4(br(),br(),"Mismatch in formats of file selected and uploaded!!",style = "color: red;")

}else if(length(data())==1){
  #h4(br(),br(),"Mismatch in formats of file selected and uploaded!",style = "font-style: italic;font-weight: bold;color: red;text-align: center;")
  h4(br(),br(),"Mismatch in formats of file selected and uploaded!",style = "color:red")
  #sprintf("testing")
}else{
  tabsetPanel(tabPanel("DATA",dataTableOutput("display")),
              tabPanel("aboufile", tableOutput("about_file")))
}})})


How to set limits of integration for joint distribution?

Question: Assume you have a headache and you take two painkillers, x and y. To determine the probability that your headache comes back within three hours, we solve
$P(X<3, Y<3)=\int_{y=0}^{3}\int_{x=0}^{3}f_{X, Y}(x,y)\,dx\,dy$
So far, so good. The next question though is, what if you take painkiller y only after x stops working? In the textbook, this is given as $P(X+Y<3)=\int_{x=0}^{3}\int_{y=0}^{x-3}f_{X, Y}(x,y)dy\,dx$.
Can someone explain where the limits of integration come from in the second example? It would have made sense to me to set up the limits of x from 0 to x (the working period of the first pain killer) and for y, from x to 3 (since the second is taken after the first one stops working). So $P(X+Y<3)=\int_{0}^{x}\int_{x}^{3}f_{X, Y}(x,y)dy\,dx$. Why is this wrong?
Thanks!
Answer: both integration limits for $P(X+Y<3)$ are wrong.
The solution given by the texbook should be
$$P(X+Y<3)=\int_0^3\left[\int_0^{3-x}f(x,y)dy   \right]dx$$
or alternavively
$$P(X+Y<3)=\int_0^3\left[\int_0^{3-y}f(x,y)dx   \right]dy$$
this because you are integrating over a triangle...a drawing can help:
Comment: Thanks for your answer! I don't really understand what integrating over a triangle means. As for the limits, why is x allowed to go from 0 to 3 but y from 0 to x-3, why is x-3 the upper limit? So the first painkiller works for 3 hours and the second one for x-3 hours? How does this mean that x+y<3? This is what I don't understand... My intuition would be that once the working period of painkiller x ends, y is taken, so the limits of y should be something like 3-x and 3, not 0 and 3-x.
Comment: @Joanna : the drawing is exactly to explain you which is the region to be integrated for $P(X+Y<3)$. If you take the second pil only after X stops working it is evident that $X \in (0;3]$ and $Y$ is in the remainig time.... $3-x$
Comment: Makes sense now, thanks!


Is a kernel function basically just a mapping?

Question: I'm currently studying machine learning (support vector machines to be more specific), and I was wondering how exactly I should understand what a kernel function is. I've read other questions on this community such as:

How to intuitively explain what a kernel is?
Understanding kernel functions for SVMs
What function could be a kernel?

However, I'm still having trouble grasping the concept and was hoping somebody would be able to help me out.
My initial understanding is that a kernel is essentially just a mapping into a higher dimension. For example, when we want to make better predictions using a linear classifier, we would use a kernel to map the decision boundary to a higher dimension and make better predictions.
Is my understanding at least on the right track?
Any feedback is appreciated. Thank you.
Answer:
My initial understanding is that a kernel is essentially just a
  mapping into a higher dimension.

No. Kernel is a function that calculates dot product in the image of this mapping.
It can be thought of as defining dot product, using dot product from another space, where the mapping into this (often higher-dimensional) space is implicit.
Comment: That means that you don't calculate it. Sometimes you even won't be able to calculate it explicitly at all - for example RBF kernel's mapping maps vectors to infinitely-dimensional space.
Comment: Thanks for the answer. What does it mean for the mapping to be "implicit?"
Comment: So the kernel is a metric tensor that defines the coordinates, wedge and dot product?
Comment: Not really. A Riemannian metric is a function that given a point on manifold defines dot product. That means m(x)(v,w) is a number, so it can be interpreted as a function of three things that returns a number. Kernel takes two points from one space and returns dot product of their embeddings. That means it's a function of two parameters.
Answer: My answer may be paraphrasing what you already gathered in the other threads, but here's my way of seeing this.
Technically, the kernel trick can indeed be seen as a mapping to a higher dimension (possibly infinite) where a linear method works. But it is much more than that, because you use an implicit definition of the transformation, through the definition of the inner product in the target space.
$$k(x_i, x_j) = \left< \phi(x_i), \phi(x_j) \right>$$
where $\phi$ is the transformation and $k$ your kernel function.
The kernel function itself can be seen as a measure of similarity between vectors, or (in my interpretation) as a representant for the local behaviour shape. Check out the comparison of how kernels determine the shape of a 1-D gaussian process regressor estimator on this page, I found it very useful on the way to understanding what the kernel choice implies.


Round Table Adjacent Seats Problem

Question: If there are 10 seats in a round table and 7 people are already sitting in some random pattern(edit: uniform distribution, thank you for the correction) what is the probability that the next two people entering the room will get to sit in adjacent seats?
I am very challenged in trying to start to think about the problem. I would sincerely appreciate any thoughts and I will definitely indicate my progress thereafter.
Comment: So far you have three completely different answers :).
Comment: This may indicate some ambiguity in how your question is written.
Comment: Two of the answers are not different from each other.
Comment: You're right; $21/36=7/12$.
Answer: We assign seats at random, by putting place mats labelled $1,2,3,\dots, A, B, C$ at random in front of the $10$ chairs. The place mats labelled $A,B,C$ indicate where any person apart from $1$ to $7$ may sit.  A pair of lovers now enters the room, and they wish to sit together. We find the probability that they can do so without asking anybody to move.
The only thing that matters is the placement of $A, B, C$. And since the table is round, all that matters is the placement of $B$ and $C$ relative to $A$. So we have $9$ empty spaces, and have to choose $2$ of them. There are $\binom{9}{2}$ choices, all equally likely.
We count the bad choices. For a choice to be bad, it must involve choosing $2$ non-adjacent seats from the $7$ not next to $A$. There are $\binom{7}{2}$ ways to choose $2$ seats, of which $6$ give an adjacent pair. So there are $15$ bad choices, out of the $\binom{9}{2}$ choices. Thus the probability there will be an adjacent pair is $\frac{21}{36}$.
Comment: Thank you so much for the detailed response. I edited it to be a uniform distribution. Thank you, I fully comprehend the problem now.
Answer: This is impossible to determine without knowing the distribution function of the patterns in which the $7$ people are already sitting. I will assume a uniform distribution since this seems most natural.
Assuming a linear distribution, the $7$ people are a red herring. We just need to calculate the probability that two random seats are next to each other. After the first seat is chosen, two of the remaining $9$ are adjacent to it, so the probability is $2/9$.
Comment: Yes, I apologize for the ambiguity of the question. Thank you.
Answer: Based on the phrasing of the question, I will assume that the next two people will enter together, and that they'll sit next to each other if they can.  If all configurations of the first $7$ people are equally likely, then so are all configurations of the remaining $3$ empty seats; we want to know how likely it is that any pair of those empty seats are adjacent.  There are ${{10}\choose{3}}=120$ configurations, of which the number with an adjacent pair is $10\cdot 8 - 10=70$.  (Or count the number with no adjacent pairs.  After placing the first seat, there are seven spots left.  Two of them leave five spots for the third seat; the others leave four.  So this number is $10\cdot \left(2\cdot 5 + 5\cdot 4\right)=300$; dividing by $3!$ leaves $50$ blocked configurations.)
So the desired probability is $7/12$.
Comment: Yes, we are to assume uniform distribution. Thank you so much for the detailed response.
Answer: Consider 10 chairs arranged in a circle.
The number of ways of leaving three seats empty is C(10,7) = 240.
Of these, the number of ways in which atleast 2 of the empty seats are adjacent is 10.8 = 80.
(Think of this situation as having 10 fixed spaces. There are 10 ways to choose a pair of adjacent spaces, considering the first and last also as adjacent-one for each space being the left space of the chosen pair. There are 8 ways to choose one of the remaining 8 spaces)
Hence, the required probability is 80/240 = 1/3.
Comment: There are two mistakes. $\binom{10}7=120\ne240$. And you're overcounting the configurations with three adjacent empty seats.

Round Table Adjacent Seats Problem


If $K$ is an extension of $\mathbb{Z}/p\mathbb{Z}$, every elements of $K$ is a root of $t^{p^n -1}-1$

Question:
Problem :

Show that the characteristic of a finite field $K$ is a prime number.
Show that $K$ is an extension of $\mathbb{Z}/p\mathbb{Z}$ and there exists $n$ such that Card($K$) $= p^n$.
Show that every non zero elements of $K$ is a root of $t^{p^n -1}-1$.
Show that $K$ is the splitting field of $t^{p^n}-t$.

I managed to prove the first and second problems. The first one by contradiction and the second by showing that $\mathbb{Z}/p\mathbb{Z}$ was isomorphic to a subfield of K (the image of the characteristic homomorphism).
However I have difficulties showing the third problem. I think it would equivalent to showing that $\forall x \in K : x^{p^n -1} = 1$, or maybe that $\forall x \in K : x^{p^n} = x$ and use Ferma's little theorem.
Answer: You're on the right track, but there are a couple of slips in your equivalences.  The equation $\ x^{p^n-1} = 1\ $ doesn't hold for all $\ x\in K\ $, only for all non-zero $\ x\in K\ $, but that's precisely what it is that you're being asked to show in the third leg of your problem.  And you can indeed use Lagrange's theorem (a generalisation of Fermat's little theorem) to show it, since the nonzero elements of $\ K\ $ form a multiplicative group of order $\ p^n-1\ $.
The other slip (just a typo, I presume) is in the equation $\ x^{p^n} = p\ $.  This should be $\ x^{p^n} = x\ $.
Comment: You need one more observation.  A splitting field of a polynomial is the  *smallest* extension of the field generated by its coefficients over which the polynomial splits into linear factors.  That's trivially true in this case, because *every* member of $\ K\ $ is a root.
Comment: Thank you! I was trying to figure out how to prove that for any $x \in K$, $x^{p^{n}-1} = 1$, and I totally forgot the group of inversible elements of $K$ was cyclic and precisely of order $p^{n} -1$.
Comment: For the last question, can I conclude that since $t^{p^n}-t=t(t^{p^{n}-1}-1)$ and all the non zero roots of $(t^{p^{n}-1}-1)$ are in $K$ by the 3rd question, and the $0$ root is clearly in $K$, all the roots of $(t^{p^{n}-1}-1)$  are in $K$, thus $K$ is its splitting field?


RMSE value of LSTM model vs ARIMA model

Question: I have a question that is a little bit confusing,,
I have developed three models and one of them is LSTM,,,
for the LSTM model ( I scaled the data -1,1 ) and run the model,, and to make a fair comparison with other models ( statistical models (ARIMA) required no scale and normalization developed on raw data) I got LSTM RMSE value so is this value a final one or should I convert it?
if anyone can please can help I would very much appreciate it
Answer: Yes, you should do a conversion.
You're effectively measuring your LSTM in feet and your other modes in meters (or miles and kilometers). The comparison is not fair. So LSTM has an error of 6 and ARIMA an error of 7...if the units aren't the same (they're not) then you cannot say which is performing better.
This has nothing to do with LSTM or neural networks. If you did yet another ARIMA mode but with scaled data, you would have to do some kind of conversion.
(I am assuming you've scaled your response variable. Since you're considering an autoregression, it seems like you have just a univariate time series that you've scaled, meaning that you've scaled the response variable. I think you know this, but I want this comment here for someone coming by and getting confused.)
Comment: yes I have univariate for ARIMA model but for LSTM I have included other predictors but the target is univariate
Comment: @Feddah that doesn't change my post but is an interesting clarification.

RMSE value of LSTM model vs ARIMA model