text:
Q: How to do join of multiindex dataframe with another multiindex dataframe? This is to go further from the following thread:
How to do join of multiindex dataframe with a single index dataframe?
The multi-indices of df1 are sublevel indices of df2.
In [1]: import pandas as pd
In [2]: import numpy as np
In [3]: import itertools
In [4]: inner = ('a','b')
In [5]: outer = ((10,20), (1,2))
In [6]: cols = ('one','two','three','four')
In [7]: sngl = pd.DataFrame(np.random.randn(2,4), index=inner, columns=cols)
In [8]: index_tups = list(itertools.product(*(outer + (inner,))))
In [9]: index_mult = pd.MultiIndex.from_tuples(index_tups)
In [10]: mult = pd.DataFrame(index=index_mult, columns=cols)
In [11]: sngl
Out[11]:
        one       two     three      four
a  2.946876 -0.751171  2.306766  0.323146
b  0.192558  0.928031  1.230475 -0.256739

In [12]: mult
Out[12]:
        one  two three four
10 1 a  NaN  NaN   NaN  NaN
     b  NaN  NaN   NaN  NaN
   2 a  NaN  NaN   NaN  NaN
     b  NaN  NaN   NaN  NaN
20 1 a  NaN  NaN   NaN  NaN
     b  NaN  NaN   NaN  NaN
   2 a  NaN  NaN   NaN  NaN
     b  NaN  NaN   NaN  NaN

In [13]: mult.ix[(10,1)] = sngl

In [14]: mult
Out[14]:
        one  two three four
10 1 a  NaN  NaN   NaN  NaN
     b  NaN  NaN   NaN  NaN
   2 a  NaN  NaN   NaN  NaN
     b  NaN  NaN   NaN  NaN
20 1 a  NaN  NaN   NaN  NaN
     b  NaN  NaN   NaN  NaN
   2 a  NaN  NaN   NaN  NaN
     b  NaN  NaN   NaN  NaN

# the new dataframes
sng2=pd.concat([sng1,sng1],keys=['X','Y'])
mult2=pd.concat([mult,mult],keys=['X','Y'])

In [110]:

sng2
Out[110]:
             one     two           three    four
X   a   0.206810    -1.056264   -0.572809   -0.314475
    b   0.514873    -0.941380   0.132694    -0.682903
Y   a   0.206810    -1.056264   -0.572809   -0.314475
    b   0.514873    -0.941380   0.132694    -0.682903

In [121]: mult2
Out[121]:
               one  two three   four
X   10  1   a   NaN NaN NaN NaN
            b   NaN NaN NaN NaN
        2   a   NaN NaN NaN NaN
            b   NaN NaN NaN NaN
    20  1   a   NaN NaN NaN NaN
            b   NaN NaN NaN NaN
        2   a   NaN NaN NaN NaN
            b   NaN NaN NaN NaN
Y   10  1   a   NaN NaN NaN NaN
            b   NaN NaN NaN NaN
        2   a   NaN NaN NaN NaN
            b   NaN NaN NaN NaN
    20  1   a   NaN NaN NaN NaN
            b   NaN NaN NaN NaN
        2   a   NaN NaN NaN NaN
            b   NaN NaN NaN NaN

the code above is long, please scroll
The two multilevel indices of sng2 share the 1st and 4th indices of mul2. ('X','a') for example.
@DSM proposed a solution to work with a multiindex df2 and single index df1
mult[:] = sngl.loc[mult.index.get_level_values(2)].values

BUt DataFrame.index.get_level_values(2) can only work for one level of index.

A: It's not clear from the question which index levels the data frames share. I think you need to revise the set-up code as it gives an error at the definition of sngl. Anyway, suppose mult shares the first and second level with sngl you can just drop the second level from the index of mult and index in:
mult[:] = sngl.loc[mult.index.droplevel(2)].values

On a side note, you can construct a multi index from a product directly using pd.MultiIndex.from_product rather than using itertools


text:
Q: I have a old battery charge, which says its output is 6 - 12 Volt 4 Amps R.M.S. Does this mean the output is AC? The battery charger is an HC45 which I could not find any information online about. As stated in the question does the 4 Amps R.M.S mean the output is AC or is the peak of the input equal to 4 Amps?

A: Those older chargers are very simple — just a transformer and a rectifier, no filter. The output is pulsating rather than what we would consider "pure DC". Therefore, it makes a certain amount of sense to rate the output current in terms of its RMS value rather than its peak or average value — mainly because that's how the internal transformer is rated.
While the voltage pulses are half-sinewaves, the actual current pulses are narrower spikes whose actual shape depends on the state of charge (i.e., terminal voltage) of the battery. It is the RMS value of the current that determines how much stress is being put on the transformer and rectifier.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Address text element on .qml I would like to change a text in my gui. I can address the ListView element for which I have found a solution.
I would also like to address the text element arbitrarily and, for example, replace the text.
Also, I can't manage to address another ListView element with different content.
Here is my little program. Please excuse my English too
main.py
import sys
import vensoft_main
from time import sleep
import urllib.request
from pathlib import Path
from PySide6 import QtCore, QtWidgets, QtGui
from PySide6.QtQuick import QQuickView
from PySide6.QtCore import QStringListModel, QUrl
from PySide6.QtGui import QGuiApplication
from PySide6.QtWidgets import QApplication
import json
import sys
from typing import Text
import urllib.request
import json
import pandas as pd
import random

if __name__ == '__main__':
    # get our data
    url = "file:///Users/joerg/Documents/python/Rohertrag/rohertrag_fenster/output_heute.json"
    response = urllib.request.urlopen(url)
    data = json.loads(response.read().decode('utf-8'))

    # Format and sort the data
    data_list = list(data.values())

    # Set up the application window
    app = QGuiApplication(sys.argv)
    view = QQuickView()
    view.setResizeMode(QQuickView.SizeRootObjectToView)
    view.update()

    # Expose the list to the Qml code
    my_model = QStringListModel()
    my_model.setStringList(data_list)
    view.setInitialProperties({"myModel": my_model})

    # Load the QML file
    qml_file = Path(__file__).parent / "view.qml"
    view.setSource(QUrl.fromLocalFile(qml_file.resolve()))

    # Show the window
    if view.status() == QQuickView.Error:
        sys.exit(-1)
    view.show()
    view.update()

    # execute and cleanup
    app.exec()
    del view

new.qml
import QtQuick
import QtQuick.Controls
Page {
    width: 640
    height: 480

    Rectangle {
        id: root

        anchors.fill: parent

        ListView {
            id: view_1

            anchors.fill: parent
            anchors.margins: 25
            anchors.bottomMargin: 230
            anchors.rightMargin: 375
            model: manager.model

            delegate: Text {
                anchors.leftMargin: 50
                font.pointSize: 15
                horizontalAlignment: Text.AlignHCenter
                text: display
            }

        }

        Text {
            id: text1

            x: 486
            y: 46
            width: 127
            height: 118
            text: manager.text
            font.pixelSize: 12
        }

        ListView {
            id: view_2
            anchors.fill: parent
            anchors.margins: 25
            anchors.leftMargin: 25
            anchors.topMargin: 238
            anchors.rightMargin: 375
            delegate: Text {
                text: display
                horizontalAlignment: Text.AlignHCenter
                anchors.leftMargin: 50
                font.pointSize: 15
            }
            anchors.bottomMargin: 17
            model: manager.model
        }

        Text {
            id: text2
            x: 479
            y: 272
            width: 127
            height: 118
            text: manager.text
            font.pixelSize: 12
        }

    }

    header: Label {
        color: "#15af15"
        text: qsTr("Wie ist den der Umsatz Heute?")
        font.pointSize: 17
        font.bold: true
        font.family: "Arial"
        renderType: Text.NativeRendering
        horizontalAlignment: Text.AlignHCenter
        padding: 10
    }

}

A: Less is more, you don't need to place unnecessary imports, also you don't need data from external resources, a simple list is enough.
If you want to manipulate the QML view from python then it is better to create a QObject that has data as properties and export it to QML.
import sys
from pathlib import Path

from PySide6.QtCore import (
    Property,
    QDateTime,
    QObject,
    QStringListModel,
    QTimer,
    QUrl,
    Signal,
)
from PySide6.QtQuick import QQuickView
from PySide6.QtGui import QGuiApplication

class Manager(QObject):
    text_changed = Signal(name="textChanged")

    def __init__(self, parent=None):
        super().__init__(parent)
        self._model = QStringListModel()
        self._text = ""

    @Property(QObject, constant=True)
    def model(self):
        return self._model

    @Property(str, notify=text_changed)
    def text(self):
        return self._text

    @text.setter
    def text(self, text):
        if self.text == text:
            return
        self._text = text
        self.text_changed.emit()

def main():
    # get our data
    data_list = ["foo", "bar", "baz"]

    manager = Manager()

    # Set up the application window
    app = QGuiApplication(sys.argv)
    view = QQuickView()
    view.rootContext().setContextProperty("manager", manager)
    view.setResizeMode(QQuickView.SizeRootObjectToView)

    manager.model.setStringList(data_list)
    manager.text = "text"

    qml_file = Path(__file__).parent / "view.qml"
    view.setSource(QUrl.fromLocalFile(qml_file.resolve()))

    if view.status() == QQuickView.Error:
        sys.exit(-1)

    view.show()

    def handle_timeout():
        text = QDateTime.currentDateTime().toString()
        manager.text = text

    timer = QTimer(interval=1000, timeout=handle_timeout)
    timer.start()

    app.exec()
    del view

if __name__ == "__main__":
    main()

import QtQuick
import QtQuick.Controls

Page {
    width: 640
    height: 480

    Rectangle {
        id: root

        anchors.fill: parent

        ListView {
            id: view_1

            anchors.fill: parent
            anchors.margins: 25
            anchors.rightMargin: 375
            model: manager.model

            delegate: Text {
                anchors.leftMargin: 50
                font.pointSize: 15
                horizontalAlignment: Text.AlignHCenter
                text: display
            }

        }

        Text {
            id: text1

            x: 486
            y: 46
            width: 127
            height: 201
            text: manager.text
            font.pixelSize: 12
        }

    }

    header: Label {
        color: "#15af15"
        text: qsTr("Wie ist den der Umsatz Heute?")
        font.pointSize: 17
        font.bold: true
        font.family: "Arial"
        renderType: Text.NativeRendering
        horizontalAlignment: Text.AlignHCenter
        padding: 10
    }

}


text:
Q: numpy: efficient execution of a complex reshape of an array I am reading a vendor-provided large binary array into a 2D numpy array tempfid(M, N)
# load data
data=numpy.fromfile(file=dirname+'/fid', dtype=numpy.dtype('i4'))

# convert to complex data
fid=data[::2]+1j*data[1::2]

tempfid=fid.reshape(I*J*K, N)

and then I need to reshape it into a 4D array useful4d(N,I,J,K) using non-trivial mappings for the indices. I do this with a for loop along the following lines:
for idx in range(M):
    i=f1(idx) # f1, f2, and f3 are functions involving / and % as well as some lookups
    j=f2(idx)
    k=f3(idx)
    newfid[:,i,j,k] = tempfid[idx,:] #SLOW! CAN WE IMPROVE THIS?

Converting to complex takes 33% of the time while the copying of these slices M slices takes the remaining 66%. Calculating the indices is fast irrespective of whether I do this one by one in a loop as shown or by numpy.vectorizing the operation and applying it to an arange(M).
Is there a way to speed this up? Any help on more efficient slicing, copying (or not) etc appreciated.
EDIT:
As learned in the answer to question "What's the fastest way to convert an interleaved NumPy integer array to complex64?" the conversion to complex can be sped up by a factor of 6 if a view is used instead:
 fid = data.astype(numpy.float32).view(numpy.complex64)

A: How about this. Set us your indicies using the vectorized versions of f1,f2,f3 (not necessarily using np.vectorize, but perhaps just writing a function that takes an array and returns an array), then use np.ix_:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.ix_.html
to get the index arrays. Then reshape tempfid to the same shape as newfid and then use the results of np.ix_ to set the values. For example:
tempfid = np.arange(10)
i = f1(idx) # i = [4,3,2,1,0]
j = f2(idx) # j = [1,0]
ii = np.ix_(i,j)
newfid = tempfid.reshape((5,2))[ii]

This maps the elements of tempfid onto a new shape with a different ordering.

A: idx = numpy.arange(M)
i = numpy.vectorize(f1)(idx)
j = numpy.vectorize(f2)(idx)
k = numpy.vectorize(f3)(idx)

# you can index arrays with other arrays
# that lets you specify this operation in one line.
newfid[:, i,j,k] = tempfid.T

I've never used numpy's vectorize. Vectorize just means that numpy will call your python function multiple times. In order to get speed, you need use array operations like the one I showed here and you used to get complex numbers.
EDIT
The problem is that the dimension of size 128 was first in newfid, but last in tempfid. This is easily by using .T which takes the transpose.


text:
Q: How do i use coordinators with a UIITabBarController? I'm playing around with the MVVM-C architecture, but i'm unsure how i can instantiate multiple coordinators with different tabs when a tab is selected.
Here's my main app coordinator class...
protocol UINavigationControllerType: class {
func pushViewController(_ viewController: UIViewController, animated: Bool)
func popViewController(animated: Bool) -> UIViewController?
}

protocol Coordinator: class {
func start()
}

final class AppCoordinator: Coordinator {
// MARK: - Properties
var managedObjectContext: NSManagedObjectContext!
var coordinators = [String : Coordinator]()

var tabController: UITabBarController?

// MARK: - Object Lifecycle
init(moc: NSManagedObjectContext, tabController: UITabBarController) {
    self.managedObjectContext = moc
    self.tabController = tabController
}

// MARK: - Coordinator
func start() {
    guard let tabController = tabController else {return}

    let profileNavigationController = NavigationController()
    profileNavigationController.tabBarItem = UITabBarItem(title: "Profile", image: UIImage(named: "profileUnselected"), selectedImage: UIImage(named: "profileSelected"))

    let plansNavigationController = NavigationController()
    plansNavigationController.tabBarItem = UITabBarItem(title: "Plans", image: UIImage(named: "plansUnselected"), selectedImage: UIImage(named: "plansSelected"))

    tabController.viewControllers = [profileNavigationController, plansNavigationController]
    tabController.selectedViewController = profileNavigationController

    let profileCoordinator = ProfileCoordinator(navigationController: profileNavigationController)
    profileCoordinator.managedObjectContext = managedObjectContext
    coordinators["profileCoordinator"] = profileCoordinator
    profileCoordinator.delegate = self
    profileCoordinator.start()
}
}

// MARK: - ProfileCoordinatorDelegate
extension AppCoordinator: ProfileCoordinatorDelegate {}

So how would i go from the current coordinator (ProfileCoordinator) to the PlansCoordinator when the tab is selected?

A: I want to share an example for this question. My approach a little bit different and TabCoordinator not contains everything in his body. Instead of this, every coordinator has relation with its controller and in every UIViewController (in tabbar controller) has its UITabBarController reference like delegation pattern.
class Coordinator {

    var navigationController: UINavigationController?
    var childCoordinators: [Coordinator] = [Coordinator]()

    init(with navigation: UINavigationController) {
        self.navigationController = navigation
    }

    func start() {}

}

Then here is the coordinators.

Home Coordinator

final class HomeCoordinator: Coordinator {

    var currentController: HomeController?
    weak var tabController: TabController?

    override init(with navigation: UINavigationController) {
        super.init(with: navigation)

        currentController = HomeController()
        currentController?.coordinator = self
        childCoordinators.append(self)
    }

    override func start() {

        navigationController?.pushViewController(currentController ?? UIViewController(),
                                                 animated: true)

    }

    public func getHomeData() {

        // GETTING HOME DATA

        tabController?.requestFromHomeController()

    }

}

About Coordinator

final class AboutCoordinator: Coordinator {

    var currentController: AboutController?
    weak var tabController: TabController?

    override init(with navigation: UINavigationController) {
        super.init(with: navigation)

        currentController = AboutController()
        currentController?.coordinator = self
        childCoordinators.append(self)
    }

    override func start() {

        navigationController?.pushViewController(currentController ?? UIViewController(),
                                                 animated: true)

    }

    public func getAboutData() {

        // GETTING ABOUT DATA

        tabController?.requestFromAboutController()

    }
}

UITabBarController

final class TabController: UITabBarController {

    weak var coordinator: MainTabCoordinator?

    override func viewDidLoad() {
        super.viewDidLoad()

        let navigationController1 = UINavigationController()
        let coordinator1 = HomeCoordinator(with: navigationController1)
        coordinator1.tabController = self
        coordinator1.currentController?.tabBarItem = UITabBarItem(title: "HOME",
                                                                  image: nil,
                                                                  tag: 11)

        let navigationController2 = UINavigationController()
        let coordinator2 = AboutCoordinator(with: navigationController2)
        coordinator2.tabController = self
        coordinator2.currentController?.tabBarItem = UITabBarItem(title: "ABOUT",
                                                                  image: nil,
                                                                  tag: 22)

        viewControllers = [
            coordinator1.currentController!,
            coordinator2.currentController!
        ]

        tabBar.barTintColor = UIColor.white
        tabBar.isTranslucent = false

    }

    public func requestFromHomeController() {
        print("Home Triggered the function")

        coordinator?.fetchHome(with: "Simple Data",
                               completion: { (dictionary, error) in
                                print("dict from home -> ", dictionary)
        })

    }

    public func requestFromAboutController() {
        print("About Triggered the function")

        coordinator?.handleAbout(with: "Simple Data",
                                 completion: { (dictionary, error) in
                                    print("dict from about -> ", dictionary)
        })
    }
}

Prepare the app from AppDelegate
in application(_ application: UIApplication, didFinishLaunchingWithOptions function

let appNavigationController = UINavigationController()
let tabCoordinator = MainTabCoordinator(with: appNavigationController ?? UINavigationController())
tabCoordinator.start()
window?.rootViewController = appNavigationController

Here is the AboutController

final class AboutController: UIViewController{

    weak var coordinator: AboutCoordinator?

    // define a button and add its target to handleButton function

    @objc private func handleButton(_ sender: UIButton) {

        coordinator?.getAboutData()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // ui settings
    }
}

MainTabCoordinator

final class MainTabCoordinator: Coordinator {

    var currentController: TabController?

    override init(with navigation: UINavigationController) {
        super.init(with: navigation)

        self.currentController = TabController()
        self.childCoordinators.append(self)
        currentController?.coordinator = self
    }

    override func start() {

        navigationController?.pushViewController(currentController ?? UIViewController(),
                                                 animated: true)

    }

    func fetchHome(with title: String, completion:  @escaping (_ result: Dictionary<String,Any>, _ error: NSError?) -> ()) {

        completion(["ss":"ss"], nil)

    }

    func handleAbout(with title: String, completion: @escaping (_ result: Dictionary<String,Any>, _ error: NSError?) -> ()) {

        completion(["ss":"ss"], nil)
    }

}

The working schema is like that below:
AboutController ---> triggered action ---> AboutCoordinator ---> TabBarController reference has request to about action ----> MainTabCoordinator handle works.

A: My Coordinator structure is a different than yours, but it might help you. In my case, the Coordinator protocol has a rootViewController property which points to that Coordinator's ViewController.
My AppCoordinator then persists a TabCoordinator, which looks somewhat like this: (In the real code, the persisted coordinators are NavigationCoordinators, which are special Coordinators that hold NavigationControllers. In this example I just added the ViewControllers and removed memory management stuff to make it easier to understand.)
final class TabCoordinator: NSObject, Coordinator {

var rootViewController: UIViewController {
    return tabController
}

let tabController: UITabBarController

let homeCoordinator: HomeCoordinator
let historyCoordinator: HistoryCoordinator
let profileCoordinator: ProfileCoordinator

var coordinators: [Coordinator] {
    return [homeCoordinator, historyCoordinator, profileCoordinator]
}

init(client: HTTPClient, persistence: Persistence) {

    tabController = UITabBarController()

    homeCoordinator = HomeCoordinator(client: client, persistence: persistence)

    historyCoordinator = HistoryCoordinator(client: client, persistence: persistence)

    profileCoordinator = ProfileCoordinator(client: client, persistence: persistence)

    var controllers: [UIViewController] = []

    let homeViewController = homeCoordinator.rootViewController
    homeViewController.tabBarItem = UITabBarItem(title: Localization.homeTab.string, image: Asset.iconMenuRecharge.image, selectedImage: Asset.iconMenuRechargeActivated.image)

    let historyViewController = historyCoordinator.rootViewController
    historyViewController.tabBarItem = UITabBarItem(title: Localization.walletTab.string, image: Asset.iconMenuWallet.image, selectedImage: Asset.iconMenuWalletActivated.image)

    let profileViewController = profileCoordinator.rootViewController
    profileViewController.tabBarItem = UITabBarItem(title: Localization.profileTab.string, image: Asset.iconMenuProfile.image, selectedImage: Asset.iconMenuProfileActivated.image)

    super.init()

    controllers.append(homeViewController)
    controllers.append(historyViewController)
    controllers.append(profileViewController)

    tabController.viewControllers = controllers
    tabController.tabBar.isTranslucent = false
    tabController.delegate = self

}
}

So basically, your TabBarController is a TabCoordinator whose's rootViewController is a TabBarController. The TabCoordinator instantiates the relevant Coordinators and add their respective rootViewControllers to the tab.
Here's a basic implementation of the NavigationCoordinator:
class NavigationCoordinator: NSObject, Coordinator {

    public var navigationController: UINavigationController

    public override init() {
        self.navigationController = UINavigationController()
        self.navigationController.view.backgroundColor = .white
        super.init()
    }

    public var rootViewController: UIViewController {
        return navigationController
    }
}

And a basic version of a Coordinator:
public protocol Coordinator: class {
    var rootViewController: UIViewController { get }
}


text:
Q: What is the easiest way to restore D365's code base to original? How do you restore the code base to fresh installation? I am having some build/sync issues and I would like to undo all my code changes and start over.

A: Since you are asking for the easiest way: Deploy a new environment :)
Jokes aside, what I would do is to clean up the AOSService\PackagesLocalDirectory directory and delete the folders that contain your customizations. Alternatively you can copy the contents of the directory from a clean environment of the same version, in case you don't know the names of your customization packages anymore.
From Pradeep's comment: Then Open visual studio, Go to Model Management and Refresh model. Then do a full build and synchronize database.
This should restore your environment back to a clean installation.


text:
Q: Export javascript object to use it in another program I'm trying to build an offline navigation.
I have two versions of my program: online and offline.

*

*I create an object based on a google maps request

*I want to "store" this object somehow

*I want to access this object in the offline version of the program.
If I do console.log(object) google chrome gives me the object, but I cant just copy it and paste in the offline version.
Any ideas how to "export" the object?

A: *

*Stringify your object -> JSON.stringify( yourObject );

*Save your file as JSON ( you can use library like : https://github.com/eligrey/FileSaver.js/ )

*Upload this JSON to your offline app

*Parse it -> JSON.parse( youJsonFile.json )

A: I guest you use HTML5 for you task? In the case answer is yes, is ease save local data for your use in offline mode. You can read this tutorial for localStorage object Local Storage in HTML5
Now, the next code help you to save online data in local storage, and access this in offline:
function init() {
   var googleMapObject = null;

   // This is first status verification
   if (navigator.onLine) {
      googleMapObject = anyMethodToGetData();

      // Save remote object in local storage
      localStorage['googleMapsObject'] = JSON.stringify(googleMapObject);
   } else {
      // In offline mode, return local storage data
      if (localStorage['googleMapsObject']) {
         googleMapObject = JSON.parse(localStorage['googleMapsObject']);
      }
   }

   return googleMapsObject;
}

The init method is call in load/ready event. If you need detect change in online/offline state, use online/offline events.
Regards!!


text:
Q: Sorting months with pre-defined order? I want to sort the months of the year starting at any month, but January needs to show up after December if January isn't the starting point. Can I do that in an array or do I need a special data structure or algorithm to do that?

A: you can easily do this with just an array. [Dec,Jan,Feb,...Oct,Nov] then you can iterate through with month mod 12 and it will produce a sorted list that can wrap around from Dec to Jan. You can simply stop iterating at January if you only want that month to wrap.

A: Check this Java-ish code:
public void sortMonths(int START) {
    // Jan = 0, ... , Dez = 11
    int[] myArray = new int[12];
    for (int i = START; i < 12; ++i) {
        myArray[i - START] = i;
    }

    for (int i = 0; i < START; ++i) {
        myArray[i] = i;
    }
}

A: Many sorters let you provide your own comparator which dictates the sort order.  Write one that implements your rules and and supply it to the sort function.


text:
Q: Trouble with basic mySql procedure mysql> show tables;
+---------------------+
| Tables_in_cpsc408db |
+---------------------+
| Product             |
| laptop              |
| pc                  |
| printer             |
+---------------------+
4 rows in set (0.00 sec)

mysql> create procedure hello()
    -> begin
    -> select * from product;
ERROR 1064 (42000): 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 '' at line 3
mysql>

I am not sure what is causing this syntax error, and haven't had any success so far figuring it out. Any help would be much appreciated.

A: You need to use the DELIMITER keyword:
This is so MySQL can tell which statements are within the procedure and where the end of the procedure declaration itself is
delimiter //

CREATE PROCEDURE hello()
BEGIN
    select * from product;
END//

delimiter ;

A: You need a delimiter otherwise the console does not know when you are finished:
 DELIMITER //
 CREATE PROCEDURE hello()
   BEGIN
   SELECT *  FROM product;
   END //
 DELIMITER ;

Read more about it here: Getting Started with MySQL Stored Procedures


text:
Q: java.net.UnknownHostException: stream.twitter.com occurring while trying to ingest twitter data onto hdfs I am using hortonworks sandbox HDP2.0 .Trying to ingest twitter data onto hdfs.
But getting the following error:
 TwitterException{exceptionCode=[d0031b0b-1db75522 db667dea-99334ae4], statusCode=-1, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=3.0.3}
    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:192)
    at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:61)
    at twitter4j.internal.http.HttpClientWrapper.get(HttpClientWrapper.java:89)
    at twitter4j.TwitterStreamImpl.getSampleStream(TwitterStreamImpl.java:176)
    at twitter4j.TwitterStreamImpl$4.getStream(TwitterStreamImpl.java:164)
    at twitter4j.TwitterStreamImpl$TwitterStreamConsumer.run(TwitterStreamImpl.java:462)
Caused by: java.net.UnknownHostException: stream.twitter.com
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:579)
    at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:637)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:432)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:527)
    at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:264)
    at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:367)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:191)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:933)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1301)
    at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338)
    at twitter4j.internal.http.HttpResponseImpl.<init>(HttpResponseImpl.java:34)
    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:156)


text:
Q: unable to start many Python programs in Ubuntu 11.4 I have recently begun using Ubuntu.  I am a reasonably experienced programmer, and have been using the "old" Python for years.  But, in Python 3.2, when I try to run one of several different programs which I installed from .eg, I get an error message similar to the one pasted below.
Here, I am trying to start IPython.  But the error is happening for others as well.
Traceback (most recent call last):

File "./ipython3", line 9, in <module>

load_entry_point('ipython==0.12', 'console_scripts', 'ipython3')()

File "/usr/local/lib/python3.2/dist-packages/distribute-0.6.24-py3.2.egg/pkg_resources.py", line 337, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)

File "/usr/local/lib/python3.2/dist-packages/distribute-0.6.24-y3.2.egg/pkg_resources.py", line 2279, in load_entry_point
raise ImportError("Entry point %r not found" % ((group,name),))

ImportError: Entry point ('console_scripts', 'ipython3') not found

I have googled this error, and found that other users have been having similar problems, but as far as I can see, nobody has reported a real solution.

A: My guess is that you have mixed distro installs with easy_installs.
Probably the best way to experiment and work with Python is to use a separated "sandbox". With virtualenv (it is one of the several ways) it can be done as follows:
$ virtualenv -p /usr/bin/python3.2 --distribute MYPYTHON32
Running virtualenv with interpreter /usr/bin/python3.2
New python executable in MYPYTHON32/bin/python3.2
Also creating executable in MYPYTHON32/bin/python
Installing distribute...

Then you can install whatever you want to play with:
$ cd MYPYTHON32
$ bin/easy_install ipython

I have no problem:
$ bin/ipython3
Python 3.2 (r32:88445, Dec  8 2011, 15:26:58)
Type "copyright", "credits" or "license" for more information.

IPython 0.12 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]:

Documentation on virtualenv will give you more hints. This way possible install will not interfere with system pythons and you always has control on what you install in the sandbox.


text:
Q: How to use GPU in Paperspace when running Transformers Pipeline? We are trying to run HuggingFace Transformers Pipeline model in Paperspace (using its GPU).
The problem is that when we set 'device=0' we get this error:
RuntimeError: CUDA out of memory. Tried to allocate 16.00 MiB (GPU 0; 15.90 GiB total capacity; 476.40 MiB already allocated; 7.44 MiB free; 492.00 MiB reserved in total by PyTorch) If reserved memory is >> allocated memory try setting max_split_size_mb to avoid fragmentation.  See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF

And if we don't set 'device=0' then GPU doesn't work (which is OK because default option is not to use it).
How to make GPU work for these models in Paperspace?
The code is pretty simple so far:
from transformers import pipeline
classifier = pipeline("zero-shot-classification",
                      model="Sahajtomar/German_Zeroshot"
                     #,device = 0
                     )

On Google Colab with the same model and same code we didn't have this problem. We just set 'device=0' and we got GPU running perfectly.


text:
Q: MySQL inner join not returning results I am trying to inner join two tables to add a column to one of the tables.
Here are how the tables look
Table1
Name               year
Dickerson, Molan   2015

Table 2
Person_ID Last_Name   First_Name
23        Dickerson   Molan

But, when I inner join via:
SELECT *
FROM table1
INNER JOIN table2
ON table1.name like CONCAT('%', table2.Last_Name, '%')
AND table1.name like CONCAT('%', table2.First_Name, '%')

I get empty results. Why? The goal is add the ID column to table1

A: Try this:
    SELECT *
    FROM table1 t1
    INNER JOIN table2 t2
    ON (t1.name like CONCAT('%', trim(t2.Last_Name), '%')
    AND t1.name like CONCAT('%', trim(t2.First_Name), '%') )

A: try this:
SELECT *
FROM table1
INNER JOIN table2
ON table1.name like CONCAT('%', table2.Last_Name)
AND table1.name like CONCAT(table2.First_Name, '%')


text:
Q: How can ios detect gps tampering on xcode How can ios detect gps tampering on xcode, it comes with "simulate location" on xcode, is there a way to detect gps tampering caused by it?

A: The debug output area of xcode has a button called "simulate location" which allows you to simulate the location of different countries, and when you use CLLocation to get the location it will output the location of the country selected by the simulator.
CLLocationManager *manager = [[CLLocationManager alloc] init];
[CLLocationManager authorizationStatus];
manager.delegate = self;
manager.desiredAccuracy = kCLLocationAccuracyBest;
[manager requestAlwaysAuthorization];
[manager startUpdatingLocation];

if( [CLLocationManager locationServicesEnabled] ) {
    CLLocation *location = [manager location];  //maybe other country
    NSLog(@"%@", location);
}


text:
Q: Can GNU make execute a rule whenever an error occurs? This is slightly different from Can a Makefile execute code ONLY when an error has occurred?.
I'd like a rule or special target that is made whenever an error occurs (independent of the given target; without changing the rule for every target as the other answer seems to imply with the || operator).
In dmake there is special target .ERROR that is executed whenever an error condition is detected. Is there a similar thing with GNU make?
(I'm still using GNU make 3.81, but I didn't find anything in the documentation of the new GNU make 4.0 either)

A: Gnu doesn't support it explicitly, but there's ways to hack almost anything.  Make returns 1 if any of the makes fail.  This means that you could, on the command line, rerun make with your error rule if the first make failed:
make || make error_targ

Of course, I'll assume you just want to put the added complexity within the makefile itself.  If this is the case, you can create a recursive make file:
all:
     $(MAKE) normal_targ || $(MAKE) error_targ

normal_targ:
      ... normal make rules ...

error_targ:
      ... other make rules ...

This will cause the makefile to try to build normal_targ, and iff it fails, it will run error_targ.  It makes it a bit harder to read the makefile for the inexperienced, but it puts all the logic in one place.


text:
Q: Incorrect system time, Windows 8 My computer's time keeps getting set incorrectly.  My time zone is set correctly, and if I "Update now" to synchronize with an internet time server (time-a.nist.gov), the time gets set correctly.  It seems that some other program runs that sets the time incorrectly.
The changes don't always follow the same pattern, but the when the time is set incorrectly, it is always one hour earlier than the correct time:

*

*I've created a batch file to check the time every 10 seconds; it detects a change precisely every hour.  I immediately reset to the correct time; an hour later, it changes again.  This will continue for hours (until I hibernate or shut down, I think; after starting up again, it sometimes does, and sometime does not, follow this pattern).

*Sometimes the time is correct when I hibernate the system, then is incorrect when I awaken it.
I dual boot Linux, but I haven't run Linux in weeks.  Also, my time zone is UTC-8; if this were the dual-boot problem, I would expect the incorrect time to be wrong by eight hours, not by one hour.
Any ideas?  Is there a way to detect when a system call changes the clock?  Once the one-hour pattern starts, it is predictable when the next change will happen, so I could  monitor at that time, if I knew what to monitor.
To clarify: while Windows is running, the system time gets changed to the wrong time.  It has nothing to do with Linux, BIOS, or CMOS.

A: Check weather your CMOS battery is working or not.If it has expired, then the computer won't be able to keep correct time after reboot/shutdown.

A: And you are setting them in here?

Settings Gear > Change PC Settings > Time and Language
Also..do you know if this only started happening when you had Linux installed for dual booting? ...or always a problem even when it was only Windows installed?

A: I finally figured out, more or less, what was happening, but I'm confused about why.  Windows would, from time to time, set the time based on the hardware clock.  That makes no sense to me -- the clock was getting set from a time server out on the internet; I don't understand why Windows would also to another source as well.  The issue was further confused by daylight savings time -- the hardware clock doesn't adjust for that.
If this explanation doesn't quite make sense, I won't be surprised.  In any case, the problem hasn't happened since I set the clock from the UEFI startup program.  I'll see what happens when the clock switches back to standard time.


text:
Q: Freetds with mssql domain authentication error - login packet rejected I am using Freetds with unixODBC to connect to a remote SQL server instance from linux. The linux server has AD integration and I used my domain login to ssh into the server.
However the TDS (version 7.1) doesnt connect and fails with the error message
locale is "en_US.UTF-8"
locale charset is "UTF-8"
using default charset "UTF-8"
Error 20002 (severity 9):
        Adaptive Server connection failed
There was a problem connecting to the server

Setting the TDS Dump variable, I ran the command
tsql -H server.domain.local -p 52890

The non standard port is used since I am connecting to a named instance running on port other than 1433
Below is the debug log
net.c:1370:handshake succeeded!!
gssapi.c:215:kerberos name MSSQLSvc/<server Name>
login.c:466:login packet rejected
util.c:156:Changed query state from IDLE to DEAD
util.c:331:tdserror(0x2139160, 0x2139400, 20002, 0)
util.c:361:tdserror: client library returned TDS_INT_CANCEL(2)
util.c:384:tdserror: returning TDS_INT_CANCEL(2)

I am able to connect to another server which has a SQL Server authentication enabled so its not a problem with the ODBC connection itself. This particular server only has domain authentication enabled so I am not able to check if SQL server auth is working.
****EDIT********
Added the Kerberos trace using the KRB5_TRACE variable. Sorry for the long logfile
[21067] 1382697575.336792: ccselect module realm chose cache FILE:/tmp/krb5cc_1411389785 with client principal username@domain for server principal MSSQLSvc/servername.domain:52820@domain
[21067] 1382697575.337100: Retrieving username@domain -> krb5_ccache_conf_data/proxy_impersonator@X-CACHECONF: from FILE:/tmp/krb5cc_1411389785 with result: -1765328243/Matching credential not found
[21067] 1382697575.337153: Getting credentials username@domain -> MSSQLSvc/servername.domain:52820@domain using ccache FILE:/tmp/krb5cc_1411389785
[21067] 1382697575.337267: Retrieving username@domain -> MSSQLSvc/servername.domain:52820@domain from FILE:/tmp/krb5cc_1411389785 with result: -1765328243/Matching credential not found
[21067] 1382697575.337379: Retrieving username@domain -> krbtgt/domain@domain from FILE:/tmp/krb5cc_1411389785 with result: 0/Success
[21067] 1382697575.337394: Found cached TGT for service realm: username@domain -> krbtgt/domain@domain
[21067] 1382697575.337406: Requesting tickets for MSSQLSvc/servername.domain:52820@domain, referrals on
[21067] 1382697575.337472: Generated subkey for TGS request: rc4-hmac/2124
[21067] 1382697575.337488: etypes requested in TGS request: rc4-hmac
[21067] 1382697575.337844: Sending request (1455 bytes) to domain
[21067] 1382697575.341048: Resolving hostname onau-dc01.domain.
[21067] 1382697575.351850: Sending initial UDP request to dgram <dns_server_ip>:port
[21067] 1382697575.352702: Received answer from dgram <dns_server_ip>:port
[21067] 1382697575.353576: Response was not from master KDC
[21067] 1382697575.353616: TGS request result: -1765328377/Server not found in Kerberos database
[21067] 1382697575.353629: Requesting tickets for MSSQLSvc/servername.domain:52820@domain, referrals off
[21067] 1382697575.353667: Generated subkey for TGS request: rc4-hmac/3F66
[21067] 1382697575.353687: etypes requested in TGS request: rc4-hmac
[21067] 1382697575.353804: Sending request (1455 bytes) to domain
[21067] 1382697575.355027: Resolving hostname server.domain.
[21067] 1382697575.355854: Sending initial UDP request to dgram <dns_server_ip2>:88
[21067] 1382697575.358398: Received answer from dgram <dns_server_ip2>:88
[21067] 1382697575.359061: Response was not from master KDC
[21067] 1382697575.359094: TGS request result: -1765328377/Server not found in Kerberos database
Error 20002 (severity 9):
        Adaptive Server connection failed

A: Since you are using named instance, chances are that it wants to accept only tickets issued for the port-specific SPN (MSSQLSvc/<server name>:52890), so your client software should obtain a ticket to this principal. Also, this port-specific SPN should exist for the account under which your MSSQL server is running.
Looking at FreeTDS implementation, I can see that it automaticaly tries to select port-specific SPN if no 'server_spn' is set in the config for the connection.
I would suggest you to remove explicit server_spn setting in your freetds.conf for this connection.


text:
Q: Tap event on textfield in Sencha Touch I can add tap event to textfield like this:
{
    xtype         : 'textfield',
    name          : 'GIVEN_NAME',
    label         : 'Given Name',
    disabled: false,
    listeners : {
        element : 'element',
        tap : function() {
            console.log('tap');
        }
    }
}

and it works. But this one, when used in controller, doesn't work:
control: {
    givenName: {
        element : 'element',
        tap: 'onGivenNameTap'
    }
}

Why? How can I make tap event work on textfield?

A: By default, controllers cannot listen element events: https://www.sencha.com/forum/showthread.php?251844s&p=922908&viewfull=1#post922908
But you can add your own custom event to TextField component: https://fiddle.sencha.com/#fiddle/rio
Ext.define('Fiddle.field.Text', {
    override: 'Ext.field.Text',

    initialize: function() {
        this.callParent();

        this.on('painted', function() {
            var cmp = this;

            cmp.element.on('tap', function() {
                cmp.fireEvent('elementtap', cmp, cmp.element);
            });
        });
    }
});

Ext.define('Fiddle.controller.Main', {
    extend: 'Ext.app.Controller',

    config: {
        refs: {
            givenName: 'textfield[name="givenName"]'
        },
        control: {
            givenName: {
                elementtap: 'onGivenNameTap'
            }
        }
    },

    onGivenNameTap: function() {
        Ext.Msg.alert('Tap!');
    }
});

Ext.application({
    name : 'Fiddle',
    controllers: ['Fiddle.controller.Main'],

    launch : function() {
        Ext.create('Ext.Panel', {
            fullscreen: true,
            items: [{
                xtype         : 'textfield',
                name          : 'givenName',
                label         : 'Given Name',
                disabled: false
            }]
        });
    }
});

A: Try this:
Sencha Fiddle
In your view:
Ext.define('MyApp.view.my_view', {
    extend: 'Ext.Panel',

    config: {
        layout: 'fit',
        items: [
            {
                xtype: 'textfield',
                itemId: 'my_text_field',
                label: 'My Label',
                listeners: [
                    {
                        element: 'element',
                        event: 'tap',
                        fn: function () {
                            this.fireEvent('tap', this);
                        }
                    }
                ]
            }
        ]
    }
});

In your controller:
  Ext.define('MyApp.controller.my_controller', {
        extend: 'Ext.app.Controller',

        requires: [
            'MyApp.view.my_view'
        ],

        config: {
            control: {
                'textfield[itemId=my_text_field]': {
                    tap: 'onMyTextFieldTap'
                }
            }
        },

        onMyTextFieldTap: function () {
            alert('tap');
        }
    });

You are manually firing the tap event from the view when the textfield is tapped, and the controller is listening for it and will execute onMyTextFieldTap when it happens.

A: Looks like you came with ExtJs background?
In Touch you have to do some other manner.
Ext.define('MyApp.Controller, {
    extend: 'Ext.app.Controller',
    config: {
        refs: {
             givenNameCt: 'textfield[name=GIVEN_NAME]'
        },
        control: {
            givenNameCt: {
                tap: 'onGivenNameTap'
            }
        }
    }
    ...
    onGivenNameTap: function(ct) {
        console.log('onGivenNameTap happens...', arguments);
    }
});


text:
Q: import comma delimited text file with key value pairs into R as a dataframe I was not able to find answers to this exact scenario.
I have a comma deliminated TXT file where the column names and values are separated by columns. I would like to import it into R as a dataframe. A simple read.table() does not work because of the key: value pair issue. would appreciate any insight you might have
TXT FILE
{"Hypertension":false,"lave_mains_avec4":false,"SignatureStatus":"Signature on file","sexe":1,"NomFamilleContact":"testnumbertwo","hematologique":false}

In this TXT file, the first column name is hypertension. The value for the column name hypertension is false. The next column name is lave_mains_avec4, the value for this column in false
Thanks so much

A: This format is known as JSON (short for JavaScript Object Notation). It is an extremely common and versatile format for exchanging data online. There are multiple R packages for parsing json files, including jsonlite:
library(jsonlite)

read_json("myfile.txt") |> as.data.frame()
#>   Hypertension lave_mains_avec4   SignatureStatus sexe NomFamilleContact hematologique
#> 1        FALSE            FALSE Signature on file    1     testnumbertwo         FALSE


text:
Q: Indexing strings and internationalization I have recently come up with an indexing algorithm for finding duplicate customer records. Short in short, this all works very well.
However, my issue is that I'd like to find "Diviér" should match "Divier", or "Aether" should match "Æther".
No problem, because removing diacritics is possible with libicu or boost::locale, and the problem uses wstring.
However, here is my problem: Normalizing/Latinizing a word changes it's meaning in a way that matching the may no longer make sense. I would like some input on whether this would be acceptable for names...
Also, what if someone has a Chinese name? This wouldn't be normalizable in this way, would it?
Do you have any recommendations on how to approach this?

A: You should look much more at the addresses and not to much into the names. In the end names can be very misleading. E.g. depending on the country the transcription of Chinese, Russion or Japanese characters may vary. Then sometimes names fields are to short to capture the full name of a person (especially common with Indish names) which leads to any kind of seemingly random abreviations. Sometimes people will ommit middle names, sometime they will not. And sometimes there are misspellings that give proper but different names.
So in my opinion the name should be the least important criterion in finding duplicates.


text:
Q: Codeigniter - Weird parameter 'favicon.ico' I am working with Codeigniter PHP framework.
I have the typicall Pages controller for displaying pages. I also added code for storing in the session variable in which page was the user before login. The thing is I'am getting as parameter 'favicon.ico' which make no sense because the page that was called was 'login' and displays well after that.
First as a temporary solution I checked the $page variable for the 'favicon.ico', and the weird thing was that after checking it I had inside the $page variable 'login'. It was very weird, I had to make a second check for login page as you see here for making it work. :
    public function view($page = 'index')
{
    if($page != 'favicon.ico'){
        if($page != "login"){
            $this->session->set_userdata('actual_page', $page);
        }
    }

    if ( ! file_exists('application/views/pages/'.$page.'.php'))
    {
        // Whoops, we don't have a page for that!
        $page="error";
    }
    // guardamos la página actual en la sesión

    $data['title'] = ucfirst($page); // Capitalize the first letter

    $this->load->view('templates/header', $data);
    $this->load->view('pages/'.$page, $data);
    $this->load->view('templates/footer', $data);

}

My question is, what is happening? Why if I only check for $page == 'login' it doesn't work. This is crazy.

A: Old question, but I think I have a better answer...

*

*Assuming your favicon.ico is in the root directory, make sure your CodeIgniter .htaccess file includes it in the RewriteCond so it isn't passed to the CodeIgniter index.php:
RewriteCond $1 !^(assets|images|robots.txt|favicon\ .ico)

*In your html files, include the full path to your favicon.ico, for example using CodeIgniter's base_url() function:
< link rel="shortcut icon" href="< ?php echo base_url('favicon.ico'); ?>" />
By including the full path to the icon, it won't get mysteriously passed to your controllers' _remap() function with "favicon.ico" in the $params array.

A: The browser sends a request to your web server
GET /favicon.ico HTTP/1.1

in order to retrieve Favicon. You can change the location of favicon with a link tag as described in the wikipedia article.
Try moving the file_exists check before you set the session data? The web application will need to be able to handle missing resources and return 404 accordingly.


text:
Q: PHP mail line breaks not always working I have a script that sends mail but sometimes the line breaks work and other times they do not. I have no idea what causes them to break and how to resolve.
This is an example of the type of code I have
$message .= "Name: ".$_POST['name'] . "\r\n";
$message .= "E-mail Address: ".$_POST['email'] . "\r\n";
$message .= "Telephone Number: ".$_POST['telephone'] . "\r\n";
$message .= "Subject: ".$_POST['subject'] . "\r\n";
$message .= "Message: ".$_POST['message']. "\r\n";
$message .= "=========================\r\n";

A: There is a huge issue with line endings specially when you pass it as a message and even more specially, when you pass it to mail() function.
So as I said in comment, better user normal library and I would personally recommend SwiftMailer. It is now under the wing of such developer as Fabien Potencier, who is main author behind Symfony2, etc.

A: Try to send mail using swiftmailer or PHPMailer. Here is a good tutorial to use PHPMailer
http://rohitashv.wordpress.com/2013/01/19/how-to-send-mail-using-php/


text:
Q: An integer between 1 and 1000 is chosen uniformly at random. Given that it is divisible by 4, what is the probability that it is divisible by 3? I've tried a couple different things for this problem. I know I am trying to find P[3|4].
First: P[3 and 4]/P[4] = (80/1000)/(250/1000)=.32. This wasn't right.
Second: (P[4|3]*P[3])/P[4] = ((80/1000)(333/1000))/(250/1000)=.10656 and this wasn't right.
Please let me know what I am doing wrong. Thanks.

A: Notice that if a number is divisible by $3$, and by $4$, then it is divisible by $3\times 4$. Then, out of all $250$ numbers that are divisible by $4$, how many are divisible by $12$?

A: 83 numbers are divisible by 4 and 3 both, $[1000/12] = 83$
You already have selected 250 numbers
so probability that number is also divisible by 3 is
$$\frac{83}{250}$$

A: Just a generalization: Let $A$ be the set of numbers divisible by $4$ and $B$ the set of numbers divisible by $3$. What you want is $P(B|A)$. By the definition of joint probability $P(B|A)=\frac{P(B \cap A)}{P(A)}$.
You know that $P(A \cap B)$ is the set of numbers that are divisible by both $3$ and $4$, hence this is the set divisible by multiples of $12$, $|A \cap B|=83$ and $|B|=250$, therefore $P(B|A)=\frac{83}{250}$


text:
Q: Is $f'(x)$ Riemann integrable if it is bounded The fact that $f(x)$ is differetiable dosen't guarantee the integrability of $f'(x)$ on $[a,b]$ beacuse $f'(x)$ could be unbounded, which violates the assumption of Riemann integral. However, what's the case if $f'(x)$ is bounded? Since $f'(x)$ doesn't have any discontinuity point of the first kind and $f'(x)$ is bounded, $f'(x)$ has only discontinuity points as $\sin \frac1x$ dose near $x=0$ if there are any.
Could $f'(x)$ has uncountably many discontinuity points of that kind? Otherwise, $f'(x)$ should be integrable on $[a,b]$. I think $f'(x)$ is integrable if it is bounded, could someone please give me a hand here? Or is there a counterexample?
Thanks in advance!

A: Yes, there are differentiable functions $f$ such that $f'$ is bounded but not Riemann-integrable. The standard example is Volterra's function.


text:
Q: mysql create partition with index range Let's say I have a table cars. and the table has a index column of 'brand' (int).
and currently i have 1-100 brand ids but let say brands are being added pretty often.
I want to create a partition by the brand indexed column, each partition will poses all the cars with a certain brand, and if I insert a new row to cars with a new brand_id it should also have a partition (didn't figure out completely how the partitions works ).
So how do i do it for this existing table.
And why every time I see a partition code in the net, it seems like you should define the ranges like hard coded.
Thanks

A: Not sure it can be done the way you want.
If you want even distribution of data, use HASH partitioning and set a count to have many partitions you want. That might be the better option as you could have a brand with only 1 car for instance? Or maybe not?
CREATE TABLE cars (
    id INT NOT NULL,
    brand_id INT
)
PARTITION BY HASH(brand_id)
PARTITIONS 10;

This will give 10 even sized partitions based on the brand_id
Im note sure how to and even if it is possible to have a new partition per id. When you create a partition by RANGE, you define the range per partition, something like this.
CREATE TABLE cars (
        id INT NOT NULL,
        brand_id INT

PARTITION BY RANGE (brand_id) (
    PARTITION p0 VALUES LESS THAN (10),
    PARTITION p1 VALUES LESS THAN (25),
    PARTITION p2 VALUES LESS THAN (50),
    PARTITION p3 VALUES LESS THAN (100),
    PARTITION p4 VALUES LESS THAN MAXVALUE
);

This will give 5 partitions with different sizes depending on the partiton range settings.
Reference:
https://dev.mysql.com/doc/refman/5.1/en/partitioning-range.html
https://dev.mysql.com/doc/refman/5.1/en/partitioning-hash.html


text:
Q: C#, why I can't add domain user into local group? Why this code doesn work ? What I want to do is add domain user into local group.
DirectorySearcher srch = new DirectorySearcher(new DirectoryEntry("LDAP://" + "AD1.test.it/DC=test,DC=it"));
srch.Filter = "(&(objectClass=user)(sAMAccountName=testUser))";
SearchResultCollection results = srch.FindAll();
DirectoryEntry de = new DirectoryEntry(results[0].Path);

DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
DirectoryEntry dComUsersGrp = localMachine.Children.Find("Distributed COM Users", "group");
dComUsersGrp.Invoke("Add", new object[] { de.Path.ToString() });

I get this error: "Exception has been thrown by the target of an invocation."
Simillar code works for adding local user into a local group.
DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
DirectoryEntry de = localMachine.Children.Find("testUser", "user");

DirectoryEntry dComUsersGrp = localMachine.Children.Find("Distributed COM Users", "group");
dComUsersGrp.Invoke("Add", new object[] { de.Path.ToString() });

Thank you very much for any help.

A: string userPath = string.Format("WinNT://{0}/{1},user", domain, user);
string groupPath = string.Format("WinNT://{0}/{1},group", Environment.MachineName, group);
using (DirectoryEntry group = new DirectoryEntry(groupPath))
{
    group.Invoke("Add", userPath);
    group.CommitChanges();
}

You need to use WinNT:// ADSI namespace.

A: You usually have to specify logon credentials to access the directory.  Something like:
String domainAndUsername = domain + @"\" + username;
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);


text:
Q: Create or cut 6 equal parts from a bitmap not working In my app I am having a method which cuts the 6 equal parts from a bitmap given to it. It works fine with the bitmap in square but does not work with rectangle bitmaps.
Here is the method.
public Bitmap[] splitBitmap6(Bitmap picture) {
    int w = picture.getWidth();
    int h = picture.getHeight();
    Bitmap scaledBitmap = null;

    int widthofmainBitMap  = screenWidth ;
    int heightofmainBitMap = widthofmainBitMap*h/w;

    scaledBitmap = Bitmap.createScaledBitmap(picture, widthofmainBitMap, heightofmainBitMap, true);

    Bitmap[] imgs = new Bitmap[];

    imgs[0] = Bitmap.createBitmap(scaledBitmap, 0, 0, picture.getWidth()/3 , picture.getHeight()/2);
    imgs[1] = Bitmap.createBitmap(scaledBitmap, picture.getWidth()/3, 0, picture.getWidth()/3,picture.getHeight()/2);
// i get the error at this line

    imgs[2] = Bitmap.createBitmap(scaledBitmap,((picture.getWidth()/3)+(picture.getWidth()/3)), 0, picture.getWidth()/3,picture.getHeight()/2);
    imgs[3] = Bitmap.createBitmap(scaledBitmap, 0, (picture.getHeight()/2), picture.getWidth()/3, picture.getHeight()/2);
    imgs[4] = Bitmap.createBitmap(scaledBitmap, picture.getWidth()/3, picture.getHeight()/2, picture.getWidth()/3,picture.getHeight()/2);
    imgs[5] = Bitmap.createBitmap(scaledBitmap, (picture.getWidth()/3)+(picture.getWidth()/3), picture.getHeight()/2,picture.getWidth()/3,picture.getHeight()/2);

    return imgs;
}

I get the error:
java.lang.illegalargumentexception: x + width must be <= bitmap.width.

A: The problem is that you are using picture.getWidth() and picture.getHeight(). However, you have scaled picture and stored it in scaledBitmap.
The dimensions of picture are not same as the dimensions of scaledBitmap. Therefore the above exception is being thrown.
You should be using: scaledBitmap.getWidth() and scaledBitmap.getHeight() instead.
Alternatively:
Set picture = scledBitmap as follows:
...
...
scaledBitmap = Bitmap.createScaledBitmap(picture, widthofmainBitMap, heightofmainBitMap, true);
picture = scaledBitmap;
...
...
// rest remains same


text:
Q: Is it possible to apply a ColorGradient to a string Style? After reading through the language reference on Style, ColorSchemes, ColorData and ColorFunction, I am at a loss as how to make a string appear with gradient colors. And now that I am curious, I am wondering what the easiest way to achieve this is under various scenarios, for instance:

*

*apply gradient to each character independently

*apply gradient to entire string as a whole

*apply gradient such that each character is a solid color, but as a
string it has a gradient mask applied

From reading elsewhere on stackExchange, I see I can apply a color to each character independently using Row (ex https://stackoverflow.com/questions/8956915/mathematica-how-to-have-text-in-multiple-colors). Programtically that seems rather tedious and impractical as a function.
At this point, I am not too concerned about the complexity of the gradient function - for right now, simple is better (ie, maybe a linear gradient?).
Thoughts?

A: Case 3: string with gradient, each character in a solid color (thanks to J.M. for improvements)
colorize[str_String, cf_] := "" <> MapThread[
      ToString[Style[#, cf@#2], StandardForm] &, {#, Subdivide[Length@# - 1]}] &@
   Characters@str;

colorize["Mathematica", ColorData["Rainbow"]]

Or even shorter with a bit different internal structure of the string
colorize2[str_String, cf_] := Row@MapThread[Style,
      {#, cf /@ Subdivide[Length@# - 1]} &@Characters@str]~ToString~StandardForm;

colorize2["Mathematica", ColorData["Rainbow"]]


text:
Q: Why would you ever use asp.net's ViewState storage object over the Session storage object? Other than because session storage is session-global to more than one page, why would you ever want to use the viewstate to hold values?
It seems kind of ridiculous to send any kind of information other than a few small query string like values, back and forth from the client to server.  I mean what a waste of bandwidth(!), simply for storage purposes.  The session, while global across multiple pages, seems like a completely superior alternative to the viewstate.
Especially with asp.net ajax controls and variants, the viewstate could quickly become bloated tracking the various states and variables of all those different controls and html elements.
But then why is there viewstate storage for page variables and objects at all?
Maybe I'm missing another great usage for the page's viewstate storage, does anyone know something out there?
Thanks for reading!
EDIT: Everyone had a great answer, sorry if I didn't pick yours.

A: For example when your application might be running in a computer farm and you can't configure session to use sql server.( Or using sql server is too much of a performance hit)

A: ViewState and Session have different scopes. ViewState is designed to store more or less transient data, during "postbacks", while session is used to save critical session state data. I recommend using ViewState for state related to a specific "page session".
If you don't like the normal behavior of ViewState, it's pretty simple to write your own PageStatePersister and let this object perform persistence, for instance using session, or something like Memcached. You can then completely override the default persistence mechanism.
Then, the good thing is you can seamlessly continue to use standard web controls in the .NET Framework, which will all use ViewState/ControlState for this type of data, without bloating the ViewState. A server memory persistence mechanism could be very efficient.

A: ViewState is essentially just a hidden input that must be uploaded to the server and parsed with each request.  This field is typically populated automatically, often with the programmer blissfully unaware, and can grow quite large.  For many sites that presents a problem, because even broadband users have very limited upstream bandwidth.
On intranet sites where all the users have high-speed LAN access to the server but the ram available for holding session data is limited, it may make more sense.

A: Not really a direct answer to your question, but it may resolve your issue.
You can store viewstate server side, eliminating the payload for the client.
Create a class the inherits page, and override the PageStatePersister.
http://msdn.microsoft.com/en-us/library/system.web.ui.sessionpagestatepersister.aspx
 public class RussPage : Page
    {
         protected override PageStatePersister PageStatePersister
        {
            get
            {
                return new SessionPageStatePersister(Page);
            }
        }
    }

A: Sessions run out, Viewstate does not - you can go back an hour later and your viewstate will still be available. Viewstate is also consistently available when you go back/forward on the website, Session changes.

A: Not an answer to your question but one of your assumptions is incorrect.
Session IDs can be passed in the URL. Session does not require cookies.
http://msdn.microsoft.com/en-us/library/aa479314.aspx
<sessionState cookieless="true" />

A: The whole reason for Viewstate or Session is to turn the web from a stateless system into a dynamic, customized experience.  When a user requests a page, the only way you can resume where the user left off in their experience is to remember the state either on the server or on the user's client.
Viewstate is a mechanism for remembering the user's state on the client.
Session is a mechanism for remembering the user's state on the server.
Viewstate is a transient storage mechanism.  Controls that use viewstate have their state rendered into the html page as a hidden input. To prevent tampering, it is signed.  It is not encrypted, however, so you probably want to avoid putting ANYTHING sensitive in there.  Viewstate is useful for situations where you want to post across series of multiple requests (page loads).  An example of this is when a form doesn't validate because maybe the user entered a bad email address or something, and you want to restore the form as it was before the user submitted.  The downsides to this is that viewstate is a hungry beast and can easily add 30-50% to page size.
Session, on the other hand, is stored on the server.  The client gets a token that tells the server which block of memory is theirs.  This can be much more secure than viewstate because the data isn't being retransmitted to the user over and over.  There are trade-offs though. Your server can run out of memory.  Or, the user could lose the data if their session is disrupted.
Generally, there's no "right" answer on which to use.  It is all about what you are trying to accomplish.
Most things to do with controls should use Viewstate. IF you're dealing with sensitive information however, consider Session.  If you have data that is for a specific set of pages, use viewstate. If it is data that you will need throughout a user's visit on your site, considier Session.

A: You are doing an app where viewstate bloat, for the most part, is not an issue, then it's better to store page specific data in the viewstate because it helps your server perform better.  If you go crazy with session, or any caching, for that matter, you can hurt yourself more then you help yourself.


text:
Q: puppeteer: how to wait until an element is visible? I would like to know if I can tell puppeteer to wait until an element is displayed.
const inputValidate = await page.$('input[value=validate]');
await inputValidate.click()

// I want to do something like that
waitElemenentVisble('.btnNext ')

const btnNext = await page.$('.btnNext');
await btnNext.click();

Is there any way I can accomplish this?

A: If you want to ensure the element is actually visible, you have to use
await page.waitForSelector('#myId', {visible: true})

Otherwise you are just looking for the element in the DOM and not checking for visibility.

A: While I agree with @ewwink answer. Puppeteer's API checks for not hidden by default, so when you do:
await page.waitForSelector('#id', {visible: true})

You get not hidden and visible by CSS.
To ensure rendering you can do as @ewwink's waitForFunction. However to completely answer your question, here's a snippet using puppeteer's API:
async waitElemenentVisble(selector) {
  function waitVisible(selector) {
    function hasVisibleBoundingBox(element) {
      const rect = element.getBoundingClientRect()
      return !!(rect.top || rect.bottom || rect.width || rect.height)
    }
    const elements = [document.querySelectorAll(selector)].filter(hasVisibleBoundingBox)
    return elements[0]
  }
  await page.waitForFunction(waitVisible, {visible: true}, selector)
  const jsHandle = await page.evaluateHandle(waitVisible, selector)
  return jsHandle.asElement()
}

After writing some methods like this myself, I found expect-puppeteer which does this and more better (see toMatchElement).

A:
Note, All the answers submitted until today are incorrect

Because it answer for an element if Exist or Located but NOT Visible or Displayed
The right answer is to check an element size or visibility using page.waitFor() or page.waitForFunction(), see explaination below.
// wait until present on the DOM
// await page.waitForSelector( css_selector );
// wait until "display"-ed
await page.waitForFunction("document.querySelector('.btnNext') && document.querySelector('.btnNext').clientHeight != 0");
// or wait until "visibility" not hidden
await page.waitForFunction("document.querySelector('.btnNext') && document.querySelector('.btnNext').style.visibility != 'hidden'");

const btnNext = await page.$('.btnNext');
await btnNext.click();

Explanation
The element that Exist on the DOM of page not always Visible if has CSS property display:none or visibility:hidden that why using page.waitForSelector(selector) is not good idea, let see the different in the snippet below.

function isExist(selector) {
  let el = document.querySelector(selector);
  let exist = el.length != 0 ? 'Exist!' : 'Not Exist!';
  console.log(selector + ' is ' + exist)
}

function isVisible(selector) {
  let el = document.querySelector(selector).clientHeight;
  let visible = el != 0 ? 'Visible, ' + el : 'Not Visible, ' + el;
  console.log(selector + ' is ' + visible + 'px')
}

isExist('#idA');
isVisible('#idA');
console.log('=============================')
isExist('#idB')
isVisible('#idB')
.bd {border: solid 2px blue;}

#idA, hidden element

#idB, visible element

on the snippet above the function isExist() is simulate
page.waitForSelector('#myId');

and we can see while running isExist() for both element #idA an #idB is return exist.
But when running isVisible() the  #idA is not visible or dislayed.
And here other objects to check if an element is displayed or using CSS property display.
scrollWidth
scrollHeight
offsetTop
offsetWidth
offsetHeight
offsetLeft
clientWidth
clientHeight

for style visibility check with not hidden.
note: I'm not good in Javascript or English, feel free to improve this answer.

A: async function waitForVisible (selector){
    //const selector = '.foo';
  return  await page.waitForFunction(
      (selector) => document.querySelector(selector) && document.querySelector(selector).clientHeight != 0",
      {},
      selector
    );
}

Above function makes it generic, so that you can use it anywhere.

But, if you are using pptr there is another faster and easier solution:
https://pptr.dev/#?product=Puppeteer&version=v10.0.0&show=api-pagewaitforfunctionpagefunction-options-args

page.waitForSelector('#myId', {visible: true})

A: Just tested this by scraping a fitness website. @ewwink, @0fnt, and @caram have provided the most complete answer.
Just because a DOM element is visible doesn't mean that it's content has been fully populated.
Today, I ran:
await page.waitForSelector("table#some-table", {visible:true})
const data = await page.$eval("table#some-table",(el)=>el.outerHTML)
console.log(data)

And incorrectly received the following, because the table DOM hadn't been populated fully by runtime. You can see that the outerHTML is empty.
user@env:$

Adding a pause of 1 second fixed this, as might be expected:
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

await page.waitForSelector("table#some-table", {visible:true})
await sleep(1000)
const data = await page.$eval("table#some-table",(el)=>el.outerHTML)
console.log(data)

user@env:$

Data

But so did @ewwink's answer, more elegantly (no artificial timeouts):
await page.waitForSelector("table#some-table", {visible:true})
await page.waitForFunction("document.querySelector('table#sched-records').clientHeight != 0")
const data = await page.$eval("table#some-table",(el)=>el.outerHTML)
console.log(data)

user@env:$

Data

A: You can use page.waitFor(), page.waitForSelector(), or page.waitForXPath() to wait for an element on a page:
// Selectors

const css_selector = '.btnNext';
const xpath_selector = '//*[contains(concat(" ", normalize-space(@class), " "), " btnNext ")]';

// Wait for CSS Selector

await page.waitFor(css_selector);
await page.waitForSelector(css_selector);

// Wait for XPath Selector

await page.waitFor(xpath_selector);
await page.waitForXPath(xpath_selector);

Note: In reference to a frame, you can also use frame.waitFor(), frame.waitForSelector(), or frame.waitForXPath().

A: Updated answer with some optimizations:
const puppeteer = require('puppeteer');

(async() => {
    const browser = await puppeteer.launch({headless: true});
    const page = await browser.newPage();

    await page.goto('https://www.somedomain.com', {waitUntil: 'networkidle2'});
    await page.click('input[value=validate]');
    await page.waitForSelector('#myId');
    await page.click('.btnNext');
    console.log('got it');

    browser.close();
})();

A: I think you can use page.waitForSelector(selector[, options]) function for that purpose.
const puppeteer = require('puppeteer');

puppeteer.launch().then(async browser => {

   const browser = await puppeteer.launch({executablePath: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe", headless: false});
   const page = await browser.newPage();
   await page.setUserAgent(options.agent);
   await page.goto("https://www.url.net", {timeout: 60000, waitUntil: 'domcontentloaded'});

   page
    .waitForSelector('#myId')
    .then(() => console.log('got it'));
    browser.close();
});

To check the options avaible, please see the  github link.


text:
Q: FPDF - how to create a grid of cells with background images and text Here is a picture of what i need to create
The above link shows a structure i need to create and generate with FPDF.
I have no idea how to add a background image to the container cell or a text (or a text in the nested cell) in front of it.
Would anyone help me please? Thank you.


text:
Q: backup database takes login and user backups or not i am using sql server express and visual studio on my office PC.
i have a database abcDB. i created a login abclogin with password = 'abcpass' , default database =abcDB ,
now a winform application, is allowed access to abcDB when correct id and password is supplied via textbox.
if i want to use the same application on my home pc, then what tasks would i have to perform :

*

*create an .exe of my application

*install the application from its .exe on my home pc

*install sql server on my home pc (do i have to install the same version as on my office pc)

*i would not install sql server management studio, as i only have to use the application and not to play with the database which i do on my office pc)

*start using the application

*but what about the database. i would backup it and restore on my home pc. will this also take the backup of the 'abclogin'?  or will i have to create it again from sqlcmd or installing management studio on my home pc .
when i created abclogin default database =abcDB ,then did it store this detail in the abcDB.mdf file or it is stored somewhere else?

A: Those things like logins are stored in SQL Server master tables - they are not part of your backup of abcDB.
Users on the other hand are part of your database, so they get backed up together with your data.
So when you restore your database on another computer, your database will contain the users, but if they depend on a login, that login might be missing from that SQL Server's master database (and will need to be re-created, e.g. as part of your installation)


text:
Q: Is it justify to use/report OLS model w/o assumptions check cause results are consistent with other types of models? In one paper I read that the researchers used OLS model (considered well-known, simple and robust to misspecification) but they admitted to have not tested whether its assumptions were met. However, they added that the OLS results were consistent with probit model.
My question is: is this a right way to procede? Can I use and report OLS model results (since they have the advantage of being widely known and easy to interpret also by persons with low statistical literacy) whithout testing its assumptions if its results are consistent with those of other type of models?

A: 1) I assume that by "OLS model" you mean (ordinary) least squares regression, which is in fact a method and not a model; people sometimes call the a "model" because it is (in theory) based on a model with certain assumptions. However, I can imagine also other things being meant by "OLS model". Also note that although the OLS regression theory depends on certain model assumptions, this doesn't necessarily mean that it is useless or meaningless if the model assumptions are not met. It still has some kind of interpretation as line/hyperplane/function (depending on what OLS method you are exactly talking about) approximating the data, and even statistical inference may (or may not) be approximately correct, depending on in which way assumptions are violated.
2) The OLS regression is not in fact robust against misspecification. There is a big literature on how particularly outliers will cause trouble.
3) "Is it OK to report...?" That's a weird kind of question. I'd certainly say it is not a good way to find out something valid from the data. This would require some more inspection and maybe testing (surely it is sensible to assess problems with the model assumptions, although this doesn't necessarily have to take the form of a hypothesis test). Whether it is "OK to report" something depends on what you write around it, what audience this is for etc. One could argue it is OK in the sense that it is correct to just say "I applied OLS regression without model checking and the result was this". The reader then knows a rather weakly justified approach was used and can make up their own mind (assuming they're competent enough). However, chances are I wouldn't put too much trust into any subject-matter interpretation or conclusion from this.


text:
Q: Select all Users related to Company First of all, sorry for the meaningless title. Couldn't think of anything better. Please, take a look at my following tables:
User
+-----+-------+---------------+
|  id | name  | email         |
+-----+-------+---------------+
|   1 | NameA | namea@srv.com |
|   2 | NameB | nameb@srv.com |
|   3 | NameC | namec@srv.com |
+-----+-------+---------------+

Department
+-----+---------+-------+---------+
|  id | company | name  | manager |
+-----+---------+-------+---------+
|   1 |       1 | DeptA |       1 |
|   2 |       1 | DeptB |       2 |
+-----+---------+-------+---------+

Company
+-----+------+-------+
|  id | name | owner |
+-----+------+-------+
|   1 | Buzz |     3 |
+-----+-------+------+

I need to find all users related to a Company. Something like:
+---------+------------+
| user_id | company_id |
+---------+------------+
|       1 |          1 |
|       2 |          1 |
|       3 |          1 |
+---------+------------+

How can I do that? I read about the different kind of joins (inner, outer, full, etc), but I couldn't figure out how to handle that "Department" table in the middle of everything.

A: I would do this with two queries:
select Department.manager as user_id, Company.id
from Company
join Department on Department.company=Company.id

union

select Company.owner as user_id, Company.id
from Company

A: select User.id, User.name, User.email, CASE WHEN User.id = Company.Owner THEN 'YES' ELSE 'NO' END as CompanyOwner
from User
inner join Department on User.DepartmentID = Department.id
inner join Company on Company.id = Department.company

I think you're missing an entitiy relationship between Users and Departments, perhaps a departmentID on the User Table.  I think that might be the part you're missing.

A: Typically, you would have some way to link Users to the Department they work in.  Either with a DeptID column added onto the User table.  In this example, the owner's department is represented as null, while the department of managers is populated, but which way you do this is up to you.
 User
+-----+-------+---------------+------+
|  id | name  | email         | dept |
+-----+-------+---------------+------+
|   1 | NameA | namea@srv.com |    1 |
|   2 | NameB | nameb@srv.com |    2 |
|   3 | NameC | namec@srv.com |  +++ |
|   4 | NameD | named@srv.com |    2 |
|   5 | NameE | namee@srv.com |    2 |
+-----+-------+---------------+------+

So to get the list of all company 1 users where the department is populated on the User table, this becomes simple
SELECT u.id       as user_id,
       d.company  as company_id
  FROM User u
  INNER JOIN Department d   ON u.dept=d.id
  WHERE d.company=1

UNION

SELECT owner  as user_id,
       id     as company_id
  FROM Company

If you chose not to populate manager's department in the User table, you would have to append a UNION for that part as well, similar in construct to the first part directly above.
Or you might instead have an association table to show which employees work for which department.  This might be needed if a person could work in more than one department.  (The managers and owners might not need to be in this table, since they are already accounted for.  Again, up to you.  But if you do include them, then you wont need the UNIONs, so it will keep things simpler.  You might even put the owner in an "OWNERSHIP" department.)
 UserDept
+--------+--------+
| UserID | DeptID |
+--------+--------+
|    4   |    2   |
|    5   |    2   |
+--------+--------+

SELECT u.id       as user_id,
       d.company  as company_id
  FROM UserDept u
  INNER JOIN Department d   ON u.dept=d.id
  WHERE d.company=1

(Add UNIONs on as needed, if you did not include owners / managers in the UserDept table.)
But in case you need a deeper example, let's suppose you also needed the name from the User table:
SELECT u.id       as user_id,
       d.company  as company_id,
       u.name     as user_name
  FROM User u
  INNER JOIN UserDept x     ON u.id=x.user
  INNER JOIN Department d   ON x.dept=d.id
  WHERE d.company=1


text:
Q: With GCP Compute Engine, how do I create a custom role, enabling only these three activities: start, stop, ssh, and nothing more?
*

*Summarize the problem

I want to grant to a user, the ability to perform these three activities only on GCE.

*

*start a specific instance (from the console, or any other method)

*stop that same specific instance

*ssh (direct ssh command, or gcloud ssh)

and nothing more.  Simply and only 1. & 2. would work also, as no GCE permissions need be granted to allow ssh (can be done through ssh).
The user will not have any permissions to edit the instance in any way, would not be able to delete the instance, would not be able to add or delete disks, or change any aspect of networking, nor would the user be able to start/stop or ssh into the other GCE VM's in the same project.
I wish to create a role, that would be tied to a specific existing VM, and grant those three permissions (or a combination of permissions, that would allow those three activities) to a specific user with a GCP account.

*Provide background including what you've already tried.

I have read thoroughly through all the IAM / roles documentation for GCE.  I see no way to apply these fine grained permissions to a specific, existing VM.
Reference:
https://cloud.google.com/compute/docs/access/iam
This is the document I am reading, searching for answers.  I see nothing here that would allow this.
I am hoping that I am missing something, that there is some magic or incantation that would allow this.

*Describe expected and actual results including any error messages

From the documentation I have read, any permissions that can be granted, are too far reaching.  It is seemingly give everything (ability to edit the instance including creating, modifying other VM instances), or nothing at all.

A: Updated answer based on the comments:
You would need to create a custom role and attach the specific permissions. Below is the sample terraform code to do that. The sample below creates a custom role which allows only authenticating with the GKE cluster, nothing else.
# Deleted custom roles prevent similarly named roles from being created for up to 30 days
resource "random_string" "role_suffix" {
  length  = 8
  special = false
}

# Allow frontend/test user to only authenticate
resource "google_project_iam_custom_role" "kube-api-ro" {
  project = local.project_id
  role_id = "kube_api_ro_${random_string.role_suffix.result}"

  title       = "Kubernetes API (RO)"
  description = "Grants read-only API access that can be further restricted with RBAC"

  permissions = [
    "container.apiServices.get",
    "container.apiServices.list",
    "container.clusters.get",
    "container.clusters.getCredentials",
  ]
}

resource "google_project_iam_binding" "kube-api-ro" {
  project = local.project_id
  role    = "projects/${local.project_id}/roles/${google_project_iam_custom_role.kube-api-ro.role_id}"

  members = [
    "user:${var.rbac_test_user}",
  ]
}


text:
Q: Asp.net MVC 2, spark engine and strongly Typed Html Helpers Will I get the advantage of the new Strongly Typed Html Helpers with asp.net MVC 2 if were to use the spark engine for rendering?

A: You can use any HtmlHelper that ship with the MVC framework in Spark view engine.
${Html.TextBoxFor(p => p.Name)}

A: Spark view page base class doesn't have public property Html with HtmlHelper type but u can add it yourself.
Add
<var Html="new HtmlHelper<YourModel>(base.ViewContext, this)"/>
on your spark view and after  that u can use
${ Html.LabelFor(model => model.UserName)} as well as ${Html.Label("some label")}.

A: Whenever you are confused about it, you can't definitely know how to do, you still use aspx-like expression - <%statement%> :) Inline code in Spark supports #statement variation too.
Source: Spark expressions


text:
Q: Fetch youtube channels having content revolving around a certain topic How do I fetch the names of youtube channels having content revolving around a certain topic?
fetchChannels("cats")

should fetch channel names revolving around cat vidoes.
Before asking this question I've checked the youtube API but didn't found anything useful.
How would I go about doing this preferably in JavaScript or Python?

A: You can use the  link below and fetch the data.
You will get the channel by any name
https://www.googleapis.com/youtube/v3/search?part=snippet&type=channel&maxResults=100&key=[api-key]&q=cat


text:
Q: Using the fifth root of unity to show the cosine equation Consider the equation expressed the fifth root of unity: $z^5-1=0$
To show that: $$2(\cos(\frac{2\pi}{5})+\cos(\frac{4\pi}{5}))=-1\\4\cos(\frac{2\pi}{5})\cos(\frac{4\pi}{5})=-1$$
I have already shown the first one by using the sum of the root is zero and the truth that $\cos(\frac{2\pi}{5})=\cos(\frac{8\pi}{5})$ and $\cos(\frac{4\pi}{5})=\cos(\frac{6\pi}{5})$.
Now I am stacking on the second one and totally have no idea about how to do it.

A: Hint: The sum of the five roots is zero because $z^5-1$ has no fourth-degree term. What does the fact that there is no third-degree term tell you?


text:
Q: Angular momentum of an $N$-body system is of the form $Q(y,z)=y^TDz$? I was reading in a book that the angular momentum of the $N$-body system is of the form $Q(y,z)=y^TDz$ with $y, z$ vectors and $D$ a matrix. But the angular momentum of the $N$-body system is something like $L=\sum_{i=1}^Nq_i\times p_i$ no? How do you put it in the previous form?
edit :
I am not sure if this helps but it is the citation that is causing me trouble.

We next consider partitioned Runge-Kutta methods for systems
$\dot{y}=f(y,z), \dot{z}=g(y,z)$. Usually such methods cannot conserve
general quadratic invariants. We therefore concentrate on quadratic
invariants of the form  \begin{equation} Q(y,z)=y^TDz \end{equation}
where $D$ is a matrix of appropriate dimensions. Observe that the
angular momentum of $N$-body systems is of this form.


text:
Q: Error al ejecutar el programa 'npm.cmd': Acceso denegado tengo una api en nodeJS el cual estoy intentando ejecutar cualquier comando en la terminal me sale este error
Error al ejecutar el programa 'npm.cmd': Acceso denegado. En línea: 1 Carácter: 1
+ npm start
+ ~~~~~~~~~.
En línea: 1 Carácter: 1
+ npm start
+ ~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (:) [], ApplicationFailedException
    + FullyQualifiedErrorId : NativeCommandFailed

Al ejecutar el archivo index.js me rechaza la conexión en el google chrome y retorna el siguiente error
(index):6774 crbug/1173575, non-JS module files deprecated.
He intentado cambiar el puerto del launch.json y borrando también el archivo pero sin éxito.

A: Revisa si tienes permisos para acceder a la consola de comandos (cmd), puede ser que algun virus u otro problema haya afectado a tu equipo y este bloqueara el acceso a la consola.


text:
Q: Make an array of input name attributes Javascript How can I make an array using a loop which contains the name attributes of inputs inside a form tag, using javascript.
This is my code so far, but it doesn't seem to be working and I have looked at other similar questions to no avail.
      <script type="text/javascript">
      var inputnames[];
      for (var i = 0; i < document.getElementsByTagName('input').length; i++)
      {
      inputnames[document.getElementsByTagName("input")[i].name]
      };
      document.write(inputnames)
      </script>

A: The issue is that you're not actually adding the values to the array. Change
inputnames[document.getElementsByTagName("input")[i].name]

to
inputnames.push(document.getElementsByTagName("input")[i].name)

A: Firstly you need to get list of elements.
Than you can iterate over them.
And do not query DOM each iteration. If you are not expected DOM mutation you can get it once and iterate over it.

var inputnames = [];
var elems = document.getElementsByTagName('input');

for (var i = 0; i < elems.length; i++) {
  inputnames.push(elems[i].name);
};
document.write(inputnames)
<input name="first" type="text" />
<input name="second" type="radio" />

A:   <script type="text/javascript">
  var inputnames=[];
  for (var i = 0; i < document.getElementsByTagName('input').length; i++)
  {
  inputnames.push(document.getElementsByTagName("input")[i].name);
  };
  alert(inputnames);
  </script>

A: Pretty close, I would not use the document.write there, not sure what you want to do  but this logs it in the console.
var inputnames = [];
for (var i = 0; i < document.getElementsByTagName('input').length; i++) {
  inputnames.push(document.getElementsByTagName("input")[i].name);
}
console.log(inputnames);

Here is another alternative
var inputnames = [];
for (var item of document.getElementsByTagName('input')) {
  inputnames.push(item.name);
};
console.log(inputnames);

Alternate 2: use map.call to treat it is an array.
var inputnames = [];
var nodelist = document.getElementsByTagName('input');

Array.prototype.map.call( nodelist, function(n){
    inputnames.push(n.name);
});

Alternate 3  get only inputs with a name attribute and push those (avoids blanks in the array)
var inputnames = [];
var named = document.querySelectorAll("input[name]");
Array.prototype.map.call( named, function(n){
    inputnames.push(n.name);
});


text:
Q: How to get partials to load once registerPartial have completed So decided to try handlebars for templating my node application (OK, no, decided to use keystone.js for something, and Handlebars seemed nicer than jade, what can I say, HTML is my dirty secret).
Built my webpage, and in the ned I want to load a number of javascripts for jquery, angular bootstrap and some other bits and pieces. All seems to work on Chrome, but the first time you access the server, you get error 500 saying that partial basejs could not be found, and the below error message on the server.
Error: The partial basejs could not be found
    at Object.invokePartial (/Users/bengtbjorkberg/WebstormProjects/constructmind_http/node_modules/handlebars/dist/cjs/handlebars/runtime.js:266:11)

basejs is just the first hook for about four scripts. The file itself looks as follows:
{{!--
    //- jQuery 1.11.3 is included by default, and required by both Bootstrap
    //- and the KeystoneJS Content Editor. If you are not targeting IE8,
    //- you can upgrade to 2.1.4 (also bundled) for better performance.
--}}
<script src="/js/jquery/jquery-1.11.3.min.js"></script>
{{!--
    //- Customise which Bootstrap javascript files are served by including
    //- them specifically here, instead of bootstrap-3.3.5.min.js
--}}
<script src="/js/bootstrap/bootstrap-3.3.5.min.js"></script>

It is loaded by a helper function called in the beginning of the template file, the helper file just takes every file in a directory and register them as handlebars partials using hbs.registerPartial
_helpers.loadJS = function(user, options){
    var partialsDir = __dirname + '/../loadjs';

    var filenames = fs.readdirSync(partialsDir);
    filenames.forEach(function (filename) {
        var matches = /^([^.]+).hbs$/.exec(filename);
        if (!matches) {
            return;
        }
        var name = matches[1];
        var template = fs.readFileSync(partialsDir + '/' + filename, 'utf8');
        hbs.registerPartial(name, template);

    });

}

In the beginning of my layout file I call the helper:
{{!-- Lets load our pariatls for scripts--}}
{{{loadJS}}}

Lastly, in the very end of the file, I then call each partial:
{{> basejs }}
{{> setscreen }}
{{> angular_load }}
{{> google_ga }}

I think all that is happening is that basejs is called before loadJS have completed, but how do I get handlebar to either
1.  run the helper then call the partials
2.  Get the layout template to check that loadJS have completed and if not wait until it has

A: OK, I don't think it is possible to do it this way, or at least not in a nice way (basically, the development team behind handlebars.js REALLY want to keep handlebars async, which is all fine).
However, what I did not realise is that the helpers are registered on server lever, so if you instead of registering it as a helper you just add it as a function in the module and call it, it will register them as the server start.
This is the code that solved it in my case
module.exports = function () {
    var loadJS = function(user, options){
        var partialsDir = __dirname + '/../loadjs';
        var filenames = fs.readdirSync(partialsDir);

        filenames.forEach(function (filename) {
            var matches = /^([^.]+).hbs$/.exec(filename);
            if (!matches) {
                return;
            }
            var name = matches[1];
            var template = fs.readFileSync(partialsDir + '/' + filename, 'utf8');
            hbs.registerPartial(name, template);
        });

    }
    loadJS();

Technically it does not need to be a function as it is called just after its created, but I like to keep it that way:)
For the discussion on async in handlebars.js
https://github.com/wycats/handlebars.js/issues/717


text:
Q: Billing First Name Should Be Alphabetic add_filter('woocommerce_billing_fields', 'custom_woocommerce_billing_fields');
function custom_woocommerce_billing_fields( $fields )
{
$fields['billing_first_name']['required'] = false;
return $fields;
}
I want to make First and Last name should be alphabetic only. Right now it's accepting numbers also.
Help will be much appreciated. I also want to limit text of review in cart.
Regards

A: $('#billing_first_name').on('input',function(){
    var node = $(this);
    node.val(node.val().replace(/[^a-z]/g,'') ); }
);

Adding this jQuery will work.! You can add for others fields too.

A: You have to add fields by custom method then use follow script for alphabetic textbox:
add_filter('woocommerce_checkout_fields', 'custom_override_checkout_fields');

function custom_override_checkout_fields($fields)
{
$fields['billing']['billing_first_name'] = array(
    'label'     => __('First name', 'woocommerce'),
    'placeholder'   => _x('First name', 'placeholder', 'woocommerce'),
    'required'    => false,
    'clear'       => false,
    'type'        => 'text',
    'class'       => array(
                    'alpha'
   )
);

and same for billing_last_name,

use all of scripts in active theme functions.php

Actually woo-commerce does not give us this functionality. You have to use your custom jquery or javascript. This might help you
You should call this script under wp_head hook
add_action('wp_head', ' alphabet_only ');

function alphabet_only() {
?>
    <script type="text/javascript">
$('.alpha').bind('keyup blur',function(){
    var node = $(this);
    node.val(node.val().replace(/[^a-z]/g,'') ); }
);
</script>
<?php
}

That's it.