Q: Converting a working code from double-precision to quadruple-precision: How to read quadruple-precision numbers in FORTRAN from an input file I have a big, old, FORTRAN 77 code that has worked for many, many years with no problems.
Double-precision is not enough anymore, so to convert to quadruple-precision I have:

*

*Replaced all occurrences of REAL*8 to REAL*16

*Replaced all functions like DCOS() into functions like COS()

*Replaced all built-in numbers like 0.d0 to 0.q0 , and 1D+01 to 1Q+01

The program compiles with no errors or warnings with the gcc-4.6 compiler on

*

*operating system: openSUSE 11.3 x86_64 (a 64-bit operating system)

*hardware: Intel Xeon E5-2650 (Sandy Bridge)

My LD_LIBRARY_PATH variable is set to the 64-bit library folder:
/gcc-4.6/lib64
The program reads an input file that has numbers in it.
Those numbers used to be of the form 1.234D+02 (for the double-precision version of the code, which works).
I have changed them so now that number is 1.234Q+02 , however I get the runtime error:
Bad real number in item 1 of list input
Indicating that the subroutine that reads in the data from the input file (called read.f) does not find the first number in the inputfile, to be compatible with what it expected.
Strangely, the quadruple-precision version of the code does not complain when the input file contains numbers like 1.234D+02 or 123.4 (which, based on the output seems to automatically be converted to the form 1.234D+02 rather than Q+02), it just does not like the Q+02 , so it seems that gcc-4.6 does not allow quadruple-precision numbers to be read in from input files in scientific notation !
Has anyone ever been able to read from an input file a quadruple-precision number in scientific notation (ie, like 1234Q+02) in FORTRAN with a gcc compiler, and if so how did you get it to work ? (or did you need a different compiler/operating system/hardware to get it to work ?)

A: Almost all of this is already in comments by @IanH and @Vladimi.
I suggest mixing in a little Fortran 90 into your FORTRAN 77 code.
Write all of your numbers with "E".   Change your other program to write the data this way.  Don't bother with "D" and don't try to use the infrequently supported "Q".  (Using "Q" in constants in source code is an extension of gfortran -- see 6.1.8 in manual.)
Since you want the same source code to support two precisions, at the top of the program, have:
use ISO_FORTRAN_ENV
WP = real128

or
use ISO_FORTRAN_ENV
WP = real64

as the variation that changes whether your code is using double or quadruple precision.  This is using the ISO Fortran Environment to select the types by their number of bits.  (use needs to between program and implicit none; the assignment statement after implicit none.)
Then declare your real variables via:
real (WP) :: MyVar

In source code, write real constants as 1.23456789012345E+12_WP.  The _type is the Fortran 90 way of specifying the type of a constant.  This way you can go back and forth between double and quadruple precision by only changing the single line defining WP
WP == Working Precision.
Just use "E" in input files.   Fortran will read according to the type of the variable.
Why not write a tiny test program to try it out?


Q: POST and PUT methods are not working in Postman but working in Swagger So the documentation is required from me on Postman. The problem is my APIs requires authentication so I can't use Swagger to test them. When I remove authorization from my controller and use Swagger it works, but using Postman it returns the following error.

Postman headers for the request:

A: Set header Content-Type: application/json.

A: Set header Content-Type: application/json.


Q: Getting the list of available languages How can I get the list of available languages (the short symbol to be passed when calling a method that represents the language) for CodeRay syntax highlighter?
I tried
require "coderay"
CodeRay::Scanners.constants

but that doesn't seem to give the information. (Even if I were able to get the constants that correspond to the languages, I still need another step to get the symbols that correspond to them.)

A related question is, I can do something like:
CodeRay::Scanners::Ruby # => CodeRay::Scanners::Ruby

but CodeRay::Scanners.constants doesn't include that. Why is that?

A: Method you are looking for is:
CodeRay::Scanners.list
#=> [:c, :clojure, :cpp, :css, :debug, :delphi, :diff, :erb, :go, :groovy,
#    :haml, :html, :java, :java_script, :json, :lua, :php, :python, :raydebug,
#    :ruby, :sass, :scanner, :sql, :taskpaper, :text, :xml, :yaml]


Q: Drupal escaping url in dynamically created meta tags I am trying to add open graph meta tags dynamically to drupal 8 using the the page_attachments hook.
The meta tags are generated correctly however image and the website urls are being encoded by drupal and the result is broken links.
function module_page_attachments(array &$page)
{
  $tags = [
    ["name" => "twitter:card", "content" => "summary"],
    ["name" => "og:url", "content" => "https://example.net/index.php?param1=1&param2=2&param3=3"],
    ["name" => "og:title", "content" => "My title"],
    ["name" => "og:description", "content" => "My description"],
    ["name" => "og:image", "content" => "https://example.net/images?id=1&size=400"],
  ];

  foreach ($tags as $tag) {

    $headerTag = array(
      '#tag' => 'meta',
      '#attributes' => array(
        'property' => $tag['name'],
        'content' => $tag['content'],
      ),
    );
    $page['#attached']['html_head'][] = [$headerTag, $tag['name'] . "Id"];
  }
}

The result is the following
<html>
<head>
    <meta charset="utf-8" />
    <meta property="twitter:card" content="summary" />
    <meta property="og:url"
        content="https://example.com/index.php?param1=1&param2=2&param3=3" />
    <meta property="og:title" content="My title" />
    <meta property="og:description"
        content="My description" />
    <meta property="og:image"
        content="https://example.net/images?id=1&size=400" />

</head>
<body>
</body>
</html>

All the & characters have been encoded and transformed into &. How can I prevent Drupal from encoding the characters?

A: DrupalCoreRenderMarkup should do the trick:
<?php
use Drupal\Core\Render\Markup;

function module_page_attachments(array &$page)
{
  $tags = [
    ["name" => "twitter:card", "content" => "summary"],
    ["name" => "og:url", "content" => Markup::create("https://example.net/index.php?param1=1&param2=2&param3=3")],
    ["name" => "og:title", "content" => "My title"],
    ["name" => "og:description", "content" => "My description"],
    ["name" => "og:image", "content" => Markup::create("https://example.net/images?id=1&size=400")],
  ];

  foreach ($tags as $tag) {

    $headerTag = array(
      '#tag' => 'meta',
      '#attributes' => array(
        'property' => $tag['name'],
        'content' => $tag['content'],
      ),
    );
    $page['#attached']['html_head'][] = [$headerTag, $tag['name'] . "Id"];
  }
}

A: There is an open ticket for issue with the status needs work on drupal's website.
The issue can be found here:
www.drupal.org/project/drupal/issues/2968558
A work around to solve the issue is to intercept the page and alter its template in the module file like the example here below shows:
file name: example.module
/**
 * Drupal bug caused the application to escape links. Therefore the og:image and og:url
 * were not working. Drupal kept converting `&` to `&`
 * The solution here below converts the tags into inline templates
 */
function spa_seo_page_attachments_alter(array &$attachments)
{
  if (isset($attachments['#attached']['html_head'])) {
    foreach ($attachments['#attached']['html_head'] as $key => $item) {

      $property = !empty($item[0]['#attributes']['property']) ? $item[0]['#attributes']['property'] : '';

      if ($property == "og:url" || $property == "og:image") {
        $content = $item[0]['#attributes']['content'];
        $property = $item[0]['#attributes']['property'];
        $attachments['#attached']['html_head'][$key][0] = [
          '#type' => 'inline_template',
          '#template' => "{{ meta|raw }}",
          '#context' => [
            'meta' => '<meta property="' . $property . '" content="' . $content . '" />',
          ]
        ];
      }
    }
  }
}

Note
Please note that DrupalCoreRenderMarkupdoes not solve the issue as this is a bug.


Q: How to show an Eclipse view like an intro I am having an eclipse view which I am trying to display as an intro page.
I am now opening the view with maximize but still the toolbars are visible.
So is there any way to make the view opening same as intro  page in eclipse.
I am not using intro as I want to make my own welcome page so I am not sure about the attitude of intro as it is mentioned that intro is basically for internal.
Please correct me if I am wrong anywhere.

A: I would still use IIntroPart (or have a look to CustomizableIntroPart):

The intro part is a visual component within the workbench responsible for introducing the product to new users. The intro part is typically shown the first time a product is started up.
The intro part implementation is contributed to the workbench via the org.eclipse.ui.intro extension point.

(See this thread as an example).

There can be several intro part implementations, and associations between intro part implementations and products.
The workbench will only make use of the intro part implementation for the current product (as given by Platform.getProduct().
There is at most one intro part instance in the entire workbench, and it resides in exactly one workbench window at a time.

See "[Eclipse Intro] Make my own welcome page." as an example.
If you don't use it, at least have a look at the code of IIntroPart to see how it


Q: non equal variances alternative for kruskal wallis anova I have a dataset with a total of about 6 groups set up, and there is a minimum of n=150-200 samples per group.  Now when I look at the data, its not normally distributed, and the variances are not equal. (eg, smallest standard deviation is 20 and the largest is 60 or simlar). The data is a function of counts, eg. how many times a player jumped during a game.
Now, if there were two groups I'd do a two sample KS test. However, since there are 6 groups, I am wondering if the lack of homogeneous variances will affect my test result if I perform a Kruskal Wallis ANOVA?
In other words, is homogeneity of variances a strict requirement that must be fulfilled for a Kruskal Wallis one way ANOVA?
Or am I wrong in using this test, and there is something else which I have not thought of?
EDIT: I am working with SPSS
EDIT2: Saw this and tried doing it with GLM, but in the end when looking at the model, it ends up being an ANOVA

A: To be optimal, the proportional odds assumption must be satisfied for K-W.  This is often a weaker assumption than constant variance.  To check the assumption, compute the empirical distribution function for each of the 6 groups, take the $\log\frac{p}{1-p}$ transformation of it, and plot this on the $y$-axis vs. the original values on the $x$ axis; check for parallelism.
K-W can be valid (though without optimal power) if the prop. odds assumption is violated, if you are careful in how $P$-values are computed.


Q: Как сделать часы, показывающие реальное время Как реализовать работающие часы в PyQt5?
Имеется ввиду, чтобы они показывали текущее время и шли дальше.
Мой код снизу:
from datetime import datetime
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.Qt import *

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(649, 168)
        MainWindow.setMinimumSize(QtCore.QSize(0, 0))
        MainWindow.setMaximumSize(QtCore.QSize(999999, 999999))
        MainWindow.setStyleSheet("MainWindow\n""{\n""    background-color: rgb(37, 37, 37);\n""}")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setMaximumSize(QtCore.QSize(99999, 999999))
        self.centralwidget.setStyleSheet("background-color: rgb(37, 37, 37)\n""")
        self.centralwidget.setObjectName("centralwidget")

        self.frame = QtWidgets.QFrame(self.centralwidget)
        self.frame.setGeometry(QtCore.QRect(0, -1, 641, 171))
        self.frame.setMinimumSize(QtCore.QSize(0, 0))
        self.frame.setMaximumSize(QtCore.QSize(99999, 999))
        self.frame.setStyleSheet("MainWindow\n""{\n""    background-color:rgb(46, 46, 46)\n""}")
        self.frame.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame.setObjectName("frame")
        self.tabWidget = QtWidgets.QTabWidget(self.frame)
        self.tabWidget.setGeometry(QtCore.QRect(0, 0, 651, 161))
        self.tabWidget.setMinimumSize(QtCore.QSize(4, 0))
        font = QtGui.QFont()
        font.setFamily("Rio Glamour personal use")
        font.setPointSize(14)
        self.tabWidget.setFont(font)
        self.tabWidget.setStyleSheet(
        "QTabWidget::pane\n""{\n""    border: 1px;\n""    background: rgb(37, 37, 37);\n""}\n""\n""QTabBar::tab\n""{\n""    background: rgb(37, 37, 37);\n""    color:rgb(255, 255, 255);\n""}\n""\n""\n""QTabBar::tab:selected\n""{\n""    background:rgb(26, 26, 26);\n""    color:rgb(255, 255, 255);\n""}\n""\n""QTabBar::tab:hover\n""{\n""    background:rgb(57, 57, 57);\n""    color:rgb(255, 255, 255);\n""}\n""\n""")
        self.tabWidget.setObjectName("tabWidget")
        self.tab = QtWidgets.QWidget()
        font = QtGui.QFont()
        font.setPointSize(8)
        self.tab.setFont(font)
        self.tab.setObjectName("tab")
        self.label = QtWidgets.QLabel(self.tab)
        self.label.setGeometry(QtCore.QRect(-4, -8, 651, 141))
        self.label.setText("")
        self.label.setObjectName("label")
        self.tabWidget.addTab(self.tab, "")

        self.tab_2 = QtWidgets.QWidget()
        self.tab_2.setObjectName("tab_2")

        self.label_2 = QtWidgets.QLabel(self.tab_2)
        self.label_2.setGeometry(QtCore.QRect(0, 0, 661, 141))
        self.label_2.setText("")
        self.label_2.setObjectName("label_2")

        # !!! +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
        self.layout = QGridLayout(self.tab_2)  # !!! +++
        self.layout.addWidget(self.label_2, 0, 0, 1, 2)  # !!! +++
        # !!! +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

        self.tabWidget.addTab(self.tab_2, "")
        self.tab_3 = QtWidgets.QWidget()
        self.tab_3.setStyleSheet("background-color: rgb(37, 37, 37);\n""color: rgb(255, 255, 255);")
        self.tab_3.setObjectName("tab_3")
        self.label_3 = QtWidgets.QLabel(self.tab_3)
        self.label_3.setGeometry(QtCore.QRect(10, 0, 661, 141))
        self.label_3.setText("")
        self.label_3.setObjectName("label_3")
        self.tabWidget.addTab(self.tab_3, "")
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(2)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Time"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Stopwatch"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("MainWindow", "Timer"))

class ManinWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
    super().__init__()
    self.setupUi(self)

    self.tabWidget.currentChanged.connect(self.current_index)
    self.tabWidget.setCurrentIndex(0)

def add_functions(self):
    # Часы
    self.label.setText(QDateTime.currentDateTime().toString('HH:mm:ss\ndd MM yyyy'))
    self.label.setFont(QtGui.QFont("Capsuula", 40))
    self.label.setStyleSheet("color: #DADDFC;")
    self.label.setAlignment(Qt.AlignHCenter)

    # !!! +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    # Секундомер --- tab_2
    self.temp = 0
    self.label_2.setText("00:00:00")
    self.label_2.setAlignment(Qt.AlignHCenter)
    self.label_2.setFont(QtGui.QFont("Capsuula", 40))
    self.label_2.setStyleSheet("color: #fff;")

    self.btn_start = QtWidgets.QPushButton("Start")
    self.btn_start.setStyleSheet("color: #fff; font-size: 15px; background-color: #555;")
    self.btn_start.clicked.connect(self.func_start)

    self.btn_continue = QtWidgets.QPushButton("Continue")
    self.btn_continue.setStyleSheet("color: #fff; font-size: 15px; background-color: #555;")
    self.btn_continue.clicked.connect(self.func_continue)

    self.btn_reset = QtWidgets.QPushButton("Reset")
    self.btn_reset.setStyleSheet("color: #fff; font-size: 15px; background-color: #555;")
    self.btn_reset.clicked.connect(self.func_reset)

    #        layout = QGridLayout(self)
    #        layout.addWidget(self.label_2, 0, 0, 1, 2)

    # ???        layout.addWidget(self.button_start, 1, 0, 1, 2)
    self.layout.addWidget(self.btn_start, 1, 0, 1, 2)

    # ???        layout.addWidget(self.button_continue, 2, 0, 1, 1)
    self.layout.addWidget(self.btn_continue, 2, 0, 1, 1)

    # ???        layout.addWidget(self.button_reset, 2, 1, 1, 1)
    self.layout.addWidget(self.btn_reset, 2, 1, 1, 1)

    self.btn_continue.hide()
    self.btn_reset.hide()

    self.timer = QtCore.QTimer()
    self.timer.setInterval(1000)
    # ???        self.timer.timeout.connect(self.displayTime)
    self.timer.timeout.connect(self.display_time)

def func_start(self):
    if self.btn_start.text() == "Start":
        self.timer.start()
        self.btn_start.setText("Stop")
    else:
        self.timer.stop()
        self.btn_start.setText("Start")
        self.btn_start.hide()
        self.btn_continue.show()
        self.btn_reset.show()

def func_reset(self):
    self.temp = 0
    self.label_2.setText("00:00:00")
    self.btn_start.setText("Start")
    self.btn_start.show()
    self.btn_continue.hide()
    self.btn_reset.hide()

def display_time(self):
    f_temp = datetime.utcfromtimestamp(self.temp).strftime("%H:%M:%S")
    # ------------------> ???????
    #        self.label_2.setTetx(f_temp)
    self.label_2.setText(f_temp)

    self.temp += 1

# !!! +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
def current_index(self, index):
    if index == 0:
        self.add_functions()

def func_continue(self):
    self.timer.start()
    self.btn_start.setText('Стоп')
    self.btn_start.show()
    self.btn_continue.hide()
    self.btn_reset.hide()
# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

if __name__ == "__main__":
import sys

app = QtWidgets.QApplication(sys.argv)
w = ManinWindow()
w.show()
sys.exit(app.exec_())

Написать код надо между комментариями "#Часы" и "#Секундомер"

A: Попробуйте так:
from datetime import datetime
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.Qt import *

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(649, 168)
        MainWindow.setMinimumSize(QtCore.QSize(0, 0))
        MainWindow.setMaximumSize(QtCore.QSize(999999, 999999))
        MainWindow.setStyleSheet("MainWindow\n""{\n""    background-color: rgb(37, 37, 37);\n""}")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setMaximumSize(QtCore.QSize(99999, 999999))
        self.centralwidget.setStyleSheet("background-color: rgb(37, 37, 37)\n""")
        self.centralwidget.setObjectName("centralwidget")

        self.frame = QtWidgets.QFrame(self.centralwidget)
        self.frame.setGeometry(QtCore.QRect(0, -1, 641, 171))
        self.frame.setMinimumSize(QtCore.QSize(0, 0))
        self.frame.setMaximumSize(QtCore.QSize(99999, 999))
        self.frame.setStyleSheet("MainWindow\n""{\n""    background-color:rgb(46, 46, 46)\n""}")
        self.frame.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame.setObjectName("frame")
        self.tabWidget = QtWidgets.QTabWidget(self.frame)
        self.tabWidget.setGeometry(QtCore.QRect(0, 0, 651, 161))
        self.tabWidget.setMinimumSize(QtCore.QSize(4, 0))
        font = QtGui.QFont()
        font.setFamily("Rio Glamour personal use")
        font.setPointSize(14)
        self.tabWidget.setFont(font)
        self.tabWidget.setStyleSheet(
        "QTabWidget::pane\n""{\n""    border: 1px;\n""    background: rgb(37, 37, 37);\n""}\n""\n""QTabBar::tab\n""{\n""    background: rgb(37, 37, 37);\n""    color:rgb(255, 255, 255);\n""}\n""\n""\n""QTabBar::tab:selected\n""{\n""    background:rgb(26, 26, 26);\n""    color:rgb(255, 255, 255);\n""}\n""\n""QTabBar::tab:hover\n""{\n""    background:rgb(57, 57, 57);\n""    color:rgb(255, 255, 255);\n""}\n""\n""")
        self.tabWidget.setObjectName("tabWidget")
        self.tab = QtWidgets.QWidget()
        font = QtGui.QFont()
        font.setPointSize(8)
        self.tab.setFont(font)
        self.tab.setObjectName("tab")
        self.label = QtWidgets.QLabel(self.tab)
        self.label.setGeometry(QtCore.QRect(-4, -8, 651, 141))
        self.label.setText("")
        self.label.setObjectName("label")
        self.tabWidget.addTab(self.tab, "")

        self.tab_2 = QtWidgets.QWidget()
        self.tab_2.setObjectName("tab_2")

        self.label_2 = QtWidgets.QLabel(self.tab_2)
        self.label_2.setGeometry(QtCore.QRect(0, 0, 661, 141))
        self.label_2.setText("")
        self.label_2.setObjectName("label_2")

        # !!! +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
        self.layout = QGridLayout(self.tab_2)  # !!! +++
        self.layout.addWidget(self.label_2, 0, 0, 1, 2)  # !!! +++
        # !!! +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

        self.tabWidget.addTab(self.tab_2, "")
        self.tab_3 = QtWidgets.QWidget()
        self.tab_3.setStyleSheet("background-color: rgb(37, 37, 37);\n""color: rgb(255, 255, 255);")
        self.tab_3.setObjectName("tab_3")
        self.label_3 = QtWidgets.QLabel(self.tab_3)
        self.label_3.setGeometry(QtCore.QRect(10, 0, 661, 141))
        self.label_3.setText("")
        self.label_3.setObjectName("label_3")
        self.tabWidget.addTab(self.tab_3, "")
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(2)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Time"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Stopwatch"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("MainWindow", "Timer"))

class ManinWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.tabWidget.currentChanged.connect(self.current_index)
        self.tabWidget.setCurrentIndex(0)

# !!! +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
        self.working_clock = QtCore.QTimer()
        self.working_clock.setInterval(1000)
        self.working_clock.timeout.connect(self.display_clock)
        self.working_clock.start()
# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    def add_functions(self):
        # Часы
        self.label.setText(QDateTime.currentDateTime().toString('HH:mm:ss\ndd MM yyyy'))
        self.label.setFont(QtGui.QFont("Capsuula", 40))
        self.label.setStyleSheet("color: #DADDFC;")
        self.label.setAlignment(Qt.AlignHCenter)

        # Секундомер --- tab_2
        self.temp = 0
        self.label_2.setText("00:00:00")
        self.label_2.setAlignment(Qt.AlignHCenter)
        self.label_2.setFont(QtGui.QFont("Capsuula", 40))
        self.label_2.setStyleSheet("color: #fff;")

        self.btn_start = QtWidgets.QPushButton("Start")
        self.btn_start.setStyleSheet("color: #fff; font-size: 15px; background-color: #555;")
        self.btn_start.clicked.connect(self.func_start)

        self.btn_continue = QtWidgets.QPushButton("Continue")
        self.btn_continue.setStyleSheet("color: #fff; font-size: 15px; background-color: #555;")
        self.btn_continue.clicked.connect(self.func_continue)

        self.btn_reset = QtWidgets.QPushButton("Reset")
        self.btn_reset.setStyleSheet("color: #fff; font-size: 15px; background-color: #555;")
        self.btn_reset.clicked.connect(self.func_reset)
        self.layout.addWidget(self.btn_start, 1, 0, 1, 2)
        self.layout.addWidget(self.btn_continue, 2, 0, 1, 1)
        self.layout.addWidget(self.btn_reset, 2, 1, 1, 1)

        self.btn_continue.hide()
        self.btn_reset.hide()

        self.timer = QtCore.QTimer()
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.display_time)

    def func_start(self):
        if self.btn_start.text() == "Start":
            self.timer.start()
            self.btn_start.setText("Stop")
        else:
            self.timer.stop()
            self.btn_start.setText("Start")
            self.btn_start.hide()
            self.btn_continue.show()
            self.btn_reset.show()

    def func_reset(self):
        self.temp = 0
        self.label_2.setText("00:00:00")
        self.btn_start.setText("Start")
        self.btn_start.show()
        self.btn_continue.hide()
        self.btn_reset.hide()

    def display_time(self):
        f_temp = datetime.utcfromtimestamp(self.temp).strftime("%H:%M:%S")
        self.label_2.setText(f_temp)
        self.temp += 1

    def current_index(self, index):
        if index == 0:
            self.add_functions()

    def func_continue(self):
        self.timer.start()
        self.btn_start.setText('Стоп')
        self.btn_start.show()
        self.btn_continue.hide()
        self.btn_reset.hide()

# !!! +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    def display_clock(self):
        self.label.setText(QDateTime.currentDateTime().toString('HH:mm:ss\ndd MM yyyy'))
# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = ManinWindow()
    w.show()
    sys.exit(app.exec_())


Q: webformmailer.php not sending user text entries So I can't find anything about why my form isn't sending the text the users are entering. Its only submitting blank fields using webformmailer.php and can't find any help on godaddy site either. I know I'm using the same id for the name and email fields so if that is really the problem I'll change it but I wouldn't think it is. Heres my code.
        <form id="contact-form" action="/webformmailer.php" method="POST" >

            <textarea id="textarea" placeholder="Message Here"></textarea>
            <input type="text"  id="username" name="Firstname" placeholder="Full Name" />
            <input type="text"  id="username" name="email" placeholder="Email"  />
            <input type="submit" name ="submit" value="Submit" />

        </form>

the file is generated from godaddy.com but heres the code. I also have a simple form with no textarea for messages that seems to work fine.
<?php

if ( !isset($_SERVER['SPI'])) {
    die();
}

if (!isset($_SERVER['DOCUMENT_ROOT'])) {
    echo("CRITICAL: we seem to be running outside of the norm.\n");
    header("Location: http://".$_SERVER["HTTP_HOST"]."/");
    die("CRITICAL: Document root unavailable.\n");
}

$request_method = $_SERVER["REQUEST_METHOD"];
if($request_method == "GET") {
    $query_vars = $_GET;
}
elseif ($request_method == "POST") {
    $query_vars = $_POST;
}

reset($query_vars);
function customsort($a,$b) {
    // $a is array for form vars, $b is comma seperated case sensitive field order
    // this is case sensitive -- good idea to hrc that.
    $data = array();
    if ( strstr($b,',') == FALSE )  {
            $b = $b.",";
    }
    $ordering = split(',',$b);
    foreach ($ordering as $orderitem) {
            if ( ($orderitem != null) && ($orderitem != "") ) {
                    if (isset($a[$orderitem])) {
                            $data[$orderitem] = $a[$orderitem];
                    }
            }
    }
    foreach ($a as $key=>$val) {
            $data[$key] = $a[$key];
    }
    return $data;
}

  function xmlentities($string) {
    return str_replace ( array('&', '"', "'", '<', '>'), array('&', '"',                    ''', '<', '>'), $string);
    }

   $t = date("U");

  $formhomedir = preg_replace('/.*\/home\/content/','',$_SERVER['DOCUMENT_ROOT']);
  $formhomedir = explode('/',$formhomedir);
  if (count($formhomedir) <= 4) {
    $formhome="/home/content/".$formhomedir[1]."/".$formhomedir[2]."/data/";
  }
  else {
            $formhome="/home/content/".$formhomedir[1]."/".$formhomedir[2]."/".$formhomedir[3]."/".$form     homedir[4]."/data/";
}

 $file_order = ".default";
 $file_format = ".text";
 $file_interval = ".15m";
 $field_order = "";

if (isset($query_vars['form_order'])) {
    if ($query_vars['form_order'] != "alpha") {
            $field_order=$query_vars['form_order'];
            $file_order=".custom";
            $query_vars = customsort($query_vars,$field_order);
    }
    else {
            switch ($query_vars['form_order']) {
                    case "alpha":
                            uksort($query_vars,'strnatcasecmp');
                            $file_order=".alpha";
                    break;
                    default:
                            $file_order=".default";
                    break;
            }
    }
  }

if (isset($query_vars['form_format'])) {
    switch ($query_vars['form_format']) {
            case "csv":
                    $file_format = ".csv";
            break;
            case "html":
                    $file_format = ".html";
            break;
            case "xml":
                    $file_format = ".xml";
            break;
            case "text":
            case "default":
            default:
                    $file_format = ".text";
            break;
    }
}

if (isset($query_vars['form_delivery'])) {
    switch ($query_vars['form_delivery']) {
            case "hourly":
                    $file_interval = ".60m";
            break;
            case "hourly_digest":
                    $file_interval = ".60mc";
            break;
            case "daily":
                    $file_interval = ".24h";
            break;
            case "daily_digest":
                    $file_interval = ".24hc";
            break;
            case "digest":
                    $file_interval = ".15mc";
            break;
            case "default":
            default:
                    $file_interval = ".15m";
            break;
    }
}

$file = $formhome."form_".$t.$file_order.$file_format.$file_interval;
$fp = fopen($file,"w");

reset($query_vars);
switch ($file_format) {
    case ".csv":
            $csvkeys = "";
            $csvvals= "";
            $firsttime = "";
            while (list ($key, $val) = each ($query_vars)) {
                    if ( ($key == "form_order") ||
                            ($key == "form_format") ||
                            ($key == "form_delivery") ||
                            ($key == "redirect") ) {
                    }
                    else {
                            if ($csvkeys != "") {
                                    $firsttime=",";
                            }
                            $tmpkey=escapeshellcmd($key);
                            $csvkeys = $csvkeys.$firsttime."'".$tmpkey."'";
                            $tmpval=escapeshellcmd($val);
                            $csvvals = $csvvals.$firsttime."'".$tmpval."'";
                    }
            }
            fputs($fp,"$csvkeys\n");
            fputs($fp,"$csvvals\n");
    break;
    case ".html":
            fputs($fp,"
\n");
    break;
    case ".xml":
            fputs($fp,"<form>\n");
    break;
}

  reset($query_vars);
  while (list ($key, $val) = each ($query_vars)) {
    if ($key == "redirect") {
            $landing_page = $val;
    }
    if ( ($key == "form_order") ||
            ($key == "form_format") ||
            ($key == "form_delivery") ||
            ($key == "redirect") ) {

    }
    else {
            switch ($file_format) {
                    case ".html":
                            fputs($fp,"\t
\n");
                            fputs($fp,"\t\t$key	\n");
                            fputs($fp,"\t\t$val	\n");
                            fputs($fp,"\t
\n");

                    break;
                    case ".csv":
                            // content is already output
                    break;
                    case ".xml":
                       fputs($fp,"\t<field>\n");
                       fputs($fp,"\t\t<fieldname>".xmlentities($key)."
  </fieldname>\n");
                       fputs($fp,"\t\t<fieldvalue>".xmlentities($val)
  </fieldvalue>\n");
                            fputs($fp,"\t</field>\n");
                    break;
                    case ".text":
                    default:
                            fputs($fp,$key.": ".$val."\n");
                    break;
            }
    }
}

switch ($file_format) {
    case ".html":
            fputs($fp,"
\n");
    break;
    case ".xml":
            fputs($fp,"</form>\n");
    break;
}

fclose($fp);

if ($landing_page != "") {
    header("Location: http://".$_SERVER["HTTP_HOST"]."/$landing_page");
}
else {
    header("Location: http://".$_SERVER["HTTP_HOST"]."/");
}

?>

A: *

*Your <textarea> doesn't have a name, so it can't be a successful control.

*You never attempt to access $_POST['Firstname'] (or $query_vars['Firstname] for that matter)

*Ditto $_POST['email']

Also your HTML is invalid (use a validator) and you are abusing the placeholder attribute as a label.


Q: Solving linear difference equation $f(n)=\frac{1}{6}f(n-1)+\frac{2}{3}f(n+1)$, $0
Solving linear difference equation $f(n)=\frac{1}{6}f(n-1)+\frac{2}{3}f(n+1)$, $0<n<\infty$

with $f(0)=4, f(1)=3$

The text says to solve $f(n)=af(n-1)+bf(n+1)$ to try functions of the form $f(n)=\alpha^n$ and that such functions are solutions iff $\alpha^n=a\alpha^{n-1}+b\alpha^{n+1}$ or $\alpha=a+b\alpha^2$ and then using quadradic formula $\alpha=\frac{1+\sqrt{1-4ab}}{2b}$
So my thought was for this question I need to use $a=\frac{1}{6}$, $b=\frac{2}{3}$ which gives me $\alpha=\frac{1\pm\sqrt{1-4(\frac{1}{6})(\frac{2}{3})}}{2(\frac{2}{3})}$ but the text gives a solution as $\alpha=\frac{3\pm \sqrt{5}}{4}$ which I can't see how this is determined.
The general solution is then given as $f(n)=c_1(\frac{3+\sqrt{5}}{4})^n+c_2(\frac{3-\sqrt{5}}{4})^n$


Q: EF 5 & MVC 4: unable to get tables with no reference in Controller using Databse first I am using MVC 4, EF 5 and Database first approach. I have added 2 new tables(UserDetails and UserAddress) with no reference in existing database. I am able to see all tables including these 2 new table in EDMX file and created model also. But when im trying to get the tables in controller, its showing all Models except UserDetails and UserAddress - in following way.
[Authorize]
[InitializeSimpleMembership]
public class AccountController : Controller
{
  private DbRestaurantEntities db = new DbRestaurantEntities();

   public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                    var userId = WebSecurity.GetUserId(User.Identity.Name);
                    //db.UserDetails -- Not showing
                    WebSecurity.Login(model.UserName, model.Password);
                    return RedirectToAction("Index", "Home");
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }
            return View(model);
        }
}

Am i missing something?

A: WebSecurity uses different dbContext
, you need to use the same dbContext, which is used to create the database tables. you can check it out in the web.config file for the connectionstring.. and use the exact dbContext
Add this in AuthConfig.cs
WebSecurity.InitializeDatabaseConnection(
        "specifyTheDbContextHere",
        "UserProfile",
        "UserId",
        "UserName",
        autoCreateTables: true
    );


Q: how to implement PHP file_get_contents() function in JSP(java)? In PHP we can use file_get_contents() like this:
<?php

  $data = file_get_contents('php://input');
  echo file_put_contents("image.jpg", $data);

?>

How can I implement this in Java (JSP)?

A: Here's a function I created in Java a while back that returns a String of the file contents. Hope it helps.
There might be some issues with \n and \r but it should get you started at least.
// Converts a file to a string
private String fileToString(String filename) throws IOException
{
    BufferedReader reader = new BufferedReader(new FileReader(filename));
    StringBuilder builder = new StringBuilder();
    String line;

    // For every line in the file, append it to the string builder
    while((line = reader.readLine()) != null)
    {
        builder.append(line);
    }

    reader.close();
    return builder.toString();
}

A: This will read a file from an URL and write it to a local file. Just add try/catch and imports as needed.
   byte buf[] = new byte[4096];
   URL url = new URL("http://path.to.file");
   BufferedInputStream bis = new BufferedInputStream(url.openStream());
   FileOutputStream fos = new FileOutputStream(target_filename);

   int bytesRead = 0;

   while((bytesRead = bis.read(buf)) != -1) {
       fos.write(buf, 0, bytesRead);
   }

   fos.flush();
   fos.close();
   bis.close();


Q: Invalid Argument Running Google Go Binary in Linux I’ve written a very small application in Go, and configured an AWS Linux AMI to host. The application is a very simple web server. I’ve installed Go on the Linux VM by following the instructions in the official documentation to the letter. My application runs as expected when invoked with the “go run main.go” command.
However, I receive an “Invalid argument” error when I attempt to manually launch the binary file generated as a result of running “go install”. Instead, if I run “go build” (which I understand to be essentially the same thing, with a few exceptions) and then invoke the resulting binary, the application launches as expected.
I’m invoking the file from within the $GOPATH/bin/ folder as follows:
./myapp

I’ve also added $GOPATH/bin to the $PATH variable.
I have also moved the binary from $GOPATH/bin/ to the src folder, and successfully run it from there.
The Linux instance is a 64-bit instance, and I have installed the corresponding Go 64-bit installation.

A: go build builds everything (that is, all dependent packages), then produces the resulting executable files and then discards the intermediate results (see this for an alternative take; also consider carefully reading outputs of go help build and go help install).
go install, on the contrary, uses precompiled versions of the dependent packages, if it finds them; otherwise it builds them as well, and installs under $PATH/pkg. Hence I might suggest that go install sees some outdated packages which screw the resulting build.
Consider running go install ./... in your $GOPATH/src.
Or may be just selective go install uri/of/the/package for each dependent package, and then retry building the executable.


Q: Docker run on sub domains My goal is to deploy multiple webapps and access them through sub-domains, I'm currently running them on different ports, I have nginx on the server and the containers are running apache.
docker run -p 8001:80 -d apache-test1
docker run -p 8002:80 -d apache-test2

and I'm able to access them by going to
http://example.com:8001

or
    http://example.com:8002
But I like to access them through sub-domains instead
http://example.com:8001 -> http://test1.example.com
http://example.com:8002 -> http://test2.example.com

I have nginx running on the server with the following server settings
server {
    server_name test1.anomamedia.com;
    location / {
        proxy_redirect off;
        proxy_set_header Host $host ;
        proxy_set_header X-Real-IP $remote_addr ;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for ;
        proxy_pass http://localhost:8001;
    }
}

server {
    server_name test2.anomamedia.com;
    location / {
        proxy_redirect off;
        proxy_set_header Host $host ;
        proxy_set_header X-Real-IP $remote_addr ;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for ;
        proxy_pass http://localhost:8002;
    }
}

If its of any help this is my Dockerfile
FROM ubuntu

RUN apt-get update
RUN apt-get -y upgrade

RUN sudo apt-get -y install apache2 php5 libapache2-mod-php5

# Install apache, PHP, and supplimentary programs. curl and lynx-cur are for debugging the container.
RUN DEBIAN_FRONTEND=noninteractive apt-get -y install apache2 libapache2-mod-php5 php5-mysql php5-gd php-pear php-apc php5-curl curl lynx-cur

# Enable apache mods.
RUN a2enmod php5
RUN a2enmod rewrite

EXPOSE 80

# Copy site into place.
ADD html /var/www/html

# Update the default apache site with the config we created.
ADD apache-config.conf /etc/apache2/sites-enabled/000-default.conf

# By default, simply start apache.
CMD /usr/sbin/apache2ctl -D FOREGROUND

A: I have similar problems. Also I often need to add and remove containers, so I don't whant to edit nginx conf everytime. My solution was using jwilder/nginx-proxy.
then you just start containers with exposed port (--expose 80, not -p 80:80) and add env variables:
-e VIRTUAL_HOST=foo.bar.com

Don't forget to transfer with your main nginx traffic with right headers:
server {
    listen       80;# default_server;
    #send all subdomains to nginx-proxy
    server_name  *.bar.com;

    #proxy to docker nginx reverse proxy
    location / {
        proxy_set_header   X-Real-IP $remote_addr; #for some reason nginx
        proxy_set_header   Host      $http_host;   #doesn't pass these by default
        proxy_pass         http://127.0.0.1:5100;
    }

}

A: Have a look at the nginx-proxy project (https://github.com/jwilder/nginx-proxy). I wrote a tutorial in my blog which demonstrates exactly what you want to achieve using it: https://blog.florianlopes.io/host-multiple-websites-on-single-host-docker
This tool automatically forwards requests to the appropriate container (based on subdomain via the VIRTUAL_HOST container environment variable).
For example, if you want to access your container through test1.example.com, simply set the VIRTUAL_HOST container environment variable to test1.example.com.


Q: Before/After is not working in catalog_category_view_type_layered.xml inside sidebar.main? I am trying to add a string at the top of the product details page navigation referenceContainer name="sidebar.main" but the string is coming after product Filters.
How can i change or move my block at the top of the filters section or sidebar main, as i have tried so many ways but no luck as i added below.
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <referenceContainer name="sidebar.main">
          <block class="I95dev\Categorysearch\Block\Index\Index" name="index_index" template="index/index.phtml" before="-">
            </block>
        </referenceContainer>
</page>

Can any one help me on this.

A: It's because the layered nav is also set to before="-", the fix is to move the layered nav so it displays after your new block.
<move element="catalog.leftnav" destination="sidebar.main" after="index_index" />

Old Answer
It's likely happening because the product filters also have before="-" set, so both are fighting to display first. I think setting your block to display before the product filters (name is catalog.leftnav) will fix it, like so:
<block class="I95dev\Categorysearch\Block\Index\Index" name="index_index" template="index/index.phtml" before="catalog.leftnav" />

~~Or~~
<move element="catalog.leftnav" destination="sidebar.main" after="index_index" />

~~I'm not sure if this matters but I usually prefix the template with the module so the template would be:~~
template="I95dev/Categorysearch::index/index.phtml"


Q: How to improve look and feel of JAVA swing GUI? I am working on a project that uses Java Swing. The default look and feel of the Java Swing GUI is very boring. Is there any way I can use a better look and feel? Something like on web pages...

A: You can set the look and feel to reflect the platform:
try {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
    e.printStackTrace();
}

If this is not nice enough for you, take a look at SWT for Eclipse.

A: if you're good with Photo shop you could declare the JFrame as undecorated and create your own image that will server as your custom GUI.
in this example refer to the JFrame as frame.
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
//If you want full screen enter frame.setExtendedState(JFrame.MAXIMIZE_BOTH);
frame.setUndecorated(true);

now that the JFrame has its own border and custom GUI, if you defined your own custom buttons for minimize, maximize, and exit you need to lay a JPanel over the buttons and declare what those buttons will do in a action listener function(lol sorry...I don't know if it's called function like c++ or class...)
for example we will refer to the JPanel as panel and we will set up a exit button.
panel.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
System.exit(JFrame.EXIT_ON_CLOSE);
});
}


Q: smoothing between pixels of imagesc\imshow in matlab like the matplotlib imshow When I use matplotlib's imshow() in python to represent a small matrix, it produces a some sort if smoothing between pixels. Is there any way to have this in Matlab when using imshow or imagesc?
For example, using matplotlib this is the output of the identity matrix imshow(eye(3)):

while in matlab,  imagesc(eye(3)):

A solution I can think of is to extrapolate and smooth using some filter, but that won't be relevant for the single pixel levels. I've also tried myaa and export_fig, but they are not satisfactory. Myaa is taking all GUI usabily after being applied, so I can't zoom in or out, and export_fig makes me save the figure to a file and then operate on that file, too cumbersome. So, is there a way to tell the figure engine of matlab (java or what not) to do this smoothing while keeping the nice usability of the figure GUI?

A: It is due to the default interpolation which is set to 'bilinear'. I think 'none' would be a more intuitive default. You can change the default interpolation method (eg interpolation=None) with:
mpl.rcParams['image.interpolation'] = 'none'

More information about customising Matplotlib can be found on the website
The code below will give you an overview of all interpolation methods:
methods = [None, 'none', 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', \
           'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos']

grid = np.random.rand(4,4)

fig, ax = plt.subplots(3,6,figsize=(12,6), subplot_kw={'xticks': [], 'yticks': []})
fig.subplots_adjust(hspace=0.3, wspace=0.05)

ax = ax.ravel()

for n, interp in enumerate(methods):
    ax[n].imshow(grid, interpolation=interp)
    ax[n].set_title(interp)


Q: PCMCIA Card SD Reader not recognized I have a Dell 620 running Ubuntu 14.04 (all updates done, fresh install), and an old "Four in One PCMCIA CardReader" plugged into the PCMCDI slot of the Dell machine.
I have a working SD Card in the card reader, but this machine do not see the card.
I tried the SD card directly in another Ubuntu machine (which has a SD Card reader embedded in the hardware), and it works. So the issue is likely to be with the PCMCIA card.
How can I troubleshoot this?
Thanks,
FX


Q: Why java ThreadPoolExecutor kill thread when RuntimeException occurs? Why the unhanded exception is rethrown in worker when calling execute method ? As result new Thread will be created on next execution to maximize threads count

A:
Why java ThreadPoolExecutor kill thread when RuntimeException occurs?

I can only guess that the reason why ThreadPoolExecutor.execute(...) has the thread call runnable.run() directly and not wrap it in a FutureTask is so you would not incur the overhead of the FutureTask if you didn't care about the result.
If your thread throws a RuntimeException, which is hopefully a rare thing, and there is no mechanism to return the exception to the caller then why pay for the wrapping class?  So worst case, the thread is killed and will be reaped and restarted by the thread-pool.

A: There is no way to handle exception properly. Exception can't be propagated to caller thread and can't be simply swallowed.
Unhandled exception is thrown in thread is delegated to ThreadGroup.uncaughtException method, which prints output to System.err.print, until desired behavior is overridden for ThreadGroup.
So this is expected behavior, it can be compared with throwing unhanded exception in main method. In this case, JVM terminates execution and prints exception to the output.
But I'm not sure, why ThreadPoolExecutor does not handle it itself, ThreadPoolExecutor can log it itself. Creating new Thread is not so cheap.
Maybe there is an assumption, that some resources (native, threadLocal, threadStack, etc) associated with Thread should be released.


Q: Array Compatiblilty java These are my instructions:

Two arrays are said to be compatible if they are of the same size and
  if the ith element in the first array is greater than or equal to the
  ith element in the second array for all elements. If the array size is
  zero or less then display the message "Invalid array size". Write a Java
  program to find whether 2 arrays are compatible or not. If the arrays
  are compatible display the message as "Arrays are Compatible", if not
  then display the message as "Arrays are Not Compatible".

My solution is as follows:
class CompaibleArrays {
    public static void main(String []args){
        int n1=0;
        int n2=0;
        int flag=0;
        int []a1 = new int[20];
        int []a2 = new int[20];
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the size for First array:");
        n1 = sc.nextInt();
        if(n1<1){
            System.out.println("Invalid array size");
        }
        else{
            System.out.println("Enter the elements for First array:");
            for(int i=0 ; i<n1 ; i++){
                a1[i] = sc.nextInt();
            }

            System.out.println("Enter the size for Second array:");
            n2 = sc.nextInt();
            if(n1<1){
                System.out.println("Invalid array size");
            }
            else{
                System.out.println("Enter the elements for Second array:");
                for(int j=0 ; j<n2 ; j++){
                    a2[j] = sc.nextInt();
                }
            }
        }
        if(n1==n2){
            System.out.println("Arrays are Not Compatible");
        }
        else{
            for(int x=0 ; x<n1 ; x++){
                if(a1[x]>=a2[x]){
                    flag++;
                }
            }
            if(flag==n1){
                System.out.println("Arrays are Compatible");
            }
            else{
                System.out.println("Arrays are Not Compatible");
            }
        }

    }
}

Sample Input 1 :
 Enter the size for First array:
 5
 Enter the elements for First array:
 5
 14
 17
 19
 15
 Enter the size for Second array:
 5
 Enter the elements for Second array:
 2
 5
 9
 15
 7
 Sample Output 1:
 Arrays are Compatible

Sample Input 2 :
 Enter the size for First array:
 3
 Enter the elements for First array:
 1
 4
 7
 Enter the size for Second array:
 5
 Enter the elements for Second array:
 2
 5
 9
 5
 7
 Sample Output 2:
 Arrays are Not Compatible

Sample Input 3 :
 Enter the size for First array:
 -2
 Sample Output 3:
 Invalid array size

** Help me out **

A: There are a few issues in your code.

*

*In your else block, you need to replace (n1<1) with (n2<1).

*Replace if(n1==n2) with if(n1!=n2)

*You do not need to iterate through all the elements. If at any point you find the index elements of both the arrays do not satisfy the condition, you should break the loop. Use a boolean flag for this.

public class CompaibleArrays {
    public static void main(String []args){
        int n1=0;
        int n2=0;
        boolean flag=true;
        int []a1 = new int[20];
        int []a2 = new int[20];
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the size for First array:");
        n1 = sc.nextInt();
        if(n1<1){
            System.out.println("Invalid array size");
        }
        else{
            System.out.println("Enter the elements for First array:");
            for(int i=0 ; i<n1 ; i++){
                a1[i] = sc.nextInt();
            }

            System.out.println("Enter the size for Second array:");
            n2 = sc.nextInt();
            if(n2<1){
                System.out.println("Invalid array size");
            }
            else{
                System.out.println("Enter the elements for Second array:");
                for(int j=0 ; j<n2 ; j++){
                    a2[j] = sc.nextInt();
                }
            }
        }
        if(n1!=n2){
            System.out.println("Arrays are Not Compatible");
        }
        else{
            for(int x=0 ; x<n1 ; x++){
                if(a1[x]<a2[x]){
                    flag = false;
                    break;
                }
            }
            if(flag==true){
                System.out.println("Arrays are Compatible");
            }
            else{
                System.out.println("Arrays are Not Compatible");
            }
        }

    }
}


Q: On telnet session file edit not happening using vi editor I used rlwrap because with telnet session arrow keys were not working, after starting telnet session with rlwrap am not able to edit the file in using vi editor.
Whether its problem with rlwrap.If i don't use arrow keys wont work in my telnet session.

A: how do you mean the arrow keys wont work?
is it a terminal emulation problem?
you should be able to use hjkl instead of the arrow keys in vi.


Q: Два условия в Foreach Возможно ли в foreach запихнуть два условия, что бы избежать foreach в foreach?
Пример:
foreach(var t in ViewBag.News){
       foreach(var n in ViewBag.Like){
    }
}

это превратить в это:
 foreach(var t in ViewBag.News && var n in ViewBag.Like){}

Весь код страницы:
@using WebPhotoArchive.Models
@model IQueryable<Post>
@{
    ViewBag.Title = "Home Page";
    string Name = null;
    int id_link = 0;
}

@if (ViewBag.News == null)
{

Подпишитесь на других пользователей, чтобы получать их публикации!

}
else
{
    foreach (var n in ViewBag.News)
    {

                @{ Name = n.UserDoName; id_link = n.UserDoId;}
                <input type="hidden" name="id_post" value="@n.Id" />

@Html.ActionLink(Name, "/UserProfile/" + id_link, "Home", new { @class = "nav navbar-nav", @style = "text-decoration: none; color: #000000;" })

                @Html.Raw("") @*для уменьшения добавить в img style='width:300px; height:350px;'*@

@Name:@n.Description

                            @foreach (var t in ViewBag.LikePost)
                            {
                                if (n.Id == t.LikingId)
                                {

                                }
                                else
                                {

                                }
                            }

    }
}

Контроллер:
public ActionResult Index()//новости
    {
        #region My Id, variable 'i' for get it
        int i = 0;
        var id = from c in db.Users where c.Login == User.Identity.Name select c.Id;
        foreach (var t in id)
        {
            i = t;
        }
        #endregion
        using (WebArchiveContext dbc = new WebArchiveContext())
        {
            var list_like = dbc.Likes.Where(l => l.LikerId == i);
            ViewBag.LikePost = list_like;
        }
        var news_following_id = db.Follows.Where(u => u.FollowerId == i).Select(u => u.FollowingId);
        IQueryable<Post> list_news = null;
        list_news = db.Posts.Where(u => news_following_id.Contains(u.UserDoId)).OrderByDescending(p => p.Time);
        if (list_news.Any())
        {
            ViewBag.News = list_news;
        }
        else ViewBag.News = null;
        return View();
    }

A: Смотрим на ваш цикл
@foreach (var t in ViewBag.LikePost)
{
    if (n.Id == t.LikingId)
    {

    }
    else
    {

    }
}

и что видим? Для каждого совпадающего поста вы ставите лайк, а для остальных картинку с отсутсвием лайка. Это неверно, так как для лайков, которые не относятся к посту, вы тоже что то нарисуете.
Как испроавить - заменить вложенный цикл, который вам не нужен, на условие:
@if (((IEnumerable<Like>)ViewBag.LikePost).Any(l=>l.LikingId == n.Id))
{

}
else
{

}

Dummy вариант
@{
    bool likeFound = false;

    foreach (var t in ViewBag.LikePost)
    {
        if (n.Id == t.LikingId)
        {
            likeFound = true;

            break;
        }
    }

    if (!likeFound)
    {

    }
}

A: Давайте не будем возиться со страницами ASP.NET, а используем консольное приложение. Ведь главное - сделать одновременную итерацию по двум коллекциям сразу. Я правильно понял?
Наши гипотетические коллекции:
var ViewBagNews = new List<string> { "a", "b", "c", "d" };
var ViewBagLike = new List<int> { 1, 2, 3, 4 };

Стандартный способ прохода сразу по двум коллекциям, когда их размеры равны. Используем цикл for:
for (int i = 0; i < ViewBagNews.Count; i++)
{
    Console.WriteLine(ViewBagNews[i] + " " + ViewBagLike[i]);
}

Допустим, коллекции не реализуют интерфейс IList, поэтому обращение по индексу невозможно.
Используем другой стандартный способ с применением энумераторов:
using (var newsEnumerator = ViewBagNews.GetEnumerator())
using (var likeEnumerator = ViewBagLike.GetEnumerator())
{
    while (newsEnumerator.MoveNext() && likeEnumerator.MoveNext())
    {
        Console.WriteLine(newsEnumerator.Current + " " + likeEnumerator.Current);
    }
}


Q: Use LIKE for strings in sql server 2008 I want to make a function that search in a table and returns rows that contain a certain word that I Insert like below. But when I use LIKE it give me an error: Incorrect syntax near '@perberesi'
CREATE FUNCTION perberesit7
(@perberesi varchar(100))
RETURNS @menu_rest TABLE
(emri_hotelit varchar(50),
emri_menuse varchar(50),
perberesit varchar(255))
AS
Begin
   insert into @menu_rest
   Select  dbo.RESTORANTET.Emri_Rest, dbo.MENU.Emri_Pjatës, dbo.MENU.Pershkrimi
   From RESTORANTET, MENU
   Where dbo.MENU.Rest_ID=dbo.RESTORANTET.ID_Rest and
          dbo.MENU.Pershkrimi LIKE %@perberesi%

   return

End

Pleae help me...How can I use LIKE in this case

A: try using:
'%' + @perberesi + '%'
instead of:
%@perberesi%
Some Examples

A: Ok, I just realized that you are creating a function, which means that you can't use INSERT. You should also really take Gordon's advice and use explicit joins and table aliases.
CREATE FUNCTION perberesit7(@perberesi varchar(100))
RETURNS @menu_rest TABLE (  emri_hotelit varchar(50),
                            emri_menuse varchar(50),
                            perberesit varchar(255))
AS
Begin
   return(
   Select  R.Emri_Rest, M.Emri_Pjatës, M.Pershkrimi
   From RESTORANTET R
   INNER JOIN MENU M
        ON M.Rest_ID = R.ID_Rest
   Where M.Pershkrimi LIKE '%' + @perberesi + '%')
End

A: Why do you have to define the return table?
The following is a inline table variable function that performs better than a multi-line table.  I wrote one to return columns that have the two letters 'id'.  Just modify for your own case.
See article from Wayne Sheffield.
http://blog.waynesheffield.com/wayne/archive/2012/02/comparing-inline-and-multistatement-table-valued-functions/
-- Use tempdb
use tempdb;
go

-- Simple ITVF
create function search_columns (@name varchar(128))
returns TABLE
return
(
select * from sys.columns where name like '%' + @name + '%'
)
go

-- Call the function
select * from search_columns('id');
go

However, since you have a '%' in the like clause at the front of the expression, a full table or index scan is likely.  You might want to look at full text indexing if you data is large.
http://craftydba.com/?p=1629


Q: Can Multiple WSO2 API manager integrate with single WSO2IS-KM 5.7.0? We have installed WSO2 IS-KM version 5.7.0 and we want to integrate Multiple WSO2 API Manager version 2.6.0 with WSO2 IS-KM.
 Requesting you to please suggest and share the link to configure multiple WSO2 API manager with WSO2 IS-KM version 5.7.0

A: Please find a simple set of configurations on setting up multiple API Manager nodes with a single IS as Key Manager. It is required to front the API Manager nodes with a load balancer (with sticky sessions enabled & data-sources are shared among all the nodes) and configure the API Manager nodes as follows
API Manager Nodes: api-manager.xml (assumption IS-KM port offset 1, therefore 9444)
<AuthManager>
  <!-- Server URL of the Authentication service -->
  <ServerURL>https://localhost:9444/services/</ServerURL>
  ...
</AuthManager>
...
<APIKeyValidator>
  <!-- Server URL of the API key manager -->
  <ServerURL>https://localhost:9444/services/</ServerURL>
  ...
</APIKeyValidator>

IS Key Manager Node: api-manager.xml
<APIGateway>
  <Environments>
    <Environment type="hybrid" api-console="true">
      ...
      <!-- Server URL of the API gateway -->
      <ServerURL>https://loadbalancer/services/</ServerURL>
      ...
</APIGateway>

Sample NGINX
upstream mgtnode {
  server localhost:9443; # api manager node 01
  server localhost:9443; # api manager node 02
}

server {
  listen 443;
  server_name mgtgw.am.wso2.com;
  proxy_set_header X-Forwarded-Port 443;
  ...
  location / {
    ...
    proxy_pass https://mgtnode;
  }
}

References

*

*Configuring IS as Key Manager


Q: Tensorflow did not save the required models I ask tensorflow to save models every 100 iterations in every epoch, the following is my code. But after 900 iterations, only trained models for the 500th, 600th, 700th, 800th, 900th iterations were saved.
with tf.Session(config = tf.ConfigProto(log_device_placement = True)) as sess:

    sess.run(init_op)

    for i in range(args.num_epochs):
        start_time = time.time()
        k = 0
        acc_train = 0
        # initialize the iterator to train_dataset
        sess.run(train_init_op)
        while True:
            try:
                accu, l, _ = sess.run([accuracy, loss, optimizer], feed_dict = {training: True})
                k += 1
                acc_train += accu
                if k % 100 == 0:
                    print('Epoch: {}, step: {}, training loss: {:.3f}, training accuracy: {:.2f}%'.format(i, k, l, accu * 100))
                    saver.save(sess, args.saved_model_path, global_step = (i+1) * k)
            except tf.errors.OutOfRangeError:
                break

The following is the training accuracies:
Epoch: 0, step: 100, training loss: 0.669, training accuracy: 59.38%
Epoch: 0, step: 200, training loss: 0.806, training accuracy: 54.69%
Epoch: 0, step: 300, training loss: 0.781, training accuracy: 57.81%
Epoch: 0, step: 400, training loss: 0.725, training accuracy: 64.06%
Epoch: 0, step: 500, training loss: 0.347, training accuracy: 89.06%
Epoch: 0, step: 600, training loss: 0.193, training accuracy: 89.06%
Epoch: 0, step: 700, training loss: 0.003, training accuracy: 100.00%
Epoch: 0, step: 800, training loss: 0.190, training accuracy: 98.44%
Epoch: 0, step: 900, training loss: 0.009, training accuracy: 100.00%
My question is why tensorflow did not saved models for the 100th, 200th, 300th, 400th iterations? Thank you!

A: It did, but I'm guessing the Saver instance you created had the default max_keep value of 5, so it overwrote them as the last 5 were created. To keep 10, change your saver creation line to
saver = tf.train.Saver(max_keep=10)

You might also want to play with the keep_checkpoint_every_n_hours argument if you don't want to save -every- one.


Q: Embedding Loops with 2 Variables Dim rng As Range, cell As Range, copyToCell As Range

For j = 9 To 23

         For i = 2 To 23
                 Set rng = ThisWorkbook.Sheets("Sheet A").Range(Cells(3, j), Cells(11, j))
                 Set copyToCell = ThisWorkbook.Sheets("Sheet B").Cells(3, i)

                  For Each cell In rng
                    If cell.Value <> vbNullString Then
                    copyToCell.Value = cell.Value
                    Set copyToCell = copyToCell.Offset(1, 0)
                    End If
                  Next cell

         i = i + 2
        Next i

j = j + 2
Next j

I'm trying to copy an array of cells from one sheet and have them pasted to another. The code I wrote places the values that are copied from "Sheet A" to "Sheet B" correctly, however, the values are incorrect.

The pic above is Sheet A. I'm trying to copy values from Range I3:Ill (Sheet A) and then have them pasted to the following Sheet B Range B3:B11 and so on for each plan listed.

I created a loop so that the values under Plan 2 and so on in Sheet A will transfer those values under Plan 2 and so on in Sheet B.
When I run my code it results in all 0's in each plan on Sheet B instead of 5,5,4 (under Plan 1) and 5 (under plan 2). Any ideas or another way around it besides having to use 2 variables in a loop?

A: Why the loop? Just put the loop values in the Range statements:

  Dim rng As Range, cell As Range, copyToCell As Range

  Set rng = ThisWorkbook.Sheets("Sheet1").Range(Cells(9, "j"), Cells(23, "j"))
  Set copyToCell = ThisWorkbook.Sheets("Sheet2").Cells(3, "i")

  rng.Copy copyToCell

End Sub

HTH


Q: Angular directive - update parent scope when another directive as also isolated scope I have written an angular directive that needs to update the parent scope.
angular.module('app').directive('googlePlace', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function ($scope, element, attributes, model) {

              $scope.property1 = 'some val';
              $scope.property2 = 'another val';
              $scope.$apply();

    };
});

But in my controller I do this:
MyCtrl = function($scope){
$scope.doSave = function(){
   // do some logic
   console.log($scope.property1);
   console.log($scope.property2);

}

}
When doSave runs, I'm getting undefined values in my console. How can I get it applied to the parents scope WITHOUT isolating the scope. I don't have this option because another directive on the same element isolates the scope.

A: It should work. By default if you don't specify scope in your directive it uses the parent scope so property1 and property2 should be set. try setting the scope in your directive to false. As a side note is not a good practice what you are doing. It will be better isolate the scope and add the property as attributes. This way you will have good encapsulation.
for example
angular.module('app').directive('googlePlace', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        scope: {
            property1: '=',
            property2: '='
        }
        link: function ($scope, element, attributes, model) {

            //here you have access to property 1 and 2

    };
});

function MyCtrl($scope) {
    $scope.property1 = null;
    $scope.property2 = null;

    $scope.doSave = function(){
   // do some logic
       console.log($scope.property1);
       console.log($scope.property2);
    }
}

And your html

A: I don't know what you are doing wrong, because it seems to work: http://jsfiddle.net/HB7LU/2865/
var myApp = angular.module('myApp',[]);
angular.module('myApp').directive('googlePlace', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function ($scope, element, attributes, model) {

              $scope.property1 = 'some val';
              $scope.property2 = 'another val';
              $scope.$apply();

    }
}
});

    angular.module('myApp').controller('MyCtrl', MyCtrl);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.doSave = function(){
   // do some logic
   console.log($scope.property1);
   console.log($scope.property2);

}
}


Q: Use API v2 to work with Customer Group Prices We are using a tool to integrate our financial software with Magento.
Does anyone know a way to write and read the Customer Group Prices with API v2?
Each customer has a different agreed price for products in Dynamics GP and we need to match this price in Magento.
This way, when a Customer logs into the Magento site, their agreed price will be displayed in all simple products.


Q: Instance variable to stop a running thread Header :
@interface CodeTest : NSObject {
BOOL cancelThread;
}

-(void) testCode;
-(void) stopRunning;
-(void) startRunning;

@property (assign) BOOL cancelThread;
@end

Implementation :
-(void)stopRunning{
    self.cancelThread = YES;
}

-(void)startRunning{
    self.cancelThread = NO;

    [NSThread detachNewThreadSelector:@selector(testCode) toTarget:self withObject:nil];

}
-(void)testCode{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSLog(@"STARTED");
    /* Std C99 code */
    while( conditions ){
            if(self.cancelThread){
                 conditions = NO;
            }
            ...
            ...
    }
    /* end of C code */
    [pool release];
}

As you can see, it tires to execute testCode on a separate thread and using the cancelThread BOOL as a stop execution flag in the separate thread.
I have the following issue :

*

*The compiler signals that self.cancelThread in the middle of the std c code is not valid (self is not defined). I think, it tries to interpret that statement as c code but this is obj-c.

There is something missing ?
UPDATE : It's not related to missing {}'s as one of you suggested... The code works perfectly without the if(self.cancelThread){ conditions = NO; }.

A:
-[CodeTest setCancelThread:]: unrecognized selector.

Means that you don't have a setter defined for the cancelThread property. You're missing
@synthesize cancelThread;

(in your @implementation section)

A: What do you mean by "    /* Std C99 code */"?
If that code is really being compiled as C99 code, then self.cancelThread is problematic because it is an Objective-C expression.  First, it is the equivalent of [self cancelThread], a method call and, secondly, it requiresself` which wouldn't be present in the body of a C99 function.
However, given that the code you showed has it in a method, the comment doesn't make sense.


Q: MySQL 5.7 group replication disables access over TCP/IP I'am testing new group-replication feature on MySQL 5.7 with multi-master replication on a Windows 2012 R2 system. I'm using for testing a single server and install to MySQL instance onm  TCP-Ports 3306 and 3306 using diffent data-dirs and tcp-ports, etc.
All works fine, even setting up group replication. But when i use start replication, i can't connect per TCP/IP (mysql -h 127.0.0.1 -u root -p) anymore only by socket (mysql -h localhost -u root -p).
Before starting group replication on second master:
>mysql -h 127.0.0.1 -P 3307 -u root -p -e "status; show processlist; SELECT * FROM performance_schema.replication_group_members"
--------------
mysql  Ver 14.14 Distrib 5.7.17, for Win64 (x86_64)

Connection id:          16
Current database:
Current user:           root@localhost
SSL:                    Cipher in use is DHE-RSA-AES128-GCM-SHA256
Using delimiter:        ;
Server version:         5.7.17-enterprise-commercial-advanced-log MySQL Enterprise Server - Advanced Edition (Commercial)
Protocol version:       10
Connection:             127.0.0.1 via TCP/IP
Server characterset:    utf8
Db     characterset:    utf8
Client characterset:    cp850
Conn.  characterset:    cp850
TCP port:               3307
Uptime:                 2 min 52 sec

Threads: 1  Questions: 43  Slow queries: 0  Opens: 127  Flush tables: 1  Open tables: 120  Queries per second avg: 0.250
--------------

+----+------+-----------------+------+---------+------+----------+------------------+
| Id | User | Host            | db   | Command | Time | State    | Info             |
+----+------+-----------------+------+---------+------+----------+------------------+
| 16 | root | localhost:49333 | NULL | Query   |    0 | starting | show processlist |
+----+------+-----------------+------+---------+------+----------+------------------+
+---------------------------+--------------------------------------+-------------+-------------+--------------+
| CHANNEL_NAME              | MEMBER_ID                            | MEMBER_HOST | MEMBER_PORT | MEMBER_STATE |
+---------------------------+--------------------------------------+-------------+-------------+--------------+
| group_replication_applier | c6dc60ef-f8db-11e6-b78f-005056aae5b3 | RS-6-48     |        3307 | OFFLINE      |
+---------------------------+--------------------------------------+-------------+-------------+--------------+

starting group replication with mysql -P 3307 -u root -p -e "START GROUP_REPLICATION"
After that trying to connect per tcp/ip is stucked endless. The TCP-Port is open and you can connect, but nothing more. The server is only reachable by localhost:
>mysql -h localhost -P 3307 -u root -p -e "status; show processlist; SELECT * FROM performance_schema.replication_group_members"
--------------
mysql  Ver 14.14 Distrib 5.7.17, for Win64 (x86_64)

Connection id:          39
Current database:
Current user:           root@localhost
SSL:                    Cipher in use is DHE-RSA-AES128-GCM-SHA256
Using delimiter:        ;
Server version:         5.7.17-enterprise-commercial-advanced-log MySQL Enterprise Server - Advanced Edition (Commercial)
Protocol version:       10
Connection:             localhost via TCP/IP
Server characterset:    utf8
Db     characterset:    utf8
Client characterset:    cp850
Conn.  characterset:    cp850
TCP port:               3307
Uptime:                 6 min 33 sec

Threads: 4  Questions: 87  Slow queries: 0  Opens: 137  Flush tables: 1  Open tables: 130  Queries per second avg: 0.221
--------------

+----+-------------+-----------------+------+---------+------+--------------------------------------------------------+------------------+
| Id | User        | Host            | db   | Command | Time | State                                                  | Info             |
+----+-------------+-----------------+------+---------+------+--------------------------------------------------------+------------------+
| 28 | system user |                 | NULL | Connect |   30 | System lock                                            | NULL             |
| 31 | system user |                 | NULL | Connect |   30 | Slave has read all relay log; waiting for more updates | NULL             |
| 39 | root        | localhost:49358 | NULL | Query   |    0 | starting                                               | show processlist |
+----+-------------+-----------------+------+---------+------+--------------------------------------------------------+------------------+
+---------------------------+--------------------------------------+-------------+-------------+--------------+
| CHANNEL_NAME              | MEMBER_ID                            | MEMBER_HOST | MEMBER_PORT | MEMBER_STATE |
+---------------------------+--------------------------------------+-------------+-------------+--------------+
| group_replication_applier | 76c585ef-f8df-11e6-80f7-005056aae5b3 | RS-6-48     |        3306 | ONLINE       |
| group_replication_applier | c6dc60ef-f8db-11e6-b78f-005056aae5b3 | RS-6-48     |        3307 | ONLINE       |
+---------------------------+--------------------------------------+-------------+-------------+--------------+

If a stop the replication again. Server is reachable under 127.0.0.1 again.
Any hints solving this problem? Thanks.
Appendix 1: excerpt from MySQL error log when starting group replication:
2017-02-23T06:59:15.291541Z 12 [Note] Plugin group_replication reported: 'Group communication SSL configuration: group_replication_ssl_mode: "DISABLED"'
2017-02-23T06:59:15.291541Z 12 [Note] Plugin group_replication reported: 'The Winsock 2.2 dll was found okay'
2017-02-23T06:59:15.291541Z 12 [Note] Plugin group_replication reported: '[GCS] Added automatically IP ranges 10.32.6.48/8,127.0.0.1/8 to the whitelist'
2017-02-23T06:59:15.291541Z 12 [Note] Plugin group_replication reported: '[GCS] SSL was not enabled'
2017-02-23T06:59:15.291541Z 12 [Note] Plugin group_replication reported: 'Initialized group communication with configuration: group_replication_group_name: "ced7cae9-6e09-455e-9fe0-a55627f7291d"; group_replication_local_address: "10.32.6.48:3307"; group_replication_group_seeds: "10.32.6.48:3306,10.32.6.48:3307"; group_replication_bootstrap_group: false; group_replication_poll_spin_loops: 0; group_replication_compression_threshold: 1000000; group_replication_ip_whitelist: "AUTOMATIC"'
2017-02-23T06:59:15.291541Z 14 [Note] 'CHANGE MASTER TO FOR CHANNEL 'group_replication_applier' executed'. Previous state master_host='<NULL>', master_port= 0, master_log_file='', master_log_pos= 4, master_bind=''. New state master_host='<NULL>', master_port= 0, master_log_file='', master_log_pos= 4, master_bind=''.
2017-02-23T06:59:15.307218Z 12 [Note] Plugin group_replication reported: 'Group Replication applier module successfully initialized!'
2017-02-23T06:59:15.307218Z 17 [Note] Slave SQL thread for channel 'group_replication_applier' initialized, starting replication in log 'FIRST' at position 0, relay log '.\railsys-enterprise-relay-bin-group_replication_applier.000008' position: 4
2017-02-23T06:59:15.307218Z 12 [Note] Plugin group_replication reported: 'auto_increment_increment is set to 7'
2017-02-23T06:59:15.307218Z 12 [Note] Plugin group_replication reported: 'auto_increment_offset is set to 2'
2017-02-23T06:59:15.307218Z 0 [Note] Plugin group_replication reported: 'state 4257 action xa_init'
2017-02-23T06:59:15.307218Z 0 [Note] Plugin group_replication reported: 'Successfully bound to 0.0.0.0:3307 (socket=2688).'
2017-02-23T06:59:15.307218Z 0 [Note] Plugin group_replication reported: 'Successfully set listen backlog to 32 (socket=2688)!'
2017-02-23T06:59:15.307218Z 0 [Note] Plugin group_replication reported: 'Successfully unblocked socket (socket=2688)!'
2017-02-23T06:59:15.307218Z 0 [Note] Plugin group_replication reported: 'connecting to 10.32.6.48 3307'
2017-02-23T06:59:15.307218Z 0 [Note] Plugin group_replication reported: 'Ready to accept incoming connections on 0.0.0.0:3307 (socket=2688)!'
2017-02-23T06:59:15.322881Z 0 [Note] Plugin group_replication reported: 'client connected to 10.32.6.48 3307 fd 2996'
2017-02-23T06:59:15.322881Z 0 [Note] Plugin group_replication reported: 'connecting to 10.32.6.48 3307'
2017-02-23T06:59:15.338478Z 0 [Note] Plugin group_replication reported: 'client connected to 10.32.6.48 3307 fd 2696'
2017-02-23T06:59:15.338478Z 0 [Note] Plugin group_replication reported: 'connecting to 10.32.6.48 3307'
2017-02-23T06:59:15.354138Z 0 [Note] Plugin group_replication reported: 'client connected to 10.32.6.48 3307 fd 2740'
2017-02-23T06:59:15.354138Z 0 [Note] Plugin group_replication reported: 'connecting to 10.32.6.48 3307'
2017-02-23T06:59:15.369687Z 0 [Note] Plugin group_replication reported: 'client connected to 10.32.6.48 3307 fd 3000'
2017-02-23T06:59:15.369687Z 0 [Note] Plugin group_replication reported: 'connecting to 10.32.6.48 3307'
2017-02-23T06:59:15.385311Z 0 [Note] Plugin group_replication reported: 'client connected to 10.32.6.48 3307 fd 2676'
2017-02-23T06:59:15.385311Z 0 [Note] Plugin group_replication reported: 'connecting to 10.32.6.48 3307'
2017-02-23T06:59:15.400933Z 0 [Note] Plugin group_replication reported: 'client connected to 10.32.6.48 3307 fd 3004'
2017-02-23T06:59:15.400933Z 0 [Note] Plugin group_replication reported: 'connecting to 10.32.6.48 3306'
2017-02-23T06:59:15.416653Z 0 [Note] Plugin group_replication reported: 'client connected to 10.32.6.48 3306 fd 2752'
2017-02-23T06:59:16.838441Z 0 [Note] Plugin group_replication reported: 'state 4257 action xa_snapshot'
2017-02-23T06:59:16.838441Z 0 [Note] Plugin group_replication reported: 'new state x_recover'
2017-02-23T06:59:16.838441Z 0 [Note] Plugin group_replication reported: 'state 4277 action xa_complete'
2017-02-23T06:59:16.838441Z 0 [Note] Plugin group_replication reported: 'new state x_run'
2017-02-23T06:59:21.213450Z 0 [ERROR] Plugin group_replication reported: 'This member has more executed transactions than those present in the group. Local transactions: 76c585ef-f8df-11e6-80f7-005056aae5b3:1,
c6dc60ef-f8db-11e6-b78f-005056aae5b3:1,
ced7cae9-6e09-455e-9fe0-a55627f7291d:1-1501 > Group transactions: 76c585ef-f8df-11e6-80f7-005056aae5b3:1,
ced7cae9-6e09-455e-9fe0-a55627f7291d:1-1502'
2017-02-23T06:59:21.213450Z 0 [Warning] Plugin group_replication reported: 'The member contains transactions not present in the group. It is only allowed to join due to group_replication_allow_local_disjoint_gtids_join option'
2017-02-23T06:59:21.213450Z 0 [Note] Plugin group_replication reported: 'Starting group replication recovery with view_id 14877553113022027:16'
2017-02-23T06:59:21.213450Z 20 [Note] Plugin group_replication reported: 'Establishing group recovery connection with a possible donor. Attempt 1/10'
2017-02-23T06:59:27.291607Z 20 [Note] 'CHANGE MASTER TO FOR CHANNEL 'group_replication_recovery' executed'. Previous state master_host='<NULL>', master_port= 0, master_log_file='', master_log_pos= 4, master_bind=''. New state master_host='RS-6-48', master_port= 3306, master_log_file='', master_log_pos= 4, master_bind=''.
2017-02-23T06:59:27.322957Z 20 [Note] Plugin group_replication reported: 'Establishing connection to a group replication recovery donor 76c585ef-f8df-11e6-80f7-005056aae5b3 at RS-6-48 port: 3306.'
2017-02-23T06:59:27.322957Z 21 [Warning] Storing MySQL user name or password information in the master info repository is not secure and is therefore not recommended. Please consider using the USER and PASSWORD connection options for START SLAVE; see the 'START SLAVE Syntax' in the MySQL Manual for more information.
2017-02-23T06:59:27.322957Z 22 [Note] Slave SQL thread for channel 'group_replication_recovery' initialized, starting replication in log 'FIRST' at position 0, relay log '.\railsys-enterprise-relay-bin-group_replication_recovery.000001' position: 4
2017-02-23T06:59:27.322957Z 21 [Note] Slave I/O thread for channel 'group_replication_recovery': connected to master 'replication@RS-6-48:3306',replication started in log 'FIRST' at position 4
2017-02-23T06:59:27.354089Z 20 [Note] Plugin group_replication reported: 'Terminating existing group replication donor connection and purging the corresponding logs.'
2017-02-23T06:59:27.354089Z 21 [Note] Slave I/O thread killed while reading event for channel 'group_replication_recovery'
2017-02-23T06:59:27.354089Z 21 [Note] Slave I/O thread exiting for channel 'group_replication_recovery', read up to log 'railsys-enterprise-bin.000002', position 607517
2017-02-23T06:59:27.354089Z 20 [Note] 'CHANGE MASTER TO FOR CHANNEL 'group_replication_recovery' executed'. Previous state master_host='RS-6-48', master_port= 3306, master_log_file='', master_log_pos= 4, master_bind=''. New state master_host='<NULL>', master_port= 0, master_log_file='', master_log_pos= 4, master_bind=''.
2017-02-23T06:59:27.385522Z 0 [Note] Plugin group_replication reported: 'This server was declared online within the replication group'

Appendix 2:
Server A my.ini:
[mysqld]
port=3306
loose-group_replication_local_address="10.32.6.48:3306"
loose-group_replication_group_seeds="10.32.6.48:3306,10.32.6.48:3307"

Server B my.ini
[mysqld]
port=3307
loose-group_replication_local_address="10.32.6.48:3307"
loose-group_replication_group_seeds="10.32.6.48:3306,10.32.6.48:3307"

A: The MySQL error log should have some clues. Can you show the log snippet from just after you issue START GROUP_REPLICATION?
Edit: after seeing the MySQL error log snippet...
It looks like you're perhaps using the same port for the mysql protocol and the GCS (group communication system)?
You have to use different ports. For example, in your config:
[mysqld]
port=3307
group_replication_local_address = '10.32.6.48:6606'
group_replication_group_seeds = '10.32.6.49:6606,10.32.6.50:6606'


Q: Obfuscating Android library projects I'm using AndEngine and two AndEngine extensions, for a total of 3 library projects. I really wish that I could obfuscate and optimize these library projects to improve application size, but I haven't seen anywhere how to do that with library projects.
Does anyone know what the Proguard configuration to do this is?

A: When Application is compiled, all *.java files in references Library Projects are compiled into Application's bin/classes folder. And obfuscation step is done using .class files in this folder. This means that all referenced Library Projects are automatically obfuscated when you obfuscate your application.


Q: MySqlException: Unable to connect to any of the specified MySQL hosts. MySql.Data.MySqlClient.NativeDriver.Open() Here is the code that connects to MySql and attemps to query data, and these are the errors i'm getting:

An unhandled exception occurred while processing the request.
  MySqlException: Timeout expired. The timeout period elapsed prior to
  completion of the operation or the server is not responding.
  MySql.Data.Common.StreamCreator.GetTcpStream(MySqlConnectionStringBuilder
  settings)
MySqlException: Unable to connect to any of the specified MySQL hosts.
  MySql.Data.MySqlClient.NativeDriver.Open()

public async Task<List<Store>> getStores(double lat, double lng)
    {
        List<Store> stores = new List<Store>();
        using (MySqlConnection connection = GetConnection())
        {
            await connection.OpenAsync();   // the code blows up here from time to time

            // request to return nearby stores
            MySqlCommand cmd = new MySqlCommand("SELECT * FROM Stores WHERE ABS(latitude- @latitude) < 0.006 AND ABS(longitude - @longtitude) < 0.006", connection);
            cmd.Parameters.Add(new MySqlParameter("@latitude", lat));
            cmd.Parameters.Add(new MySqlParameter("@longtitude", lng));
            cmd.CommandTimeout = 120;
            // MySqlDataAdapter dataAdapter = new MySqlDataAdapter(cmd);
            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    stores.Add(new Store()
                    {
                        id = Convert.ToInt32(reader["id"]),
                        address = reader["address"].ToString(),
                        latitude = Convert.ToDouble(reader["latitude"]),
                        longtitude = Convert.ToDouble(reader["longitude"])
                    });
                }
            }
        }

        return stores;
    }


Q: HighCharts: align rotated multiline label I'm trying to align axis labels in HighCharts
Labels should not be trimed, so ellipsis is not allowed
How it looks now:

How I want it to be:

Code: https://jsfiddle.net/9xw6dL3f/25/
{
  "chart": {
    "width": 500,
    "height": 300,
    "type": "column"
  },
  "title": {
    "text": null
  },
  "xAxis": {
    "type": "category",
    "labels": {
      "rotation": -90,
      "style": {
        "textOverflow": "none"
      }
    }
  },
  "series": [
    {
      "name": "",
      "data": [

        { "name": "Follow me into my theatre of lunacy", "y": -10, "color": "#ABC" },
        { "name": "1", "y": 1, "color": "#000" },
        { "name": "2", "y": 2, "color": "#000" },
        { "name": "3", "y": 3, "color": "#000" },
        { "name": "4", "y": 4, "color": "#000" },
        { "name": "5", "y": 5, "color": "#000" },

      ]
    }
  ]
}

A: It is possible to move label depending on it's rows count
Add render function to the chart object
{
  "chart": {
    ...
    events: {
      render() {
        for (let i = 0; i < this.xAxis[0].names.length; i++) {
          const label = this.xAxis[0].ticks[i].label;
          const rows = (label.element.innerHTML.match(/<\/tspan>/g) || []).length;
          label.translate(-8 * rows, 0);
        }
      }
    }

where 8 is half of row size in px
https://jsfiddle.net/kLz1uoga/5/


Q: Adding text to the beginning and end of a number of files? I have a number of files in a directory hierarchy. For each file, I'd like to add "abcdef" to the beginning, on its own line, and "ghijkl" to the end, on its own line. For example, if the files initially contained:
# one/foo.txt
apples
bananas

# two/three/bar.txt
coconuts

Then afterwards, I'd expect them to contain:
# one/foo.txt
abcdef
apples
bananas
ghijkl

# two/three/bar.txt
abcdef
coconuts
ghijkl

What's the best way to do this?
I've gotten as far as:
# put stuff at start of file
find . -type f -print0 | xargs -0 sed -i 's/.../abcdef/g'

# put stuff at end of file
find . -type f -print0 | xargs -0 sed -i 's/.../ghijkl/g'

but I can't seem to figure out how what to put in the ellipses.

A: This isn't a job for sed. To add lines, just use I/O redirection.
For a single file named filename, you can do the following:
mv filename temp
(echo abcdef ; cat temp ; echo ghijkl) > filename
rm temp

To do this automatically to all files in the current directory, use find and xargs:
find -type f -print0 | xargs -0 -I % sh -c '
    mv "%" temp
    (echo abcdef ; cat temp ; echo ghijkl) > "%"
'
rm temp

A: If you have GNU sed available you can use the i\ and a\ constructs:
Use line addresses to apply to first and last line respectively:
find . -type f -print0 | xargs -0 sed -i -e '1i\abcdef' -e '$a\ghijkl'

A: For files in directory as file
echo "abcde" && cat file && echo "fghijk" > file


Q: Interpreting odds ratio units I'm running logistic regressions in Python using statsmodels logit and, downstream, am calculating odds ratios for each independent variable.
I know that, conventionally, an odds ratio is interpreted per "one unit" increase in the value of the variable. I think my ultimate question is how can I determine with certainty what "one unit" really is for each variable, and if it depends upon the precision of the data for the relevant column.
One parameter, respiratory_rate, has values in integers (22, 26, 30, 12, etc.). So I think I can assume a one unit increase in respiratory_rate would be one whole number.
However, a second parameter, temperature, has values with decimal points to the tenths place (97.8, 98.4, 99.5, 100.3, etc.). Here, for the odds ratio for temperature, would the "one unit increase" be an increase in tenths, i.e., an increase of 0.1?

A: In the simplest terms, an odds ratio (OR) is the relationship between the probability P of the occurrence of an event A and the probability 1 - P(A) of event A not occuring. The mathematical expression is
P(A)/(1-P(A)). OR > 1 imply that A has a greater probability of happening than not happening, OR < 1 is the opposite. The numerator is the probability between 0 and 1.0 of the event occurring. The denominator is the probability between 0 and 1.0 of the event not occurring. The sum of both probabilities equals 1.0 which explains the subtraction from 1.0 to obtain the probability of the event not occurring after you know the probability of the event occurring. Here is a good explanation https://en.wikipedia.org/wiki/Odds_ratio.

A: It's literally the derivative.
$$
odds\_ratio = \beta_0 + \beta_1x$$
$$\dfrac{\partial odds\_ratio}{\partial x} = \beta_1
$$
Then $x$ increases by one, the odds ratio increases by $\beta_1$.
Let's do a concrete example with numbers.
$$
odds\_ratio = 1 + 2x\\
\beta_0 = 1\\
\beta_1 = 2
$$
When $x=0$, $odds\_ratio = 1$.
When $x$ increases by $1$ to give $x=1$, $odds\_ratio = 3$.
When $x$ increases by $1$ again to give $x=2$, $odds\_ratio = 5$.
As an exercise, what is the odds ratio for $x = 1.5$, and how does that compare to when $x=1$ or when $x=2?$


Q: Why syntax error when import my own modules in Python I created my own python package with "python setup.py bdist_wheel" and "pip install /path/to/dist/my_own_package.wheel".  After installing it, when importing it, there is error of "SyntaxError: invalid syntax". Could you help? thanks.
>>> import my-modules
  File "<stdin>", line 1
    import my-modules
             ^
SyntaxError: invalid syntax

But there is module installed in Continuum\anaconda3\Lib\site-packages

A: Your module has a minus symbol in the title. That's the reason. Sometimes (nearly never) the underline symbol may be the fault. If you name your module like "myModules" or "modules", there would be no error.
WRONG:
>>> import my-modules

  File "<stdin>", line 1
    import my-modules
             ^
SyntaxError: invalid syntax

VALID:
>>> import myModules

#No error


Q: How do you pull certain substrings(ip addresses) out of strings(Wireshark Output)? I am reading the contents of a wireshark dump from a text file, line by line.  One of the things I can pick out easily is the protocol used in that specific line of the wireshark output(as shown in the code below).  The problem I'm running into is pulling out the ip addressess from the line.  As you can see in the sample output below, and my code, it was fairly easy to pull out the protocol because it was always capitialized and there was a space on either side of it.  The ip addresses however, aren't as uniform and I'm not quite sure how to pull them out as well.  This is mostly due to the fact that I'm not quite sure how all the parts of the re.match() work.  Can somebody help me out in this, and possibly explain how the re.match() parameters work?
file = open('tcpdump.txt', 'r');
     for line in file:
          matchObj = re.match(r'(.*) TCP (.*?) .*', line, re.M)

Sample Wireshark Output:
604 1820.381625 10.200.59.77 -> 114.113.226.43 TCP 54 ssh > 47820 [FIN, ACK] Seq=1848 Ack=522 Win=16616 Len=0

A: The first regex group is greedy (.*) and is matching everything, you can make it non-greedy by adding ?, i.e.:
file = open('tcpdump.txt', 'r');
     for line in file:
          matchObj = re.match(r"->\s(.*?)\s(\w+)\s(.*?)\s", line, re.M)

The above example is will capture 3 groups containing the remote address 114.113.226.43, protocol TCP and port 54 respectively.

Regex101 Demo

A: Start by look at the regex documentation, for python it is here:
https://docs.python.org/3/library/re.html
There are also many sites that have good tutorials, samples and interactive testers such as:
http://regexr.com/
I don't know the output format of wireshark, but I would imagine it is documented somewhere.
This should get your ip addresses:
\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b

A: As people have already responded, regex is the way to go. A sample code for the purpose
import unittest
import re
from collections import namedtuple

protocol = namedtuple('Protocol', ['source', 'destination', 'protocol'])

def parse_wireshark(input):
  pat = re.findall(r"(\d+\.\d+\.\d+\.\d+) -> (\d+\.\d+\.\d+\.\d+) (\w+)", input)[0]
  return protocol(source=pat[0], destination=pat[1], protocol=pat[2])

class TestWireShark(unittest.TestCase):

  def test_sample(self):
    self.assertEqual(parse_wireshark("604 1820.381625 10.200.59.77 -> 114.113.226.43 TCP 54 ssh > 47820 [FIN, ACK] Seq=1848 Ack=522 Win=16616 Len=0"),
                     protocol(source='10.200.59.77',
                              destination='114.113.226.43',
                              protocol='TCP'))
if __name__ == '__main__':
   unittest.main()


Q: What is the correct definition of the inverse image functor on sheaves of modules? There seem to be two different definitions of the inverse image functor on sheaves of modules in the literature and I just wanted to make sure I am understanding properly. Suppose $f: X \rightarrow Y$ is a morphism of schemes and $\mathcal{F}$ is a quasicoherent sheaf on $Y$. How is the sheaf of $\mathcal{O}_{X}$-modules $f^{*}\mathcal{F}$ defined?
The most general appears to be,
$$
f^{*} \mathcal{F} = \mathcal{O}_{X} \otimes_{f^{-1}\mathcal{O}_{Y}} f^{-1} \mathcal{F} \quad \text{call this sheaf $\mathcal{H}$}.
$$
This should work (by "work" I mean provide an adjoint for the functor $f_{*}$ on the category of sheaves of modules) for any sheaf of modules, right?
However, I see another definition often,
$$
f^{*} \mathcal{F} = \mathcal{O}_{X} \otimes_{\mathcal{O}_{Y}} \mathcal{F} \quad \text{call this sheaf $\mathcal{J}$}.
$$
This definition doesn't work for arbitrary sheaves of modules, right? But it should work if we restrict ourselves to quasicoherent modules, or possibly only quasicoherent modules locally of finite type?
My idea to prove they are the same in the case of quasicoherent sheaves: I would cover the base scheme $Y$ by affines $\{  U_{i} = \text{Spec}A_{i}  \}$ and write $\mathcal{F}|_{U_{i}} \simeq \tilde{M_{i}}$ for $A_{i}$-modules $M_{i}$. Then we can cover $f^{-1}(U_{i})$ by affines $\{ V_{ij} = \text{Spec}B_{ij} \}$. Then over $V_{ij}$ we have,
$$
\varphi_{ij}: (M_{i} \otimes_{A_{i}} B_{ij})^{\sim} \longrightarrow (\mathcal{O}_{X} \otimes_{f^{-1} \mathcal{O}_{Y}} f^{-1} \mathcal{F})|_{V_{ij}}.
$$
The left hand side of this morphism is the sections of $\mathcal{J}$ and since $\mathcal{J}$ is clearly quasicoherent such a family is sufficient to provide a morphism which I claim will be an isomorphism on stalks.
Is this the correct approach? Am I correct that these are only equivalent on quasicoherent sheaves? I initially thought they were only equivalent for locally free sheaves, since you can use the projection formula, but I am quite certain this holds at least for coherent sheaves, if not quasicoherent.