Is it possible to select texts with mouse in the case of horizontally allocated QTextEdit?

Question: There are three QGraphicsView in one line. If these QGraphicsView is vertically located (orientation is 0), to select texts with mouse is no problem. But if these QGrahpicsView is horizontally located, goes bad.Even if horizontally located, I must select texts vertically.
It seems that the mouse point at the time of mouse press event is decided by QTextEdit coordinate at first.
At the time of mouse move event, the mouse point is decided by the position of mouse press event as the anchor.
So is the time of mouse release event.
Is there way to select texts with mouse naturally? Or does Qt allow us to select texts with mouse vertically only?
from PySide6.QtWidgets import QApplication, QGraphicsView, QGraphicsScene, QGraphicsProxyWidget, QTextEdit
from PySide6.QtGui import QTextDocument, QPageSize, QPainter, QBrush, QTextCharFormat, QTextOption
from PySide6.QtCore import Qt, Signal, QRect, QRectF, QEvent, QSize, QSizeF, QPointF

class MainGraphicsView(QGraphicsView):

    def __init__(self, parent=None):

        super(MainGraphicsView, self).__init__(parent)

        self._mainscene = MainGraphicsScene(1)
        self._mainscene._mainview = self
        self.setScene(self._mainscene)

class MainGraphicsScene(QGraphicsScene):

    def __init__(self, orientation = 1, parent=None):

        super(MainGraphicsScene, self).__init__(parent)

        if orientation == 0:

            self.rootView = TextGraphicsView()
            self.rootView.main_scene = self
            self.root_proxywidget = self.addWidget(self.rootView)
            self.rootView.setSceneRect(0, 0, self.document()._pageWidth, self.document()._pageHeight)

            self.secondaryView = SecondaryTextGraphicsView(2, self.rootView.scene())
            self.secondaryView.setSceneRect(0, self.document()._pageHeight, self.document()._pageWidth, self.document()._pageHeight)
            self.secondary_proxywidget = self.addWidget(self.secondaryView)
            self.secondary_proxywidget.setPos(0, self.document()._pageHeight)

            self.thirdView = SecondaryTextGraphicsView(3, self.rootView.scene())
            self.thirdView.setSceneRect(0, self.document()._pageHeight*2, self.document()._pageWidth, self.document()._pageHeight)
            self.third_proxywidget = self.addWidget(self.thirdView)
            self.third_proxywidget.setPos(0, self.document()._pageHeight*2)

        if orientation == 1:

            self.rootView = TextGraphicsView()
            self.rootView.main_scene = self
            self.root_proxywidget = self.addWidget(self.rootView)
            self.rootView.setSceneRect(0, 0, self.document()._pageWidth, self.document()._pageHeight)

            self.secondaryView = SecondaryTextGraphicsView(2, self.rootView.scene())
            self.secondaryView.setSceneRect(0, self.document()._pageHeight, self.document()._pageWidth, self.document()._pageHeight)
            self.secondary_proxywidget = self.addWidget(self.secondaryView)
            self.secondary_proxywidget.setPos(self.document()._pageWidth, 0)

            self.thirdView = SecondaryTextGraphicsView(3, self.rootView.scene())
            self.thirdView.setSceneRect(0, self.document()._pageHeight*2, self.document()._pageWidth, self.document()._pageHeight)
            self.third_proxywidget = self.addWidget(self.thirdView)
            self.third_proxywidget.setPos(self.document()._pageWidth*2, 0)

        self.setBackgroundBrush(QBrush(Qt.gray))

    def view(self):

        return self._mainview

    def textedit(self):

        return self.document().parent()

    def document(self):

        return self.rootView.document()

class TextGraphicsView(QGraphicsView):

    def __init__(self,  parent=None):

        super().__init__(parent)

        self.page = 1

        self.initScene()

    def mousePressEvent(self, event):

        SecondaryTextGraphicsView.selectedPage = self.page
        return QGraphicsView.mousePressEvent(self, event)

    def initScene(self):

        self.common_scene = TextGraphicsScene()
        self.common_scene.root_view = self

        self.setScene(self.common_scene)
        self.setSceneRect(0, self.document()._pageHeight*(self.page -1), self.document()._pageWidth, self.document()._pageHeight)
        self.resize(int(self.document()._pageWidth), int(self.document()._pageHeight))

        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

    def view(self):

        return self.main_scene._mainview

    def textedit(self):

        return self.common_scene.textedit

    def document(self):

        return self.common_scene.textedit.document()

class SecondaryTextGraphicsView(QGraphicsView):

    def __init__(self, page, scene, parent=None):

        super().__init__(scene, parent)

        self.page = page

        self.initScene()

        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

    def initScene(self):

        self.setSceneRect(0, self.document()._pageHeight*(self.page-1), self.document()._pageWidth, self.document()._pageHeight)
        self.resize(int(self.document()._pageWidth), int(self.document()._pageHeight))

    def view(self):

        return self.scene().root_view.view()

    def textedit(self):

        return self.scene().textedit()

    def document(self):

        return self.scene().textedit.document()

class TextGraphicsScene(QGraphicsScene):

    def __init__(self, parent=None):

        super().__init__(parent)

        self.textedit = TextEdit(scene=self)

        self.addWidget(self.textedit)

    def view(self):

        return self.root_view

    def document(self):

        return self.textedit.document()

class TextEdit(QTextEdit):

    def __init__(self,  scene, parent=None):

        super().__init__(parent)

        self.setAttribute(Qt.WA_InputMethodEnabled, True)
        self.setMouseTracking(False)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        self.scene = scene
        self.setDocument(TextDocument(parent=self))

        self.setWordWrapMode(QTextOption.WrapAtWordBoundaryOrAnywhere)
        self.setLineWrapMode(self.LineWrapMode.FixedPixelWidth)
        self.setLineWrapColumnOrWidth(self.document()._pageWidth)
        self.setAttribute(Qt.WA_InputMethodEnabled, True)
        self.setInputMethodHints(Qt.ImhMultiLine)
        self.resize(self.document()._pageSize.toSize().width(), self.document()._pageSize.toSize().height()*3)
        self.setPlainText("Lorem ipsum dolor sit amet, consectetur adipiscing elit, \
                        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \
                        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \
                        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. \
                        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit, \
                        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \
                        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \
                        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. \
                        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit, \
                        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \
                        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \
                        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. \
                        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit, \
                        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \
                        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \
                        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. \
                        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit, \
                        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \
                        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \
                        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. \
                        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit, \
                        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \
                        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \
                        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. \
                        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit, \
                        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \
                        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \
                        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. \
                        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit, \
                        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \
                        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \
                        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. \
                        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\
                        \Lorem ipsum dolor sit amet, consectetur adipiscing elit, \
                        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \
                        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \
                        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. \
                        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit, \
                        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \
                        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \
                        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. \
                        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit, \
                        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \
                        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \
                        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. \
                        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")

    def mouseMoveEvent(self, event):

        print(event.position())
        return QTextEdit.mouseMoveEvent(self, event)

    def view(self):

        return self.scene.root_view

    def pageSize(self):

        return self.document()._pageSize

class TextDocument(QTextDocument):

    def __init__(self, parent=None):
        super().__init__(parent)

        self._pageSize = QPageSize.size(QPageSize.A4, QPageSize.Point)

        self._pageHeight = self._pageSize.height()
        self._pageWidth  = self._pageSize.width()
        self.setDocumentMargin(30.5)

def main():
    import sys

    app = QApplication([]) if QApplication.instance() is None else QApplication.instance()
    m = MainGraphicsView()
    m.show()
    sys.exit(app.exec())

if __name__ == "__main__":
    main()

Comment: Why are you adding a *further* QGraphicsView for each QTextEdit, while you could just add a QTextEdit? Your concept (and resulting code) seems quite convoluted, can you explain what you're trying to achieve and what is your final purpose?
Comment: @musicamante if I use QGraphicsView and shows the each page, I don't have to calculate the position of QTextLines when the document is horizontally layouted. QGraphicsView  can show each page horizontally, but in actual QTextEdit is all vertically layouted. That is why it is very simple.
Comment: That doesn't clarify *at all* why you're creating other QGraphicsViews *inside* the main scene, and doing that has absolutely nothing to do with the text layout. Just add each QTextEdit to the main scene, but be aware that if you're doing all that because you want to display a document across multiple "pages", that is certainly not a good solution (especially if you want to allow editing). Besides, it's not clear what you mean by "goes bad". I tested your code with PyQt6 (but the behavior wouldn't change with PySide6) and I found no issues in selecting text.
Comment: @musicamante I want to select texts from 1 page to 2 page (3 page) with mouse horizontally dragged. If I move mouse from the top of 1 page to the top of 2 page , the texts of 1 page is all selected. But now, I must drag until the bottom of the page. That doesn't me allow to select 2 page texts at all.
Comment: That selection is invalid anyway: the fact that you can't "select" when "pages" are laid out horizontally is actually irrelevant: they are completely different widgets, you can only see an *apparent* selection just due to the orientation, but that selection is actually wrong anyway. The approach is *wrong* by nature. QTextEdit doesn't provide such feature, and trying to "hack" your way by using convoluted (and, as said, unnecessary) ways won't solve your issue in any way, *no matter what*. Sorry, but, while not impossible, what you want to do is *very* difficult, and you cannot do it like this
Comment: Text selection in an edit widget **always** uses the x and y coordinates *relative* to that widget. If you "drag" the mouse *above* the start of the selection, the selection will **still** be relative to that widget, so it will go *above* the selection start. And using another widget (or, even worse, another QGraphicsView that embeds that widget in its scene through a graphics proxy), won't change absolutely *anything*: the mouse movement will still be relative to the initial widget mouse event. If you want to achieve a "paginated" view, you have to create a custom text widget and, most ->
Comment: -> importantly, a *completely custom* [QAbstractTextDocumentLayout](https://doc.qt.io/qt-5/qabstracttextdocumentlayout.html), which is a *really* difficult task, because the default text document layout is completely private and doesn't provide any public API except from what the abstract class provides. QTextEdit is ***not*** intended for that, and (at least, at this moment, Qt6 including) doesn't provide absolutely *any* solution that allows that. This is not a bug, it's by design, and for *very good reasons*: that's not the purpose of QTextEdit, which is a text editor, not a word processor.
Answer: from your comment:

if I use QGraphicsView and shows the each page, I don't have to calculate the position of QTextLines when the document is horizontally layouted. QGraphicsView can show each page horizontally, but in actual QTextEdit is all vertically layouted. That is why it is very simple.

You need not to draw the lines on the basis of QTextLayout.
QTextLine also has draw method.
Please use QTextLine instead of QTextLayout.
QTextLine draw


UWP Media Element Custom control giving exception

Question: I am having a very strange situation over here.
I refered to the UWP samples and tried Custom Media transport controls sample. I ran it and it was working just fine, like its supposed to work. But then I tried and made my own project and I copied exactly everything which was in sample project not even name of file or folder was different. And then when I ran that project it gave me debugger unhandled exception and open App.ig.cs   some file like this and when i continue it stop debugging. Below is the attached snapshot of that error. Any help is appreciated this is a really strange error for me as it makes no sense at all.
Note: I have tried to run it in both blend and visual studio
Comment: What type of exception (in 'e')?
Comment: solved it see my answer, but thanks anyways :)
Answer: I solved it by simply ignoring the style of transport controls provided in the sample, for some reason that style was not able to verify some properties so I deleted that file and made my own style file, I copied the style of default media controls and edited them, it worked for me :)


How to get all values from one array which do not exist in another array?

Question: How to get the values from an array that are NOT in another array in PHP?
My current aproach have bad time complexity. Is there an inbuilt php function that can solve my problem?
Example:
$a1 = array(1,2,3,4);
$a2 = array(3,4,5,6,7);

Result:
[5,6,7];

Comment: http://uk1.php.net/array_diff
Answer: array_diff is your friend.

Returns an array containing all the entries from array1 that are not present in any of the other arrays.

$a1 = array(1,2,3,4);
$a2 = array(3,4,5,6,7);
$result = array_diff($a2, $a1);
print_r($result);

Will output:
Array
(
    [2] => 5
    [3] => 6
    [4] => 7
)

And if you reverse the parameters like this:
array_diff($a1, $a2)

It will output:
Array
(
    [0] => 1
    [1] => 2
)

Comment: Got it. Please change you answer as $result = array_diff($a2, $a1); Thanks
Comment: please change $a1 to $a2 and vice-versa for better explanation. Otherwise your "array1" is $a2


Postgresql 10 PL/pgSQL function array parameter

Question: I´m solving problem with PL/pgSQL function and I still can´t find clear aswer.
I need to call my function in PHP (7.2) and send an array like this one. It is array of arrays.
[
    [value1(numeric), value2(timestamp)],
    [value1(numeric), value2(timestamp)]
];

And then I need to loop over this array and access every value.
Does anybody know how to solve this?
In general I know that PHP (PDO) still is not well prepared for these situations.
Thank you very much for your answers and advices
Comment: Do you need to loop the array inside the plpgsql function?
Comment: Hello, yes I do. Now I´m thinking that I will not send an array but a JSON. Isnt that more effective?
Answer: A array value can be created as literal or as functions or array constructor result. You have to know:

PostgreSQL arrays are multidimensional.
PostgreSQL supports array of composite types
Arrays of arrays are not supported.
PostgreSQL's arrays are homogeneous - can holds a values of only one type.

So for your purpose probably you should to create own custom type, maybe constructor for this custom type.
CREATE mytype AS(value1 numeric, value2 timestamp);

CREATE OR REPLACE FUNCTION mytype_new(numeric, timestamp)
RETURNS mytype AS $$
SELECT ROW($1, $2)::mytype;
$$ LANGUAGE sql IMMUTABLE;

CREATE OR REPLACE FUNCTION myfunc(a mytype[])
RETURNS void AS $$
DECLARE i mytype;
BEGIN
  FOREACH i IN ARRAY a
  LOOP
    RAISE NOTICE '%', i;
  END LOOP;
END;
$$ LANGUAGE plpgsql IMMUTABLE STRICT;

you can create a array with type constructors:
postgres=# select myfunc(array[mytype_new(1, current_timestamp::timestamp), mytype_new(2, current_timestamp::timestamp)]);
NOTICE:  (1,"2018-11-04 05:32:55.579313")
NOTICE:  (2,"2018-11-04 05:32:55.579313")

or you can enter value as literal (attention, the values should be correctly quoted and escaped):
postgres=# select myfunc('{"(1,2018-11-04 05:32:28.44918)","(2,2018-11-04 05:32:28.44918)"}');
NOTICE:  (1,"2018-11-04 05:32:28.44918")
NOTICE:  (2,"2018-11-04 05:32:28.44918")

These last two selects can you can run from PHP.
Comment: @Vole - It depends what you are do inside function and where and what is the bottleneck. Usually this should not be performance problem - common bottlenecks are elsewhere. The performance arrays of composites should be better than json, but for small sizes (1000 is small) the difference will not be visible probably. If performance is important for you, test both. JSON is saved as string, and it can be parsed every time. Hard to say what factor is significant for your specific case.
Comment: Hello Pavel, sorry for my late answer. I understand your solution in general. But what about performance? Is this acceptable? This is my situation I´m solving:
Comment: Hello Pavel, sorry for my late answer. I understand your solution in general. But what about performance? Is this acceptable? This is my situation I´m solving:

On 99% there will be only this: [value1, value2].
But it can also happen the situation in my first question. And that array can have length of 1000. So I´m looking also for good performance. And I´m not sure about your solution, because there is a lot of casting. And I know that you are a professional (postgres.cz).

Now i realized that I can send a JSON to that function and loop over it. Isnt that easier and more effective?


SQL Join two tables with an excluding condition?

Question: I have a SQL question which I am trying to solve. Below is the question:
Given the following two tables write a SQL query that returns the
top 10000 scores excluding uuids that have any what=3 events in the
last 30 days.
TABLE scores (
  uuid INT,
  score FLOAT
)
TABLE events (
  when date,
  uuid INT,
  what INT
)

I tried to solve it in this way by dividing the question into two statements and then joining it,
For the statement: SQL query that returns the top 10000 scores, I got,
SELECT TOP 10000 score FROM scores;

For the statement:uuids that have any what=3 events in the last 30 days.
SELECT uuid FROM events WHERE what=3 AND when>2/14/2015;

By joining the two statements based on the excluding condition, i got,
SELECT TOP 10000 score
WHERE what!=3 AND when>2/14/2015
FROM scores
INNER JOIN events
ON score.uuid=events.uuid;

But I am not sure if this correct, and I feel like I am missing something here like a specific syntax for "excluding", and also I am not sure if I performed the Join operation in the right way. Any help would be appreciated.
Comment: Which RDBMS is this for? Please add a tag to specify whether you're using `mysql`, `postgresql`, `sql-server`, `oracle` or `db2` - or something else entirely.
Answer: Try this
select top 10000 score
from scores
where not exists(
     select 1
     from events
     where scores.uuid = events.uuid
     and events.when > 20150214
     and what=3
    )

Comment: @PieterGeerkens . . . I know that, and I know the SQL Server limitations in this area.  I still maintain that YYYY-MM-DD is ISO standard and readable.  I am a human, after all.  By the way, other databases will not necessarily recognize that format.
Comment: I'm upvoting, but you might as well use the ISO format `'2015-02-14'` most databases understand this in a date context (although in Oracle you need to prepend it with the keyword "date".  I also presume an `order by` is needed for the `top`, but the question is vague on the field to use.
Comment: @GordonLinoff: That's almost correct. The *one and only* date format guaranteed to be correctly recognized in all cultures and regions in 'yyyymmdd' (ie `'20150214'` in this instance) with no delimiters.
Comment: @GordonLinoff: Readability is important - but slighlly less so than being functionally correct.
Comment: Edited the answer as per your comments.


Python: How to call and run python scripts from desktop by giving command in python editor?

Question: I have two python script files in my desktop folder and I would like to run based on if statement. For example: If calling 'Ram' and 'Sam' then run python script file_1 and for 'Mohan' run python script file_2. Is there any way where I can call and run the scripts by giving some command based on if statement? Below is the path of files and dataframe.
file_1 = 'c:/users/rec/name/file_1.py'
file_2 = 'c:/users/rec/name/file_2.py'

df = {'name': ['Ram','Mohan','Sam'], 'salary':[1000, 2000, 1500]}

Comment: You can look into the `os` library for running arbitrary system commands (including running other python scripts) from python. Much better would be to structure your project in such as way as to be able to import those two files as modules. Perhaps better still (depending on the complexity of those two files) : why not just bring them into the file where your df is defined, as functions instead, taking the name as an argument ?
Comment: Sure. I will look at it. thanks.
Answer: Use an import statement to run:

First, name the file you showed us as 'c:/users/rec/name/<filename>.py'
Next, try running this:

df = {'name': ['Ram','Mohan','Sam'], 'salary':[1000, 2000, 1500]}

person = 'Ram' #Get somebody in this variable

#Import each program depending on person
if person == 'Ram' or person == 'Sam':
    import file_1

else if person == 'Mohan':
    import file_2

else:
    print('Person was not Sam, Ram, or Mohan.')

#Adjust as needed

To rename a file, use os.rename:
import os

os.rename('original file name', 'new file name')

Comment: Thanks for prompt reply. I will check and get back very soon. Hope it works. Thanks.
Comment: Importing doesn't just get the functions from modules like `numpy` or `os` or `tensorflow`. It runs the code in the module. The modules that you typically `import` don't do anything, they just define variables and functions.
Comment: I agree. I also have a output program in the above scripts which get save in directory. It means once I run the above script, I should see the output in directory.
Comment: Mark this answer as the best answer by clicking the checkmark below it.
Comment: One last thing. how to name the files ...like we use pd.read_csv to read csv files. What convention we use to read the file or any additional libraries to import?
Comment: Hi..Please suggest how to name the file. Because it is showing me error.
Comment: Done! Use `os.rename` as specified in the post.


O que é devops?

Question: Gostaria de saber o que é "devops" na prática. Sinceramente gostaria de saber uma experiência ao invés de uma definição formal.
Comment: Tirei a parte da pergunta que pede uma opinião porque isso abre espaço pra respostas baseadas somente em achismos e sem embasamento concreto.
Answer: Do artigo da Wikipedia em Português (editado):

DevOps (amálgama do termo em inglês Development and Operations, desenvolvimento e operações) é uma metodologia de desenvolvimento de software que explora a comunicação, colaboração e integração entre desenvolvedores de software e outros profissionais de TI (Tecnologia da Informação). DevOps é a reação à interdependência entre desenvolvimento de software e operações de TI. Pretende ajudar organizações a produzir software e serviços rapidamente.

Implementações atuais dessa metodologia se baseiam tanto em um conjunto de processos e métodos cobrindo comunicação e colaboração entre departamentos de desenvolvimento, QA (garantia de qualidade) e operações de TI quanto processos de automatização de entrega de software (deploy) e mudanças de infra-estrutura
Em algumas organizações, essa colaboração envolve incorporar especialistas de operações de TI em equipes de desenvolvimento de software, formando uma equipe multifuncional que também pode ser combinada com o gerenciamento de matrizes.
Fonte: https://pt.wikipedia.org/wiki/DevOps
Comment: @JeffersonQuesado *good catch*, mencionei um mas colei outro. Corrigido!
Comment: No começo você menciona a Wikipedia PT, mas depois colocou o link da Wikipedia EN? Fiquei confuso sobre sua fonte
Answer: Do Artigo da AWS (https://aws.amazon.com/pt/devops/):

O DevOps é a combinação de filosofias culturais, práticas e ferramentas que aumentam a capacidade de uma empresa de distribuir aplicativos e serviços em alta velocidade: otimizando e aperfeiçoando produtos em um ritmo mais rápido do que o das empresas que usam processos tradicionais de desenvolvimento de software e gerenciamento de infraestrutura. Essa velocidade permite que as empresas atendam melhor aos seus clientes e compitam de modo mais eficaz no mercado.

Exemplos de ferramentas: Controle de versão, automação do código para deployments, configuration management, ticketing systems, monitoramento e provisionamento.
Answer: DevOps sigla para Development and Operations, que seria em português Desenvolvimento de Operações tem como idealização a integração contínua, agilidade, qualidade, estabilidade com escalabilidade e elasticidade; considerando está diretamente relacionado a um melhor feedback entre as áreas de TI. A imagem exemplifica melhor:

O termo DevOps foi "inventado" para descrever uma cultura que abriga tanto profissionais de desenvolvimento de software quanto de operações (sysadmin). A chave está na colaboração entre essas duas equipes e tem basicamente quatro eixos principais: cultura, automação, avaliação e compartilhamento.

Um ambiente fundamentado pela cultura DevOps ajuda as empresas a
  produzirem software e serviços de forma mais ágil. Em outras palavras,
  gera aumento de produtividade e redução de custos.

Referências

O que é DevOps afinal?
DevOps: Conceitos e características
Answer: Eu gosto muito de uma definição que eu recebi de uma entrevista que eu fiz. O objetivo da cultura devops parece ser, no final das contas, otimizar o ciclo de vida do software.
Isso envolve criar rotinas automatizadas para que o fluxo desde o dev até a produção seja mais eficiente e rápida. Não apenas automatização, mas controle da qualidade do código, o que evita "bounces" e tempo desperdiçado. Alias, eu acho muito legal estudar um pouco sobre Kaizen junto com a filosofia devops. Agile vai entrar na gama de conhecimento de um analista devops, além das ferramentas de pipeline, qualidade de código, automatização, infra-as-code, além de observabilidade.
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

O que é devops?


Use UIInterpolatingMotionEffect in SpriteKit?

Question: UIInterpolatingMotionEffect is intended for use with UIView, but is there a possibility to use it within SpriteKit on a node ?
If not, does someone has an idea to realize the effect another way.
Thanks in advance
Comment: What effect are you trying to achieve?
Comment: @0x141E I want to achieve the parallax effect on the homescreen
Answer: Creating a parallax effect in Sprite Kit can be achieved by creating a set of SKNode layers, adding sprites to the layers, and then moving each layer by a different amount when the user tilts the device. You can optionally scale the layers to give the illusion of depth.
Here's an implementation in Swift. Since it uses the accelerometer, this will only work on a device (not the Simulator).
import SpriteKit
import CoreMotion

class GameScene: SKScene {

    let squareSize = CGFloat(50.0)
    let manager = CMMotionManager()
    let maxDistance = CGFloat(40.0)

    override func didMoveToView(view: SKView) {

        let colors = [SKColor.redColor(), SKColor.greenColor(), SKColor.blueColor()]

        for i in 0..<colors.count {
            let node = createLayer(colors[i], depth: CGFloat(colors.count-i), screenSize: view.frame.size)
            addChild(node)
        }

        var tiltX:CGFloat = 0.0
        var alpha:CGFloat = 0.25

        // Define block to handle accelerometer updates
        if manager.accelerometerAvailable {
            manager.accelerometerUpdateInterval = 0.1
            manager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue()) {
                [weak self] (data: CMAccelerometerData!, error: NSError!) in
                // Low-pass filter to smooth the measurements
                tiltX = tiltX * (1-alpha) + CGFloat(data.acceleration.x) * alpha
                for (index, node) in enumerate(self!.children as! [SKNode]) {
                    // Move each layer by a different amount to produce parallax effect
                    let deltaX = tiltX*CGFloat(index+1)*self!.maxDistance
                    node.position = CGPoint(x:self!.size.width/2.0+deltaX, y:self!.size.height/2.0)
                }
            }
        }
    }

    func createLayer(color:SKColor, depth:CGFloat, screenSize:CGSize) -> SKNode {
        let scale = 1.0/depth
        let node = SKNode()
        // Scale layer to create depth effect
        node.setScale(scale)
        node.zPosition = -depth
        node.position = CGPoint(x:screenSize.width/2.0, y:screenSize.height/2.0)
        let size = CGSize(width: squareSize, height: squareSize)
        // Create squares at random positions
        for i in 1...10 {
            let square = SKSpriteNode(color: color, size: size)
            let x = CGFloat(arc4random_uniform(UInt32(screenSize.width))) - screenSize.width / 2.0
            let y = CGFloat(arc4random_uniform(UInt32(screenSize.height))) - screenSize.height / 2.0
            square.position = CGPoint(x:x, y:y)
            node.addChild(square)
        }
        return node
     }
 }


Expand RAID array on HP Dynamic Smart Array B320i controller

Question: I have a few HP ProLiant DL360e Gen8 servers that are equipped with the Dynamic Smart Array B320i RAID controller.
One particular system was shipped with a single disk installed instead of a pair of drives needed for a RAID 1 mirror. I asked for another drive, but went ahead with the OS installation as RAID 0, intending to add the second disk later.
When it arrived, I went through the normal HP array expansion (transformation) process using the HP Smart Storage Administrator. Oddly, there were no actual options to add the additional drive to the existing array in the GUI.
So I took a look at the CLI options.
Current array config snippet (full configuration here):
=> ctrl all show config

Dynamic Smart Array B320i RAID in Slot 0 (Embedded)

   Internal Drive Cage at Port 1I, Box 1, OK

   Internal Drive Cage at Port 2I, Box 0, OK
   array A (SAS, Unused Space: 212343  MB)

      logicaldrive 1 (72.0 GB, RAID 0, OK)

      physicaldrive 1I:1:1 (port 1I:box 1:bay 1, SAS, 300 GB, OK)

   unassigned

      physicaldrive 1I:1:2 (port 1I:box 1:bay 2, SAS, 300 GB, OK)

Using the command line hpssacli tool to initiate the transformation yielded an error:
# hpssacli controller slot=0 array A add drives=allunassigned

Error: This operation is not supported with the current configuration. Use the
       "show" command on devices to show additional details about the
       configuration.
Reason: Transformation size zero. This may indicate that
       there is no battery or a failed battery on the controller.

A quick check of the B320i controller's specifications show:
Provides increased server uptime by providing advanced storage functionality:
- Online RAID level migration (between any RAID level/with FBWC )
- Online drive firmware upgrade
- Pre-Failure Warranty

It would seem that the Smart Array B320i should be capable of a RAID level migration, provided an FBWC unit is present. The controller in question has a healthy 512MB FBWC unit and SAS license key installed.
However, this brief note buried deep within the HP website says:

The user has a B320i, with the 512MB cache module and SAS license
  installed. Additional drives have been added to the server and user
  wishes to expand the array, then extend the logical drive. When
  looking through the Array Configuration Utility (ACU) there is no
  option to do this.
B series Smart Array Controllers do not allow for this functionality. This option is available on most P series Smart Array Controllers. If the user wishes to upgrade to the P series Smart Array, instructions for performing this action are included in [the documentation]

So, while I can accept that there may be incorrect (misleading) language in the product literature, what can I actually do about this?
I appear to be stuck with a RAID controller that has no ability to modify its physical or logical drive configuration. Is there any other option for this system other than a full reformat, array reconfiguration and rebuild?
Any other thoughts?
Comment: Anyway to dump/restore to a properly initialized physical raid-set and then do an export/import process and move the disks to the target system?
Comment: @mdpc I don't have another or spare set of disks to work with. This is a pretty routine operation that one would expect to function properly.
Comment: Battery uncharged or defect by any chance?
Comment: @Striker_84 It's a Capacitor-backed flash setup. Yes, it's healthy.
Comment: firmware / software version most recent? e.g. controller firmware should be 15.10.07.00 and hp smart storage software 18.104.22.168.
Comment: @Striker_84 Yes, the firmware and software are completely up-to-date. Also see the [full configuration output](http://pastebin.com/QipUzQHZ).
Answer: This just doesn't work.
I'll accept that the documentation which influenced the decision to buy this solution was flawed and that the HP Smart Array B320i RAID controller is not capable of logical drive expansion, migration or modification.
It's a shame.
In this specific case, I had to rebuild the server in order to add a new disk to the array set.
Comment: That's horrible........


Not receiving email : Relay access denied in Postfix (CentOS 7)

Question: For some reason my Postfix mail server running on CentOS 7 stopped working recently, maybe because I updated the modules through Webmin, I don't know. I am able to send out emails but I am not receiving emails. Also, POP3 and IMAP aren't working. I've tried many things but haven't been able to figure it out by myself, so I am looking for some help.
I read a few threads on the topics:

Fixing 'Relay access denied' in Postfix
Postfix/Dovecot relay access denied
Postfix Basic Configuration (Excellent article!)
Postfix receive email from outside not working

My initial error: Relay access denied from the file /var/log/maillog:
Jul 31 11:18:40 myhostname postfix/smtpd[6787]: connect from mail-wm0-f51.google.com[126.96.36.199]
Jul 31 11:18:40 myhostname postfix/smtpd[6787]: NOQUEUE: reject: RCPT from mail-wm0-f51.google.com[18.104.22.168]: 454 4.7.1 <firstname.lastname@example.com>: Relay access denied; from=<email@example.com> to=<firstname.lastname@example.com> proto=ESMTP helo=<mail-wm0-f51.google.com>
Jul 31 11:18:41 myhostname postfix/smtpd[6787]: disconnect from mail-wm0-f51.google.com[220.127.116.11]

My initial setting (/etc/postfix/main.cf) running the command postconf -n:
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
command_directory = /usr/sbin
config_directory = /etc/postfix
daemon_directory = /usr/libexec/postfix
data_directory = /var/lib/postfix
debug_peer_level = 2
debugger_command = PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin ddd $daemon_directory/$process_name $process_id & sleep 5
html_directory = no
mailq_path = /usr/bin/mailq.postfix
manpage_directory = /usr/share/man
mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain
newaliases_path = /usr/bin/newaliases.postfix
readme_directory = /usr/share/doc/postfix-2.10.1/README_FILES
sample_directory = /usr/share/doc/postfix-2.10.1/samples
sendmail_path = /usr/sbin/sendmail.postfix
setgid_group = postdrop
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
unknown_local_recipient_reject_code = 550

After reading the articles I mentioned above, I defined mydomain, myhostname and mynetworks; now I get a different error (see below.) Here is the main.cf settings with the alterations:
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
command_directory = /usr/sbin
config_directory = /etc/postfix
daemon_directory = /usr/libexec/postfix
data_directory = /var/lib/postfix
debug_peer_level = 2
debugger_command = PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin ddd $daemon_directory/$process_name $process_id & sleep 5
html_directory = no
mailq_path = /usr/bin/mailq.postfix
manpage_directory = /usr/share/man
mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain
mydomain = mydomain.com
myhostname = 9dok43ksalv.hostname.com
mynetworks = 126.96.36.199/28, 127.0.0.0/8
myorigin = $mydomain
newaliases_path = /usr/bin/newaliases.postfix
readme_directory = /usr/share/doc/postfix-2.10.1/README_FILES
relay_domains = $mydestination
sample_directory = /usr/share/doc/postfix-2.10.1/samples
sendmail_path = /usr/sbin/sendmail.postfix
setgid_group = postdrop
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
unknown_local_recipient_reject_code = 550

Now the error I got is Recipient address rejected: User unknown in local recipient table; as shown below:
connect from mail-wm0-f49.google.com[126.96.36.199]
Aug  1 16:22:27 9dok43ksalv postfix/smtpd[2583]: NOQUEUE: reject: RCPT from mail-wm0-f49.google.com[126.96.36.199]: 550 5.1.1 <email@example.com>: Recipient address rejected: User unknown in local recipient table; from=<email@example.com> to=<email@example.com> proto=ESMTP helo=<mail-wm0-f49.google.com>
Aug  1 16:22:28 9dok43ksalv postfix/smtpd[2583]: disconnect from mail-wm0-f49.google.com[220.127.116.11]

Apparently Postfix isn't finding the final destination for the email. I've never had to configure Postfix before, so I am a bit lost now as a first timer; VestaCP used to take care of this for me, and I never had a problem, until now.
Would someone be kind enough to point me on the right direction. I would really appreciate to receive emails again, and get POP3 & IMAP working.
Thanks in advance. Let me know if you need more information.
Comment: You say it was working fine before editing some modules in webmin? Do you have a backup of the config files from before?
Comment: It was working before upgrading (not editing) the modules as Webmin requests periodically. I am not sure if this is what caused it though, it is my guess, this server has low traffic and I was notified of this problem days after it was updated. No, unfortunately I don't have a backup of the system files, only the projects running on it. What blows my mind is that Postfix was working fine right out of the box when I installed Webmin & VestaCP.
Answer: The error message is 550 5.1.1 user unknown in local recipient table
I think you may need to look at the local recipients map/alias maps and ensure that they are configured correctly.  Also look at mydestinations value in main.conf as if domain is configured their then local delivery should occur
Worth reading this answer
Confused about alias_maps and virtual_alias_maps
Some good info below as well
http://www.postfix.org/postconf.5.html#local_recipient_maps
"Local Alias database
When mail is to be delivered locally, the local delivery agent runs each local recipient name through the aliases database. The mapping does not affect addresses in message headers. Local aliases are typically used to implement distribution lists, or to direct mail for standard aliases such as postmaster to real people. The table can also be used to map Firstname.Lastname addresses to login names."
or maybe Virtual Alias Maps
"With this approach, every hosted domain can have its own info etc. email address. However, it still uses Linux system accounts for local mailbox deliveries.
With virtual alias domains, each hosted address is aliased to a local UNIX system account or to a remote address. The example below shows how to use this mechanism for the fossedu.org and linuxelabs.com domains."
https://help.ubuntu.com/community/PostfixBasicSetupHowto#Local_Alias_database
https://help.ubuntu.com/community/PostfixBasicSetupHowto#Postfix_virtual_Aliases_for_separate_domains_and_Linux_system_accounts
Comment: Yes, that is my problem! Once I removed `$mydomain` from the line that defines `mydestination`, I tried to receive an email and it didn't work. Then I started tracing back to the virtual table of accounts (as you explained, thank you!), only to find out that it isn't managed by VestaCP. So when I was creating email accounts on VestaCP, Postfix wasn't seeing them, thus the 550 error. I also found out that VestaCP only integrates with Exim and it does not support Postfix. Exim was starting on boot, but then Postfix would shut it down and start itself. Yep yep yep... thank you so much guys!
Comment: Cool, had a few postfix headaches with mydestination in the past so felt your pain :-)
Comment: Yes, a pain in the ass, what it is. I had similar problems with Exim, first it was error 550, then other errors as I attempted to resolve it. No luck. I ended up having to remove and reinstall VestaCP, reconfigure everything, now everything is working as it should, thank goodness! I looked at the `exim.conf` file now, nothing appears to have changed from the previous version; so I don't really know what the problem in the first place was.
Answer: check this:
Postfix: Recipient address rejected: User unknown in local recipient table
The solution (in that case), as explained b techieb0y, is to remove $mydomain from the line:
mydestination = $mydomain, localhost.$mydomain, localhost


Why do different sites appear to label the pentatonic shapes with different letters?

Question: So I am fairly confident with my Pentatonic shapes (Exhibit A):
Pattern 1

Pattern 2

Pattern 3

Pattern 4

Pattern 5

However I then started seeing these shapes labelled with the letters C, A, G, E and D. I started looking into the logic behind why each of them might get given each of these letters as a name.
To me it seemed like each of them literally contained the open chord they were named after.
Thus (Exhibit B):
Pattern G

Pattern E

Pattern D

Pattern C

Pattern A

So far my investigations suggest:
Pattern 1 -> G
Pattern 2 -> E
Pattern 3 -> D
Pattern 4 -> C
Pattern 5 -> A

And this seems to be confirmed by several sites:
http://www.bristolguitarlessons.org.uk
https://emeryguitarchops.wordpress.com
However it seems to conflict with some other sites which seem to suggest (Exhibit C):
Pattern 1 -> E
Pattern 2 -> D
Pattern 3 -> C
Pattern 4 -> A
Pattern 5 -> G

Can someone please explain:
Have I gotten this wrong?
If I have, and this other system is correct, is there a simple reasoning akin to the one I've used?
Please help. I'm all confused
Comment: The first way of naming the patterns is based on the chords that match the patterns. The second way is based on where the root note falls in the pattern. I'll explain more when I have a computer in front of me and time to fully answer. Unless someone beats me to it.
Comment: Do all of these patterns use standard tuning, or does at least one of them use an alternate tuning (e.g. Drop D)?
Comment: I believe this is all in standard tuning.
Comment: I should perhaps add that I have not placed these patterns deliberately in any particular place on the fretboard.
Comment: Thanks @ToddWilcox. I look forward to reading that.
Comment: They are standard tuning, Tim's answer pretty much sums it up.  You're looking at (1) all the pentatonic forms that are "equivalent" and (2) mapped to one of the open string chords in the "CAGED" system.
Comment: @ToddWilcox Hey Todd you alluded to a possible answer which does not, so far, appear to match the one provided. Any chance you could expand on that?
Answer: This is down to the 'caged' system that works so well for guitarists. The open chords - C A G E and D all have specific open shapes, all of which can be moved up the fingerboard, a barre added underneath, and new chords produced.
This then gets translated, in a way, into extra notes which are easily within a couple of frets of the existing notes.
Let's take pattern G. Looking at the blue coloured notes, there's a version of the G open chord. Pattern E shows an open E, pattern A shows open A, etc.
The problem I have with this sort of portrayal is that it shows as much as possible, all the available notes under the hand at that position on the neck. Pentatonic major and pent. minor both use the same set of notes - G pent. maj. = E pent. min. BUT - if playing as a scale, one needs to know where to start/finish. It's like a lot of sites show similar for maj. scales, but if one plays all the notes, one is far more likely to end up playing a mode (or two!) and it doesn't sound too much like a scale. Rant over!
The second lot of examples you show ought to make more sense - just numbering patterns, could be any old numbers, doesn't give much of a clue, and it's arbitrary.
Comment: Sorry Tim. I think this has confused me even more. I have labelled some parts of my question as Exhibit A, B and C. You seem to be suggesting that Exhibit B is based on Open chords (Something I suggested myself). You then seem to suggest that Exhibit C should make more sense, but don't appear to have explained why, which was kind of the point of my question. ie to find some explanation for Exhibit C.... Or possibly I have misunderstood.
Comment: Problem is, there are many different places to play the same note on guitars. People have come up with these patterns of pentatonic scales, and as you are probably aware, notes from one pattern will overlap or be the same as those from another. The arbitrary numbering is one way, labelling with letters reminiscent of a chord shape found in them is another. Again, there will be, it almost can't be helped, two chord shapes that can be found within one pattern. Take pattern G, and there is an open G shape there, but look again, and there's also an open E shape. What does one label it?  Difficult.
Comment: A fair comment. In my case I found that whilst some of the patterns might be able to contain multiple chord shapes, only one of them appeared to be capable of containing an 'A' shape. When I extrapolated from there, I found that the others managed to fit correctly in sequence.
Comment: Note: I will admit, that the pattern I've noted as G, does seem to be capable of also containing an 'A' shape, but this appears to require that it is positioned on the left of the patten. When I extrapolated that logic to the other patterns and shapes, I found that the 'C' shape would not fit without leaving the pattern.


Complicated probability question

Question: There are 20 empty present boxes numbered from 1 to 20 are placed on a shelf, there are 4 men standing in front of the shelf. Each one asked to pick in his mind 3 numbers without telling any one then write down his selection. How can I know the following :

Probability of choosing a mutual number by any two or more men.
After finishing the selection, what is the probability for a different man, not one of the 4 men, to select the same boxes selected by them.
Comment: I must assume there is a number by box? I dont see any relation in choose 3 numbers in their mind and the 20 boxes. Can you explain please?
Comment: "to select the same boxes selected by them": Could you please make this a little clearer?
Comment: The number is just to know the selected box, you can neglect it. For the second question, I mean to select all selected boxes by the 4 men which is equal or less than 12 (because of probability of choosing mutual boxes).
Answer: The probability that some two men choose the same number is the complement of the probability that no two men choose the same number.
The number of ways to choose the three men's numbers such that they are all different is
$$\binom{20}{3}\binom{17}{3}\binom{14}{3}\binom{11}{3} = 1140\cdot 680\cdot 364\cdot 165$$
The number of ways to choose the same numbers with no restriction is
$$\binom{20}{3}\binom{20}{3}\binom{20}{3}\binom{20}{3}= 1140\cdot 1140\cdot 1140\cdot 1140$$
The probability of the numbers being different is therefore the first expression above, divided by the second expression:
$$P =\frac{1140\cdot 680 \cdot 364 \cdot 165}{1140^4}=\boxed{\frac{17017}{617310
}}$$
Comment: Assuming that the number selection is uniformly distributed and made independently; of course.  When people choose numbers from imagination they may show bias towards "lucky" numbers, or such.
Comment: You're right. I just assumed uniformly randomly chosen numbers to make answering the question possible :)
Comment: What about the solution for the second question:

Complicated probability question


Prove that there exists a path in G of length K

Question:
Let $G=(V,E)$ be a nonempty graph and let $d(v)\geq k$ for all $v\in V$. Prove that there exists a path in $G$ of length $k$.

Alright so my first intuition is
$$\sum_{i=1}^{n} d(v_i) \geq nk \quad(n=|E|)$$
So a path contains each vertex once and has no cycle. Seeing as each vertex has a degree $\geq k$, in the worst situation (because this limits the length of our path) we have:
$$\sum_{i=1}^{n} d(v_i) = nk$$
We also have $\sum_{v\in V} d(v_i) = 2|E|$, so
$$
2|E| = nk.
$$
This seems logical but I cant translate this into the length of a path. Any tips?
edit
maybe we can say because we have $\frac{nk}{2}$ edges, and $n$ vertices, we could maybe use induction?
Answer: Hint. Pick a vertex $v_1$. It is connected to $k$ vertices. Pick one of them $v_2$, this is connected to $k$ vertices, and $k-1$ of them are not in the path (only $v_1$ can be).
$v_2$ is connected to at least $k-2>0$ vertices not in the path. Pick one of them, $v_3$ repeat....
Induction by $k$ is probably the  simplest way to write the solution....
Comment: $v_3$ is connected to $k$ vertices. One of them is $v_2$, another one MIGHT be $v_1$, but there are at least $k-2$ vertices which are not $v_1,v_2$ or $v_3$. Just pick one of them at random.
Comment: OH I get it because the WORST case scenario is where each consequent vertex is connected to a previous one. I Love it!
Comment: I understand why induction is the way to go, but I'm having trouble formulating the base step.  Let me work on it a bit.
Comment: I wrote down take $v_1$ as your starting vertex, you can choose from $k$ edges to continue your path. The next vertex $v_2$ should have $k-1$ useable paths (no vertex can be visited twice) and so on until $v_k$ where it has $(k-k)$ useable verteces.

But my problem is after $v_3$ because it can also have $k-1$ edges to pick from right?


Let a, b and c be natural numbers. If a^2 = bc and gcd(b, c) = 1, then there exist natural numbers s and t such that b = s^2 and c = t^2 .

Question: We were given this proof under our Fundamental Theorem of Arithmetic section and it is supposed to involve prime factorization.
I'm totally lost so far and could use any help you can offer.
Answer: Hint.
Write the prime factorization of $bc$.
What can you say about the parity of the power to which each prime is raised?
Can $b$ and $c$ share any of the prime factors of their product?


How to check whether device is enrolled in MDM

Question: I am looking for an API which will allow me to check whether MDM profile is installed on a device.
It won't be submitted to AppStore, so private API are fine with me. However, it should work on jailed phone (so jailbreak solutions aren't applicable).
Update 1
I am looking for a way to determine on iOS device whether this device is enrolled (vs checking from MDM server what devices are enrolled).
Comment: For people who marks it as non constructive. Please, leave a comment behind, what exactly is non constructive in this question.
Comment: Does this help? http://stackoverflow.com/questions/10039236/ios-mdm-check-in-samples
Comment: @sangony: Thanks. I know about checkin. However, I need to determine on mobile device whether this device is enrolled or not (I wrote an update to the question)
Comment: Have a look at the 2013 WWDC session 301.  I can't say what's in it due to the NDA, but I think that one of the features they describe might help.
Comment: any luck with this?
Comment: you say you want to detect from app - but did you manage to detect from server side if a request that comes from an app is from an enrolled device? how?
Answer: One solution that I can think of is installing the application through the MDM server (using the ChangeManagementState option to take control of an already install application). This will allow you to set managed app configuration options on the MDM server which the application can read from UserDefaults.
You can see how to do this here: https://developer.apple.com/business/documentation/MDM-Protocol-Reference.pdf#b3
If you need to verify that the correct MDM server is managing the device and not some random MDM server, you can create some type of signed document that is unique to the device (include the UDID) and signed by a private key unique to the server. The app can then verify this signature with the public key (probably shipped in the app binary since this seems to be a private thing) and determine if the app and device are managed.
The easiest option would probably be something like JSON Web Tokens. There are other options that exist as well: pkcs7, SMIME, CMS, etc.
For example, in the body of the JWT token, you could include the server domain, and the device UDID. This way the device can verify that this signed token is intended for this device and not simply being copied and reused from another legitimately managed device. You could also include a timestamp (and/or expiration) value to require that the token be reissued by the MDM server over some set time interval to ensure that it's recent.
{
  "sub": "SOME-DEVICE-UDID",
  "iat": 1516239022,
  "iss": "mdm.example.com"
}

There are many ways to do this, I am just most familiar with JWT tokens. There are existing JWT libraries for Swift and Objective-C which could be used within your app to verify this token. Then you could be reasonably sure that the device is managed and managed by the intended server.


Can the AUC (logistic regression) be used as a measure of quality of the model?

Question: If I have a good measure of the AUC, what does it tell me in relation to the model and its variables?
Answer: No.

The AUC is a measure of discrimination. Say I only fit smoking (Y/N) in a risk model for lung cancer. If I predict 100% risk in smokers who have a 0.4% event rate and 0% risk in a non-smokers who have a 0.01% event rate, the model is optimal in terms of its AUC.
A good measure of AUC should take account of overfitting, using bootstrap or cross-validation, e.g. external validation. Model fit statistics are be definition a measure of internal validation.
Comment: Thank you, that's a  really good explanation.
Answer: There is no single number that captures the quality of a classifier: the whole path of the ROC contains more information than any single statistic. A perfect classifier has an area of 1.0 under the ROC, and a classifier with a large AUROC is good. This is especially true if the classes are balanced.
If you are classifying with unbalanced classes, e.g. screening for a few possible drugs among millions of candidates, then a big change in performance can result in only a small change in AUROC. In such cases, the PR curve (precision versus recall) is more informative to the eye than the ROC curve, although mathematically it contains the same information. In such cases, Area Under PR would be a better summary statistic than AUROC.
If you deal with unbalanced classifiers, it is worth getting used to reading PR curves. It is sensible to report ROC as well, since more people are used to reading them.


Know when to turn notes upside-down(eighth notes, sixteen notes, etc.)

Question: Suppose I have four of eighth notes(4/4 as time signature), all of them at different pitches, one being very high. An example is show below:

How would I know if I need to turn that upside down(downward stem) or not? Is there a method that applies to sixteenth notes, thirty-second notes, etc.?
Comment: I think it's worth noting that not everyone has always solved this problem in the exact same way. Sometimes in printed music you see a beam with some of the stems going down and some going up.
Comment: @ToddWilcox  Placing trust in software to get things right is the pathway to Purgatory!  (Yeah, I know that most typesetting software gets things right almost all the time, but..)
Comment: By "turn upside down" do you mean write it with downward stems? If so, if you use software it should do it automatically.
Comment: @ToddWilcox: Yeah, I know but is there some technique when not using software? I also mean downward stems.
Comment: I'm not sure what difference the duration of the note makes. Do you know when to draw stem-up or stem-down for quarter-notes?
Comment: @DavidBowling I know it for quarter notes but not the faster ones.
Comment: The duration doesn't matter, only that there is a stem.
Comment: It's the same guidelines for all notes.
Comment: @DavidBowling: Oh, Ok. I didn't know that.
Answer: Notes below the center stave have stems pointing up, and notes above the center stave have stems pointing down. It does not matter whether the notes are half, quarter, eighth, sixteenth, etc.; it only matters that the notes have stems.
For beamed groupings, if the number of notes above the center stave is equal to the number below for that grouping, choose the stem direction based on the note head furthest from the center stave. If the number of note heads above the stave is greater than the number below, use the rule for notes above the center stave. Similarly, if the number of note heads below the center stave is greater than the number above, use the rule for notes below the center stave.
When in doubt, use downward-pointing stems. As always, use your best judgement when something doesn't look quite right to you or if the context suggests one choice over another.
Comment: yep, nothing is more annoying than playing a run of 16ths and some publisher flipped the stem on one or two notes in the middle of the run.
Comment: @CarlWitthoft - I've seen those some-flipped-stems runs in piano sheet music before. Those flipped stems often mean that your other hand should play those notes instead of your primary note run hand for that passage.
Comment: @Dekkadeci  yes, that's been stated.  Us orchestra members recognize the same method of indicating divisi parts.  But when it shows up in the solo part of a concerto...
Answer: The general stemming rule (for individual notes) is: from third space upward, use downward pointing stems; from the second space downward, use upward pointing stems. On the third line, one can go either way. However, one may wish to violate the rules a bit to make stemming match a melodic contour.
Multiple notes on the same stem  follow the majority of the chord notes; in this case, the third line goes down.
With things like contrapuntal pieces or hymns (in 4-part harmony) generally stem according to voices; high voices have upward pointing stems and lower voices have downward pointing stems.
In all cases, readability is paramount.
Answer: Unless one is using stem direction to indicate voices, the most important "rule" is to use judgment in determining whether other rules "work" in a particular case, and overriding them when they don't.  Most rules take a fairly narrow view of each individual problem, but in many cases other considerations may be more important.
For example, if there are many groups of beamed notes in succession, readability may be improved if the beams can be made to follow a reasonable contour, keeping beam directions consistent when practical.  If the above message appeared between a bunch of beamed groups of low notes, and a bunch of beamed groups of high notes, it might make sense to have the preceding groups be beamed above the notes, the following groups be beamed below the notes, and the one group shown above slope down and to the right "between" the notes.
What's important is not to look at each beamed group independently, but to figure out an overall layout that visually makes sense.  Oftentimes, there will be some beamed groups that could beamed reasonably well in several different ways if viewed only in isolation, but some of those ways would fit better than others in the context of surrounding groups.
Note also that an editor who is working as a member of a publisher's staff may need to adapt a more "mechanical" approach than someone who is working independently.  If a publisher might end up having different parts of a piece laid out by different people, having those parts appear consistent may be more important than having them be maximally readable.  If one is working independently, however, then trying to figure out what layout would be more readable would be more valuable.


Difficulties matching pitch after the note was played

Question: I am trying to become decent at singing, and I have noticed some difficulties in matching pitch, if I try to sing AFTER the note was played.
I try to reproduce that with an example here, of a computer-generated voice singing a note, and me trying to reproduce it:
Matching pitch after the note
If I sing during the note, then it becomes very easy, because it resonates very clearly when I am finally on pitch:
Matching pitch during the note
I have noticed this problem to be worse depending on the timbre. If I try to match the pitch of a female voice singing one octave above mine (I am a man), then often times, I struggle a lot. If I try to match the note on a piano, it is much less acute, though still not easy to me unless I sing during the note.
Is that expected for a beginner singer, or does it point to a specific difficulty that I have? Any suggestion on a good way to solve that problem?
Comment: You have to really hear it before you can sing it. Try to _imagine_ yourself singing a pitch while you are listening to it, _then_ try to sing the same pitch.
Comment: You're just guessing, then trying to slide towards the note. Both guesses start out about same amount of 'wrong'… 3 semitones. btw, the generated note is not extraordinary for a male voice by any means. Don't think of it as a 'female' note. It isn't. Perhaps, though, you might do better if you were testing against notes in the same octave you are trying to sing. I honestly don't know what else to suggest for something that far out from pitch, unless perhaps a chord accompaniment rather than a single pitch might help.
Comment: All I can really say is you are not registering the pitch you hear at all to a sung pitch. You're singing something then checking it matches. I really don't know how to fix that. In my defence here, I've never been an educator. I've been able to do this without thinking since I was 6, & I have absolutely no recollection of ever being taught to do it.
Comment: Thanks. Yes, with an accompaniment, I can sing in tune. I took the worse example here. I wanted to check if this would be a known problem, or simply something somewhat normal that I just need to work to get rid of.
Answer: In the recording I hear a higher pitched reference note followed by a lower pitched note you sing. I can only guess what's going on there. I assume that you are not yet comfortable to sing the higher pitch notes.

Learn what is your voice range. Try to find reference notes which you can match well, and see how far up and down you can go comfortably. As you will practice your range will change (likely: improve), but it helps to know what notes you can sing right now.

For your exercise use notes which are within your range.

A good teacher can find your voice range and suggest proper exercises for you.
Answer: What's interesting here is that you are singing the minor third against the target tone. So it's not "out of tune" but rather harmony. A minor triad or chord consists of the 1st, 3rd, and 5th notes in a minor scale. If your traget note was C for example, you were singing E flat but in the octave below. This is known in music theory as a chord inversion.
I would suggest that you practice singing with a piano. Play up and down the 1st 5 notes of a C major scale: C D E F G F E D C and sing along with the piano. Repeat this slowly until you can match each not consistently. Ideally, you would repeat this moving up one semitone starting on C#, the D, D# etc until you reach the top of your range. Then repeat descending a semitone each time. I'm sure you can find an app which can help you with these types of exercises if you don't have access to a keyboard.
The idea is to be able to sing in tune in any key. You can add complexity such as singing major triad arpeggios in a similar way. If you don't understand some of the terminology I'm using, I do suggest that you learn some basic music theory in tandem or before learning how to sing. Playing any musical instrument might also be helpful if you don't already.
Comment: It's a minor 3rd. B against G♯
Comment: Don't see the relevance of ' able to sing in any key'.
Answer: First off, the pitch you're listening to sounds oddly wobbly to my ear, and that can't be helping matters.
Second, from what I heard, you have trouble zeroing in on the note regardless of whether the machine note stops before you try to join in.
So, I suggest you postpone this exercise of matching a given note for a while.  As a first step, I think it would be helpful for you to work on your sightsinging, and being able to sing a simple tune that is in tune with itself.  That is, when you're practicing sightsinging, it's allowed to sing the exercise in a different key than written, as long as you are consistent within the exercise.
In the early stages of sightsinging, you'll get comfortable with the tonic triad, and with the 5-1 interval.  You'll get more comfortable singing, period, and also with singing intervals with YOUR voice.  And sightsinging is great for developing the ability to hear a note in one's mind's ear.
Now for some reassurance and motivation.  Early in my relationship with my spouse, I noticed that they were not capable of going along with MY key when singing Happy Birthday (or whatever), if I was the one to start off.  So I said, "You start, and I'll join you in the key you choose."  But they would change key as soon as I came in!
But things are different now.  How did this person improve?  By singing to our children.
Practice makes perfect.
Comment: I'd consider sight singing to be several orders of difficulty above 'monkey see, monkey do', play a note, sing a note.
Comment: Sight singing involves learning another, quite different skill - reading dots. That's doubling the task !
Comment: @Tetsujin - You might be right.  But natural singing might be the right place to start -- singing a familiar melody.  And then the very early lessons in sightsinging would hopefully build on that.  Using RELATIVE pitch.
Comment: @Tim - But it ingrains the tonic triad and the 5-1 interval, and it connects the imagined sounds and the produced sounds.
Answer: Previous answers here are great and get to the heart of the matter.  The only real way to  get used to finding a note with your voice is to practice.
The thing about practice is, for one thing, you can easily get caught up in practicing mistakes without realizing you are doing so.  This can be an obstacle, but, like everything, can be overcome.  So having a tuner at hand to tell you you are singing the right note (different octaves wont be an issue) is a great idea.
Make a schedule, to practice a certain amount of time every day, and try to keep to it.  DONT MAKE RACTICE SESSIONS SO LONG THAT YOU LOSE INTEREST. Regular short periods of practice are more effective, but do keep challenging yourself.  Start slow and build up speed for a challenge.
So, to clarify.... Use a tuner to check you are not practicing mistakes.. Get plenty of practice (setting up a regime is most effective) And of course, there are plenty of vocal training apps for free that can help you (they very good at making things sink in)
Hope this helps.. eventually your brain will recognize when your voice (the speed of vibrations, the feeling of the note) when it is in sync with the note you are emulating.


Proof that $\sum_{k=1}^n \frac{k}{2^k} < 2 $ for all $n \geq 1$

Question: I recently completed a variation of a problem I found from a mathematical olympiad which is as follows:
Prove that, for all $n \in \mathbb{Z}^+$, $n \geq 1$, $$\sum_{k=1}^n \frac{k}{2^k} < 2 $$
I would like to hear comments on my method of proving the inequality above as well as ways of improving it or making it more rigorous. Thank you!
Proof: We begin by noticing that the series above is a Riemann sum (or approximation by areas of rectangles) for the integral $$ \int_1^n \frac{x}{2^x} dx$$ where the right endpoints are taken, hence $$\sum_{k=1}^n \frac{k}{2^k} < \int_1^n \frac{x}{2^x} dx$$ for all $n$.
By evaluating the original integral, it can be shown that $$ \int_1^n \frac{x}{2^x} dx = \frac{n \ln 2 + 1}{2^n (\ln 2)^2} + \frac{\ln 2 + 1}{2 (\ln 2)^2}$$
As $n$ approaches infinity, the integral approaches the value $\frac{\ln 2 + 1}{2 (\ln 2)^2}$, which is less than $2$. Hence, it can be deduced that $$ \int_1^n \frac{x}{2^x} dx < 2$$ for a large enough $n$.
By inspection and calculation, it is obvious that $$ \int_1^n \frac{x}{2^x} dx < 2$$ when $n > 5, n \in \mathbb{Z}^+$. Hence, when $1 \leq n \leq 5$, the integral has a value that is greater than $2$.
However, it can be verified by calculation that for $1 \leq n \leq 5$, $$\sum_{k=1}^n \frac{k}{2^k} < 2 $$ Since the statement holds true for $1 \leq n \leq 5$ as well as for $n > 5$, where $n \in Z^+$, the statement must be true for all $n \geq 1$. Hence, the proof is complete.
Hope to hear your thoughts on this!
Comment: This is   an sum of an  arithmetico geometric  series,and the value of the sum can be actually found rather than approximating
Comment: Note that for the ratio test, you have that $\sum_{k\geq 1} \frac{k}{2^{k}}$ converges and since that $$\sum_{k\geq 1} \frac{k}{2^{k}}=\sum_{k\geq 0}\frac{k+1}{2^{k+1}}=\frac{1}{2}\sum_{k\geq 1}\frac{k}{2^{k}}+1$$Therefore, $$\sum_{k\geq 1} \frac{k}{2^{k}}=2.$$
Comment: It is important when presenting a solution to be verified that the ideas are as clear as possible and not miss details, to make the review easy. On the other hand, his approach is not transparent to me.
Answer: Note that no calculus is needed:
$$\begin{align*}
\sum_{k=1}^n\frac{k}{2^k}&=\sum_{k=1}^n\sum_{\ell=1}^k\frac1{2^k}\\
&=\sum_{\ell=1}^n\sum_{k=\ell}^n\frac1{2^k}\\
&=\sum_{\ell=1}^n\frac{\frac1{2^{\ell}}-\frac1{2^{n+1}}}{1-\frac12}\\
&=\sum_{\ell=1}^n\left(\frac1{2^{\ell-1}}-\frac1{2^n}\right)\\
&=\sum_{\ell=0}^{n-1}\frac1{2^\ell}-\frac{n}{2^n}\\
&=\frac{1-\frac1{2^n}}{1-\frac12}-\frac{n}{2^n}\\
&=2\left(1-\frac1{2^n}\right)-\frac{n}{2^n}\\
&=2-\frac{n+2}{2^n}\\
&<2\,.
\end{align*}$$
For the visually oriented this has a nice schematic representation:
$$\begin{array}{cccccc|c}
\frac12&\frac14&\frac18&\frac1{16}&\cdots&\frac1{2^n}&2\left(\frac12-\frac1{2^{n+1}}\right)=1-\frac1{2^n}\\
&\frac14&\frac18&\frac1{16}&\cdots&\frac1{2^n}&2\left(\frac14-\frac1{2^{n+1}}\right)=\frac12-\frac1{2^n}\\
&&\frac18&\frac1{16}&\cdots&\frac1{2^n}&2\left(\frac18-\frac1{2^{n+1}}\right)=\frac14-\frac1{2^n}\\
&&&\frac1{16}&\cdots&\frac1{2^n}&2\left(\frac1{16}-\frac1{2^{n+1}}\right)=\frac18-\frac1{2^n}\\
&&&&\ddots&\vdots&\vdots\\
&&&&&\frac1{2^n}&2\left(\frac1{2^n}-\frac1{2^{n+1}}\right)=\frac1{2^{n-1}}-\frac1{2^n}\\\hline
\frac12&\frac2{2^2}&\frac3{2^3}&\frac4{2^4}&\cdots&\frac{n}{2^n}&2\left(1-\frac1{2^n}\right)-\frac{n}{2^n}=2-\frac{n+2}{2^n}
\end{array}$$
Instead of summing the columns to the left of the vertical line to get the terms of the summation and then adding, I've summed the rows of the triangular matrix, each of which is a geometric progression, to get the totals in the righthand column above the horizontal line, and then summed those row sums to get the desired total.
Comment: Nice answer, without using calculus :-)
Comment: Wow, even I never thought of using this method, I'm still having a bit of trouble understanding it but I'm sure I'll get the hang of it soon, thanks!
Comment: @DarrellTan: You're welcome.
Comment: Nice way of interchanging the 'sigma' This is essentially how the sum of an AGP is calculated but this looks different
Comment: This is so beautiful. Thanks MASTER!
Answer: As commented by Albus, the values can be found.
In fact, let $p \in (0,1)$, then
$$\sum_{k=1}^{n}kp^k\le \sum_{k=1}^{\infty}kp^k=p\sum_{k=1}^{\infty}kp^{k-1}=p\frac{d}{dp}\left(\sum_{k=1}^{\infty}p^k\right)=p\frac{d}{dp}\frac{p}{1-p}=\frac{p}{(1-p)^2}.$$
Therefore, when $p=1/2$, the R.H.S. of the above is $2$, which proves your inequality.
In general, you can use integration to estimate the partial sum, as you did in your post.
Comment: I was completely unaware that it was an arithmetico-geometric series until it was mentioned, this is definitely much easier, thanks!
Comment: This shows that the limit is $2$. You also need to add that the sequence is monotone increasing because $kp^k>0$
Answer: There are some major issues.  First, when $n = 1$, the integral is trivially $0$, so you cannot make the claim that $$S(n) = \sum_{k=1}^n \frac{k}{2^k} < \int_{x=1}^n \frac{x}{2^x} \, dx$$ for all $n$.  In fact, this inequality is never true.  I suspect you intended
$$S(n) < \int_{x=0}^n \frac{x}{2^x} \, dx = I(n)$$ but once again this is not true unless $n \ge 5$, and more worrisome is that as $n \to \infty$, $I(\infty) > 2$, so the bound is simply too loose to show that $S(n) < 2$, even if you attempt to patch the reasoning for small cases of $n$.
When we use an integral to bound a sum, the behavior of the summand that is converted to an integrand must be monotone, otherwise you cannot make the argument.  If you study the graph of $y = 2^{-x} x$ on $[0, \infty)$, we see that it is increasing from $x = 0$ to $x = (\log 2)^{-1}$, then decreasing afterward.  This makes your approach fundamentally problematic.
Instead, what I would recommend is either the direct evaluation of $S$, for which there are numerous methods.  This can be accomplished by differentiation of geometric series, e.g. consider $$f(z) = \sum_{k=0}^\infty z^k = \frac{1}{1-z}, \quad |z| < 1,$$ hence $$z f'(z) = \sum_{k=1}^\infty kz^k = \frac{z}{(1-z)^2}.$$  Then $$S(n) < S(\infty) = \left[z f'(z) \right]_{z=1/2} = \frac{1/2}{(1-1/2)^2} = 2$$ with the first inequality a direct consequence of the fact that all terms in $S$ are positive.
Comment: Oh wow, my sincere apologies for not noticing all these discrepancies earlier. I just did some checking and found that the inequality cannot hold true as the sum ends up becoming larger than the integral as n becomes large. I was unaware of the method of using series to evaluate the sum. Guess I should've read up on my calculus more, thanks!
Answer: $$2S_n-S_n=\sum_{k=1}^nk2^{1-k}-\sum_{k=1}^nk2^{-k}=\sum_{k=0}^{n-1}(k+1)2^{-k}-\sum_{k=1}^nk2^{-k}
\\=1-n2^{-n}+\sum_{k=0}^{n-1}2^{-k}<1+1.$$


Laravel SSH Ouput not returning full output content

Question: I'm running the following code using Laravel 4 and the SSH command.
SSH::into('runtime')->run(array(
   'cd /home/ubuntu',
   './update.sh'
), function ($line){

   echo $line.PHP_EOL;

});

The SSH command works absolutely fine and the contents of the update.sh file run. However...
If I run the update.sh script from the command line the output is:
Already up-to-date. (This part of the message depends on the output of git pull)
Stopping nginx: nginx.
Starting nginx: nginx.

What i'm getting returned when running the Laravel code:
nginx.

Is there a way to get the full output or does Laravel trim it in anyway?
Comment: Could you please try executing the script in the current shell, like `. ./update.sh` or `source ./update.sh`? Maybe it just can't capture the subshell output...
Comment: Hi @matpop i've run those two commands and the full output appears.
Comment: Hi ajtrichards, have you tried these commands with Laravel? Does the full output appear with Laravel? Any changes?
Comment: Yeah i've run the commands in Laravel and nothing changes :-(
Answer: Try appending to the command a redirection to send stderr to stdout.
SSH::into('runtime')->run(array(
    'cd /home/ubuntu',
    './update.sh 2>&1'
), function ($line){
    $this->line($line);
});

Answer: The problem that was occurring was that the update.sh was running 3 commands and the Laravel SSH function was only returning the last part of the output as the variable I was using to capture kept getting overwritten.
I created a private variable in my class:
private $output;

Then changed my SSH run code to:
SSH::into('runtime')->run(array(
   'cd /home/ubuntu',
   './update.sh'
), function ($line){

   $this -> output .= $line.PHP_EOL;

});

So for this to work I'm appending the output of $line to my output variable. I can then access my output using:
echo $this -> output;
That printed everything out
Comment: Hi ajtrichards, does this print all the output lines at once? Or is it in real time? Meaning, if you have a set of 4 commands that are pretty hefty in terms of performance, is the returned value (the output) returned right away or is it only after all of the commands are run? For example, creating copies of a set of files, then building a set of HTML files, then back up those files, then sending those files by email, etc.


Display different content on node pages depending on user role

Question: I have a list of items visible for all anonymous user and authenticated user. Then when the user click through, if the user is anonymous, I want to tell them, "sorry must be authenticated". But if they are already authenticated I want to show them the node.
I am using:
if($logged_in) {
   //display node
}

In my node--mycontenttype.tpl.php. How do I make this work?
Comment: This is wrong because: 1. Don't put this kind of logic in templates. 2. You don't really describe what you're trying to do. 3. Don't reinvent the wheel: https://drupal.org/project/nodeaccess does what you want already I think.
Comment: I can not use nodeacces and content_acces, Because I shows the list of items to anonymous users
Comment: Please clarify, then, with some background about what you're attempting to do.
Comment: You might be able to reuse some code from https://github.com/bbinkovitz/foreshadow_menu which is a little proto-module that allows a menu to display items the user lacks permissions for as non-linked text, but only links to them if the user has permission.
Comment: You wouldn't put that in a template though, for many reasons. That would go in a module that defines or alters the list that you show to anonymous users.
Comment: There's also the option of using a block with custom role-based visibility to display the particular information you want to show. Or a panels pane with an access rule. Many options.
Comment: Look I have a list of items visible for all anonymous user and authenticated user. Then when the user click on the title anonymous, sorry must be authenticated. you understand me?
Answer: Showing different content on the same page to user depending on role could be accomplished with the Panels module like so:

Install the Panels module and its dependencies.
Go to admin » structure » panels.
Enable and edit the page "node_view" template.
Click "add new variant".
Click "continue" on each screen until there is a button with "Add variant." Click "Add variant".
Under panel » content, click the gear in the upper left to add a panel of content for the logged in user to see. Save.
Click the gear in the upper right of the new content to get a menu. Select visibility rules » add new rule. Select role and set it how you want. Save.
If you want to show something different to anonymous users, repeat step 6 and 7 to add content and make it visible only to anonymous users.
Don't forget to save.
Answer: Or you can use the Context Module.  Its better for developers, I think panels is better for users.
Comment: Can you explain how one would use Context module for this? I looked at the UI and it was not obvious how that would work.


Using hook_form_FORM_ID_alter to add CSS class to Simple Hierarchical Select

Question: I'm trying to use hook_form_FORM_ID_alter to add a CSS class to one of the select element.
I'm trying to add a CSS class "form-control", to the <select id="edit-shs-term-node-tid-depth-select-1">'s class.
I have added it and even performed drush cc all, but still nothing was added to the class of select.
HTML
 <form action="/properties" method="get" id=
  "views-exposed-form-view-property-page-master" accept-charset="UTF-8" class=
  "jquery-once-1-processed">

            Search

                <input class="form-control form-text" type="text" id="edit-title" name=
                "title" value="" size="30" maxlength="128" />

            Developer

                <select class="form-control form-select" id="edit-field-developer2-tid"
                name="field_developer2_tid">
                  <option value="All" selected="selected">
                    - Any -
                  </option>
                </select>

            Location

              <input class=
              "element-invisible shs-enabled form-control form-text shs-processed"
                type="text" id="edit-shs-term-node-tid-depth" name=
                "shs_term_node_tid_depth" value="All" size="60" maxlength="128" />
                <select id="edit-shs-term-node-tid-depth-select-1" class=
                "shs-select form-select shs-select-level-1" style=
                "display: inline-block;">
                  <option value="0">
                    - None -
                  </option>
                </select>

            Property Type

                <select class="form-control form-select" id=
                "edit-field-property-type-tid" name="field_property_type_tid">
                  <option value="All" selected="selected">
                    - Any -
                  </option>
                </select>

            <button class="btn btn-info form-submit" id="edit-submit-view-property" name=
            "" value="Apply" type="submit">Apply</button>

  </form>

template.php
/*
 * implements hook_form_FORM_ID_alter
 *
 */
function directbootstrap_form_views_exposed_form_view_property_page_master_alter(&$form, &$form_state, $form_id) {

    $form['shs_term_node_tid_depth']['#attributes'][] = array('class' => array('form-control'));
}

EDIT
I have updated my question,
What I'm trying to accomplish is insert a class 'form-control' on to the hierarchical select.  But after inserting dpm($form); inside the function. All I can find is the array for the element shs_term_node_tid_depth but not the <select> itself.
here is my template.php
/**
 * implementation of hook_form_FORM_ID_alter()
 */
function directbootstrap_form_views_exposed_form_alter(&$form, &$form_state, $form_id)
{
 if ($form['#id'] == 'views-exposed-form-view-property-page-master')) {
    $form['shs_term_node_tid_depth']['#attributes']['class'][] = 'form-control';
  }
}

Answer: You need:
$form['shs_term_node_tid_depth']['#attributes'] = array('class' => array('form-control'));

or more succinct version:
$form['shs_term_node_tid_depth']['#attributes']['class'][] = 'form-control';

Comment: Small note - the second one should always be preferred (so you don't wind up removing attributes that another module might have added). This is only half the story though, the form alter isn't even being invoked at the moment
Comment: I tried it but I don't think it worked, tested by changing 'form-control' into 'test-class' no change was reflected. And also I was not trying to insert it to the ` `. Instead I want to add class to the ``
Answer: Views exposed forms are...fun. For example, the form ID you get will always be views_exposed_form, regardless of the ID you see in HTML or anywhere else. So currently your form alter function isn't named quite right.
You need to alter the form by its correct ID on the PHP side, and grab the context from something else in the form, maybe the html ID itself.
So, a rudimentary version of what you're looking for would be
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-view-property-page-master')) {
    $form['shs_term_node_tid_depth']['#attributes']['class'][] = 'form-control';
  }
}

Remember to clear the caches after you've changed the function name.
Comment: Thanks @Clive, for pointing that out. I remember reading somewhere [here](https://api.drupal.org/comment/39503#comment-39503) on using hook_form_FORM_ID_alter with Views.
But what the element I'm trying to add the class into is the ``. Does this mean I can do something like `$form['edit-shs-term-node-tid-depth-select-1']['#attributes']['class'][] = 'form-control';`?
Comment: You can't reference the server side elements by their HTML ID, no...do you have the Devel module installed? If not, get it immediately, and once installed use `dpm($form);` in the alter function. That will show you both that the alter function is definitely being called (an obvious requirement for anything to happen), and will print a nice pretty representation of the `$form` array to the messages area on screen. From there you can easily see the exact array key of the element you're trying to override. In the case of more complex elements like SHS, though, it might be more complicated...
Comment: ...see how you get on with that method first, and if you still get nowhere just update the question and ping me to have a look
Comment: I have made an update to my question.


send a mail if user does not login for a month or so in asp.net c#

Question: In the first project I'm doing i have got a problem. I'm explaining it below.
first a user registers in our website while registering he will choose a reminder period like 1 month or 2 months etc.. when ever user does not log in into our site for that particular period he should get a mail saying that he need to log in
for example if user John registered in our site and chooses 2 months as reminder period. and he logs in on august 1st and did not log in for 2 months then he should get a email on October 1st saying that he need to log in. I don't know how to approach this problem. please give your ideas.
thank you
regards
vinay.J
Comment: Create a scheduler which sends mail after specified period of time.
Comment: Suggestion: treat it as two problems: 1. sending an email, 2. detecting when to send the email. For part 2 consider storing "last login" and "reminder period" with your other user data.
Answer: Here is my advice :

Create a table containing the reminder configuration for each user
Fields : IdUser / ReminderPeriod
Create a windows service running each day at 2am for example. This little windows service will contain all the logic for sending emails
It will compare the last login date of each user with the date of the day + reminded period
Comment: I'm a fresher got my training completed less than aweek. i have been given this task and there are no seniors who can guide me so i put up this question here.. i dont know whether windows sheduler could be used to send a mail on behalf of a website..
Comment: This has to be done by a service. Windows scheduler or Windows service. I will advice you to use the Windows Service written using C#. So you can do whatever you want. Your project is not a big deal dont worry and take your time to study windows services implementation
Answer: You can achieve your problem through window service scheduler. Your scheduler will get info from db, and checks whether user logs in for 1 months, if not then fire mail to user. You can set your scheduler for any time. Say for example you set time interval 30 min. Then after every 30 min. scheduler checks for your user and send mail.
To learn window service see below links:
http://www.aspdotnet-suresh.com/2011/06/creating-windows-service-in-c-or.html
http://www.codeproject.com/Articles/3990/Simple-Windows-Service-Sample
Hope it helps.
Comment: I'm working on web application.. not windows one.. can i use the same solution for web application..?
Comment: yes, you just need to create your service, and install your service, it will work. This is the only way to achieve your work.


GET request equivalente em arquivos separados (controller e route)

Question: Boa noite!
To trabalhando num projeto, e na tela de login após realizar a autenticação(Passportjs), o usuário será redirecionado para a Home page.
Porém, a pouco tempo comecei a adotar alguns novos métodos para organizar melhor a estrutura do programa etc. E estou deixando um arquivo só para rotas (routes) e outro só pra gerenciar as chamadas GET, POST, DELETE, PATCH, PUT (controllers).
Antes de migrar os arquivos para esse novo formato, tudo funcionava normalmente...
Nesse trecho de código que estou com problemas...
Nesse formato funciona tudo normalmente

app.get("/home", isAuth, (req, res) => {
    res.render("home", {
      name: req.user.username
    });
  });

isAuth é um modulo para checar se o usuário está autenticado ou não, e caso esteja, será redirecionado.

module.exports = {
  isAuth: (req, res, next) => {
    if(req.isAuthenticated()) {
      return next();
    } else {
      req.flash("error_msg", "Please, log in to view this page");
      res.redirect("/login");
    }
  }
}

Nesse formato recebo o erro "Cannot GET /home"

// @desc Home Page
// @route GET /home
// @acess Private
exports.getHome = (isAuth),(req, res) => {
  res.render("home", {
    name: req.user.username
  });
};

Alguem sabe dizer o que estou fazendo de errado?
Comment: Como você está importando esse novo módulo? E como está ligando-o no Express?
Comment: Ao que me parece, o erro é na hora que você exporta. Tente exportar um array: `exports.getHome = [isAuth, (req, res) => {
  res.render("home", {
    name: req.user.username
  });
}]`.
Comment: Estou importando desta forma:

const { isAuth } = require("../config/auth");
Answer: O teu problema está na sintaxe de exports.getHome = (isAuth),(req, res) => {. Esse isAuth (que é um middleware) não pode ser exportado dessa maneira.
Podias exportar uma array com essas duas funções e depois usar app.get("/home", ...controlers).
Eu costumo fazer assim:
Rotas:
const {isAuth} = require('./isAuth.js');
const controllers = require('./controllers.js');
app.get("/home", isAuth, controllers.getHome);
app.get("/store", isAuth, controllers.getStore);

isAuth.js:
module.isAuth = (req, res, next) => {
  if(req.isAuthenticated()) {
    return next();
  } else {
    req.flash("error_msg", "Please, log in to view this page");
    res.redirect("/login");
  }
}

controllers.js:
exports.getHome = (req, res) => {
  res.render("home", {
    name: req.user.username
  });
};
exports.getStore = (req, res) => {
  res.render("store", {
    name: req.user.username,
    items: db.userItems // só um exemplo
  });
};

Comment: Deu certo! Obrigado!
Comment: No arquivo das rotas está assim:
// Home Page
router
  .route("/home")
  .get(getHome);
Answer: Aaaaah consegui!
Com as informações que vcs passaram fiz umas alterações e deu boa!
isAuth.js (middleware)

module.exports = {
  isAuth: (req, res, next) => {
    if(req.isAuthenticated()) {
      return next();
    } else {
      req.flash("error_msg", "Please, log in to view this page, yo!");
      res.redirect("/login");
    }
  }
}

Rotas

const express = require("express");
const { getHome } = require("../controllers/users");
const { isAuth } = require("../config/auth");

// Home Page
router
  .route("/home")
  .get(isAuth, getHome);

users.js (Controller)

const express = require("express");
const router = express.Router();

// @desc Home Page
// @route GET /home
// @acess Private
exports.getHome = (req, res, next) => {
  res.render("home", {
    name: req.user.username
  });
};

:D