text:
Q: Unigine Heaven run directly from terminal? I think a lot of you would have benchmarked your Linux system using Unigine Heaven Benchmark 4.0. I know to run the it you can simply go to the Unigine Heaven folder and run the shell script file using "./heaven". And then the settings window will open in which you configure and click on "Run" button. What I want to do is from shell script. All I want is to know if there is some way I can modify the script so that it doesn't show the Settings window where I need to click "Run" but directly starts the Benchmarking using the default settings.
So can anyone please let me know the modification in the script so that I can just run the script and no intermediate settings window appears rather benchmarking starts directly..?
Also is there some keyboard shortcut to "Run" i.e. I press some combination of keys and benchmarking starts.
Thanks

A: The benchmark is deliberately hobbled so so cannot be scripted to run.
This was done to "encourage" people to buy the pro or advanced licenses.
You can automate the mouse and keyboard to do things so you could fake it... But you have to monitor where things actually are. A lot of trial and error is required. Here's a little snippet that just clicks the Run button:
xdotool mousemove --window $(xdotool search heaven) 620 420 click 1

If you want to do anything serious though it seems likely that the $15 license will be the cheaper option (unless your time is worthless).


text:
Q: Как делать шкалу громкости в PyQt5 и при изменении менять ее громкость на ту, которую указал пользователь Мне нужно, чтобы при нажатии на кнопку Настройки громкости открывалось меню, где была шкала громкости и при её изменении менялась громкость всех звуков, и эти настройки сохранялись.
Мой код:
#!/usr/bin/python3
import sys
from PyQt5 import QtWidgets, QtGui, QtCore, QtMultimedia
from PyQt5.Qt import *

try:
    from PyQt5.QtWinExtras import QtWin
    myappid = 'mycompany.myproduct.subproduct.version'
    QtWin.setCurrentProcessExplicitAppUserModelID(myappid)
except ImportError:
    pass

class Button(QPushButton):
    mouseMoved = pyqtSignal()
    def mouseMoveEvent(self, event):
        self.mouseMoved.emit()

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        def Button(btn_name, text, color1, px, resize, resize_2, move, move_2, color):
            btn_name.setMouseTracking(True);
            btn_name.setText(text)
            btn_name.setStyleSheet(
                "background-color: " + color1 + "; color: " + color + "; border-radius: " + str(px) + "px")
            btn_name.setFont(QtGui.QFont('MS Serif', 14))
            btn_name.resize(resize, resize_2)
            btn_name.move(move, move_2)
            #btn_name.clicked.connect(mains)

        def Button_2(btn_name, text, px, resize, resize_2, move, move_2, color, size):
            btn_name.setMouseTracking(True);
            btn_name.setText(text)
            btn_name.setStyleSheet(
                "color: " + color + "; border-radius: " + str(px) + "px")
            btn_name.setFont(QtGui.QFont('Gabriola', size))
            btn_name.resize(resize, resize_2)
            btn_name.move(move, move_2)
            #btn_name.clicked.connect(mains)

        def Button_3(btn_name, text, px, resize, resize_2, move, move_2, color, mains):
            btn_name.setMouseTracking(True);
            btn_name.setText(text)
            btn_name.setStyleSheet(
                "color: " + color + "; border-radius: " + str(px) + "px")
            btn_name.setFont(QtGui.QFont('MS Serif', 14))
            btn_name.resize(resize, resize_2)
            btn_name.move(move, move_2)
            btn_name.clicked.connect(mains)

        def Image(lbl_name, move_1, move_2, resize_1, resize_2):
            lbl_name.setPixmap(self.pix)
            lbl_name.move(move_1, move_2)
            lbl_name.resize(resize_1, resize_2)

        self.lbl2 = QtWidgets.QLabel(self)
        self.pix = QtGui.QPixmap("image.jpg")
        Image(self.lbl2, 0, 0, 1920, 1080)
        self.lbl1 = QtWidgets.QLabel(self)
        self.pix = QtGui.QPixmap("System_image/textbox.png")
        Image(self.lbl1, 0, 800, 1920, 300)
        self.btn1 = QPushButton(self)

        Button_2(self.btn1, "Вы появились в неизвестном вам месте,\nгде было невероятно красиво", 10, 1000, 200, 430, 830, "White", 30)
        self.btn3 = QPushButton(self)
        Button_2(self.btn3, "", 10, 150, 100, -30, 500, "White", 14)
        self.inv = QtWidgets.QLabel(self)
        self.pix = QtGui.QPixmap("Button_image/inventory_btn.png")
        Image(self.inv, -30, 600, 156, 96)
        self.btn31 = QPushButton(self)
        Button_3(self.btn31, "", 0, 100, 100, 0, 600, "White", self.inventory)
        self.inv_open = QtWidgets.QLabel(self)
        self.pix = QtGui.QPixmap("Button_image/inventory.png")
        Image(self.inv_open, 70, 40, 1770, 996)
        self.inv_open.close()
        self.btn4 = QPushButton(self)
        Button_3(self.btn4, "", 5, 100, 100, 1650, 110, "White", self.inventory_close)
        self.btn4.close()
        self.lbl20 = QtWidgets.QLabel(self)
        self.pix = QtGui.QPixmap("System_image/Selection_menu.png")
        Image(self.lbl20, 0, 0, 1920, 1080)
        self.lbl20.close()
        self.mg_open = QtWidgets.QLabel(self)
        self.pix = QtGui.QPixmap("Button_image/Magazine.png")
        Image(self.mg_open, -30, 480, 156, 96)
        self.btn5 = QPushButton(self)
        Button_3(self.btn5, "", 0, 100, 100, 0, 480, "White", self.event_log)
        self.btn6 = QPushButton(self)
        Button_3(self.btn6, "", 0, 460, 800, 160, 100, "White", self.notes)
        self.btn6.close()
        self.btn7 = QPushButton(self)
        Button_3(self.btn7, "", 0, 460, 800, 700, 100, "White", self.easter)
        self.btn7.close()
        self.btn8 = QPushButton(self)
        Button_3(self.btn8, "", 0, 460, 800, 1260, 100, "White", self.tasks)
        self.btn8.close()
        self.notes_open = QtWidgets.QLabel(self)
        self.pix = QtGui.QPixmap("The_event_log/Notes.png")
        Image(self.notes_open, 0, 0, 1920, 1080)
        self.notes_open.close()
        self.btn9 = QPushButton(self)
        Button_3(self.btn9, "", 5, 80, 80, 1730, 50, "White", self.inventory_close)
        self.btn9.close()
        self.easter_open = QtWidgets.QLabel(self)
        self.pix = QtGui.QPixmap("The_event_log/Easter.png")
        Image(self.easter_open, 0, 0, 1920, 1080)
        self.easter_open.close()
        self.btn10 = QPushButton(self)
        Button_3(self.btn10, "", 5, 80, 80, 1730, 50, "White", self.inventory_close)
        self.btn10.close()

        self.tasks_open = QtWidgets.QLabel(self)
        self.pix = QtGui.QPixmap("The_event_log/Tasks.png")
        Image(self.tasks_open, 0, 0, 1920, 1080)
        self.tasks_open.close()
        self.btn11 = QPushButton(self)
        Button_3(self.btn11, "", 5, 80, 80, 1730, 50, "White", self.inventory_close)
        self.btn11.close()

        self.lbl2.close()
        self.btn31.close()
        self.btn1.close()
        self.lbl1.close()
        self.inv.close()
        self.mg_open.close()
        self.btn5.close()
        self.btn6.close()
        self.btn_start = QPushButton(self)
        Button_3(self.btn_start, "Начать", 20, 300, 100, 800, 400, "Black", self.start)
        self.btn_select = QPushButton(self)
        Button_3(self.btn_select, "Настройки громкости", 20, 300, 100, 800, 520, "Black", self.volume_custom)

    def inventory(self):
        self.btn31.close()
        self.btn1.close()
        self.lbl1.close()
        self.inv.close()
        self.inv_open.show()
        self.btn4.show()
        self.mg_open.close()
        self.btn5.close()
        self.btn6.close()

    def inventory_close(self):
        self.btn3.show()
        self.btn1.show()
        self.lbl1.show()
        self.inv.show()
        self.inv_open.close()
        self.btn4.close()
        self.notes_open.close()
        self.btn9.close()
        self.mg_open.show()
        self.btn5.show()
        self.btn6.close()
        self.btn7.close()
        self.btn8.close()
        self.easter_open.close()
        self.btn10.close()
        self.btn11.close()
        self.tasks_open.close()
        self.btn31.show()

    def animations(self):
        animation = QPropertyAnimation(self)
        animation.setTargetObject(self.btn_name)
        animation.setPropertyName(b'pos')
        animation.setStartValue(QPoint(250, -200))
        animation.setEndValue(QPoint(250, 0))
        animation.setDuration(500)
        animation.start()

    def event_log(self):
        self.btn31.close()
        self.btn3.close()
        self.btn1.close()
        self.lbl1.close()
        self.inv.close()
        self.btn5.close()
        self.mg_open.close()
        self.lbl20.show()
        self.btn6.show()
        self.btn7.show()
        self.btn8.show()

    def notes(self):
        self.lbl20.close()
        self.notes_open.show()
        self.btn9.show()

    def easter(self):
        self.lbl2.close()
        self.easter_open.show()
        self.btn10.show()

    def tasks(self):
        self.lbl2.close()
        self.tasks_open.show()
        self.btn11.show()

    def start(self):
        self.btn3.show()
        self.btn1.show()
        self.lbl1.show()
        self.inv.show()
        self.inv_open.close()
        self.btn4.close()
        self.notes_open.close()
        self.btn9.close()
        self.mg_open.show()
        self.btn5.show()
        self.btn6.close()
        self.btn7.close()
        self.btn8.close()
        self.easter_open.close()
        self.btn10.close()
        self.btn11.close()
        self.tasks_open.close()
        self.btn31.show()
        self.lbl2.show()

    def volume_custom(self):
        #тут действие, но я поставил print что бы не выдавал ошибку
        print()

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    app.setWindowIcon(QtGui.QIcon('icon.png'))
    ex = MainWindow()
    ex.setWindowTitle('Story Telling')
    ex.setWindowIcon(QIcon('System_image/icon.png'))
    ex.showFullScreen()
    ex.show()
    filename = 'music.mp3'
    fullpath = QtCore.QDir.current().absoluteFilePath(filename)
    url = QtCore.QUrl.fromLocalFile(fullpath)
    content = QtMultimedia.QMediaContent(url)
    player = QtMultimedia.QMediaPlayer()
    player.setMedia(content)
    player.play()
    sys.exit(app.exec_())

A: Sorry, ваш код очень тяжелый, в нем присутствует много ненужных вещей.
Вы также используете не очень понятные функции для заполнения
объектов виджетов (def Button(), def Button_2() и т.д).
Вы используете абсолютное позиционирование виджетов, например:
        btn_name.resize(resize, resize_2)
        btn_name.move(move, move_2)

и поэтому на своем экране я не вижу полную картину окна вашего приложения,
кроме текста названия кнопок "Начать" и "Настройки громкости".
Вам надо изучить раздел Layout Management
и использовать менеджеры компоновки в своем приложении.
Вы злоупотребляете использованием:
self.widget.show()
self.widget.close()

это очень затратные операции и так их использовать не правильно.

Теперь по сути вопроса.
Я создал объект слайдер для изменения громкости:
self.slider = QSlider(Qt.Horizontal, self)
...

который отображается при нажатии на кнопку "Настройки громкости"
и скрывается при повторном нажатии на эту же кнопку.
ВНИМАНИЕ, после нажатия на кнопку "Начать" слайдер перекрывается
какой-то label и с ним невозможно взаимодействовать.
Поэтому вам надо его как-то разместить по другому или
как я уже писал выше использовать размещение виджетов в Layout Management.

import sys
from PyQt5 import QtWidgets, QtGui, QtCore, QtMultimedia
from PyQt5.Qt import *

# ??? зачем вам это ???
# https://doc.qt.io/qt-5/qtwin-obsolete.html#setCurrentProcessExplicitAppUserModelID
# Эта функция устарела. Он предназначен для сохранения работоспособности
# старого исходного кода. Мы настоятельно не рекомендуем использовать его в новом коде.
# ???try:
# ???    from PyQt5.QtWinExtras import QtWin
# ???    myappid = 'mycompany.myproduct.subproduct.version'
# ???    QtWin.setCurrentProcessExplicitAppUserModelID(myappid)
# ???except ImportError:
# ???    pass

# ??? зачем вам это ???
# вы это негде не используете
# ???class Button(QPushButton):
# ???    mouseMoved = pyqtSignal()
# ???    def mouseMoveEvent(self, event):
# ???        self.mouseMoved.emit()

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

# +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
#       filename = 'music.mp3'                          # установите свое music.mp3
        filename = 'D:/_Qt/Mp3/zvuki_prirody-td.wav'

        fullpath = QtCore.QDir.current().absoluteFilePath(filename)
        url = QtCore.QUrl.fromLocalFile(fullpath)
        content = QtMultimedia.QMediaContent(url)
        self.player = QtMultimedia.QMediaPlayer()
        self.player.setMedia(content)
        self.player.setVolume(50.0)
        self.player.play()

        self.slider = QSlider(Qt.Horizontal, self)
        self.slider.setRange(0, 100)
        self.slider.setValue(50)
        self.slider.setGeometry(800, 620, 300, 70)
        self.slider.hide()
        self.slider.valueChanged.connect(self.player.setVolume)
# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

        def Button(btn_name, text, color1, px, resize, resize_2, move, move_2, color):
            btn_name.setMouseTracking(True);
            btn_name.setText(text)
            btn_name.setStyleSheet(
                "background-color: " + color1 + "; color: " + color + "; border-radius: " + str(px) + "px")
            btn_name.setFont(QtGui.QFont('MS Serif', 14))
            btn_name.resize(resize, resize_2)
            btn_name.move(move, move_2)
            #btn_name.clicked.connect(mains)

        def Button_2(btn_name, text, px, resize, resize_2, move, move_2, color, size):
            btn_name.setMouseTracking(True);
            btn_name.setText(text)
            btn_name.setStyleSheet(
                "color: " + color + "; border-radius: " + str(px) + "px")
            btn_name.setFont(QtGui.QFont('Gabriola', size))
            btn_name.resize(resize, resize_2)
            btn_name.move(move, move_2)
            #btn_name.clicked.connect(mains)

# !!!   self.btn_select, "Настройки громкости", 20, 300, 100, 800, 520, "Black", self.volume_custom
        def Button_3(btn_name, text, px, resize, resize_2, move, move_2, color, mains):
            btn_name.setMouseTracking(True);
# !!!
# +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
            if text == "Настройки громкости":
                btn_name.setCheckable(True)
                btn_name.setText(f'{text}: ({self.slider.value()})')
            else:
                btn_name.setText(text)
# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

            btn_name.setStyleSheet(
                "color: " + color + "; border-radius: " + str(px) + "px")
            btn_name.setFont(QtGui.QFont('MS Serif', 14))
            btn_name.resize(resize, resize_2)
            btn_name.move(move, move_2)
            btn_name.clicked.connect(mains)

        def Image(lbl_name, move_1, move_2, resize_1, resize_2):
            lbl_name.setPixmap(self.pix)
            lbl_name.move(move_1, move_2)
            lbl_name.resize(resize_1, resize_2)

        self.lbl2 = QtWidgets.QLabel(self)

        self.pix = QtGui.QPixmap("lena.jpg")
        Image(self.lbl2, 0, 0, 1920, 1080)

        self.lbl1 = QtWidgets.QLabel(self)
        self.pix = QtGui.QPixmap("ball.png")
        Image(self.lbl1, 0, 800, 1920, 300)
        self.btn1 = QPushButton(self)
        Button_2(self.btn1, "Вы появились в неизвестном вам месте,\nгде было невероятно красиво", 10, 1000, 200, 430, 830, "White", 30)
        self.btn3 = QPushButton(self)
        Button_2(self.btn3, "", 10, 150, 100, -30, 500, "White", 14)
        self.inv = QtWidgets.QLabel(self)
        self.pix = QtGui.QPixmap("ball.png")
        Image(self.inv, -30, 600, 156, 96)
        self.btn31 = QPushButton(self)
        Button_3(self.btn31, "", 0, 100, 100, 0, 600, "White", self.inventory)
        self.inv_open = QtWidgets.QLabel(self)
        self.pix = QtGui.QPixmap("ball.png")
        Image(self.inv_open, 70, 40, 1770, 996)
        self.inv_open.close()
        self.btn4 = QPushButton(self)
        Button_3(self.btn4, "", 5, 100, 100, 1650, 110, "White", self.inventory_close)
        self.btn4.close()
        self.lbl20 = QtWidgets.QLabel(self)
        self.pix = QtGui.QPixmap("ball.png")
        Image(self.lbl20, 0, 0, 1920, 1080)
        self.lbl20.close()
        self.mg_open = QtWidgets.QLabel(self)
        self.pix = QtGui.QPixmap("ball.png")
        Image(self.mg_open, -30, 480, 156, 96)
        self.btn5 = QPushButton(self)
        Button_3(self.btn5, "", 0, 100, 100, 0, 480, "White", self.event_log)
        self.btn6 = QPushButton(self)
        Button_3(self.btn6, "", 0, 460, 800, 160, 100, "White", self.notes)
        self.btn6.close()
        self.btn7 = QPushButton(self)
        Button_3(self.btn7, "", 0, 460, 800, 700, 100, "White", self.easter)
        self.btn7.close()
        self.btn8 = QPushButton(self)
        Button_3(self.btn8, "", 0, 460, 800, 1260, 100, "White", self.tasks)
        self.btn8.close()
        self.notes_open = QtWidgets.QLabel(self)
        self.pix = QtGui.QPixmap("ball.png")
        Image(self.notes_open, 0, 0, 1920, 1080)
        self.notes_open.close()
        self.btn9 = QPushButton(self)
        Button_3(self.btn9, "", 5, 80, 80, 1730, 50, "White", self.inventory_close)
        self.btn9.close()
        self.easter_open = QtWidgets.QLabel(self)
        self.pix = QtGui.QPixmap("ball.png")
        Image(self.easter_open, 0, 0, 1920, 1080)
        self.easter_open.close()
        self.btn10 = QPushButton(self)
        Button_3(self.btn10, "", 5, 80, 80, 1730, 50, "White", self.inventory_close)
        self.btn10.close()

        self.tasks_open = QtWidgets.QLabel(self)
        self.pix = QtGui.QPixmap("ball.png")
        Image(self.tasks_open, 0, 0, 1920, 1080)
        self.tasks_open.close()
        self.btn11 = QPushButton(self)
        Button_3(self.btn11, "", 5, 80, 80, 1730, 50, "White", self.inventory_close)
        self.btn11.close()

        self.lbl2.close()
        self.btn31.close()
        self.btn1.close()
        self.lbl1.close()
        self.inv.close()
        self.mg_open.close()
        self.btn5.close()
        self.btn6.close()

        self.btn_start = QPushButton(self)
        Button_3(self.btn_start, "Начать", 20, 300, 100, 800, 400, "Black", self.start)
# !!!
        self.btn_select = QPushButton(self)
        Button_3(self.btn_select, "Настройки громкости", 20, 300, 100, 800, 520, "Black", self.volume_custom)

    def inventory(self):
        self.btn31.close()
        self.btn1.close()
        self.lbl1.close()
        self.inv.close()
        self.inv_open.show()
        self.btn4.show()
        self.mg_open.close()
        self.btn5.close()
        self.btn6.close()

    def inventory_close(self):
        self.btn3.show()
        self.btn1.show()
        self.lbl1.show()
        self.inv.show()
        self.inv_open.close()
        self.btn4.close()
        self.notes_open.close()
        self.btn9.close()
        self.mg_open.show()
        self.btn5.show()
        self.btn6.close()
        self.btn7.close()
        self.btn8.close()
        self.easter_open.close()
        self.btn10.close()
        self.btn11.close()
        self.tasks_open.close()
        self.btn31.show()

    def animations(self):
        animation = QPropertyAnimation(self)
        animation.setTargetObject(self.btn_name)
        animation.setPropertyName(b'pos')
        animation.setStartValue(QPoint(250, -200))
        animation.setEndValue(QPoint(250, 0))
        animation.setDuration(500)
        animation.start()

    def event_log(self):
        self.btn31.close()
        self.btn3.close()
        self.btn1.close()
        self.lbl1.close()
        self.inv.close()
        self.btn5.close()
        self.mg_open.close()
        self.lbl20.show()
        self.btn6.show()
        self.btn7.show()
        self.btn8.show()

    def notes(self):
        self.lbl20.close()
        self.notes_open.show()
        self.btn9.show()

    def easter(self):
        self.lbl2.close()
        self.easter_open.show()
        self.btn10.show()

    def tasks(self):
        self.lbl2.close()
        self.tasks_open.show()
        self.btn11.show()

# !!!
    def start(self):
        self.btn3.show()
        self.btn1.show()
        self.lbl1.show()
        self.inv.show()
        self.inv_open.close()
        self.btn4.close()
        self.notes_open.close()
        self.btn9.close()
        self.mg_open.show()
        self.btn5.show()
        self.btn6.close()
        self.btn7.close()
        self.btn8.close()
        self.easter_open.close()
        self.btn10.close()
        self.btn11.close()
        self.tasks_open.close()
        self.btn31.show()
        self.lbl2.show()

# !!!
# +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    def volume_custom(self):
        #тут действие, но я поставил print что бы не выдавал ошибку
        sender = self.sender()
        print(f'def volume_custom(): {sender.text()} - {sender.isChecked()}')

        if sender.isChecked():
            self.slider.show()
        else:
            self.slider.hide()

        sender.setText(f'Настройки громкости: ({self.slider.value()})')
# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    app.setWindowIcon(QtGui.QIcon('Ok.png'))
    ex = MainWindow()
    ex.setWindowTitle('Story Telling')
    ex.setWindowIcon(QIcon('Ok.png'))
    ex.showFullScreen()
    ex.show()

    sys.exit(app.exec_())

Вот окно, которое я вижу у себя, с установкой всех своих изображений.
А теперь замените все изображения на свои и попробуйте.

redpajama_set_name: RedPajamaStackExchange


text:
Q: URL rewrite apache my problem today is to rewriting URL with apache on local wamp.
I've a page like:
localhost/TEST/index.php

I would like this page like:
localhost/TEST/index

I pass this step with:
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^index$ /TEST/index.php [L,QSA,NC]

The problem is I would like when I type localhost/TEST/index.php the url is redirect to localhost/TEST/index
How can i do that please?
Thx

A: Did you resolve your problem? if not, try this :
RewriteRule ^Test/test$ Test/index.php [L]


text:
Q: Extracting data from hgt files? SRTM3 .hgt files have 1201*1201 DEM elevation data, I extract .hgt files data elevation into file Elevation.json with index.js with the help from this GitHub project.
Then I rename Elevation.json into Elevation.txt, replacing all ],[ from inside the converted .hgt file in json array into ]^l[ with MS Word to get each row from json at new line.
Finally, I import this .txt file into .xlsx file with "comma" as separating delimiter.
I expect as final result in Excel, just 2101 rows and 2101 columns.
Why is there an error always at these cells?
I shortcuted the first and the last 3 columns and the first and the last 2 rows to show you the result
.
Note: blank cells = no found data.
I tried different .hgt file from world wide, the problem still exist.

A: I think it is bug in index.js. I just replicate what you did but differently, and got to the same result:
I run index.js in a .hgt file, then replaced the "],[" by new lines and removed any extra "[" or "]" doing
cat heights.json | sed 's/\],\[/\n/g' | tr -d ']' | tr -d '[' > heights.csv

Then loading the csv in matlab in fact produced an error of inconsistency in the number of columns per row.
By counting the number of commas per line using:
sed 's/[^,]//g' heights+cr.txt | awk '{ print length }'

It indeed show that the first row has 1202 columns, the last 1200 columns and all the rest 1201 columns.
However, after loading the same .htg file directly in Matlab, it produce a nice 1201x1201 matrix.
You can load it directly in Matlab with the following code:
fileID=fopen('S40W067.hgt','r');% Replace by your HTG file
data = fread(fileID,[1201,1300],'uint16',0,'b');
fclose(fileID);

If you rather python, this question show some code examples.
By looking at the data from index.js and from Matlab, it seem that if you move the extra element at the end of row one, to be the first of row two, and then the last of two to be the first of the third row and so on, you will end up with the correct 1201x1201 data matrix.


text:
Q: How to enable/view hidden tabs in magento admin panel? I need to enable the SSL certificate through my magento admin panel. The SSL certificate is already installed on the server. Some of the tabs in configuration menu (web, currency etc) are hidden or disabled by the previous website developer. I cannot see the 'WEB' option under 'GENERAL' tab in the configuration menu. Could anyone help me please how to enable the hidden tabs?

A: If you have database access, you can change the role of current user in table admin_role in row role_type.

A: If you are unable to view the web tab inside general it may be due to several reasons
1) you are login not as admin in magento admin section.
2) The tab must be disable programmatically from core.
Hope it helps you
THanks,


text:
Q: GWT DatePicker to show specific day of the Week How do I show only a particular day of the week in gwt-datePicker ?
E.g
If I select January or any month of the year, I want to see only "Tuesdays" for that month.
Cheers
Prince

A: Short answer: With the default component you cannot.
I would recommend you to create your own widget. Remember that GWT doesn't have support for the Calendar Object, so you'll need to do your own calculations.

A: I had a similar requirement once where the datepicker popup needed to show the week number in an additional column. Since you cannot subclass/override all the necessary behaviour of the standard classes, there was nothing for it in the end but to rip out the source code and create a new implementation with minor changes.
As for date calculations, there is a port of joda time which you can import client-side. Quite a bit of overkill if you only need the day of the week, though.
http://code.google.com/p/gwt-time/


text:
Q: Unable to SSH into Centos server unless root user I have a digital ocean droplet that currently allows me to login directly via the root user via SSH as the relevant keys have been added to the authorized_keys file.
ssh root@master // this works fine and i'm logged in as root

The problem comes when I try to login as a normal non-root user - I have the following output below when I run the following command:
Note I have added the relevant keys for 'bobby' to both the root authorized_keys file & the users authorized_keys file but am unable to login - any ideas?
Note - this is on a Centos server - it keeps returning the error
Permission denied (publickey,gssapi-keyex,gssapi-with-mic).
ssh bobby@master -vT
OpenSSH_7.6p1 Ubuntu-4ubuntu0.3, OpenSSL 1.0.2n  7 Dec 2017
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to master [123.456.789.111] port 22.
debug1: Connection established.
debug1: identity file /home/bobby/.ssh/id_rsa type 0
debug1: key_load_public: No such file or directory
debug1: identity file /home/bobby/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/bobby/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/bobby/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/bobby/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/bobby/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/bobby/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/bobby/.ssh/id_ed25519-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.6p1 Ubuntu-4ubuntu0.3
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.4
debug1: match: OpenSSH_7.4 pat OpenSSH* compat 0x04000000
debug1: Authenticating to master:22 as 'bobby'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:TLaJd7HJk3UVeqzrBgrQq6FfT1P20ZYAO918vRgU9Xg
debug1: Host 'master' is known and matches the ECDSA host key.
debug1: Found key in /home/bobby/.ssh/known_hosts:17
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<rsa-sha2-256,rsa-sha2-512>
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic
debug1: Next authentication method: gssapi-keyex
debug1: No valid Key exchange context
debug1: Next authentication method: gssapi-with-mic
debug1: Unspecified GSS failure.  Minor code may provide more information
No Kerberos credentials available (default cache: FILE:/tmp/krb5cc_1000)

debug1: Unspecified GSS failure.  Minor code may provide more information
No Kerberos credentials available (default cache: FILE:/tmp/krb5cc_1000)

debug1: Next authentication method: publickey
debug1: Offering public key: RSA SHA256:1vSLjFQBt1RFnBAwsTqBRE6RWQM0lDyqBdIRblVhkk8 /home/bobby/.ssh/id_rsa
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic
debug1: Trying private key: /home/bobby/.ssh/id_dsa
debug1: Trying private key: /home/bobby/.ssh/id_ecdsa
debug1: Trying private key: /home/bobby/.ssh/id_ed25519
debug1: No more authentication methods to try.
bobby@master: Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

A: In general: you can only debug so much from the client side; check the logs on the remote server too.
Typically sshd wil log why it refused access in /var/log/secure. (Fairly typical are ownership and permission problems on the  ~/.ssh/authorized_keys.)

A:
Offering public key: RSA SHA256:1vSLjFQBt1RFnBAwsTqBRE6RWQM0lDyqBdIRblVhkk8 /home/bobby/.ssh/id_rsa
Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic
d

That says it all. You have only enabled publickey authentication. Make sure you have valid authorized_keys for user since your rsa is rejected.
authorized_keys should be owned by user and chmod 700

A: As root on your Linux box, check to see the file "/etc/ssh/sshd_config" for a line of "AllowUsers".
Add there the users you want to be able to SSH and then run "service sshd restart".
Also, you may want to add that user to the SUDO'ers.


text:
Q: Programmatically know if the current font has the powerline patch I use vim with vim-airline that can use patched fonts for additional awesomeness.

I also use fish shell (if you want read zsh here since it is equivalent for the analysis) with a theme that also uses patched fonts.
I save my dotfiles online and I use them in different systems. But in some of them I don't have a patched font.
I would really love to have generic dotfiles that for example do not use a theme that needs patched font if the current font is not patched. Also in my vimrc I disabled the use of patched characters for vim-airline because of this.
Is there a way to programmatically know if the font that is currently in use is a patched one so that is possible to write generic dotfiles that fit perfectly in all the situations?

A: In Vim, you would need to directly ask your terminal emulator what font it is currently using. The exact method will certainly be different from terminal to terminal and from OS to OS. If that's even possible.
If you have it on all your systems, you could use lsof to find what font is currently used by a given program:
$ lsof | grep iTerm | grep '\.\(otf\|ttf\)'

In GVim/MacVim, you would check if the current font name matches some pattern with something like:
if &guifont =~? 'powerline'
    " do something
else
    " do something else
endif

And that's assuming your font's filename contains that pattern.
But it's impossible to guarantee that an actual "powerline font" has powerline in its file name and it's equally impossible to guarantee that a font with powerline in its file name is an actual "powerline font".
It would be safer to check for the presence of the Powerline string somewhere in the font with something like:
$ xxd ~/Downloads/FuraMono-Bold\ Powerline.otf | grep Powerline

But that's assuming:

*

*xxd is available,

*you were able to derive the path of the actual font from whatever info you managed to gather from your terminal emulator or from GVim/MacVim.

That's a lot of assumptions and seemingly a lot of work for something as superficial as a "powerline font".

A: You can do this the other way around and only enable Powerline fonts for known machines in your .vimrc e.g.
let hostname = substitute(system('hostname'), '\n', '', '')
let patched_font_hosts = ['host1', 'host2', 'host3']   " List of know patched hosts
if(index(patched_font_hosts, hostname) >= 0)
  let g:airline_powerline_fonts = 1
endif

It's easier to know which hosts you have patched and it's not a really a problem if the list is not up to date.


text:
Q: Characterization of Volumes of Lattice Cubes Here is a problem that came up in a conversation with a professor. I do not know if he knew the answer (and told me none of it) and has since passed so I can no longer ask him about it.
Let $C$ be a lattice cube in $\mathbb{R}^n$. Characterize all possible volumes for $C$. A cube is called a lattice cube if and only if every vertex has integer coordinates.
I broke this proof into three cases, the last of which I am having trouble with in one direction. We will let $V(n)$ be the set of all numbers $V$ for which there exists a lattice cube of volume $V$ in dimension $n$. We will break into three cases based on the value mod 4.
\begin{align*}
V(2k+1)&=\{a^n:a\in\mathbb{N}\} \\
V(4k)&=\{a^\frac{n}{2}:a\in\mathbb{N}\} \\
V(4k+2)&\supseteq\{(a^2+b^2)^\frac{n}{2}:a,b\in\mathbb{N}\}
\end{align*}
These statements I have proven, and conjecture that the last one is an equality. I've been trying to use a collapsing dimension argument to show if I can make a cube of side length $s$ in $\mathbb{R}^{4k+2}$ then I can in $\mathbb{R}^{4k-2}$, at which point the theorem follows since I have proven the special case of $n=2$ (which is quite trivial - there is no way to write down a square whose volume is not of the specified form in $2$D.
The above assertions (sans my conjecture) are proven here

A: An excellent, but theoretically advanced proof can be found here at my cross-post to MO, thanks to Noam D. Elkies.


text:
Q: Should I install the Windows 8 Developer Preview on top of Windows 7? I've installed the Windows 8 Developer Preview on a separate partition, and it seems fine enough to keep. Now I'm wondering if it's worth installing on top of my original installation.
I really don't want to mess up my original installation, so I have a few questions:

*

*Has anyone already done this?

*Is doing so a bad idea?

*Is it easy to go back if I don't like it?

*Does it expire at any time?

A: How good is your backup system?  If, and/or when it does blow up will you be able to easily go back?  Are you willing to accept that you will almost certainly have to reinstall Windows when then next release or patch comes out?  Do you have the tools and ability to actually backup your data under Windows 8, so if you have to re-install, you can accept that and do it easily?
Microsoft did not support converting from any of the pre-released versions of Vista/7 to a full version. I don't believe there is any reason why you should expect them to support it here.  Microsoft doesn't even support using a pre-release of service packs, and this has cause problems for many people in the past.
Based on Microsoft's past release behavior, if you try to use this as your main OS, you will basically be at a dead end from a upgrade standpoint.  Your system will almost certainly not be getting security updates, you may not have any ability to update or anything.  You will not be able to patch or anything.
The dialog you clicked past when you downloaded it had this to say.

The Windows Developer Preview is a pre-beta version of Windows 8 for
  developers. These downloads include prerelease software that may
  change without notice. The software is provided as is, and you bear
  the risk of using it. It may not be stable, operate correctly or work
  the way the final version of the software will. It should not be used
  in a production environment.

and

You can't uninstall the Windows Developer Preview. To reinstall your
  previous operating system, you must have restore or installation
  media.

A: Simple answer... No! You should not install it on top of an older version of Windows.
Has anyone already done this by any chance?
Yes - This guy did and he regretted his actions.
Is doing so a bad idea?
Yes  - It isn't even beta yet. Even then it's not a good idea.
Is it easy to go back, if I don't like it?
No -  It's not possible.

A: I did it!
I installed Windows 8 over Windows 7.  Technically it worked smoothly, kept all my account settings, machine name and stuff.  It connects to the internet, and to my Homegroup.  And I don't regret it because it's not my main machine.
However, I do realize that one day I am going to have to reformat, re-install and start all over again.
Here are more details:
http://www.computerperformance.co.uk/win8/windows8-install.htm


text:
Q: Why can't I fully uninstall Grabit? I uninstalled Grabit last month, but occasionally I found some Grabit files on my disc C! I tried to uninstall it again but found no Grabit files on Windows Add/Remove Programs. Why can't I fully uninstall it?

A: Applications when installed on Windows:
- they put their files in their folder. i.e. C:\Program Files\Grabit
- they put *.dll files in windows directory
- they put values & keys in windows registry ( accessed by regedit)
- they might put files in common windows directories.
I found the better way that another good application could collect all those related information & remove them all when you want to uninstall.
This excellent application (for me) is revouninstaller.
It is available to download for free on http://www.revouninstaller.com/
It is very easy to use.
Hope this will get your issue fixed.

A: I do not know the software, but some apps leave a lot of trash in system after uninstall. In some cases this is because the author wants to prevent you from repeated trial version installation but I hate when the software leaves such hidden fragments in my system. I often have to use tools like Revo Uninstaller, some tools are also in Piriform Ccleaner and in more difficult cases I also had to use RegClean or Regseeker to remove these fragments from system.

A: RevoUninstaller works pretty well.
Some programs create a list of their files to help the uninstall process and yet do not update the list when their files are updated either through program updates or other changes. This is one common cause of partial uninstalls. Others assume you'll be reinstalling the app, and so leave their config files to "make it easier" for you.
I have gotten used to going into Program Files and deleting program directories after uninstall. Also check the following locations for files:
C:\Program Files\Common Files\
C:\Documents and Settings\\Application Data\
C:\Documents and Settings\\Local Settings\Application Data\
These tend to be the most common places for programs to leave files.
Regarding the registry, don't modify it yourself unless you know what you're doing. Use Piriform CCleaner to remove extraneous and unused registry entries.


text:
Q: Solving a PDE similar to wave equation I have the following PDE:
$$x^2u_{xx} - y^2u_{yy}-2yu_y = 0 $$
I noted that this looks very similar to the wave equation,
$$u_{yy} = C^2u_{xx}$$
I am, however, unable to proceed from here.

A: A method of solving is shown below. The general solution is :
$$u(x,y)=\sqrt{\frac{x}{y}}\:\Phi(xy)+\Psi\left(\frac{x}{y}\right)$$
where $\Phi$ and $\Psi$ are any derivable functions.


text:
Q: How to scale svg in x and y axis from a object tag? In my html file, I have a svg loaded through a object tag. I want to scale it in the x and y axis but it is not working. Does anyone know how to do it?
Thanks
<!DOCTYPE html>
<html>
    <head>
        <title>Animate</title>
        <style>
        </style>

    </head>
    <body>

        <object data="images/steve/steve.svg" type="image/svg+xml" id="steve" width="100%" height="100%"></object>

        <script>

            var steve = document.getElementById("steve");

            steve.addEventListener("load", function() {

                var svgDoc = steve.contentDocument;

                //steve.setAttribute('transform','scale(1.0 2.0)');   // this does not work

            },false);
        </script>
    </body>

</html>

A: put the svg element in a div and scale that instead. Also, make sure you set width and height to 100% on the svg element itself within "steve.svg" so that it scales with the element. You can do this by opening steve.svg in a text editor and adding width="100%" height="100%" to the <svg></svg> tags
<div id="steve-container">
    <object data="images/steve/steve.svg" type="image/svg+xml" id="steve" width="100%" height="100%"></object>
</div>

then just set the css style on steve-container to the desired size


text:
Q: Recaptcha.Net connection error with proxy I am developing an enterprise system using ASP.NET MVC 5. There I have a Registration action with captcha which is powered by RecaptchaNet library from NuGet which works with Google Recaptcha.
Now, I have encountered a problem. That's the beginning of my registration action:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<JsonResult> Register(RegisterViewModel model)
{
    try
    {
        RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();
        if (String.IsNullOrEmpty(recaptchaHelper.Response))
        {
            // return error
        }

        RecaptchaVerificationResult recaptchaResult = await recaptchaHelper.VerifyRecaptchaResponseTaskAsync();
        if (recaptchaResult != RecaptchaVerificationResult.Success)
        {
            // return error
        }

At line
RecaptchaVerificationResult recaptchaResult = await recaptchaHelper.VerifyRecaptchaResponseTaskAsync();

I get the following exception:
Exception text (depth 0): Unable to connect to the remote server
at Recaptcha.Web.RecaptchaVerificationHelper.<VerifyRecaptchaResponseTaskAsync>b__0()
at System.Threading.Tasks.Task1.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at BankingClient.Controllers.AccountController.<Register>d__8.MoveNext() in c:\Src\IBRC-SVN\WebClients\BankingClient\Controllers\AccountController.cs:line 152

Exception text (depth 1): No connection could be made because the target machine actively refused it 88.204.142.34:443
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)

After seaching for the answer at StackOverflow, I have understood that the problem is that I use proxy. I have decompiled RecaptchaNet library with DotPeek of Resharper and here is the code:
public Task<RecaptchaVerificationResult> VerifyRecaptchaResponseTaskAsync()
{
    // some code
    byte[] bytes = Encoding.ASCII.GetBytes(string.Format("privatekey={0}&remoteip={1}&challenge={2}&response={3}", (object) RecaptchaKeyHelper.ParseKey(this.PrivateKey), (object) this.UserHostAddress, (object) this._Challenge, (object) this.Response));
    Uri requestUri = this.UseSsl ? new Uri("https://www.google.com/recaptcha/api/verify", UriKind.Absolute) : new Uri("http://www.google.com/recaptcha/api/verify", UriKind.Absolute);

    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
    httpWebRequest.ContentType = "application/x-www-form-urlencoded";
    httpWebRequest.ContentLength = (long)bytes.Length;
    httpWebRequest.Method = "POST";
    IWebProxy systemWebProxy = WebRequest.GetSystemWebProxy();
    systemWebProxy.Credentials = CredentialCache.DefaultCredentials;
    httpWebRequest.Proxy = systemWebProxy;
    httpWebRequest.GetRequestStream().Write(bytes, 0, bytes.Length);
    HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    string[] strArray = (string[])null;
    using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
        strArray = streamReader.ReadToEnd().Split('\n');

Now, I copy this code to my own class in an empty console application:
byte[] bytes = Encoding.ASCII.GetBytes("check");
Uri requestUri = new Uri("https://www.google.com/recaptcha/api/verify", UriKind.Absolute);

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.ContentLength = (long)bytes.Length;
httpWebRequest.Method = "POST";
IWebProxy systemWebProxy = WebRequest.GetSystemWebProxy();
systemWebProxy.Credentials = CredentialCache.DefaultCredentials;
httpWebRequest.Proxy = systemWebProxy;
httpWebRequest.GetRequestStream().Write(bytes, 0, bytes.Length);
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
string[] strArray = (string[])null;
using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
    strArray = streamReader.ReadToEnd().Split('\n');

And it perfectly works. I just spent a bunch of time trying to understand what is going wrong. If it can probably affect something, we have an ActiveDirectory authentication everywhere in an organization including proxy authentication.


text:
Q: Cambiar el color de un TextView solo a unos determinados caracteres Tengo este TextView:
<TextView
     android:id="@+id/textView17"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_marginTop="10dp"
     android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean dapibus sem vel magna venenatis, nec tempus enim mattis. Proin tristique faucibus nisl eget volutpat."
     android:textColor="@color/black"
     android:textSize="16sp"
     android:textStyle="bold" />

Lo que necesito es poner Lorem ipsum dolor sit amet en verde y lo demás en negro (Por defecto).
Es posible hacerlo mediante código?

A: Si lo que quieres es cambiar el color de un trozo del texto que tienes dentro del XML puedes reemplazar un trozo de texto mediante la función replace y utilizar un SpannableString para ello.
TextView textview = (TextView) findViewById(R.id.textview);
SpannableString texto = textview.getText().toString();
texto = texto.replace("Lorem ipsum dolor sit amet", "Lorem ipsum dolor sit amet");
textview.setText(Html.fromHtml(newText));

A: Lo he conseguido con este código, no es exactamente como queria pero funciona:
SpannableStringBuilder builder = new SpannableStringBuilder();

SpannableString str1= new SpannableString("Lorem ipsum dolor sit amet");
str1.setSpan(new ForegroundColorSpan(Color.RED), 0, str1.length(), 0);
builder.append(str1);

SpannableString str2= new SpannableString(", consectetur adipiscing elit. Aenean dapibus sem vel magna venenatis, nec tempus enim mattis. Proin tristique faucibus nisl eget volutpat.");
str2.setSpan(new ForegroundColorSpan(Color.BLACK), 0, str2.length(), 0);
builder.append(str2);

TextView tv = (TextView) dialogView.findViewById(R.id.punto1);
tv.setText( builder, TextView.BufferType.SPANNABLE);

A: Se puede realizar de diversas formas,
1) Mediante el método Html.fromHtml() y definiendo en  strings.xml el texto a cambiar el color
 <string name="mi_mensaje"><![CDATA[Hola StackOverflow.com, como te encuentras el día de hoy!]]></string>

de esta forma realizas el cambio:
   if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
        textView.setText(Html.fromHtml(getString(R.string.mi_mensaje),Html.FROM_HTML_MODE_LEGACY));
    } else {
        textView.setText(Html.fromHtml(getString(R.string.mi_mensaje)));
    }

2) Definiendo el texto directamente, usando Html.fromHtml():
String mensaje = "Hola StackOverflow.com, como te encuentras el día de hoy!";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
    textView.setText(Html.fromHtml(mensaje,Html.FROM_HTML_MODE_LEGACY));
} else {
    textView.setText(Html.fromHtml(mensaje));
}

3) Usando un SpannableString, definiendo un Span con el color deseado :
SpannableString mensaje = new SpannableString("Hola StackOverflow.com, como te encuentras el día de hoy!");
ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#FF0040"));// Puedes usar tambien .. new ForegroundColorSpan(Color.RED);
mensaje.setSpan(colorSpan, 5, 22, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
textView.setText(mensaje);

El método setSpan()  define como parametros:

*

*El objeto ForegroundColorSpan.

*El inicio en la cadena de caracteres a aplicar el span.

*El final en la cadena de caracteres a aplicar el span.

*Las banderas, en este caso SPAN_INCLUSIVE_INCLUSIVE, que indica Expandir para incluir el texto insertado en su punto inicial o final.

Las 3 opciones obtienen como resultado:

similar a lo que se tiene en esta  respuesta:
Negrita en una parte de un TextView


text:
Q: MPMoviePlayerController fullscreen mode issue I have a problem with my code that plays a video file. Whenever I play the file in fullscreen mode the playback doesn't occupy all of my screen. Here is the relevant code:
     NSURL *url = [NSURL fileURLWithPath:@"Somefile.mov"];
     moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
    [moviePlayer setControlStyle:MPMovieControlStyleFullscreen];
    [moviePlayer setFullscreen:YES];
    moviePlayer.view.frame = self.switchView.frame;
    [self.switchView addSubview:moviePlayer.view];

    [[NSNotificationCenter defaultCenter]
    addObserver:self
    selector:@selector(movieFinishedCallback:)
    name:MPMoviePlayerPlaybackDidFinishNotification
    object:moviePlayer];

    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(playbackStateDidChange:)
     name:MPMoviePlayerPlaybackStateDidChangeNotification
     object:moviePlayer];

    [moviePlayer prepareToPlay];
    [moviePlayer play];

Here is the output I get:

A: Option A: Use the MPMovieViewController instead and display it modally using presentMoviePlayerViewControllerAnimated:.
Option B: Make sure your switchView (which you use for adding the moviePlayer's view to) actually occupies the entire screen.
Option C: Readjust the frame of the moviePlayer's view with negative vertical offsets until it fits - eg.: moviePlayer.view.frame = CGRectMake(0.0f, -20.0f, 320.0f, 480.0f);
Note: MPMoviePlayerController always displays a status bar when using the control style MPMovieControlStyleFullscreen, no matter how the rest of your app handles the status-bar.

A: Change the controlstyle property of your player from the method below:           -(void)applyUserSettingsToMoviePlayer
player.controlStyle = MPMovieControlStyleFullScreen causes the above problem,change it to MPMovieControlStyleEmbedded and see if that works.


text:
Q: SDK Location on Different Drive Trying to setup a Android Project on one of my external drives.
My Sdk is located on my D: drive
and my project is on E:
Easy enough, but however when I have my local.properties set to that it does not work.
sdk.dir = D:\Android_SDK

When it attempts to compile it'll look like this:
sdk.dir = E:\projectDirectory\D:\Android_SDK

Is there a way I can go up a directory like '../' or some sort of way I can tell it to map to the other drive and not the E drive.
Hopefully that is clear enough.

A: 1 - Open Android Studio
2 - Up, Left corner click File->Settings
3 - Look for Appearance & Behavior -> Android SDK
4 - Click Edit, and browse you SDK location (usually is in :Users\\AppData\Local\Android\Sdk) http://i.imgur.com/JIzMebh.png

Or you can try in some versions:
From Android Studio 1.0.1
Go to
File -> project Structure into Project Structure
Left -> SDK Location
SDK location select Android SDK location (old version use Press +, add another sdk)
and you should find jre version and NDK location as well as SDK to edit. ;)

For even older versions (<1.0 of Android Studio):
1. Close current Project (File->Close project)
You'll get a Welcome to Android Studio Dialog. In that:

*Click on Configure -> Project Defaults -> Project Structure

*Click on SDK Location in the left column

*Put the path to the Android SDK in "Android SDK location" field.
(Example SDK location: C:\android-sdk; I have sub-folders like  add-ons, platforms etc under C:\android-sdk)
5. Click OK to save changes


text:
Q: How to rollback transaction after class (using TestNg and Spring)? Let's say we have the next test:
@ContextConfiguration(classes = {MyDaoContext.class})
public class MyDaoTest extends AbstractTransactionalTestNGSpringContextTests {

@Autowired
private MyDao dao;

@Test
public void insertDataTest() {
    // insert data here and test something
}

@Test(dependsOnMethods = "insertDataTest")
public void modifyPreviouslyInsertedDataTest() {
    // get previously inserted data and test something
}
}

Second test will fall because when we have finished first test the inserted data are gone.
Is there a way to rollback a transaction after all tests have finished their work?

A: Each test runs in its own transaction and rollbacks at the end. You can tune that by adding @Rollback(false) to your first test.
The problem now is that the transaction of insertDataTest has completed so you should remove what it has created manually. To do that, the class you extends from has several utility methods such as deleteFromTables or deleteFromTableWhere.
This should go ideally in an @AfterClass or something.
But that's not what I would do. I would factor out the data that are inserted by insertDataTest in a shared utility. That way, you could call it again in your second test and remove the dependsOnMethods. Having such dependency is not recommended as you can't run that test in isolation.

A: Try the following (which would work in JUnit, I'm not sure about TestBG)
@ContextConfiguration(classes = {MyDaoContext.class})
public class MyDaoTest extends AbstractTransactionalTestNGSpringContextTests {

   @Autowired
   private MyDao dao;

   @Test
   @Rollback(false)
   public void insertDataTest() {
       // insert data here and test something
   }

   @Test(dependsOnMethods = "insertDataTest")
   public void modifyPreviouslyInsertedDataTest() {
       // get previously inserted data and test something
   }
}

In that case of course you would have to delete the data from the first method manually


text:
Q: What's Microsoft's strategy on Windows CE development? Lots of specialized mobile devices use Windows CE or Windows Mobile.
I'm not talking about smart phones here -- I know that Windows Phone 7 is Microsoft's current technology of choice here. I'm talking about barcode readers, embedded devices, industry PDAs with specialized hardware, etc... the kind of devices (Example 1, Example 2) where Windows Phone Silverlight development is not an option (no P/Invoke to access the hardware, etc.).
Since direct Compact Framework support has been dropped in Visual Studio 2010, the only option to develop for these device currently is to use outdated development tools (VS 2008), which already start to cause trouble on modern machines (e.g. there's no supported way to make the Windows Mobile Device Emulator's network stack work on Windows 7).
Thus, my question is: What are Microsoft's plans regarding these mobile devices? Will they allow native applications on Windows Phone, such that, for example, barcode reader drivers can be developed that can be accessed in Silverlight applications? Will they re-add "native" Compact Framework support to Visual Studio and just haven't found the time yet? Or will they leave this niche market?

A: Given my experience with Microsoft I am not sure they know themselves.
Windows Phone 7 is still based on Windows CE (6.5), but the platform is hidden under thick layer of .NET. At work we have a C++ application that was developed for WCE and is now ported to a couple of other platforms, so we also inquired at Microsoft how we could port that application to WP7. The answer was along the lines of "$company did it, so it must be possible. By the way, you need to renew your .NET certification". It seems $company (our competitor) only has (or had at the time; didn't check since) a mock up or demo, not a working product.
I'd really suggest you start looking for some embedded Linux vendor. If you have existing CF code, you should be able to get it working using Mono.

A: I think the roadmap of Windows CE is still clear, because there's Microsoft Windows CE 7, the next successor of Windows CE 6.x.
Frustatingly, they named the product officially as Microsoft Windows Embedded Compact 7, but they said it's because in line with Windows 7 releases, only now for embedded.
http://www.microsoft.com/windowsembedded/en-us/develop/windows-embedded-compact-for-developers.aspx
for Windows Embedded Compact 7:
http://www.microsoft.com/windowsembedded/en-us/develop/windows-embedded-compact-7-for-developers.aspx
I suggest you install VS 2008 for Windows CE 7 because VS 2008 support Windows CE5, CE6 and CE7 devices, and VS 2010 still can't support Windows CE devices.
This is from CE7 website:

NEW: Developing with Windows Embedded Compact 7 (formerly CE)
  Just released, Windows Embedded Compact 7 (the next generation of Windows
  Embedded CE) is based on the power of the Windows 7 platform. Compact
  7 is a real-time operating systems for a wide range of small-footprint
  consumer and enterprise devices. Development tools like Platform
  Builder, a Visual Studio 2008 plug in, provide an integrated
  development environment (IDE) that enables you to build applications
  and Windows Embedded CE operating system software in a familiar
  environment.

And Windows CE 7 has little relation with Windows Phone 7, because they share the same code base of basic services of Windows 7. There's also no detail information about Silverlight running on Windows CE 7, but I can assure you they support it:
http://www.microsoft.com/windowsembedded/en-us/develop/windows-embedded-compact-7-user-interface-development-gui-design.aspx


text:
Q: Running MPI program on windows. working fine on Linux but giving error on windows I have program written in open MPI on linux where it is running fine, I complied it on windows but when i am running it using command mpirun -n 2 abc.exe, its showing error on receiving signals. Below I attached error:
[Novo_Comp5-PC:09596] [[INVALID],INVALID] ORTE_ERROR_LOG: Not found in
file /pub/devel/openmpi/openmpi-1.7.2-1/src/openmpi-1.7.2/orte/mca/ess/hnp/ess_hnp_module.c
at line 270

It looks like orte_init failed for some reason; your parallel process is
likely to abort.  There are many reasons that a parallel process can
fail during orte_init; some of which are due to configuration or
environment problems.  This failure appears to be an internal failure;
here's some additional information (which may only be relevant to an
Open MPI developer):
  orte_plm_base_select failed
  --> Returned value Not found (-13) instead of ORTE_SUCCES


text:
Q: I have a problem in my code when updating react-navigation v2 to v3 I want to update the react-navigation library V2 to V3 and change part of my code thinking that there would not be any problems but it turns out that I have problems creating createStackNavigator with a screen of type createDrawerNavigator and that in turn contains createBottomTabNavigator.
my code that works with the previous version was:
export const createRootNavigator = (signedIn = false) => {
  const commonNavigationOptions = {
    headerStyle: {
      shadowColor: 'transparent',
      elevation: 0
    },
    headerTintColor: DEFAULT_THEME.topaz
  };

  const SignedIn = createStackNavigator(
    {
      Home: {
        screen: Drawer('Home'),
        navigationOptions: () => ({
          headerStyle: {
            height: 0
          },
          header: getSafeArea(DEFAULT_THEME.backgrouncolorHomeSafeArea)
        })
      },
      Cards: {
        screen: Tabs('Cards'),
        navigationOptions: () => ({
          headerStyle: {
            height: 0
          }
        })
      },
   );

const SignedOut = createStackNavigator(
    {
      SignIn: {
        screen: LoginContainer,
        navigationOptions: () => ({
          headerStyle: {
            height: 0
          },
          header: getSafeArea(DEFAULT_THEME.dark)
        })
      },
      SelectableCardsList: { screen: SelectableCardsListComponent },
);

  return createSwitchNavigator(
    {
      SignedIn: { screen: SignedIn },
      SignedOut: { screen: SignedOut }
    },
    {
      initialRouteName: signedIn ? 'SignedIn' : 'SignedOut'
    }
  );
};

const Drawer = (initialRoute) => createDrawerNavigator(
  {
    Home: { screen: Tabs('Home') },

  {
    initialRouteName: initialRoute,
    contentComponent: CustomDrawerComponent
  }
);

const Tabs = (initialRouteName) => createBottomTabNavigator(
  {
    Home: {
      screen: HomeContainer,
      navigationOptions: {
        tabBarLabel: I18n.t('tabs.me')
      }
    },
    Home2: {
      screen: Home2,
      navigationOptions: {
        tabBarLabel: I18n.t('tabs.credentials')
      }
 },
  {
    initialRouteName: initialRouteName,
    tabBarComponent: ({ navigation }) => <CustomBottomBarComponent navigation={navigation} navigationState={navigation['state']} />,
    tabBarOptions: {
      style: {
        backgroundColor: 'white'
      }
    }
  }
);

try this solution with react-navigation V3 and send me an error
I try the following:
encapsulate createSwitchNavigator in createAppContainer and separate (SignedOut and SignedOut) createStackNavigator out of createSwitchNavigator, the rest is still the same.
export const createRootNavigator = (signedIn = false) => createAppContainer(createSwitchNavigator(
    {
        SignedIn: { screen: SignedIn },
        SignedOut: { screen: SignedOut }
    },
    {
        initialRouteName: signedIn ? 'SignedIn' : 'SignedOut'
    }
));

I get the following error: The component for route 'Home' must be a react component. For Example
import MyScreen from './MyScreen';
...
Home : MyScreen,
}
you can also use a navigator:
The problem is located in this part:
const SignedIn = createStackNavigator(
    {
        Home: {
            screen: Drawer,

Also try to change Drawer for any component (a component with a blank screen) and this works, but I can not insert the Tabs in the Drawer.
Thank you very much for your help.


text:
Q: Add Product to Session of Wishlist and not delete the session like now I got a problem with my shopping cart wishlist sessions. I add with a button an article to wishlist in form of an session array when i click another icon to whishlist he removes me the clicked item before an delete the session of the item selected before.
here is my js code to grab values for session:
 $(document).ready(function(){
    $(".addButton").on("click", function(event){
        event.preventDefault();
        var button = $(this);
        var parent = button.parent();
        var wlproducturl = parent.find("input[name$='.id']").val();
        var wlproduct = parent.find("input[name$='.name']").val();

            $.ajax({
        type : "POST",
        url : "../assets/wlscript.php",
        data : { wlproduct : wlproduct, wlproducturl : wlproducturl },
        success : function(data) {
        $('div#resultwish').html('
<button type="button" class="close" data-dismiss="alert">×</button>You added '+wlproducturl+' '+wlproduct+'\'s to your wishlist.
');
        }
    });

        // alert("Add article with id = " + idArticle + " and name = " + nameArticle);
    });
});

This is my wlscript php file:
<?php
session_start();

$p = trim($_POST['wlproduct']);
$q = trim($_POST['wlproducturl']);
$orders[$p] = $q;
$_SESSION['orders'] = $orders;
?>

And so I output the selected items:
                              <?php
session_start();
print_r($_SESSION['orders']);
?>

So how can I add new item to session  without deleting the old one add a product more to wishlist?

A: Maybe simply because you are overwriting $orders each time, with your actual code:
<?php
session_start();

$p = trim($_POST['wlproduct']);
$q = trim($_POST['wlproducturl']);
$orders[$p] = $q; // UNAWARE IF $_SESSION['orders'], OR $orders ALREADY CONTAIN SOMETHING...
$_SESSION['orders'] = $orders; // ... AND THEREFORE ALL IS OVERWRITTEN.
?>

Maybe this ?
<?php
session_start();

// if (session_is_registered("orders")) // CAREFUL, OBSOLETE SINCE PHP 5.4.0
if (is_array($_SESSION['orders']))
{
$orders = $_SESSION['orders']; // RETRIEVING WHAT HAS PREVIOUSLY BEEN STORED
}

$p = trim($_POST['wlproduct']);
$q = trim($_POST['wlproducturl']);
$orders[$p] = $q; // THIS NOW ADDS TO EXISITNG
$_SESSION['orders'] = $orders;
?>


text:
Q: Angular asyncValidator with BehaviorSubject I'm creating Angular form. In given example you can find my code. I'm trying to create multi group form with async validator.
Case is simple to validate if number exists on list. In real case this list will be fetched from server but for purposes of demo I just added two buttons.
If I use
{ asyncValidators: [DataDuplicatedAsyncFuncValidator(of([1, 11]))] }

to pass data. Everything works. If I pass observable from subject form is in weird state when its valid and invalid :)
Please help me:
Example

A: the reason is your source of ids is never got completed. to complete it after one event you can use take(1) operator
 return existing$.pipe(
      take(1),
      ...

A: You are changing the data that the input value is validated against, not the input data that is validated. As soon as the observable returned by the validation function returns a value, angular does not care about changes happening after.
Also, i think angular is waiting until the observable completes, the mixed state means that neither is true, because the validator did not complete yet.
This means to re-evaluate the validity, you need to call updateValueAndValidity() on the validated control.
here's the modified example: https://stackblitz.com/edit/angular-ivy-nmrymb
Note:

*

*i shared the observable through shareReplay, not sure that's necessary, did that wile debugging

*i added a take(1) in the validator function

*i added the updateValueAndValidity() on changes to the validation data


text:
Q: How to update a div in htmleditor Could someone help me in updating a div in a htmleditor? Its in an iframe, so I could not do:
Ext.fly('mydiv').update('New value');

Right now I am updating the whole content with:
xtype:'textfield',
listeners:{
                keyup:{
                    fn:function(){
                        var e = this.up().down('htmleditor');
                        var v = 'some text

 some more text'
                        e.setValue(v);
                    }
                }
            },
xtype:'htmleditor',
...

where as I would only like to update the mydiv part only but cannot get reference to it somehow. Thanks.

A: If I understand correctly, the real question here is "How do I access a DIV inside an IFRAME from its parent document?"
I haven't used EXT JS for anything, so I don't know its syntax.  But here it is in basic JavaScript.
First, the document in the IFRAME:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Child Document</title>

Child Document

This is a div with some text in it.

And then the parent document:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Parent Document</title>

Parent Docment

<form action="" method="get">

    <input type="button" id="get-it" value="Get It" />

</form>

The key is this:
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;

That lets you get access to the document object of the IFRAME, after which you can use it as normal.


text:
Q: How do I add the numeric values to a pack circles plot in R? I used the following code to plot a packing circle graph and I want to add the numbers (values) for each bubble in addition to the text. How do I do that?
Another question is whether someone knows how to deal with a large number of categories (about 200) which makes some of the plot unreadable. Is there another visualization that might be more useful in this case?
Thanks in advance!
library(packcircles)
library(ggplot2)
library(viridis)
library(ggiraph)
packing <- circleProgressiveLayout(data$Number, sizetype='area')
data <- cbind(data, packing)
dat.gg <- circleLayoutVertices(packing, npoints=50)
ggplot() +
    geom_polygon(data = dat.gg, aes(x, y, fill=as.factor(id), colour = "black", alpha = 0.6)) +
  geom_text(data = data, aes(x, y, size=Number, label = Journal)) +
  scale_size_continuous(range = c(2,4)) +
  theme_void() +
  theme(legend.position="none")+
  coord_equal()```


text:
Q: PostgreSQL check constraint CREATE TABLE my_table
(
    fk      INTEGER,
    field_1 INTEGER,
    field_2 INTEGER,
    field_3 INTEGER
)

VALID:

    fk    |    field_1    |    field_2    |    field_3
----------+---------------+---------------+---------------
     1    |      1        |      null     |      null
     1    |      null     |      1        |      null
     1    |      null     |      null     |      1

It's possible to create check constraint which allows only 1 field of 3 can be not null for 1 fk ?

A: The straight forward way come to mind:
CHECK ((field_1 IS NOT NULL AND field_2 IS NULL AND field_3 IS NULL) OR
       (field_2 IS NOT NULL AND field_1 IS NULL AND field_3 IS NULL) OR
       (field_3 IS NOT NULL AND field_1 IS NULL AND field_2 IS NULL))

A: It is not quite clear what you'd like to achieve.
If you need only one column being NOT NULL per row, then Nitram's answer will do, you can also try:
CHECK ((sign(coalesce(field_1,0)) +
        sign(coalesce(field_2,0)) + sign(coalesce(field_3,0))) <= 1)

Otherwise, if you need to have only single NOT NULL column per all rows with the given FK, you should look into the CONSTRAINT TRIGGER, something like this:
CREATE OR REPLACE FUNCTION only_one() RETURNS trigger AS $only_one$
DECLARE
    cnt  int4;
BEGIN
    SELECT sign(coalesce(field_1,0)) +
           sign(coalesce(field_2,0)) +
           sign(coalesce(field_3,0)) +
           sign(coalesce(NEW.field_1,0)) +
           sign(coalesce(NEW.field_2,0))+
           sign(coalesce(NEW.field_3,0))
      INTO cnt
      FROM my_table WHERE fk = NEW.fk;

    IF cnt > 1 THEN
        RAISE EXCEPTION 'Sorry, too much NOT NULL values for FK=%', NEW.fk;
    END IF;

    RETURN NEW;
END;
$only_one$ LANGUAGE plpgsql;
CREATE CONSTRAINT TRIGGER my_table_only_one
 AFTER INSERT OR UPDATE ON my_table
   FOR EACH ROW EXECUTE PROCEDURE only_one();


text:
Q: Align text and image side by side at horizontally centered level I am trying to align horizontally text+image+text+image side by side.
The below code works when all elements are text but with images in between I cannot get it right.
Also, all text has to always centered at 50% of the height of the largest image in the row, like in below example img1. The width I set in my CSS, but the height is auto, so variable, so I dont know how to make the text positioned at 50% of the height of the largest image. How to do it?

.merc {
 font-size:11px;
 font-weight:700;
 /*margin-left:10px;*/
 color:#777 !important;
 display:inline-block;
 max-width:35%
}

.merc-image-two img {
 display:inline-block;
 max-width:25%;
 height:auto;
 padding-left:5px;
}

.merc-image img {
 display:inline-block;
 max-width:15%;
 height:auto;
 padding-left:5px;
}

#wrapper {
 max-width:100%
}

                    MERC MERC MERC

                    MERC MERC MERC

A: Maybe so:

.merc {
 font-size:11px;
 font-weight:700;
 /*margin-left:10px;*/
 color:#777 !important;
 display:inline-block;
    vertical-align: middle;
 max-width:35%
}

.merc-image-two {
 display:inline-block;
    vertical-align: middle;
 max-width:25%;
 height:auto;
 padding-left:5px;
}

.merc-image {
 display:inline-block;
    vertical-align: middle;
 max-width:15%;
 height:auto;
 padding-left:5px;
}

#wrapper {
 max-width:100%
}

                    MERC MERC MERC

                    MERC MERC MERC


text:
Q: не понял синтаксис функционального выражения Всем привет! Объясните, пожалуйста, функциональное выражение по теме "замыкания, область видимости":
return function() {
        alert( x );
      };

})(i); </pre>

Чтобы создать функцию, нужно ее объявить, в фигурных скобках описано то что она выполняет: return function(){код}(i). Как понять переменную i в скобках в конце?


text:
Q: SQL Order By blanks at bottom when the main order by is a Case statement? I'd like to ORDER BY listing items that are blanks at the bottom of the result, however the main order by is a case statement.
So, my main Order By clause is this:
ORDER BY CASE WHEN pub = 1 THEN title ELSE t.othertitle END;

To that, I'd like to apply the following CASE so that blanks go to the bottom:
ORDER BY CASE WHEN (above case) = '' THEN 1 ELSE 0 END

Problem is I cannot embed CASE statements.
How would this be done?
Thanks!

A: You didn't specify your DBMS, so this is ANSI SQL:
ORDER BY nullif(CASE WHEN pub = 1 THEN title ELSE t.othertitle END, '') NULLS LAST

A: You can in fact embed case statements
ORDER BY CASE COALESCE(CASE pub WHEN 1 THEN title ELSE t.othertitle END, '') WHEN '' THEN 1 ELSE 0 END

A: You can do this explicitly:
ORDER BY (CASE WHEN pub = 1 AND title = '' THEN 1
               WHEN pub <> 1 AND t.othertitle = '' THEN 1
               ELSE 2
          END) DESC,
         (CASE WHEN pub = 1 THEN title ELSE t.othertitle END)

A: Case statements can only(?) be included in Order by when structuring it to return an INT. Create any kind of ordering logic you'd like but make sure it returns an INT in ascending order:
order by
(case when pub = 1 then 1
      when pub is null or pub = '' then 2
      else 3 end)


text:
Q: Chromecast won't load my receiver app. Request on stick is pending I have taken the cast-chrome-sender-helloworld sample app from https://github.com/googlecast/cast-chrome-sender-helloworld and inserted my APP ID. The APP ID is associated with a URL that points to http://<server>/<path>/chromecast and please notice the lack of ending "/" or ".html" which I did on purpose because it's basically a servlet that handles the receiver.
My sender app sends the request to the chromecast stick alright. Using the debugger in Chrome I can see that the request to launch a specific app associated with my APP ID is received and the stick tries to load the receiving app from the above mentioned URL. However, I see the HTTP GET request is executed but it's state is "pending" for a while before (I guess) it times out.
Could this failure to load the receiver app be due to the whitelisted URL is without ".html"?
** Edited on the 27th of September
I still see the Chromecast browser issuing the correct request URL but it "hangs" with the network status message "pending". No requests hits my apache server. If I use a laptop to issue the same request on the same wifi network, then I get the following correct answer (using CURL):
curl -vvv http://server.domain.com/path/device/chromecast
* About to connect() to server.domain.com port 80 (#0)
*   Trying 192.168.1.42...
* connected
* Connected to server.domain.com (192.168.1.42) port 80 (#0)
> GET /path/device/chromecast HTTP/1.1
> User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8y zlib/1.2.5
> Host: server.domain.com
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Fri, 27 Sep 2013 06:46:23 GMT
< Server: Apache-Coyote/1.1
< Content-Type: text/html;charset=ISO-8859-1
< Content-Length: 1850
< Set-Cookie: JSESSIONID=81A3A6184F014A7FBEC60C0B6375E8B0; Path=/client-portal/; HttpOnly
<
<!DOCTYPE html>

  <title>Media Player App</title>

    <video id="vid"
           style="position:absolute;top:0;left:0;height:100%;width:100%"></video>

* Connection #0 to host server.domain.com left intact
* Closing connection #0f

The debugger just shows the following before reloading the "brain freeze" screen:

A: Turns out that the Chromecast stick does not use the local wifi routers DNS, but rely on an external one. My problem was that the host I was contacting had a different ip address on my local lan. (Thanks Google for the help with debugging this).
The documentation on https://developers.google.com/cast/whitelisting states that it is okay to whitelist NAT'ed addresses however, I don't see how this could work since the external DNS typically are unaware of that:

Two (2) URLs for the location of your receiver app, typically one for QA and one for production, on your server. A Receiver is a HTML5 web page that hosts your content on the Chromecast devices. Good Receiver URL's usually look like https://website.com/rcvr/myreceiver.html or https://website.com/qarcvr/myreceiver.html (It is ok for your receiver to be on an internal (NAT'd) IP address, but not localhost. They are rarely a top level domain.

I solved this by using pagekite.net, which allows me to have a public address reachable by the external DNS and still access my local development machines web server.


text:
Q: Import CSP blob exported from .NET into python pyCrypto I have a CPS Blob exported from certificate using RSACryptoServiceProvider.ExportCspBlob in my .NET application.

return Convert.ToBase64String(rsaAlg.ExportCspBlob(false /*includePrivateParameters*/));

Now, I need to import that blob in python application. I tried using pyCrypto, but with no luck.

# that's the value I'm getting from .NET code above
key = 'BgIAAAAkAABSU0ExAAgAAAEAAQARMnLlzOgHkmHssf6ZSFJn8TlTiOBSoRSEnkI4U0UI6n1jFY2bTWS9O5uApMNXz1vr5OyxoXsNVF2XrNM4DOC+lRn3R/H+mZZxZY1F8oXxhe4L5AFOMhyykPreQtu9z+oKOzVB80zR+EU+nc/290POVK9/LGzP94cTk0VHSZdXDgL1eOiXLSg8h1OnJmMGxY6HyNvbF90onoHMWNrIeRue1vP/S5QLwuzkHv6tgm54bSwXWXFdDRbjtrA9HJkbf74hflAIqivO34bx+53whl2fEsC51eXqFdCr7XJJw+bwlENwDF9bUtCXQ+jXbiYtzvMbntRCKZ8LPRqlN9OWrBC2';

from Crypto.PublicKey import RSA
from Crypto.Util import asn1
from base64 import b64decode

# let's decrypt base64 first
keyDER = b64decode(key)

seq = asn1.DerSequence()
seq.decode(keyDER)
keyPub = RSA.importKey(keyDER)

I'm getting

Traceback (most recent call last):   File "C:\Program Files
  (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensio
  ns\Microsoft\Python Tools for Visual
  Studio\2.1\visualstudio_py_util.py", line 1 06, in exec_file
      exec_code(code, file, global_variables)   File "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensio
  ns\Microsoft\Python Tools for Visual
  Studio\2.1\visualstudio_py_util.py", line 8 2, in exec_code
      exec(code_obj, global_variables)   File "c:\users\marcinj\documents\visual studio
  2013\Projects\PythonApplication
  1\PythonApplication1\PythonApplication1.py", line 12, in
      seq.decode(keyDER)   File "C:\Python27\lib\site-packages\Crypto\Util\asn1.py", line 237, in
  decode
      raise ValueError("Not a DER SEQUENCE.") ValueError: Not a DER SEQUENCE.

A: The CSP blob format is proprietary to Microsoft and poorly documented. Rather than use that format I would instead use the ExportParameters method to get an RSAParameters struct. From this struct I would directly access the Exponent and Modulus byte arrays and base64 encode them for transfer to the python program, as in the following snippet:
var rsa = RSA.Create ();
var RsaParms = rsa.ExportParameters (false);
Console.WriteLine (Convert.ToBase64String( RsaParms.Modulus));
Console.WriteLine (Convert.ToBase64String (RsaParms.Exponent));

In the python program, the documentation for PyCrypto's RSA importKey mentions a few options for acceptable formats. The simplest of these is the PKCS#1 RSAPublicKey structure. This is quite easy to construct from the asn1 module, as in the following snippet:
mod_raw = b64decode('qLhDLGNh7+9xRahkaWILm5HcG3T0Q4SUoDA3bpQtqLxU3AQ/fmYQWLXh0Se1mhQ3AIMduVgKaJhK1sH+G/toXuQ0n5ENw6PtGMODwsDXF072kaBKD3JBZSESC9a9a8QDoGtv7WwvH1UcIE9di60C7YdBMlqqBgkjMQ6c3CTh9KU=')
exp_raw = b64decode('EQ==')
mod = int.from_bytes(mod_raw, 'big')
exp = int.from_bytes(exp_raw, 'big')
seq = asn1.DerSequence()
seq.append(mod)
seq.append(exp)
der = seq.encode()
keyPub = RSA.importKey(der)


text:
Q: C# Dynamically add DataGridViewRow malfunction I have a program that will add rows dynamically in certain conditions, I've tried implement the function in this way:
if (student.UUID == AppliedStudent)
{
    using (DataGridViewRow row = new DataGridViewRow())
    {
        row.SetValues(new object[] { lesson.Name, Course.Course_Name, lesson.Level, lesson.Time, Teacher.C_Name, lesson.Price, Classroom.Classroom_Name });
        row.DefaultCellStyle.BackColor = Color.LightGreen;
        row.DefaultCellStyle.SelectionBackColor = Color.SkyBlue;
        dataGridView1.Rows.Add(row);
    }
}

With this code, it can add in rows indeed however they are all empty, all those rows has no data in it. (It has been confirmed that lesson, course and Teacher aren't null.) Can anyone help? Thanks!

A: I figured it out by myself at last, I replaced the row.SetValues to row.CreateCells:
if (student.UUID == AppliedStudent)
{
    DataGridViewRow row = new DataGridViewRow();
    row.CreateCells(dataGridView1, lesson.Name, Course.Course_Name, lesson.Level, lesson.Time, Teacher.C_Name, lesson.Price, Classroom.Classroom_Name);
    row.DefaultCellStyle.BackColor = Color.LightGreen;
    row.DefaultCellStyle.SelectionBackColor = Color.SkyBlue;
    dataGridView1.Rows.Add(row);
}

With this code it will work well. Thank you all for trying to help!

A: You need to leave out the usingpart. After it the rowobject will be disposed:
if (student.UUID == AppliedStudent)
{
    DataGridViewRow row = new DataGridViewRow();
    row.SetValues(new object[] { lesson.Name, Course.Course_Name, lesson.Level, lesson.Time, Teacher.C_Name, lesson.Price, Classroom.Classroom_Name });
    row.DefaultCellStyle.BackColor = Color.LightGreen;
    row.DefaultCellStyle.SelectionBackColor = Color.SkyBlue;
    dataGridView1.Rows.Add(row);
}


text:
Q: VPNC modp2048 IKE support I am having trouble to connect to company VPN via vpnc using "IKE DH group 14" (modp2048). The vpnc only seems to support the old modp1024 algorithm. See config below...
Actually the whole story is - I am using bitrise.io as CI and I need it to connect to company VPN. They are using this plugin, bitrise-step-vpnc-connect, but based on communication with both sides, it is an issue with vpnc itself...
When I set "IKE DH group 14" in the config file, the result is:
vpnc: IKE DH Group "14" unsupported

The only supported algorithm is modp1024, but it is broken and not recommended: Security Recommendations.
Thats why we need the stronger IKE algorithm:

*

*IKEv1 Cipher Suites

*5.6.1
Config:

*

*Local Port 0

*IPSec gateway XXXX

*IPSec ID XXXX

*IPSec secret XXXX

*IKE Authmode psk

*Xauth username XXXX

*Xauth password XXXX

*NAT Traversal Mode cisco-udp

*IKE DH group 14

Result:
vpnc: IKE DH Group "14" unsupported


text:
Q: SDL GUI buttons: how to properly detect hover? I'm looking for an efficient and performant way of detecting a "hover" event on SDL surfaces. Is there any example of detecting button events on SDL?

A: It depends on what the shape of the buttons will be.
Option 1
This is the simplest way. If your buttons are rectangular, and there are less than few hundred on the screen, you can use a simple rect collide function. Where for each button, you check if the point lies in the rect that is on the screen.
Option 2
In this approach, you need to create a new surface, that will have the other buttons drawn in different colors. Then you can check if the pixel under a mouse belongs to a button, and with the aid of a dictionary, find which one it really is. This approach is a bit more complicated, but you can have buttons of any size and shape.


text:
Q: Comment Count for each Comment Author In WordPress 3.4.1:
I am trying to add the Comment Author's total number of comments beside their info. (name + date/time) in the comment's list.
Here is the SQL that I am using:
$count = $wpdb->get_var('SELECT COUNT(comment_ID) FROM '. $wpdb->comments. ' WHERE comment_author_email = "' . get_comment_author_email() .'" ' AND comment_approved = '1' AND comment_type = '');

Basically The Author's email will be checked and the total number of comments will be displayed. But also I want only approved comments to be counted and also I don't want pingbacks/trackbacks to be counted. The above code is returning a syntax error and probably is wrong in terms of logic.
Any help is appreciated. thanks.

A: Place this in your functions.php theme file:
<?php
function ps_count_user_comments() {
    global $wpdb;
    $count = $wpdb->get_var(
    'SELECT COUNT(comment_ID) FROM ' . $wpdb->comments. '
    WHERE comment_author_email = "' . get_comment_author_email() . '"
    AND comment_approved = "1"
    AND comment_type IN ("comment", "")'
    );

    return $count . ' comments';
}
?>

This code will count the author comments and do NOT include Trackbacks/Pingbacks.
Then You print it like this:
<?php echo ps_count_user_comments(); ?>

You can try to run this in your SQL and change mail@example.com to your mail. I assume your database prefix is wp_ but if its not, just change wp_comments to your prefix.
SELECT COUNT(comment_ID) FROM wp_comments
WHERE comment_author_email = "mail@example.com"
AND comment_approved = "1"
AND comment_type IN ("comment", "")

A: You can use the built-in WordPress comment query for that. I also use get_comments(); for this feature on my template.
For the parameters, I simply use 3 parameters, the same as you want.
    $comail = get_comment_author_email();
    $args = array(
                'author_email' => $comail,
                'status'  => 'approve',
                'type'  => 'comment',
                );

wp_comment_query is limitless. So anything is possible. Multiple comment-type is also supported with the 'type__in' parameter.
Next, you can echo the count($comments);. You can also use 'count'=>'true', parameter.

A: Bikran solutions can also uses as function, so you can use in several places at your theme. Also, I think he's code is needing an extra line before count($comments):
$comments = get_comments( $args );

So the ready-to-use function would be:
function my_count_comments($comail){
    $args = array(
                'author_email' => $comail,
                'status'  => 'approve',
                'type'  => 'comment',
                );
    $comments = get_comments( $args );
    return count($comments);
}

And uses:
echo my_count_comments(get_comment_author_email());


text:
Q: 'qiskit' has no attribute '__qiskit_version__' as title says, I type
qiskit.__qiskit_version__

and get the error AttributeError: module 'qiskit' has no attribute 'qiskit_version'.
I have Anaconda installed as well as pip installed qiskit and qiskit[visualization]. The jupyter notebook only works within my python file and not sure what else to do?

A: The issue was python was installed in 2 different locations. Had to delete both then reinstall!


text:
Q: Вывод строк из .txt файла Как найти слово в строке .txt файла, а затем вывести эту строку? Подобных строк несколько, нужно, чтобы на выходе выводились несколько строк, в которых было найдено слово.
<?php
$date_today = date("mdy");
$today[1] = date("His");
$file=file("listofplayers.txt");
$open=fopen("listofplayers.txt","a");
$nickname = $_GET['nickname'];
$text=$_GET["nickname"]." ".$_GET['x']." ".$_GET['y']." ".$_GET['z']." ".$_GET['skin']." ".$date_today.$today[1]." ".$_GET["playerColor"]; # на что нужно изменить

 if (strpos(file_get_contents("listofplayers.txt"), $_GET['nickname']) !== false){
    fclose($open);
    $open=fopen("listofplayers.txt","w");
    $file = file('listofplayers.txt');

    for($i = 0, $j = count($file); $i < $j; $i++) {
        $str = strpos($file[$i], $_GET['nickname']);
         if (strpos($file[$i], $_GET['nickname'])) {
         echo $str;
        }
    }

} else {
    fwrite($open,$text."\r\n");
    echo ("added");

}

fclose($open);

?>


text:
Q: JQuery Datepicker open at initialization with today´s date set I am using Jquery Datepicker and want to set today's date at initialisation.
That is working properly, but once I open my html page with the datepicker, the current date is in the input field, but the datepicker remain open too. This just happens at the initialisation. Once I select a different date, the datepicker overlay disappears.
I want to know how to make the datepicker disappear at initialisation with today's date set.

$('#datepicker').datepicker({
  inline: true,
  autoSize: true,
  nextText: '→',
  prevText: '←',
  showOtherMonths: true,
  dateFormat: 'dd-mm-yy',
  dayNamesMin: ['SO', 'MO', 'DI', 'MI', 'DO', 'FR', 'SA'],
  showOn: "button",
  buttonImage: "/images/calendar.svg",
  buttonImageOnly: true,
}).datepicker("setDate", "today");

<input type="text" name="datepicker" id="datepicker">

I expect, that after initialisation the datepicker with current date set, the datepicker doesn't show up

A: Probably you missed display: none style for modal of datepicker.

A: I´ve solved this issue by setting  $('#ui-datepicker-div').css('display', 'none')after setDate method.


text:
Q: How can the Wigner function of squeezed states be non-negative? It is always said that when the Wigner function of quantum states takes a negative value, then it is a clear signature of non-classicality of this particular state. It is also well-known that the Wigner function of squeezed states is completely non-negative, yet, we still call squeezed states quantum. How does one explain this supposed contradiction here? is the Wigner function just not a "strong enough" measure of non-classicality? if so, what is? Also, what defines non-classicality for that matter (specifically for squeezed states)?
Thanks!

A: There is no contradiction because positivity of the Wigner is not enough to guarantee classicality: squeezed states are precisely examples of this.  What is known for pure states (Hudson's theorem) is that only  Gaussian states have non-negative WFs (at least in the $xp$ plane), but the theorem is silent on the classicality of the Gaussian states.
Most non-classical states have singular $P$-functions, although it is recognized that the criteria is not so simple and there are recent results in

Damanet, F., Kübler, J., Martin, J. and Braun, D., 2018. Nonclassical states of light with a smooth P function. Physical Review A, 97(2), p.023832

that suggest a way of engineering non-classical states so that their P-function behaves more smoothly.
I do not know of a necessary and sufficient condition for a state to be classical, although negativity in the Wigner function guarantees it is NOT.


text:
Q: Create CIDR dynamically in AWS Cloud Formation Template Below is my AWS cloud formation template for creating VPC and subnets.The VPC is getting created successfully, but not the subnet's. I have tried giving my specific IP range , but it's failing with the error 'The CIDR '172.31.48.0/20' is invalid' How can i create the respective CIDRBlock dynamically in the template using JSON ?
"VPC1": {
      "Type": "AWS::EC2::VPC",
      "Properties": {
        "CidrBlock": "10.10.0.0/16",
        "InstanceTenancy": "default",
        "EnableDnsSupport": "true",
        "EnableDnsHostnames": "false",
        "Tags": [
          {
            "Key": "Name",
            "Value": "My Dashboard"
          }
        ]
      }
    },
    "subnet1": {
      "Type": "AWS::EC2::Subnet",
      "Properties": {
        "CidrBlock": "172.31.48.0/20",
        "AvailabilityZone": "us-east-2a",
        "VpcId": {
          "Ref": "VPC1"
        }
      }
    },
    "subnet2": {
      "Type": "AWS::EC2::Subnet",
      "Properties": {
        "CidrBlock": "172.31.0.0/20",
        "AvailabilityZone": "us-east-2b",
        "VpcId": {
          "Ref": "VPC1"
        },
        "Tags": [
          {
            "Key": "Name",
            "Value": "MyDashboard"
          }
        ]
      }
    },
    "subnet3": {
      "Type": "AWS::EC2::Subnet",
      "Properties": {
        "CidrBlock": "172.31.32.0/20",
        "AvailabilityZone": "us-east-2a",
        "VpcId": {
          "Ref": "VPC1"
        }
      }
    }

The VPC is getting created successfully, but not the subnet's. I have tried giving my specific IP range , but it's failing with the error 'The CIDR '172.31.48.0/20' is invalid' How can i create the respective CIDRBlock dynamically in the template using JSON ?

A: Subnets should be in the same network as the vpc. Trying 10.10.1.0/24 , 10.10.2.0/24 and 10.10.3.0/24 worked for subnets.
got the answer here : https://forums.aws.amazon.com/thread.jspa?messageID=756147#756147


text:
Q: Fluent NHibernate - recursive maps I have an object that represents a Location. Locations can contain other locations. How can I represent this relationship with Fluent NHibernate. The class looks like this:
public class Location : EntityBase
{
    #region Properties
    public string LocationName { get; set; }
    public Location ParentLocation { get; private set; }

    private List<Location> _locations = new List<Location>();
    public IEnumerable<Location> Locations
    {
        get { return _locations; }
    }

    private List<Device> _devices = new List<Device>();
    public IEnumerable<Device> Devices
    {
        get { return _devices; }
    }

    #endregion
    //Other logic omitted
}

Thanks.

A: Its possible to get private fields
HasManyToMany(Member.Reveal<Location>("_locations"))


text:
Q: How to insert a dataframe into a SQL Server table? I'm trying to upload a dataframe to a SQL Server table, I tried breaking it down to a simple SQL query string..
library(RODBC)
con <- odbcDriverConnect("driver=SQL Server; server=database")

df <- data.frame(a=1:10, b=10:1, c=11:20)

values <- paste("(",df$a,",", df$b,",",df$c,")", sep="", collapse=",")

cmd <- paste("insert into MyTable values ", values)

result <- sqlQuery(con, cmd, as.is=TRUE)

..which seems to work but does not scale very well. Is there an easier way?

A: This worked for me and I found it to be simpler.
library(sqldf)
library(odbc)
con <- dbConnect(odbc(),
                 Driver = "SQL Server",
                 Server = "ServerName",
                 Database = "DBName",
                 UID = "UserName",
                 PWD = "Password")
dbWriteTable(conn = con,
             name = "TableName",
             value = x)  ## x is any data frame

A: Since insert INTO is limited to 1000 rows, you can dbBulkCopy from rsqlserver package.
dbBulkCopy is a DBI extension that interfaces the Microsoft SQL Server popular command-line utility named bcp to quickly bulk copying large files into table. For example:
url = "Server=localhost;Database=TEST_RSQLSERVER;Trusted_Connection=True;"
conn <- dbConnect('SqlServer',url=url)
## I assume the table already exist
dbBulkCopy(conn,name='T_BULKCOPY',value=df,overwrite=TRUE)
dbDisconnect(conn)

A: [edited] Perhaps pasting the names(df) would solve the scaling problem:
   values <- paste( " df[  , c(",
                     paste( names(df),collapse=",") ,
                                   ")] ", collapse="" )
      values
      #[1] " df[  , c( a,b,c )] "

You say your code is "working".. I would also have thought one would use sqlSave rather than sqlQuery if one wanted to "upload".
I would have guessed this would be more likely to do what you described:
 sqlSave(con, df, tablename = "MyTable")


text:
Q: Estimating parameters from multiple ODEs using experimental data from only one of them I am trying to use a system of Differential Equations to fit data from an experiment. These equations describe the transcription/translation of proteins, and are as follows:
$$
\frac{d\text{ mRNA}}{dt} = \frac{k_{ts} \cdot \text{TsR} \cdot \text{DNA}}{K_{s} + \text{DNA}} - \delta_{\text{mRNA}} \cdot \text{mRNA}
$$
$$
\frac{d\text{ GFP}}{dt} = \frac{k_{tl} \cdot \text{TlR} \cdot \text{mRNA}}{K_l + \text{mRNA}} - k_{\text{mat}} \cdot \text{GFP}
$$
$$
\frac{d\text{ GFP*}}{dt} = k_{\text{mat}} \cdot \text{GFP} - bl_{\text{GFP}} \cdot \text{GFP*}
$$
$$
\frac{d\text{ TsR}}{dt} = -\frac{kc_{s} \cdot \text{TsR} \cdot \text{DNA}}{K_{s} + \text{DNA}}
$$
$$
\frac{d\text{ TlR}}{dt} = -\frac{\delta_{\text{TlR}} \cdot \text{TlR}}{K_{\text{TlR}} + \text{TlR}}
$$
The parameters i wish to estimate are the ones listed in the table below:

Parameter

$k_{ts}$

$K_{s}$

$\delta_{mRNA}$

$k_{tl}$

$K_{l}$

$k_{mat}$

$bl_{GFP}$

$kc_{s}$

$\delta_{TlR}$

$K_{TlR}$

The problem is as follows, I only have the data for the differential equation describing the mature GFP ($\frac{d GFP*}{dt}$), so I was wondering if there is any way to estimate all the parameters including those from the other differential equations.
I would really appreciate any guidance on how to tackle the problem. Thanks in advance!


text:
Q: interact with n (random) radio buttons groups generated dynamically I want to interact with groups of radio button that are generated for each record on my database.
I want to be able to edit each record and change the radio button choose before save.
This is my html code

Example of 2 records open for edit at same time
example of my app