text:
Q: Displaying a popup window from action toolbar on a compiled PyQt4 Qt Designer So, i tried to build an app and struggling on how to connect an action to another dialog window. I searched for it but only found a solution for a window that wasn't built with Qt Designer. I designed it with Qt Designer and compiled the .ui to .py format.
This is my first window:
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'home.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui
from howto import Ui_HowToDialog

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_HomeWindow(object):
    def setupUi(self, HomeWindow):
        HomeWindow.setObjectName(_fromUtf8("HomeWindow"))
        HomeWindow.resize(1106, 259)
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Consolas"))
        HomeWindow.setFont(font)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/resources/plottwist.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        HomeWindow.setWindowIcon(icon)
        HomeWindow.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.centralwidget = QtGui.QWidget(HomeWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.horizontalLayout = QtGui.QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.homeBrowser = QtGui.QTextBrowser(self.centralwidget)
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Consolas"))
        self.homeBrowser.setFont(font)
        self.homeBrowser.setObjectName(_fromUtf8("homeBrowser"))
        self.horizontalLayout.addWidget(self.homeBrowser)
        HomeWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtGui.QStatusBar(HomeWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        HomeWindow.setStatusBar(self.statusbar)
        self.homeToolbar = QtGui.QToolBar(HomeWindow)
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Consolas"))
        font.setPointSize(10)
        self.homeToolbar.setFont(font)
        self.homeToolbar.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.homeToolbar.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.homeToolbar.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
        self.homeToolbar.setObjectName(_fromUtf8("homeToolbar"))
        HomeWindow.addToolBar(QtCore.Qt.LeftToolBarArea, self.homeToolbar)
        self.actionOpenDataset = QtGui.QAction(HomeWindow)
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap(_fromUtf8(":/resources/dataset.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.actionOpenDataset.setIcon(icon1)
        self.actionOpenDataset.setObjectName(_fromUtf8("actionOpenDataset"))
        self.actionHowTo = QtGui.QAction(HomeWindow)
        self.actionHowTo.triggered.connect(self.showHowto)
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap(_fromUtf8(":/resources/howto.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.actionHowTo.setIcon(icon2)
        self.actionHowTo.setObjectName(_fromUtf8("actionHowTo"))
        self.actionAbout = QtGui.QAction(HomeWindow)
        icon3 = QtGui.QIcon()
        icon3.addPixmap(QtGui.QPixmap(_fromUtf8(":/resources/about.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.actionAbout.setIcon(icon3)
        self.actionAbout.setObjectName(_fromUtf8("actionAbout"))
        self.homeToolbar.addAction(self.actionOpenDataset)
        self.homeToolbar.addAction(self.actionHowTo)
        self.homeToolbar.addAction(self.actionAbout)

        self.retranslateUi(HomeWindow)
        QtCore.QMetaObject.connectSlotsByName(HomeWindow)

    def retranslateUi(self, HomeWindow):
        HomeWindow.setWindowTitle(_translate("HomeWindow", "Plot Twist", None))
        self.homeBrowser.setHtml(_translate("HomeWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<meta name=\"qrichtext\" content=\"1\" />\n"
"
Data Visualization is as important as it sounds, you can visualize your data with this app just by inserting any dataset you want. For more detailed instructions, simply go to How To icon.
\n"
"

\n"
"
With Plot Twist, you can:
\n"
"
- Look inside your dataset
\n"
"
- Visualize it by choosing any possible diagrams of any columns
\n"
"
- Find out specific calculation of any column
", None))
        self.homeToolbar.setWindowTitle(_translate("HomeWindow", "toolBar", None))
        self.actionOpenDataset.setText(_translate("HomeWindow", "Open Dataset", None))
        self.actionOpenDataset.setStatusTip(_translate("HomeWindow", "Open dataset to visualize it.", None))
        self.actionOpenDataset.setShortcut(_translate("HomeWindow", "Ctrl+O", None))
        self.actionHowTo.setText(_translate("HomeWindow", "How To", None))
        self.actionHowTo.setToolTip(_translate("HomeWindow", "How To Do This?", None))
        self.actionHowTo.setStatusTip(_translate("HomeWindow", "Instructions on how this app works.", None))
        self.actionHowTo.setShortcut(_translate("HomeWindow", "F1", None))
        self.actionAbout.setText(_translate("HomeWindow", "About", None))
        self.actionAbout.setToolTip(_translate("HomeWindow", "About", None))
        self.actionAbout.setStatusTip(_translate("HomeWindow", "Description and message by creator.", None))
        self.actionAbout.setShortcut(_translate("HomeWindow", "F2", None))

    def showHowto(self):
        HowToDialog = QtGui.QDialog()
        hui = Ui_HowToDialog()
        hui.setupUi(HowToDialog)
        HowToDialog.show()
        sys.exit(app.exec_())

import resources_rc

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    HomeWindow = QtGui.QMainWindow()
    ui = Ui_HomeWindow()
    ui.setupUi(HomeWindow)
    HomeWindow.show()
    sys.exit(app.exec_())

And this is the dialog i tried to pop up. It's supposed to show HowTo dialog when the icon on toolbar is triggered.
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'howto.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_HowToDialog(object):
    def setupUi(self, HowToDialog):
        HowToDialog.setObjectName(_fromUtf8("HowToDialog"))
        HowToDialog.resize(585, 242)
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Consolas"))
        HowToDialog.setFont(font)
        HowToDialog.setAcceptDrops(False)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/resources/howto.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        HowToDialog.setWindowIcon(icon)
        self.horizontalLayout = QtGui.QHBoxLayout(HowToDialog)
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.howtoBrowser = QtGui.QTextBrowser(HowToDialog)
        self.howtoBrowser.setObjectName(_fromUtf8("howtoBrowser"))
        self.horizontalLayout.addWidget(self.howtoBrowser)

        self.retranslateUi(HowToDialog)
        QtCore.QMetaObject.connectSlotsByName(HowToDialog)

    def retranslateUi(self, HowToDialog):
        HowToDialog.setWindowTitle(_translate("HowToDialog", "How To Do This?", None))
        self.howtoBrowser.setHtml(_translate("HowToDialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<meta name=\"qrichtext\" content=\"1\" />\n"
"
How to insert your dataset:
\n"
"
1. Click Open Dataset icon.
\n"
"
2. Click Browse and select your dataset.
\n"
"
3. Note that the dataset has to be a .csv file.
\n"
"
4. Click Insert File button.
\n"
"
5. Your dataset visualization window will appear, and you can start to visualize it.
\n"
"

\n"
"
Happy visualizing :)
", None))

import resources_rc

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    HowToDialog = QtGui.QDialog()
    ui = Ui_HowToDialog()
    ui.setupUi(HowToDialog)
    HowToDialog.show()
    sys.exit(app.exec_())

As you can see, this is the function i define to show the second window:
def showHowto(self):
    HowToDialog = QtGui.QDialog()
    hui = Ui_HowToDialog()
    hui.setupUi(HowToDialog)
    HowToDialog.show()
    sys.exit(app.exec_())

And i have connected it with the action toolbar with self.actionHowTo.triggered.connect(self.showHowto).
When i run it, it displays QCoreApplication::exec: The event loop is already running. Can somebody tell me what's wrong and the solution? Thanks before!

A: I had similar trouble when starting with pyqt.
You should create another class for the dialog window like so:
#!python3
'''docs'''
import sys
from PyQt4.QtGui import *
from _apps.PyUi import DialogUi

class DialogApp(QDialog, DialogUi.Ui_DialogApp):
    """Dialog class"""

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

def main(self):
    app = QApplication(sys.argv)
    form = DialogApp()
    form.show()
    app.exec_()

if __name__ == '__main__':
    main()

The main i included for easy testing...
The next part is in the main window just the slot connected with action:
def openDialog(self):

    self.dialog= DialogApp(self)
    self.dialog.show()

The part which you need to be careful about is who is the parent to the dialog, if None is parent like in my example the dialog will get a separate tab on the task bar and can be instantiated as many times as you click the action, assuming the dialog itself is modeless.
If you pass the mainwindow (self) to the dialog, which is recommended in most cases concerning dialog windows, the main will be the parent, by default the dialog will be centered on main when it appears.
Edit:
Also you need and can have only one QApplication active, all the windows shown and underlying methods and functions go through this initial QApplication, as far as I know.


text:
Q: Netbeans format JS code inside html tags NetBeans is not smart enough to format Javascript code inside HTML tags.
Is there any plugins or solutions for this?
I have only found this link but it only works on a clean.js file.
Only thing that comes on my mind is copying content to a js file formatting it and then past it back.

A: You can use any online tool to format your code as there is present a lot of tools to beautify it.
Here is the one link. This tool is very nice as I have seen that you can use this tool to formatting any code like HTML, PHP, Javascript, or CSS as a time.
Hope this will be helpful to you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: JS replace hashtag with slash Im wondering how do I replace a hashtag with a slash in the URL with Javascript or Jquery.
Example:
www.mysite.com/service#new

To:
www.mysite.com/service/new

Is this possible? I really can´t figure it out.
Greetings!

A: Why not just do this:
var url = "www.mysite.com/service#new";
url = url.replace('#', '/');

Or if you're trying to manipulate DOM elements directly, something like this should work:
$('a').each(function(i, e) {
    e.href = e.href.replace('#', '/');
});


text:
Q: How can I remove the empty string resulting from a split? When I split a String :
A.B.C.

by .. I get 4 strings. The fourth being the white space. How can I remove that ?
String tokens[] = text.split("\\.");
    for(String token : tokens) {
        System.out.println("Token : " + token);
    }

A: If whitespace at the beginning or end is the problem, trim it off:
String tokens[] = text.trim().split("\\.");

A: Remove all the whitespace with a replaceAll() before your code.
text.replaceAll("\\s+","");

A: Your String is A.B.C. so that whenever you split that it with . it will be give four substrings only. Even though you use trim() it will give four substrings. So try to remove last . and then split string. You will get proper output.


text:
Q: Polar Decomposition: Approximation Given a C*-algebra $\mathcal{A}$.
Polar Decomposition:
$$\forall A\in\mathcal{A}\exists V_\varepsilon\in\mathcal{A}:\quad A=V_\varepsilon|A|^{1-\varepsilon}\quad(\varepsilon>0)$$
How can I construct this?
Similar statement: Wegge-Olsen, Exercise 1.A.c


text:
Q: How can I save text with formatting in JavaScript? I'm working on a Chrome Extension that has a notes page as a feature. It's not the main feature (meaning it won't be a lot of text) so I don't need to store the notes in a database, so I plan on storing the notes in LocalStorage.
Is there a way I can store this text with formatting such as new lines. For example, I want  the following text:
Hello,
world.
to be saved as is, instead of "Hello,world."

A: To format the text, you need to use:
    const formattedText = text.split('\n').join("\\n")

To get the text back, you should use:
    const text = formattedText.split('\\n').join('\n')


text:
Q: Sqlite3 C++ database is locked I want to modify the records of a row in my database, but somehow I get a database is locked error
void Bookshop::modifyBookRecords () {
    std::cout << "You want to modify a book" << std::endl;
    std::cout << "Title/ISBN: ";
    std::string input;
    std::getline (std::cin, input);
    bool isAvailable = database.checkAvailability (input);
    database.closeDb ();
    if (isAvailable) {
        std::cout << "Title: ";
        std::string title;
        std::getline (std::cin, title);
        std::cout << "Author: ";
        std::string author;
        std::getline (std::cin, author);
        std::cout << "Pages: ";
        int pages;
        std::cin >> pages;
        std::cin.ignore (std::numeric_limits<std::streamsize>::max (), '\n');
        std::cout << "Genre: ";
        std::string genre;
        std::getline (std::cin, genre);
        std::cout << "Publisher: ";
        std::string publisher;
        std::getline (std::cin, publisher);
        std::cout << "ISBN: ";
        std::string isbn;
        std::getline (std::cin, isbn);
        std::cout << "Number of Copies: ";
        int numberOfCopies;
        std::cin >> numberOfCopies;
        std::cin.ignore (std::numeric_limits<std::streamsize>::max (), '\n');
        database.updateRecord (input, title, author, pages, genre, publisher, isbn, numberOfCopies);
     }
     else {
         std::cout << "The book was not found" << std::endl;
     }
}

CheckAvailability Method
bool Database::checkAvailability (std::string& input) {
    openDb (dir);
    sqlite3_stmt* stmt;
    rc = sqlite3_prepare_v2 (db, "SELECT * FROM Books WHERE Title = ? OR Isbn = ?", -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        std::cout << sqlite3_errmsg (db);
        closeDb ();
        return false;
    }
    sqlite3_bind_text (stmt, 1, input.c_str (), input.length (), NULL);
    sqlite3_bind_text (stmt, 2, input.c_str (), input.length (), NULL);

    if (sqlite3_step (stmt) == SQLITE_ROW) {
        return true;
        sqlite3_finalize (stmt);
        sqlite3_close (db);
    }
    else {
        return false;
        sqlite3_finalize (stmt);
        sqlite3_close (db);
    }
}

updateRecords method
// Method updates the whole row with the values from the parameter list
void Database::updateRecord (const std::string& input,
                         const std::string& title,
                         const std::string& author,
                         const int& pages,
                         const std::string& genre,
                         const std::string& publisher,
                         const std::string& isbn,
                         const int& numberOfCopies) {
    openDb (dir);
    sqlite3_stmt* stmt;
    rc = sqlite3_prepare_v2 (db, "UPDATE Books SET Title = ?, Author = ?, Pages = ?, Genre = ?, Publisher = ?, Isbn = ?, Copies = ? WHERE Title = ? OR Isbn = ?", -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        std::cerr << sqlite3_errmsg (db);
        closeDb ();
    }
    sqlite3_bind_text (stmt, 1, title.c_str (), title.length (), NULL);
    sqlite3_bind_text (stmt, 2, author.c_str (), author.length (), NULL);
    sqlite3_bind_int (stmt, 3, pages);
    sqlite3_bind_text (stmt, 4, genre.c_str (), genre.length (), NULL);
    sqlite3_bind_text (stmt, 5, publisher.c_str (), publisher.length (), NULL);
    sqlite3_bind_text (stmt, 6, isbn.c_str (), isbn.length (), NULL);
    sqlite3_bind_int (stmt, 7, numberOfCopies);
    sqlite3_bind_text (stmt, 8, input.c_str (), input.length (), NULL);
    sqlite3_bind_text (stmt, 9, input.c_str (), input.length (), NULL);
    rc = sqlite3_step (stmt);
    if (rc != SQLITE_OK) {
        std::cerr << sqlite3_errmsg (db);
    }
    else {
        std::cout << "books was updated successfully" << std::endl;
    }
    sqlite3_finalize (stmt);
    closeDb ();
}

The error is somewhere in the checkAvailability Method, because when I remove it everything works. Someone told me, that the database is open somewhere, so it is not allowed to open it in the method later. But I closed the database at the end of checkAvailability(), so I do not know the problem.

A: You are returning from checkAvailability before you have closed the database. Once you return from a function, statements following the return statement are not executed. The control flow goes back to the caller of the function.
bool Database::checkAvailability (std::string& input) {
    openDb (dir);
    sqlite3_stmt* stmt;
    rc = sqlite3_prepare_v2 (db, "SELECT * FROM Books WHERE Title = ? OR Isbn = ?", -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        std::cout << sqlite3_errmsg (db);
        closeDb ();
        return false;
    }
    sqlite3_bind_text (stmt, 1, input.c_str (), input.length (), NULL);
    sqlite3_bind_text (stmt, 2, input.c_str (), input.length (), NULL);

    if (sqlite3_step (stmt) == SQLITE_ROW) {
        sqlite3_finalize (stmt);
        sqlite3_close (db);
        return true;
    }
    else {
        sqlite3_finalize (stmt);
        sqlite3_close (db);
        return false;
    }
}


text:
Q: Disable the configuration tool in Zsh When there is no .zshrc file in a user's home directory and zsh is started, an interactive configuration utility is run instead of directly giving access to the shell prompt.
I set up zsh to be the default shell on my Debian Wheezy systems. Therefore every newly created user gets zsh as login shell if I do not change that manually. Also there is a default .zshrc in /etc/skel, so all regular users on my system have a copy of the file in their home directory. This is not the case for system users.
When I now change into a system user (for example the user for a specific network daemon) via sudo or sh I run into the configuration tool, because these users have no .zshrc in their home directories.
It doesn't feel right to place a .zshrc into each and every daemon's home directory, which also would be a pain to setup and maintain on a lot of systems. But I still wouldn't want to downgrade to a less comfortable bash for these users.
Is there a way to disable the zsh configuration tool without having to create a .zshrc file in the user's home directory? Additionally a way to setup a single file to be the system-wide default .zshrc for all users which don't have one would be nice too.

A: from: http://www.zsh.org/mla/users/2007/msg00398.html
The shell then executes code in the file
scripts/newuser in the shared library area (by default
/usr/local/share/zsh/<VERSION>/scripts/newuser).  This feature can be
turned off simply by removing this script.  The module can be removed
entirely from the configured shell by editing the line starting
"name=zsh/newuser" in the config.modules file, which is generated in the
top level distribution directory during configuration: change the line to
include "link=no auto=no".

and /etc/zsh/zshrc is sourced by every shell that has the interactive,rcs, & globalrc options set. (which most interactive zsh processes do)

or add zsh-newuser-install() { :; } in /etc/zsh/zshenv
Which has the obvious side-effect of users not being able to use the function until they undefine yours.
You can refine that by adding a test of the UID.
if (( EUID < 1000 )) && (( EUID != 0 )); then # or whatever the highest daemon uid on your system
  zsh-newuser-install() { :; }
fi


text:
Q: Check : Whether my string contain any character except specified characters (M,d,y,-,/,:,h,D,Y,m,S,s,\,_) I am trying implement filter/expression to check my string not contain any character except these (M,d,y,-,/,:,h,D,Y,m,S,s,\,_).
Please help to write regular expression to verify that string should not contain any character except specified character set (M,d,y,-,/,:,h,D,Y,m,S,s,\,_)
Thanks,
Nitin

A: The regular expression:
[^(Mdy\-/:hDYmSs\\_)]

will match any character outside that set.

A: If your string can only contain these characters, you can validate it with this regex:
^[-/:MmDdYyhSs,_\\]+$

*

*Match => it's a good string

*No match => it contains other characters


text:
Q: Deploy python web server on AWS Elastic Beanstalk I'm deploying an python web server on AWS now and I have a some question about it. I'm using websocket to communicate between back end and front end.

*

*Do I have to use framework like django or flask?

*If not, where should I put the index.html file? in other word, after deploying, how do AWS know the default page of my application?

Thanks in advance.

A: AWS doesn't "know" anything about your content. The webserver that you install will be configured to point to the "root" directory in which index.html (or something equivalent) should be.
Since it depends on which webserver (django, flask, Jinja etc) you install - you should lookup its documentation!


text:
Q: Once I have created a session variable, can I use it in every way on asp.net? Session["USER_ID"]  = "1";

This is the session variable. I want to know how long the session variable value can be stored.

A: Session duration in ASP.NET is 20 minutes. There are two ways to change the session duration:

*

*Setting a value to the timeout attribute in the <sessionState> field in the web.config file.

*To set Session.Timeout property in Session_Start() method in Global.asax.cs file.

You can change the session duration in the web.config file as follows:
<configuration>
    <system.web>
        <sessionState mode="InProc" cookieless="false" timeout="60" />
    </system.web>
</configuration>

You can change the session duration in the global.asax.cs file as follows:
public class ApplicationName : System.Web.HttpApplication
{
    protected void Session_Start(object sender, EventArgs e)
    {
        /* Sets the session duration to 60 minutes. */
        Session.Timeout = 60;
    }
}

References

*

*Setting session duration in ASP.NET MVC application doesn't work in web.config


text:
Q: Loop in python not incrementing properly I am using a for loop in python with range function (range(0,100000 ).
Inside the loop,I am creating a thread to call some method to do some task and passing index of loop as parameter to target function of thread.
I am observing  that value of index in loop does not get incremented in every iteration.
Instead it produces same index multiple times and some times skips iteration
for index in range(0,100000):
    t=Thread(target=somefunction,args=(index,)
    t.start()
    t.join()

Inside somefunction, I am performing some operation and also printing value of index. Same value of index is getting printed.which means loop is not incrementing properly.
Please help

A: You can implement something like below to solve the problem. threads will run complete program that's why loop is not increment properly.
Here i have used map (Apply the given function to each item of a given iterable) to pass the param to function
from multiprocessing.dummy import Pool as ThreadPool
import time
import datetime

def operation(value):
    # whatever operation needs to be performed
    print("{} : Thread no {}\n".format(datetime.datetime.now(),value))
    time.sleep(20)

# Data/tasks needs to be processed added in list
Data = [1,2,3,4,5,6,7,8,9]

# Creating pools
c_pool = ThreadPool(5) # using 5 threads
c_pool.map(operation, Data) # using map method to perform operation
c_pool.close()
c_pool.join()

it will perform 5 tasks/operation at the time.
Here 1st 5 are taken for process
2019-04-26 **12:47:37**.800258 : Thread no 1
2019-04-26 **12:47:37**.800258 : Thread no 2
2019-04-26 **12:47:37**.800258 : Thread no 3
2019-04-26 **12:47:37**.800258 : Thread no 4
2019-04-26 **12:47:37**.800258 : Thread no 5

Here rest 5 started after 20 seconds (time.sleep(20))
2019-04-26 **12:47:57**.809258 : Thread no 6
2019-04-26 **12:47:57**.809258 : Thread no 7
2019-04-26 **12:47:57**.809258 : Thread no 8
2019-04-26 **12:47:57**.809258 : Thread no 9


text:
Q: How can I avoid 'Not Found The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again' I have Machine learning predictor which predicts number of rooms with price and area. When I click the predict button I get error(Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again). How can I avoid that.
import numpy as np
import sklearn
from sklearn import linear_model
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from flask import Flask, render_template, request

df = pd.read_excel('filtered.xlsx')
x = df[['area','price']]
y =df['number_of_rooms']

x_train, x_test ,y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size = 0.1)

model = LinearRegression()

model.fit(x_train,y_train)
app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')

@app.route('/predict,', methods=['POST'])
def predict():
    price = request.form['price']
    area = request.form['area']

    rooms = model.predict([[price, area]])[0]

    return render_template('predict.html', rooms=rooms)

if __name__ == '__main__':
    app.run(debug=True)

My html is like below.

<!DOCTYPE html>

    <title>House Number of Rooms Predictor</title>

Predict the Number of Rooms of a House

    <form action="/predict" method="post">
    Price:
    <input type="text" id="price">
name="price">

    Area:
    <input type="text" id="area">
name="area">

    <input type="submit" value="Predict">
    </form>


text:
Q: filter datatable in vuetify using daepicker? i'am new to vuetify,  I am  working on using a datepicker to filter a vuetify datatable [ from:date - to:date ], i couldn't solve the part of comparing the picked date to a date inside the table and make the filtering process to the data .
                   enter code here

<script>
  export default {
    data: vm => ({
      date: new Date().toISOString().substr(0, 10),
      dateFormatted: vm.formatDate(new Date().toISOString().substr(0, 10)),
      menu1: false,
      menu2: false,
      search:'',
       headers: [
        {
          text: 'Names',
          align: 'left',
          value: 'name'
        },
        {
          text: 'Birth date',
          value: 'birth_date'
        },

      ],
      rows: [
        {
          value: false,
          name: 'Marcelo Tosco',
          birth_date: 1538006400000,
        },
        {
          value: false,
          name: 'Carlos Campos',
          birth_date: 1537401600000,
        },
        {
          value: false,
          name: 'Luis Gonzalez',
          birth_date: 1536537600000,
        },
        {
          value: false,
          name: 'Keopx',
          birth_date: 1536364800000,
        },
        {
          value: false,
          name: 'Marco Marocchi',
          birth_date: 1535846400000,
        },
      ]
    }),

    computed: {
      computedDateFormatted () {
        return this.formatDate(this.date)
      },
    },

    watch: {
      // eslint-disable-next-line no-unused-vars
      date (val) {
        this.dateFormatted = this.formatDate(this.date)
      },
    },

    methods: {
      formatDate (date) {
        if (!date) return null

        const [year, month, day] = date.split('-')
        return `${month}/${day}/${year}`
      },
      parseDate (date) {
        if (!date) return null

        const [month, day, year] = date.split('/')
        return `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`
      },
    },
  }
</script>

                    <v-container fluid  class="page-name">
                        <v-row>
                            <v-col cols="8">
                                <v-row class="pa-6">
                                    <!-- Filter for dessert name-->
                                    <v-text-field
                                        v-model="search"
                                        append-icon="search"
                                        label="بحث"
                                        single-line
                                        hide-details>
                                    </v-text-field>
                                </v-row>
                             </v-col>

                                <v-row>
                                <v-col cols="12" lg="6">
                                    <v-menu
                                    ref="menu1"
                                    v-model="menu1"
                                    :close-on-content-click="false"
                                    transition="scale-transition"
                                    offset-y
                                    max-width="290px"
                                    min-width="290px"
                                    >
                                    <template v-slot:activator="{ on, attrs }">
                                        <v-text-field
                                        v-model="dateFormatted"
                                        label="Date"
                                        hint="MM/DD/YYYY format"
                                        persistent-hint
                                        prepend-icon="event"
                                        v-bind="attrs"
                                        @blur="date = parseDate(dateFormatted)"
                                        v-on="on"
                                        ></v-text-field>
                                    </template>
                                    <v-date-picker v-model="date" no-title @input="menu1 = false"></v-date-picker>
                                    </v-menu>
                                </v-col>

                                <v-col cols="12" lg="6">
                                    <v-menu
                                    v-model="menu2"
                                    :close-on-content-click="false"
                                    transition="scale-transition"
                                    offset-y
                                    max-width="290px"
                                    min-width="290px"
                                    >
                                    <template v-slot:activator="{ on, attrs }">
                                        <v-text-field
                                        v-model="computedDateFormatted"
                                        label="Date (read only text field)"
                                        hint="MM/DD/YYYY format"
                                        persistent-hint
                                        prepend-icon="event"
                                        readonly
                                        v-bind="attrs"
                                        v-on="on"
                                        ></v-text-field>
                                    </template>
                                    <v-date-picke`enter code here`r v-model="date" no-title @input="menu2 = false"></v-date-picker>
                                    </v-menu>
                                </v-col>
                                </v-row>

                        </v-row>

                    </v-container>
                </template>

              </v-data-table>
enter code here

A: One approach is to listen to change event in v-date-picker so in this case I created a function call filterDate in order to listen to the change
<v-date-picker
    v-model="date"
    @change="filterDate"
>

<v-data-table
    :headers="headers"
    :items="rows"
>

// In data defines a variable dates
    date: undefined

// In method
filterDate() {
    if (this.date !== undefined) {
        this.rows = this.copyOfRows.filter((item) => item.birthday == this.date)
    }
}

In my case I stored the original data that will be in v-data-table in vuex, so that when we filter items, the data is still there.
You might have to find a way to compare the date.
Hope this helps (:


text:
Q: What is a property attribute and how do I use it? I created a class that takes 2 coordinates and returns the slope and distance of the respective coordinates.
It works fine but, apparently, what I did was wrong and was supposed to give an error.
My code:
class Line:
    def __init__(self, coord1, coord2):

        self.coord1 = coord1
        self.coord2 = coord2

    def distance(self):

        return math.sqrt( ((self.coord1[0]-self.coord2[0])**2)+((self.coord1[1]-self.coord2[1])**2) )

    def slope(self):

        c = self.coord2[0]-self.coord1[0]
        d = self.coord2[1]-self.coord1[1]
        if d==0:
            return "zero"
        elif c==0:
            return "Infinity"
        else:
            return d/c

line1=Line((8,3),(0,-4))
print(line1.distance())
print(line1.slope())

RESTART: C:\Users.....\Classes.py
10.63014581273465 **The result is right...?**
0.875

I get the right output, but this is how I am supposed to do it:
>>> line1=Line((8,3),(0,-4))
>>> line1.distance()
Traceback (most recent call last):File "<stdin>", line
1, in <module>TypeError: 'float' object is not callable  **This is like mine but error?**
>>> line1.slope()
Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError:
    'float' object is not callable **Just like mine but error?**
>>> line1.distance
10.63
>>> line1.slope
0.875

What is the difference and is mine wrong?

A: just put property decorator behind the func some useful docs
@property
def distance(self):
    ...

@property
def slope(self):
    ...

A: you need distance/slope to be variables
class Line:

def __init__(self, coord1, coord2):

    self.coord1 = coord1
    self.coord2 = coord2
    self.distance = self.get_distance()
    self.slope = self.get_slope()

def get_distance(self):

    return math.sqrt( ((self.coord1[0]-self.coord2[0])**2)+((self.coord1[1]-self.coord2[1])**2) )

def get_slope(self):

    c = self.coord2[0]-self.coord1[0]
    d = self.coord2[1]-self.coord1[1]
    if d==0:
        return "zero"
    elif c==0:
        return "Infinity"
    else:
        return d/c

This way, distance/slope are floats, and not functions; so you'll get the error that you're after


text:
Q: how to decrease border size to fit a div My question is, how to reduce the border size so to fit the div, so it's consists of a h5, hr and 2 p elements?

xxxx

xxxx

xxxx

A: You can use the following code to remove padding and margin sets by browser
*{
    padding: 0px;
    margin: 0px;
}

add it below  inside HERE!
and it will decrease border size to fit a the page so you can work on the div


text:
Q: If $B$ is a local ring with maximal ideal $n$, and $A$ is a unital subring over which $B$ is integral, is $B = A + n$ (as $A$-modules)? If $B$ is a local ring with maximal ideal $n$, and $A$ is a unital subring over which $B$ is integral, is $B = A + n$ (as $A$-modules)?
Not sure if all of these assumptions are necessary. I am just reading a proof in Harris First Course (that finite unramified bijections between projective varieties are isomorphisms, chapter 14), and I don't understand this step in his argument.
Is there some obvious reason why maybe this set is also a $B$-module? It is not clear to me that $n$ would also be a maximal $A$ module, though it is clear that $A + n > n$, since for example $1 \in A$ but not $n$.

A: We can consider $A=\mathbb{Q}$ and $B=\mathbb{Q}(\sqrt{3})$ and they both have only one prime ideal $(0)$ but $A+(0)\neq B$.


text:
Q: Hanami - How to properly check if a model has been persisted? I'm a newbie in hanami coming from a rails background, and I would like to know the best practice in verifying that a model has been persisted in a create Action.
I created a users/create action that looks like this:
class Create
    include Web::Action

    def call(params)
          repository = UserRepository.new

          @user = repository.create(name: params[:user][:name],
                                    email: params[:user][:email],
                                    type: 'standard')
          redirect_to '/users'
    end
  end

I wanted to make sure that I only redirect the users if the user was successfully created. I rails, I would do something like this:
redirect_to '/users' if @user.persisted?

But that is not the hanami way of doing things. Currently I'm doing this:
redirect_to '/users' if !@user.id.nil?

Which does the job, but it doesn't looks clean. How would be the best way to do this with hanami?

A: Try something like this.
def call(params)
  repository = UserRepository.new

  @user = repository.create(name: params[:user][:name],
                            email: params[:user][:email],
                            type: 'standard')
  redirect_to '/users'
rescue Hanami::Model::Error
  # handle the error
end

A: ROM/Hanami cannot silently discard the changes you're passing to a repo, it either raises an exception of some kind (Hanami::Model::Error in the case of hanami-model) or persists your entity. That said, checks like @user.id.nil? are completely redundant.


text:
Q: MS Teams Personal tabs Apps can have subtabs/submenus in it? Is that possible to add child tabs(similar to sub-menus) to a Personal Tab Apps in MS Teams? If not, is there any workaround to achieve this.
Please note we have used the App studio to build the app not the custom code.
(refer screenshot below)?

A: There's nothing like that in the main tab infrastructure, but -inside- your tab you could build whatever you like - it's just a normal web page. You could tabs, menus, etc. For instance, see how Planner has it's own top menu in the first screenshot over here: https://techcommunity.microsoft.com/t5/planner-blog/microsoft-teams-in-microsoft-365-government-gcc-now-includes/ba-p/360089


text:
Q: google dropdown when you click inside the search engine space enter image description hereIm working on a project and add the dropdown. I've done all I could and not working.
I'm trying to put it right after the input type but still lost. Trying to achieve this using only HTML and CSS. No Java knowledge yet.


text:
Q: Show that $W(Y_{\tau \land k})$ is a martingale where Y is a Markov chain and that it converges almost surley My questions refers to this paper by T. Lyons. I'm quite new to stochastic processes.
Let $(Y_n)_{n \in \mathbb{N}}$ be a time-homogenous, recurrent, reversible Markov chain with statespace $X$ and transitions $p_{ij}$ for $i,j\in X$.
For reversibility there exist strictly positive weights $\pi_i, i\in X$ with $\pi_ip_{ij}=\pi_jp_{ji}$.
We denote the conditioned expected value and probability on $i\in X$ as $\mathbb{E}^i$ and $\mathbb{P}^i$.
Furthermore we have a function $W:X \to \mathbb{R}$ satisfying:
(i) $W_{i_0}=0$ for a certain $i_0 \in X$
(ii) $W\neq 0$
(iii) $W_i=\sum_{j\in X}p_{ij}W_j$ for $i\neq i_0$
(iv) $\sum_{i,j\in X}\pi_ip_{ij}(W_i-W_j)^2<\infty$
Let $\tau$ be the first hitting time of $i_0$
First question:
Why is $W(Y_{\tau \land k})$ a $\mathbb{P}^i$ martingale?
Second question:  Why does $\lim_{k \to \infty}W(Y_{\tau \land k})=0$ a.s. hold?

My thoughts:
Regarding the first question my idea was to show that $W(Y)$ is a martingale and than make use of the optional stopping theorem. But somehow I'm confusing myself with this "under $\mathbb{P}^i$" condition. Let $\Sigma_k=\sigma({W(Y_{\tau \land l})}|l=1,...k)$ the induced sigma algebra. Do I have to show that for every $A \in \Sigma_s$ it holds that $$\Bbb{E}^i[\Bbb{E}[W(Y_{\tau \land m})|\Sigma_s]*\Bbb{1}_A]=\Bbb{E}^i[W(Y_{\tau \land s})*\Bbb{1}_A]$$ when $s \leq m$?
Regarding the second question I feel like we do need irreducibility? Why should $\Bbb{P}^i[\tau < \infty]=1$ if there is no way between $i$ and $i_0$? Is this somehow implicitly given?


text:
Q: Role of the Thom space in the Pontryagin-Thom construction I am trying to understand the Pontryagin-Thom theorem; especially how the Thom space comes into play. Just to bring everyone on the same page: I am specifically talking about the construction of an isomorphism $\Omega_n^k \cong \pi_{n + k}(MO(k))$, where $\Omega_n^k$ is the set of bordism classes of $n$-manifolds embedding in $\mathbb{R}^{n+k}$ and $MO(k) = \mathrm{Th}(\xi)$ is the Thom space of the universal $k$-plane bundle $\xi\colon EO(k) \to BO(k)$.
I find the construction of the Thom space rather peculiar, so I was looking around for intuition behind its role in this theorem. I found these notes, which, on page 4, hint at an approach to introduce the Thom space which I find quite interesting:
We want to classify (bordism classes of) $n$-manifolds which embed in $\mathrm{R}^{n+k}$ by homotopy classes of maps from $S^{n+k}$. So given such a manifold $M$, we are tasked with finding such a map that carries some information of $M$. Now we know that $S^{n+k}$ is the one point compactification of $\mathbb{R}^{n+k}$ and we know that $M$ embeds into this space openly, when we consider a tubular neighbourhood.
But given an open embedding $U \hookrightarrow S$, we can contravariantly construct a map $S^{+} \to U^{+}$ between the one point compactifications, so in our case, the open embedding $i\colon N \to \mathbb{R}^{n+k}$ of the normal bundle $\nu\colon N \to M$ gives us a map $S^{n+k} \to N^{+}$ which carries quite a lot of information about $M$.
The text assumes $M$ to be compact in this context and then goes on to present the Thom space as a generalisation of this idea that also works for non compact base spaces.
The question, at last
Does the above idea not work with non compact $M$? If not: why?
If it does, where else in the remainder of the proof of the above theorem does a simple one point compactification stop to "work"? And what is it that then makes the Thom space the "correct" generalisation?
I do have one idea, but I'm absolutely not sure whether this is anywhere near the right answer: One point compactification is not functorial, right? And the next step in our construction would be to extend the map constructed above by the bundle map that covers the classifying map $f\colon M \to BO(k)$ of $\nu$, but we would have to apply one point compactification to it as well. As far as I know, this only works for proper maps, and we don't know $f$ to be proper?
According to the above notes, the Thom construction is functorial, but only on bundle maps which are injective on each fiber; do we have that in our situation? And is this really the crux of the matter?


text:
Q: Expected number of elements does not match I am having an issue with the following code on a BMI data set with dimensions (500,4). The issue I am getting can be seen below the code.
'''
def detailed_analysis(data, pred = None):
    obs = data.shape[0]
    types = data.dtypes
    counts = data.apply(lambda x: x.count())
    uniques = data.apply(lambda x: [x.unique])
    nulls = data.apply(lambda x: x.isnull().sum())
    distincts = data.apply(lambda x: x.unique().shape[0])
    missing_ratio = (nulls / obs)*100
    skewness = data.skew()
    kurtosis = data.kurt()
    print('Data shape:', data.shape)

    if pred is None:
        cols = ['types', 'counts', 'nulls', 'distincts', 'missing_ratio', 'uniques', 'skewness', 'kurtosis']
        details = pd.concat([types, counts, nulls, distincts, missing_ratio, uniques, skewness, kurtosis], axis=1)
    else:
        corr = BMI_df.corr()[pred]
        details = pd.concat([types, counts, nulls, distincts, missing_ratio, uniques, skewness, kurtosis, corr], axis=1
                            , sort=False)
        corr_col = 'corr' + pred
        cols = ['types', 'counts', 'nulls', 'distincts', 'missing_ratio', 'uniques', 'skewness', 'kurtosis', corr_col]

    details.columns = cols
    dtypes = details.types.value_counts()
    print('____________________________\nData types:\n', dtypes)
    print('____________________________')
    return details

details = detailed_analysis(BMI_df, 'Weight')
display(details.sort_values(by='corr Weight', ascending=False))

'''
Error:
ValueError: Length mismatch: Expected axis has 12 elements, new values have 9 elements
'''
   Gender  Height  Weight  Index
0    Male     174      96      4
1    Male     189      87      2
2  Female     185     110      4
3  Female     195     104      3
4    Male     149      61      3
Data shape: (500, 4)

'''


text:
Q: How to set association class_name based on model attribute I have the following models:
class Schematic < ApplicationRecord
  belongs_to :branch, foreign_key: :location_cd
  has_many :schematics_stocks, class_name: 'SchematicsStock', dependent: :destroy
end

class SchematicsStock < ApplicationRecord
  belongs_to :schematic
  belongs_to :stock, foreign_key: "stock_no"
end

class Stock < ApplicationRecord
  self.table_name = 'stockslc'
  self.primary_key = 'stock_no'
  has_one :schematics_stock
end

There are various stock tables (stockslc, stockalb, etc.) based on the location_cd (slc, alb, etc.) of the schematic. Is there some way I can do schematic.schematics_stocks[0].stock and have it automatically choose the right stock table?
I thought about creating a model for each stock table. In the SchematicsStock class I could do
Object.const_get("Stock#{schematic.location_cd.downcase}").find(stock_no)

but this would query the database for every stock no, whereas previously it only did one db call for all the schematics.
I looked into ActiveRecord association extensions to see if I could define a belongs_to stock method based on the location_cd at the same time schematics_stocks is defined. Something like
class Schematic < ApplicationRecord
  belongs_to :branch, foreign_key: :location_cd
  has_many :schematics_stocks, class_name: 'SchematicsStock', dependent: :destroy do
    belongs_to stock, class_name: "Stock#{location_cd.downcase}"
  end
end

This looks like a perfect opportunity to use Postgresql table partioning where I could partition a stock table based on the location_cd, but changing the stock schema isn't an option and the there is already a lot of production data in the other tables.
I have code like the following in my view.
  <% @schematic.schematics_stocks.includes(:stock)
    .order(:stock_no).each do |s_stock| %>

I am trying to decide if I should just write a query to get it from the correct table and then rewrite my view code or if there is a way to keep my view code the same.

A: Maybe the following is a workound, if you just want to be efficient with SQL?
class Schematic < ApplicationRecord
  has_many :schematic_stocks, dependent: :destroy

  def stocks
    # say if `location_cd` == 'alb', then
    # you'll need to create a model named Stockalb in your app/models
    # and a model for each "stock table" you have.
    stock_class = ('Stock' + location_cd).constantize
    stock_class.joins(:schematic_stocks)
  end
end

A: I realized that I could set the model's table_name at runtime. Initially I used the following code to use the correct stock table
<% Stock.table_name = "stock" + @schematic.location_cd.downcase %>
<% @schematic.schematics_stocks.includes(:stock)
  .order(:stock_no).each do |s_stock| %>

Based on Jay-Ar Polidario's answer, I decided to make a method in the schematic model to change the table_name.
# schematic.rb
def schematics_stocks_with_stocks
  Stock.table_name = 'stock' + location_cd.downcase
  schematics_stocks.includes(:stock)
end

# view
<% @schematic.schematics_stocks_with_stocks
  .order(:stock_no).each do |s_stock| %>


text:
Q: PHP include not working for index page I am trying to use PHP include on my website but I am running into trouble...
To start this is my code:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Future | Origins</title>
</head>
<body>
    <?php
        if (isset($_GET['p'])) {
            $p = $_GET['p'];

            include('include/header.php');

            switch($p) {

                case "about":
                include('include/about.php');
                break;

                default:
                    $p = "include/main.php";
                break;

            }

            include('include/footer.php');
        }
    ?>
</body>
</html>

It only shows content for my index page if my URL is styled like
localhost/index.php?p=

I would like it to show content for my index page using the default
localhost

I don't have much knowledge of PHP and there never seems to be a straightforward solution. I am including multiple pages in my website using a switch case.
Many thanks

A: Just move your includes outside the if statement
<body>
<?php
    include('include/header.php');
    if (isset($_GET['p'])) {
        $p = $_GET['p'];

        switch($p) {

            case "about":
            include('include/about.php');
            break;

            default:
                $p = "include/main.php";
            break;

        }
    }
        include('include/footer.php');

?>
</body>


text:
Q: How to show font awesome icons (like,views) on css hover overlay? When i hover on top of div tag then am showing one css overlay and i like to add couple of buttons (Like and Share) on top of overlay how can i do that?
this is my code for hover
.portfolio-item img {
    width:100%;
    vertical-align:top;
}
.portfolio-item:after {
    content:'\A';
    position:absolute;
    width:100%; height:100%;
    top:0; left:0;
    background:rgba(0,0,0,0.6);
    opacity:0;
    transition: all 0.5s;
    -webkit-transition: all 0.5s;
}
.portfolio-item:hover:after {
    opacity:1;
}

#like {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 70px;
    height: 70px;
    margin: -35px 0 0 -35px;
    z-index: 10;
}

javascript used to create div
var element = document.createElement("div");
element.setAttribute("id",listItem"+i);
element.setAttribute("class","col-md-4  portfolio-item");
output.appendChild(element);

javascript to show overlay icon
var ele = document.createElement("div");
ele.setAttribute("id","like");
ele.setAttribute("class","like"+i);

document.getElementById("red"+i).appendChild(ele);

html code

Now it look like this on hover"

and am expecting something like this:

A: You can create a child div inside the main container

23

In css
#output img {
    width:100%;
    height:100%;
}
#output > div{
    display:none;
    position: absolute;
    top: 50%;
    left: 50%;
    width: 70px;
    height: 70px;
    z-index: 10;
}
#output > div:hover{
    display:block;
}

A: Assuming you have setup font awesome properly,
you could do something like this when you are creating the overlay.
var ele = document.createElement("div");
    ele.setAttribute("id","like");
    ele.setAttribute("class","like"+i);

var faHeart = document.createElement("div");
    faHeart.setAttribute("class","fa fa-heart-o");

ele.appendChild(faHeart);


text:
Q: In asp.net using c# publishing a website takes more time i created a website using c# in asp.net when i am publishing it. Its taking more than 1 hours to publish that particular site.

A: It seems you are trying to publish to remote server via FTP. Now this will surely take time due to network operations.
Try publishing website to local machine first and then upload it using your preferred FTP client.
I also recommend using Web Deployment Projects.

A: You can check Publishing Web Sites to see if you do website publishing properly.


text:
Q: Is there a way to launch a stored procedure before and after every SSIS package? I'm looking for a way - either using in-built SSIS functionality or custom-built (3rd party software or internally-coded) - to "wrap" every executed SSIS bundle with specific code, e.g. launch certain SQL procedures prior to and after all execution steps.
These are meant to log flow steps, handle errors, set up notifications, etc.
The key idea here is to avoid editing and adding this code manually to every single SSIS bundle manually - albeit doable, it's a pain in the neck to maintain if anything were to change in above setup.
Any advice on the topic from you SSIS / SQL Server gurus would be highly appreciated.
EDIT: alternatively, is there a way to easily refactor existing deployed SSIS packages and add / modify that code quickly and easily in one go?

A: 1.I'm looking for a way - either using in-built SSIS functionality or custom-built (3rd party software or internally-coded) - to "wrap" every executed SSIS bundle with specific code, e.g. launch certain SQL procedures prior to and after all execution steps.
Please refer to Execute SQL Task.
2.These are meant to log flow steps, handle errors, set up notifications, etc.
log flow steps--Please refer to SSIS Logging.
handle errors--Please refer to Integration Services (SSIS) Event Handlers and
Capturing SQL Server Integration Services Package Errors Using OnError Event Handlers.
set up notifications--Please refer to SSIS Script Task and Getting started with the SSIS Script Task.
3.Alternatively, is there a way to easily refactor existing deployed SSIS packages and add / modify that code quickly and easily in one go?
Please refer to Editing Published SSIS Package in SQL Server 2012.


text:
Q: Data validation matching with a list with VBA I have a certain range of cells in excel where I want to apply data validation on another data validation.
I want the user to only have 3 options for data input within range of cells:

*

*either a number,

*a range of numbers or by

*choosing from a dropdown list that contains words and numbers.

I already implemented number 1 and 2 with the following function:
Function checkStr(ByVal str As String) As String

    Dim objRegEx As Object, allMatches As Object
    Set objRegEx = CreateObject("VBScript.RegExp")

    With objRegEx
        .MultiLine = False
        .IgnoreCase = False
        .Global = True
        .Pattern = "^\d+(-\d+)?$"
    End With

    Set allMatches = objRegEx.Execute(str)
    checkStr = (allMatches.Count > 0)

End Function

Since the above function will only allow numbers or a range of numbers to be inputted, any ideas on how to add a validation to allow values from a pre-defined list containing both words and numbers?

A: The list is taking values from some range. Thus, take the range of the list and use the Application.Match() to check whether the str is there:
Public Function checkStr(str As String) As Boolean

    Dim isItError As Variant
    isItError = Application.Match(str, Worksheets(1).Range("A1:A5"), 0)

    checkStr = Not IsError(isItError)

End Function

Application.Match() would return either error or true. Thus, your function can be fixed with Not IsError().

And if you want to compare Strings with Strings and Numbers as Numbers, try to pass the variable as Variant and let VBA decide what it is actually:
Public Function checkMe(someVar As Variant) As Boolean

    Dim isItError As Variant
    Dim formulaAddress As String

    With Range("C1").Validation
        formulaAddress = Right(.Formula1, Len(.Formula1) - 1)
    End With

    isItError = Application.Match(someVar, Range(formulaAddress))
    checkMe = Not IsError(isItError)

End Function

If you explicitly define the variable as a numeric or string, the other option would be excluded in the Application.Match() comparison:
?Application.Match("1",Array(1,2,3))
Error 2042
?Application.Match(1,Array(1,2,3))
1
?Application.Match("1",Array("1","2","3"))
1
?Application.Match(1,Array("1","2","3"))
Error 2042

A: I suggest to change the return As Boolean and then just filter the str against an array of valid list entries.
Function checkStr(ByVal str As String) As Boolean

    Dim objRegEx As Object, allMatches As Object
    Set objRegEx = CreateObject("VBScript.RegExp")

    With objRegEx
        .MultiLine = False
        .IgnoreCase = False
        .Global = True
        .Pattern = "^\d+(-\d+)?$"
    End With

    Set allMatches = objRegEx.Execute(str)

    Dim ValidList As Variant
    ValidList = Array("123", "456") 'your list of valid entries

    'check if either str is in the ValidList OR matches the regex
    If (UBound(Filter(ValidList, str)) > -1) Or (allMatches.Count > 0) Then
        checkStr = True
    End If

End Function

If the list of valid entries is in a range you can replace it with:
ValidList = WorksheetFunction.Transpose(Worksheets("SheetName").Range("A1:A10").Value)


text:
Q: Changing the border color of parent div when the child select is hovered, active, focused I need your help.
Is there a way to change the border color of the parent div, when the child select box is either hovered, active or focused?

  <select style="width: 100%; border:0px; outline:0px; padding: 2px;">
    <option value="Sal">Sal</option>
    <option value="Awesome">Awesome!</option>
  </select>

A: An alternative solution would be to use the focus-within selector: https://css-tricks.com/almanac/selectors/f/focus-within/

A: As we know, there is no CSS parent selector, but if all you need to do is change border-color (and possibly background) on :hover, you can use a pseudo element & some positioning + z-index hacks to do it. Here's an example with comments inline

div.select {
  height: 50px;
  background: #FFF;
  width: 200px;
  position: relative;
  /* to position the pseudo element */
  z-index: 1;
  /* HACK: to make sure it doesn't affect anything globally. */
  /* Increase this value if the element is not visible */
  /* or you have z-index set in your code */
}

.select-wrap::after {
  content: ' ';
  position: absolute;
  top: -1px;
  /* for outside border */
  left: -1px;
  right: -1px;
  bottom: -1px;
  background: #eee;
  border: 1px solid transparent;
  pointer-events: none;
  /* to make sure hovering on the background doesn't trigger color change */
}

.select-wrap:hover::after {
  background: yellow;
  border-color: black;
}

select {
  width: 100%;
  border: 0px;
  outline: 0px;
  padding: 2px;
  position: relative;
  z-index: 10;
  /* HACK: Can be any number more than the :after element's z-index. */
  /* As the parent has a z-index, it won't affect anything globally */
}

    <select>
    <option value="Sal">Sal</option>
    <option value="Awesome">Awesome!</option>
  </select>

Codepen link: https://codepen.io/palash/pen/wpRVQV
Also, note that pseudo elements do not work with <select>, hence the need for the 'select-wrap'


text:
Q: php post method working in localhost! not working in server My php file Picture_gallery.php:
 <?php
    include('connect-db.php');
    $response = array("total_records" => "", "result_returned" => "");
    $data = array("error_code" => "", "error_message" => "");
    $order = "";
    $sql = "Select * from ju_picture_gallery";
    $total_row = "";
    $result = "";
    $image_gallery = "folder_name";
    //$start_index =$_POST['start_index'];
    //$per_page =$_POST['per_page'];

    $folder_name = $_POST['folder_name'];
    $start_index = htmlspecialchars($_POST['start_index']);
    $per_page =htmlspecialchars($_POST['per_page']);

    //$folder_name = htmlspecialchars($_POST['folder_name']);

    //$start_index = print_r($_POST['start_index']);
    //$per_page =print_r($_POST['per_page']);
    //$folder_name = print_r($_POST['folder_name']);

    if ($folder_name == "$folder_name")
    {
        $sql = "select pg_image_url from ju_picture_gallery where folder_name ='$folder_name' LIMIT $start_index,$per_page";
        $total_row = "SELECT *  FROM ju_picture_gallery where folder_name ='$folder_name' ";
        $image_gallery = "image_gallery";
        json_encode($result);

    }

    $result = mysqli_query($con, $sql);
    $count = mysqli_num_rows($result);
    $total=mysqli_num_rows(mysqli_query($con,$total_row));
    $response["result_returned"]=(string)$count;
    $response["total_records"]=(string)$total;
    $response["folder_name"] = (string)$folder_name;
    if ($result) {
        while ($r = mysqli_fetch_assoc($result)) {
            $json[] = $r;

        }
        $row_count = mysqli_num_rows($result);
        if ($row_count > 0) {
            print json_encode(array_merge($data, array('pagination_info' => $response), array($image_gallery => $json)));

        } else {
            $data["error_code"] = "1012";
            $data["error_message"] = "No Content!";
            print json_encode(array_merge($data, array('pagination_info' => $response)));

        }

    }
    mysqli_close($con);
    ?>

Here if run this file in localhost it asks the 3 values for all the above post values.if i run in web hosing it does not asking the post values..displaying an empty sceen.
here is my webhosting link:

*

*The o/p is an empty screen

*On this link i getting an error

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\Inetpub\vhosts\certifytechnologies.com\mobileapp\jumeirah\picture_gallery.php on line 36
PHP Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\Inetpub\vhosts\certifytechnologies.com\mobileapp\jumeirah\picture_gallery.php on line 36

A: I think you need to change some lines in your code to this
 $result = mysqli_query($con, $total_row);
$count = mysqli_num_rows($result);

  $total=mysqli_num_rows(mysqli_query($con,$count));
$response["result_returned"]=(string)$count;
$response["total_records"]=(string)$total;
$response["folder_name"] = (string)$folder_name;
if ($result) {
 while ($r = mysqli_fetch_assoc($result)) {
        $json[] = $r;

    }


text:
Q: Exception with SpringJPA native query When I am trying to execute my native query, I am facing following exception:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an
  error in your SQL syntax; check the manual that corresponds to your
  MySQL server version for the right syntax to use near 'f,
  codigoleyenda cl, tipocomprobante tc, moneda m, cliente c, tipotaxigv
  ttig, t' at line 1

and my repository is as follows-
@Repository
public interface FacturaRepository extends JpaRepository<Factura, Integer>, CrudRepository<Factura, Integer>{
    @Query(value="select " +
            "f.facId," +
            "facBaja," +
            "f.facEnvioSunat," +
            "f.facEnvioServidor," +
            "f.facEstadoEnvioCorreo," +
            "f.facFechaRespuesta," +
            "f.facRuta," +
            "f.facSubTotal," +
            "f.facInafecta," +
            "f.facExonerada," +
            "f.facGratuita," +
            "f.facGravada," +
            "f.facPercepcion," +
            "f.facOtrosTributos," +
            "f.facDescuento," +
            "cl.codLeyCodigo," +
            "f.facLeyenda," +
            "f.facDetraccion," +
            "f.facNroSerie," +
            "f.facNroCorrelativo," +
            "f.facFechaEmision," +
            "tc.tipComCodigo,"+
            "m.monCodigo,"+
            "ub.ubiDepartamento," +
            "ub.ubiProvincia," +
            "ub.ubiDistrito," +
            "ub.ubiCodigo," +
            "p.parRuta," +
            "s.sucDireccionFiscal," +
            "s.sucRuc," +
            "s.sucTipoDocumento," +
            "s.sucPais," +
            "s.sucRazonSocial," +
            "c.cliCondicionDomicilio," +
            "c.cliDireccionFiscal," +
            "c.cliEstado," +
            "c.cliNumeroDocumento," +
            "c.cliRazonSocial," +
            "td.tipDocCodigo," +
            "f.facIgv," +
            "f.facIsc," +
            "ttig.tipTaxIgvCodigo," +
            "ttis.tipTaxIscCodigo," +
            "f.facOtrosConceptos," +
            "oc.otrConCodigo," +
            "f.facTaxIgvPorcentaje," +
            "f.facTaxIscPorcentaje," +
            "f.facHashcode," +
            "f.facNombreZip," +
            "f.facTotal," +
            "f.facRetencion," +
            "f.facPlaca" +
            "from factura f, codigoleyenda cl, tipocomprobante tc, moneda m, cliente c, tipotaxigv ttig, tipotaxisc ttis, otrosconceptos oc," +
            "tipodocumento td, sucursal s, ubigeo ub, parametros p" +
            "where c.tipDocId = td.tipDocId and  f.sucId=s.sucId and s.ubiId=ub.ubiId and s.parId=p.parId" +
            "and f.codLeyId=cl.codLeyId and f.tipComId=tc.tipComId  and f.monId=m.monId and f.cliId=c.cliId and " +
            "f.tipTaxIgvId=ttig.tipTaxIgvId and f.tipTaxIscId=ttis.tipTaxIscId and f.OtrConId=oc.otrConId and f.facId=?1", nativeQuery=true)
            FacturaXmlDto getFacturaXml(int facId);

this query is working fine with mysql, but facing the exception with SpringJPA and I need help on this issue.

A: For this type of question, you would need to give out the exception.  But from just looking at it, check your spaces. You definitely need to add a space before the closing quote on the following lines:
"f.facPlaca" +
"tipodocumento td, sucursal s, ubigeo ub, parametros p" +
"where c.tipDocId = td.tipDocId and  f.sucId=s.sucId and s.ubiId=ub.ubiId and s.parId=p.parId" +

without the space, the last word on that line runs into the first word on the next line.  Also, in your code, you might want to println the resulting query, and copy and paste that query to your database browser, and see what happens.


text:
Q: How to emit/broadast an event upon clearing all filters in ui-grid Is it possible to emit an event to $rootScope upon triggering the clearAllFilters method in ui-grid (without editing the library)?
To give some context, I have a custom filter which requires a method be called once the 'clear all filters' menu item is clicked.  I had intended to include a watcher within the component e.g:
$rootScope.$on('clearAllFilters', function(){ });

However I can't find any way to emit such an event from the clearFilters method.

// snippet from custom filter code

angular
    .module('my-ui-components.grid')
    .controller('MyCustomFilterController', function (_) {

        vm.inputValue = '';
        vm.removeFilter = removeFilter;
        vm.updateFilter = updateFilter;

        //  this method is called successfully on clicking the individual clear button / x
        //  however unable to call it programmatically upon clicking the 'clear all filters' button
        function removeFilter() {
            vm.inputValue = '';
            vm.colFilter.term = '';
        }

        function updateFilter() {
            vm.colFilter.term = parseCapacity(vm.inputValue, fromUnit, vm.toUnit);
        }

        // attempt at watching for filters being cleared however no event emitted to do so
        $rootScope.$on('clearAllFilters', function() {
            vm.removeFilter();
        });

<input type="text" class="ui-grid-filter-input" ng-model="vm.inputValue" ng-change="vm.updateFilter()"
       placeholder="{{vm.colFilter.placeholder}}"/>


text:
Q: General question about derivatives. Consider a differentiable function $f:\mathbb{R} \rightarrow \mathbb{R}$. The derivative of the function at any point can be written as:
\begin{align*}
f'(x) = \lim_{h \to 0} \frac{f(x+h) - f(x)}{h}
\end{align*}
Suppose we have a constant $c > 0$, is it true that:
\begin{align*}
f'(x) = \lim_{h \to 0} \frac{f(x+\frac{h}{c}) - f(x)}{h} \hspace{3ex}?
\end{align*}
Since when dividing $h$ by some constant in the numerator, it will still become arbitrarily small. Or does it follow that:
\begin{align*}
\lim_{h \to 0} \frac{f(x+\frac{h}{c}) - f(x)}{h} = \frac{1}{c}\lim_{h \to 0} \frac{f(x+\frac{h}{c}) - f(x)}{\frac{h}{c}} = \frac{f'(x)}{c} \hspace{3ex} ?
\end{align*}
I think that the second case is correct, but I still wanted to be 100% sure.

A: The last equation you wrote is the correct one. You can check with examples. If $f$ is the identity, namely $f(x)=x$. Then
$$
\lim_{h\rightarrow 0} \frac{f(x+\frac{h}{c})-f(x)}{h}= \lim_{h\rightarrow 0} \frac{x+\frac{h}{c}-x}{h}=\lim_{h\rightarrow 0} \frac{\frac{h}{c}}{h}=\frac{1}{c}.
$$
If $f(x)=x^2$ then
$$
\lim_{h\rightarrow 0} \frac{f(x+\frac{h}{c})-f(x)}{h}= \lim_{h\rightarrow 0} \frac{x^2+2x\frac{h}{c}+\frac{h^2}{c^2}-x^2}{h}=\lim_{h\rightarrow 0} \frac{2x\frac{h}{c}+\frac{h^2}{c^2}}{h}=\lim_{h\rightarrow 0} \frac{2x}{c}+\frac{h}{c^2}=\frac{2x}{c}.
$$

A: Here is the proof in case you're interested.  It isn't saying much new compared to Anguepa's examples.
$$
\begin{array}{}
&&\displaystyle \lim_{h \to 0} { f(x + h/c) - f(x) \over h} \\
&=& \displaystyle \lim_{h \to 0} \frac1c { f(x + h/c) - f(x) \over h/c} & \text{...basic algebra}\\
&=& \displaystyle \frac1c \lim_{h \to 0}  { f(x + h/c) - f(x) \over h/c} & \text{...pull out the $1/c$ constant}\\
&=& \displaystyle \frac1c \lim_{cg \to 0}  { f(x + g) - f(x) \over g} & \text{...rename $g = h/c$}\\
&=& \displaystyle \frac1c \lim_{g \to 0}  { f(x + g) - f(x) \over g} & \text{...basic property of limit, see below}\\
&=& \displaystyle \frac1c f'(x) &\text{...by definition of $f'(x)$}
\end{array}
$$
The only step that actually involves calculus is the $4$th equal sign, and further explanation will need to invoke the $(\epsilon, \delta)$-based definition of what a limit is.  It's a bit tedious, so hopefully you are OK with leaving it as "basic property of limit."  :)

A: You have to replace $h$ everywhere by $h/c$ for the limit to still be $f'(x).$ Otherwise, it is generally different.


text:
Q: Data pre-filtering on SQL based Report I made a SQL-based report in Visual Studio 2008 and uploaded it to the CRM. I indicated that you can only run it on "Forms for related record types". I thought this would generate 1 report for the current record you are in.
This isn't the case. It generates a report for each record of the specific entity (Order), 1 record per page in the report.
I know I have to use Data-Prefiltering (automatic or specific?), but there are no good examples online and there is even a thread here on stackoverflow but I jsut can't figure it out.
Link to thread: CRMAF Filtering in CRM 2011
SELECT FilteredSalesOrder.customerid AS x1, FilteredAccount.accountid AS x2, FilteredSalesOrderDetail.salesorderid AS x3, FilteredSystemUser.systemuserid AS x4,
FilteredProduct.productid AS x5, FilteredAccount.address1_city, FilteredAccount.address1_line1, FilteredAccount.address1_postalcode, FilteredAccount.name AS AccountName,
FilteredSalesOrder.ordernumber, FilteredSalesOrderDetail.quantity, FilteredSystemUser.fullname, FilteredProduct.fmcg_erpreference, FilteredProduct.name AS ProductName
FROM FilteredSalesOrder INNER JOIN FilteredAccount
ON FilteredSalesOrder.customerid = FilteredAccount.accountid INNER JOIN FilteredSalesOrderDetail
ON FilteredSalesOrderDetail.salesorderid = FilteredSalesOrder.salesorderid INNER JOIN FilteredProduct
ON FilteredProduct.productid = FilteredSalesOrderDetail.productid INNER JOIN FilteredSystemUser
ON FilteredSystemUser.systemuserid = FilteredSalesOrder.ownerid

To pre-filter the data only to use the current Order:

*

*Use CRMAF_ with only the SalesOrder Table, is that enough?

FROM FilteredSalesOrder AS CRMAF_FilteredSalesOrder INNER JOIN FilteredAccount

*

*Use CRMAF_ with all the tables?

EDIT:
This is my new entire SQL where I used the CRMAF_ on FilteredSalesOrder. But alas it does not work. It still gives me only the opportunity to run it against all records, and thus generates all the Salesorders that exist (luckily there are not that many).
SELECT CRMAF_FilteredSalesOrder.customerid AS x1, CustomerAccount.accountid AS x2,
FilteredSalesOrderDetail.salesorderid AS x3, FilteredSystemUser.systemuserid AS x4,
FilteredProduct.productid AS x5,CRMAF_FilteredSalesOrder.fmcg_supplierid as x6,
CustomerAccount.address1_city as customerCity, CustomerAccount.address1_line1 as
customerStreet1, CustomerAccount.address1_postalcode as customerPostalCode,
CustomerAccount.name AS CustomerAccountName, CRMAF_FilteredSalesOrder.ordernumber,
FilteredSalesOrderDetail.quantity, FilteredSystemUser.fullname,
FilteredProduct.fmcg_erpreference, FilteredProduct.name AS ProductName,
SupplierAccount.name as supplierAccountName, SupplierAccount.address1_city AS
supplierCity,SupplierAccount.address1_line1 as supplierStreet1,
SupplierAccount.address1_postalcode as supplierPostalCode,
CRMAF_FilteredSalesOrder.requestdeliveryby, CRMAF_FilteredSalesOrder.createdon

FROM FilteredSalesOrder AS CRMAF_FilteredSalesOrder INNER JOIN FilteredAccount AS CustomerAccount
ON CRMAF_FilteredSalesOrder.customerid = CustomerAccount.accountid INNER JOIN FilteredSalesOrderDetail
ON FilteredSalesOrderDetail.salesorderid = CRMAF_FilteredSalesOrder.salesorderid INNER JOIN FilteredProduct
ON FilteredProduct.productid = FilteredSalesOrderDetail.productid INNER JOIN FilteredSystemUser
ON FilteredSystemUser.systemuserid = CRMAF_FilteredSalesOrder.ownerid INNER JOIN FilteredAccount AS SupplierAccount
ON CRMAF_FilteredSalesOrder.fmcg_supplierid = SupplierAccount.accountid

Solution: Deleted Report and redeployed it.

A: See Sample: Make a Report Context-Sensitive on MSDN.
You only need to filter on the current SalesOrder.
The documentation on automatic prefiltering in CRM 2011 is sparse, however, I think it hasn't changed much between CRM 2011 and CRM 4. So please refer to Using Filters in a Report on MSDN regarding SSRS reports in CRM 4 for a better explanation.
What I often use in reports are parameters like CRM_FilteredSalesOrder combined with a SQL query like the following:
EXEC('
    SELECT FSO.*
    FROM (' + @CRM_FilteredSalesOrder + ') AS FSO
')

It is the same principle as automatic prefiltering, but now you control where the prefilter is inserted. Also remember that an automatic prefilter can't be used more than once in a single query in an SSRS report.
EDIT: OK, let me just literally use your example:
EXEC('
  SELECT
    FSO.customerid AS x1,
    FilteredAccount.accountid AS x2,
    FilteredSalesOrderDetail.salesorderid AS x3,
    FilteredSystemUser.systemuserid AS x4,
    FilteredProduct.productid AS x5,
    FilteredAccount.address1_city,
    FilteredAccount.address1_line1,
    FilteredAccount.address1_postalcode,
    FilteredAccount.name AS AccountName,
    FSO.ordernumber,
    FilteredSalesOrderDetail.quantity,
    FilteredSystemUser.fullname,
    FilteredProduct.fmcg_erpreference,
    FilteredProduct.name AS ProductName
  FROM (' + @CRM_FilteredSalesOrder + ') AS FSO
  INNER JOIN FilteredAccount ON FSO.customerid = FilteredAccount.accountid
  INNER JOIN FilteredSalesOrderDetail ON FilteredSalesOrderDetail.salesorderid = FSO.salesorderid
  INNER JOIN FilteredProduct ON FilteredProduct.productid = FilteredSalesOrderDetail.productid
  INNER JOIN FilteredSystemUser ON FilteredSystemUser.systemuserid = FSO.ownerid
')

If you want to understand what the CRM inserts, put the CRM_FilteredSalesOrder parameter in a textbox on the report. It will be a query in the form SELECT f0.* FROM FilteredSalesOrder AS f0 WHERE f0.salesorderid = '3641478b-5022-40fa-90c1-a4d407e8b99b' when it's on "Forms for related record types". This is effectively a subquery for this one particular Order. That's what they call "prefiltering", you'll just query a subquery.


text:
Q: Show only specific labels on network graph using igraph in R I'm trying to plot a graph that only displays the labels for certain vertices. In this case, I want to only display labels for vertices with a certain number of edges.
I'm reading vertices and edges into the graph object like so:
nodes <- read.csv("path_to_file.csv")
edges <- read.csv("path_to_file.csv")
g <- graph_from_data_frame(edges,directed=TRUE,vertices=nodes)

I use the following command to plot the graph and vary the width of the edge based on number of connections (the $rels attribute is the number of connections between two vertices):
plot.igraph(g,vertex.size=3,vertex.label.cex=0.5,layout=layout.fruchterman.reingold(g,niter=10000),edge.arrow.size=0.15,edge.width=E(g)$rels/100)

Is there a way to say, for instance, that only vertices with > 100 edges should have their label displayed? If I try to leave vertex labels out in my csv files, igraph thinks they are duplicate vertices.

Examples of data
nodes.csv
name | org_id
U.S. Department of Energy | 70063
Environmental Protection Agency | 100000

edges.csv
from | to | rels
U.S. Department of Energy | Hanford SSAB | 477
Natural Resources Defense Council | Environmental Protection Agency | 322

A: Try
library(igraph)
set.seed(1)
g <- sample_pa(20)
V(g)$label <- letters[1:20]
plot(g, vertex.label = ifelse(degree(g) > 2, V(g)$label, NA))

to display only the labels for vertices with a degree greater than 2:


text:
Q: What is the fastest way to change a clustered index on a 64GB table? We have a table (64 GB in size, 256795926 rows) which has a very bad PK (clustered) index. Currently it's a varchar(99) column (average size 50 characters).
There is already a bigint identity column, so we would like to convert the PK to this column.
However altering a PK is not possible, so a drop / recreate seems the only solution. But this table is constantly updated, so downtime must be a minimum. We have SQL Server 2019 Enterprise, but online dropping / recreating would be a very long time I guess, and the logfile will be also huge.
I am thinking of recreating a new table with the correct structure, transfer the latest ID to this new table (so my identities are ok) and transfer the data to this new table. To my opinion this will give the least downtime, but does somebody have a better idea?

A: If you can't take the downtime, then an copy to a new table followed by a final incremental copy/rename/drop in a transaction is the only way to go.

A: You have 2 alternatives:
Enterprise Edition: If you are on SQL Server Enterprise Edition you can use WITH (ONLINE=ON):
DROP INDEX [Old_Index] ON dbo.Table;
GO

CREATE UNIQUE CLUSTERED INDEX CX_Table ON dbo.Table(ID) WITH (ONLINE=ON);
GO

I haven't tested but you could also use WITH (DATA_COMPRESSION = ROW, ONLINE = ON); it might be faster. I don't knwo. Sorry, I don't have time test it right now for you :(
Standard Edition: You have to schedule a maintenance window


text:
Q: Changing a property of a managed object in NSFetchedResultsController I've got a NSFetchedResultsController *fetchedResultsController, which works with a subclass of a NSManagedObject - Element.
I receive an object:
Element *element = [fetchedResultsController objectAtIndexPath: indexPath];
I want to change the property of my element instance and save it to the database. How can do it?

A: Change the attribute on the Element object as you would normally do, and then save the ManagedObjectContext, as you would normally do.
Be sure to cast the object from that array to an Element object to prevent compiler warnings/ errors.


text:
Q: When is it appropriate to write $\sqrt{-1}$ in mathematics? The principal square root of $x$, denoted $\sqrt{x}$, occurs strictly when $x\in \mathbb{R}^{\geq 0}$. Every mathematician knows that writing $\sqrt{25}=-5$ is clearly $\underline{\text{incorrect}}$ here as it is the positive solution we want and not the negative. Also, writing $\sqrt{x}$ for when $x<0$ would be contradictory to a set of solutions (see incorrect result) when dealing with different algebraic equations.

$\textbf{Question:}$ So, why is it acceptable to define $\pm i=\sqrt{-1}$ when I just said the same exact notation for the principal root is reserved for non-negative real numbers? How are we able to distinguish the notation for square roots over $\mathbb{C}$ instead of over $\mathbb{R}$ when dealing with algebraic equations? I mean there has got to be a notation out there somewhere that avoids conflating these concepts as to when it is and is not appropriate to venture into the complex world.

The problem is is that we want $\sqrt{-5}$ to not be defined so often; yet, it is perfectly acceptable to write a square root around a discriminant that is $<0$ when dealing with the quadratic formula.

*

*Here is a link to a previous question I asked too.

A: I personally find it acceptable when you are clear that you interpret all of $\sqrt{-1}$ as a single symbol, not as a square root with a $-1$ under it. In other words, the $-1$ and the square root carry no mathematical significance, but just serve as a remainder of what happens when you square it.
It's not so common to see with $\sqrt{-1}$, because that role is filled by the symbol $i$. But the same notation with other numbers, like $\sqrt{-5}$, I see from time to time.


text:
Q: tf.train.batch is showing insufficient elements I am working on LSTM based models. the data consists of 80000 images. I am using batchsize of 1  and getting the following as error log:

OutOfRangeError (see above for traceback): PaddingFIFOQueue
  '_1_Train_data/batch/padding_fifo_queue' is closed and has
  insufficient elements (requested 1, current size 0)    [[Node:
  Train_data/batch = QueueDequeueManyV2[component_types=[DT_FLOAT,
  DT_STRING, DT_INT32], timeout_ms=-1,
  _device="/job:localhost/replica:0/task:0/cpu:0"](Train_data/batch/padding_fifo_queue,
  Train_data/batch/n)]]

Can someone suggests what can be the possible issue? as the fifoqueue size is shown as 0 for all possible batch sizes I tried.

A: The error doesn't have to do with LSTM, you are getting it from tf.train.batch.
You have to initialize your TF local variable along with global variables.
From this open issue https://github.com/tensorflow/tensorflow/issues/1045, it seems that the order of initialization matters.
global_init_op = tf.global_variables_initializer()
local_init_op = tf.local_variables_initializer()

with tf.Session() as sess:
    sess.run(global_init_op)
    sess.run(local_init_op)
    # rest of your code

A: some of the images were corrupted in the database which was causing the program to run into this error. Removed those images and now working fine.


text:
Q: Добавить запись в базу с id AUTO_INCREMENT Работая в NetBeans. В Java новичок.
Есть таблица : id (AI) , login, password, role.
Я передаю  ему 3 значения (понимаю , что он ожидает ещё и ID)
insertStr = "INSERT INTO users VALUES ("
                + quotate(dlg.getLogin()) + ","
                + quotate(dlg.getPassword()) + ","
                + quotate(dlg.getRole()) + ")";

Как мне ему передать только эти три значения и попросить самостоятельно сгенерировать ID ?

A: Нужно указать поля в которые вы передаете значения:
insertStr = "INSERT INTO users (login, password, role) VALUES ("
                + quotate(dlg.getLogin()) + ","
                + quotate(dlg.getPassword()) + ","
                + quotate(dlg.getRole()) + ")";


text:
Q: Required foreign keys in EF Core & sqlite not working for type long I use Entity Framework Core code first with these two related tables:
public class Teacher
{
  [Key]
  public long Id { get; set; }
}

public class Student
{
  [Key]
  public long Id { get; set; }

  [Required]
  public long TeacherId { get; set; }
  public Teacher Teacher { get; set; }
}

On an empty database the following insert will fail with SQLite Error 19: 'FOREIGN KEY constraint failed' since there is no teacher with Id 123456:
var student = new Student();
student.TeacherId = 123456;
dbcontext.Add(student);
dbcontext.SaveChanges();

I would expect the following to fail, too, but it does not throw an error. Instead it will add a student without relation:
var student = new Student();
student.TeacherId = 0; // why is this allowed??
dbcontext.Add(student);
dbcontext.SaveChanges();

Since there is no teacher with Id 0 I want this second code sample to fail, too. I thought [require] would get EF core /sqlite to really require the relation and am surprised why adding the student with foreign key 0 does not throw an error.
How do I get ef core / sqlite to really require the relation?


text:
Q: Determine the number of positive integers $a$ such that $a\mid 9!$ and gcd $(a, 3600)=180$. Determine the number of positive integers $a$ such that $a\mid 9!$ and gcd $(a, 3600)=180$.
What I know as of now is that $180\mid 9!$ and that $180\le a\le9!$.
The prime factorization of 180 is $(2^2)(3^2)(5^1)$
and the prime factorization of 9! is $(2^7)(3^4)(5^1)(7^1)$.
So I think I figured it out, there are exactly 7 positive integers for $a$. I'm not sure if this is correct, but this is what I have concluded.

A: What we know:

*

*$180 \mid a$

*$a$ and $3600$ share no common factors greater than $180$. In particular, any prime divisor of $3600$ cannot occur more times in $a$ than it does in $180$.

*$a \mid 9!$
So one strategy for counting the number of possible $a$'s can be counting the number of ways to build one, using these facts. First we know that $180 \mid a$, so $a$'s prime factorization must contain $(2^2)(3^2)(5^1)$. Additionally, it cannot contain any more $2$'s or $5$'s, as this would give a larger gcd with $3600$ (however, it can contain more $3$'s).
Considering the factorization of $9! = (2^7)(3^4)(5^1)(7^1)$, and removing the $180$ which is already fixed leaves the factorization $(2^5)(3^2)(7^1)$ to work with. But we can't multiply by $2$, as noted above. So we can really multiply by any factor of $(3^2)(7^1)$. There are $6$ such numbers -- we have $3$ ways to choose a power of $3$ and $2$ ways to choose a power of $7$ to use.

A: Hint $ $  Let $\,d={\large \frac{a}{180}}\,$ and cancel $180$ to get: $\,(d,20)=1\ $ & $\ d\:{\large\mid\, \frac{9!}{180}}\! = 2^5\cdot 3^2\cdot 7\iff d\mid 3^2\cdot 7$


text:
Q: Why is my Application_BeginRequest in Global.asax.cs not getting called with a self hosted WCF service I'm self hosting a WCF service that needs to support inbound CORS REST traffic. So I added the Global.asax.cs file with the following code block, but the Application_BeginRequest() never fires. I also have  set in my app.Config. Is there anything else I need to do and does this work for self hosted services or just services hosted via IIS?
    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        string origin = HttpContext.Current.Request.Headers["origin"];
        if (!String.IsNullOrEmpty(origin)) // CORS origin?
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", origin);

        if (HttpContext.Current.Request.HttpMethod == "OPTIONS") // CORS origin w/ options?
        {
            var requestedHeaders = HttpContext.Current.Request.Headers["Access-Control-Request-Headers"];
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", requestedHeaders);
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST,PUT,OPTIONS,DELETE");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.StatusCode = 200;
            HttpContext.Current.Response.End();
        }
    }

A: Only Global files hosted on IIS will take effect. IIS will treat WCF service as a web service to parse its Global file. If it is self-hosted, Global file will not be parsed and run.
We can make WCF support JSONP to solve cross-domain:
<binding name="bind1" crossDomainScriptAccessEnabled="true">
</binding>

You can also implement IDispatchMessageInspector to add response headers before the service responds.This solution is suitable for self-hosting.
public class ServerMessageLogger : IDispatchMessageInspector
    {
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
           return null;
        }

        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            WebOperationContext ctx = WebOperationContext.Current;
            ctx.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
        }
    }

For more information about IDispatchMessageInspector,Please refer to the following link:
https://learn.microsoft.com/en-us/dotnet/api/system.servicemodel.dispatcher.idispatchmessageinspector?view=netframework-4.8
If you are still unclear, you can refer to the link below, which contains the complete code:
How to enable Cross-Origin Resource Sharing in .Net Console Application WCF Service?
UPDATE
The following pictures is my demo:

One of the two pictures above uses WebOperationContext one does not use.
In fact, WebOperationContext is similar to HttpContext. WebOperationContext is usually used in WCF REST methods, and HttpContext is usually used in ASP.NET WebForms pages or ASMX Web Service Web methods.


text:
Q: Maintain drawing path on image with orientation changes in device android I have issue for maintaining drawing (lines with use of finger) on image while device orientation changes.
This image shows the drawing on image with finger

After change the orientation, the draw line misplaced.

I have path object which have this drawing data.
Please help me to resolve this.
Thanks in advance.

A: Now, It is obvious that landscape image's height is less than portrait one. So in this situation image is down scale. So we need to calculate using some equations to get that value which require to scale down the Path to adjust the position of that Path
To resolved this, Let's consider the portrait mode's image has H1 height and landscape mode's image has H2 height.
val scale = H2/H1
val matrix = Matrix()
matrix.setScale(scale, scale)
path.transform(matrix)

This way you will update the all the path objects for landscape mode.
Now when you rotate back to portrait mode, you need to undo scaling by below code.
val scale = 1 / (H2/H1)
val matrix = Matrix()
matrix.setScale(scale, scale)
path.transform(matrix)


text:
Q: Firefox 42.0 won't start anymore in 14.04 LTS (firefox:2547): GLib-GObject-WARNING Ubuntu 14.04.3 LTS - Firefox ver 42.0 doesn't start anymore via Unity bar shortcut, one day after I installed the system.
I can turn it on via terminal (sudo firefox ), but displays  the following warnings:

~$ sudo firefox
(firefox:2879): GLib-GObject-WARNING **: Attempt to add property GnomeProgram::sm-connect after class was initialised
(firefox:2879): GLib-GObject-WARNING **: Attempt to add property GnomeProgram::show-crash-dialog after class was initialised
(firefox:2879): GLib-GObject-WARNING **: Attempt to add property GnomeProgram::display after class was initialised
(firefox:2879): GLib-GObject-WARNING **: Attempt to add property GnomeProgram::default-icon after class was initialised

Any suggestions are welcome.

A: Try to reinstall Firefox run this in terminal to remove the package.
sudo apt-get remove firefox

and then install it again
sudo apt-get install firefox

for some reason removing Firefox also removes xul-ext-unity xul-ext-webaccounts install them again by runing this command.
sudo apt-get install xul-ext-unity xul-ext-webaccounts

also Firefox shortcut on the Unity bar will be gone so you would want to add it back.
To add Firefox back to the Unity bar.
click on the Unity launcher then type in Firefox then simply drag the Firefox launcher to the Unity bar.


text:
Q: Uncaught ReferenceError: findWeather is not defined I am currently working on a simple web-app for my studies that shows the current weather per location and current weather on the location you type in.
I have in my HTML file:
<div id="data">
</div>
<input type="text" value="Which city are you in?">
<input type="button" value ="Submit" onclick="findWeather()">

and for the JavaScript file:
function findWeather() {
    $.get("http://api.openweathermap.org/data/2.5/forecast?q=Eindhoven&appid=*My_APP_ID*",
            function () {
                document.getElementById("data").innerHTML = data.list.main.temp;
            })
}

Of course I have filled in the right App ID, I'm just not sure whether to share it here or not.
The JavaScript script won't run and I have no clue why.
EDIT: I seem to getUncaught ReferenceError: findWeather is not defined
error, while I did declare findWeather..?

A: You haven't defined data.
Presumably it is supposed to be the first argument of the function you pass as the second argument to $.get.

A: After passing the URL, as a second argument of the .get() function you are passing a callback anonymous function. In this function you must declare the parameter in which the data should be stored. For example:
function findWeather(){
    $.get("http://api.openweathermap.org/data/2.5/forecast?q=Eindhoven&appid=*My_APP_ID*",
           function(data) {
               document.getElementById("data").innerHTML = data.list.main.temp;
    })
}


text:
Q: Internet Explorer(8/9) ignores new line characters while printing plain text I show jBoss logs via browsers. In Firefox each line of log is ended by a new line (as it should) - IE 8 and 9 shows the entire log as a huge blob and not with new line after each line in the log file.
The source of HTML is like:

entire log content

Anyone faced this nuisance ?


text:
Q: python settings for a project - circular imports / dependency injection I've created a 'Django style' settings files for different environments.
The settings files define some variables, and also serves as dependency injection for other modules.
So the structure is:
settings/
    ___init__.py
    base.py
    dev.py
    dev2.py
    prod.py

service/
    __init__.py
    service.py
    service_mock.py

And in settings/__init__.py I write:
settings_env = os.environ.get('PROJECT_SETTINGS', '')
if settings_env == 'prod':
   from .prod import *
elif settings_env == 'dev':
   from .dev import *

Each settings file define different some variables, and also import a class from service.py or service_mock.py, depends on the environment variable.
This works mostly fine.
Now, the problem is that the service.py cannot import the settings package, because the settings files import the service.py, so that will become a circular import.
As I see in Django it is solved by using import strings in the settings files, instead of actual imports.
I don't really like the idea as I lose some of the IDE autocomplete features, also I'm not sure how to actually create the settings object that Django provides.
What are the solutions to this problem? Having a settings file that serves as a dependency injection container that imports modules, and get imported by the same modules?  Preferably a simple solution.

A: A very common, and certainly easiest solution to circular imports, is to defer imports until you actually need them. For example, change
import settings
def func():
    settings.things

to
def func():
    import settings
    settings.things

If you absolutely must have module-global imports, there are various tricks you could use, such as
settings = None
def import_stuff():
    global settings
    import settings as s
    settings = s

or have a class
class Settings():
    mod = None

    def __getattr__(self, attr):
        if self.mod is None:
            import settings
            self.mod = settings
        return getattr(self.mod, attr)

settings = Settings()

(or generalise for any module name)

A: Instead of:
settings_env = os.environ.get('PROJECT_SETTINGS', '')
if settings_env == 'prod':
   from .prod import *
elif settings_env == 'dev':
   from .dev import *

you can just export a variable:
DJANGO_SETTINGS_MODULE your_project.settings.dev2

and Django will read the right file.
Also:
Instead of
import settings

you'd like to use:
from django.conf import settings

and above can be nested in methods/functions to avoid circular imports.
see: https://docs.djangoproject.com/en/dev/topics/settings/#using-settings-in-python-code
see: https://docs.djangoproject.com/en/dev/topics/settings/#custom-default-settings


text:
Q: Instantiate the Endofunctor type with the Show class How can the Show class be instantiated with the Endo type?
{-# LANGUAGE FlexibleInstances #-}

import Data.Monoid

data Value
    = E (Endo [Value])
    | I Int
    deriving Show

instance Show (Endo [Value]) where
   show (Endo f) = ... -- f :: a -> a

I would like to be able to display the content of my constructor E and I know that wanting to display a function doesn't make much sense, so how do I view the content of my list, if possible, how do I do this correctly?

A: You should just write a Show instance for Value. One such instance would look roughly like this (untested) :
instance Show Value where
    Show (I i) = "I " ++ show i
    show (E (Endo e)) = "E (Endo (" ++ show (e []) ++ "++))"


text:
Q: Regex matches repeated group in parent group I tried to match multiple group which under another group.
Input
182507 { 6661(T) }, 182514 { 5551(T), 5553(T), 5552(T) }

Output
Full match: 182507 { 6661(T) }
Group 1: 182507
Group 2: 6661(T)

Full match: 182514 { 5551(T), 5553(T), 5552(T) }
Group 1: 182514
Group 2: 5551(T)
Group 3: 5553(T)
Group 4: 5552(T)

I tried the pattern but not seems to work that I excepted
/([0-9]+)\s*\{\s*(\s*[0-9]+\s*\(\s*[A-Z]+\s*\))\s*?(?:,*\s*([0-9]+\s*\(\s*[A-Z]+\s*\))\s*)*+\s*\}+/

A: Your problem is that repeated capturing groups only capture the last match of that group, hence your regex does not capture 5553(T) in the second part of the string. It is probably simpler to do this using a two-step approach, first to match the digits followed by the part in {}, and then split that second part into its components:
$string = '182507 { 6661(T) }, 182514 { 5551(T), 5553(T), 5552(T) }';
preg_match_all('/(\d+)\s*{\s*([^}]+)\s*}/', $string, $matches);
$output = array();
foreach ($matches[1] as $key => $value) {
    $output[$key] = array_merge(array($value), preg_split('/\s*,\s*/', $matches[2][$key]));
}
print_r($output);

Output:
Array
(
    [0] => Array
        (
            [0] => 182507
            [1] => 6661(T)
        )
    [1] => Array
        (
            [0] => 182514
            [1] => 5551(T)
            [2] => 5553(T)
            [3] => 5552(T)
        )
)

Demo on 3v4l.org