text:
Q: Load balancer and API Gateway confusion I have always worked on mobile technologies and now I am stepping into backend systems, more specifically systems design. I keep coming across conflicting statements for the roles of api gateway and load balancer. Googling has only returned the same half a dozen results that mostly focus on the implementations of load balancer or api gateway service provided by some famous service. I will list here all the confusing I am facing, in hope someone can clarify all of them.
Sometimes, i come across that API Gateway is the single point of communication with client devices. On the other hand, some places mention that 'request goes to load balancer, which spreads it across servers equally'. So what is correct? API Gateway receives requests or load balancer?
Other places, when I googled the topic, say that the two are totally different. I've understood that API Gateway does a lot of stuff, like SSL termination, logging, throttling, validation, etc, but it also does load balancing. So API Gateway is a load balancer itself, equipped with other responsibilities?
On the topic, I want to understand if load balancer distribute load among servers of the same cluster or across different data centers or clusters? And what about API Gateway?
What is so specific to api gateway that it is a choice by default for micro-service architecture? Where are API gateways hosted? A DNS resolves domain name to a load balancer or api gateway?
As it might be clear, I am totally confused. In what systems does a load balancer benefit more than API Gateway, if the question is correct.

A: There are two scenarios to consider here to clarify the confusion. I have clarified this using microservices example as this would make sense there only.
Scenario 1: You have a cluster of API Gateways
User ---> Load Balancer (provided by Cloud Providers like AWS or your own) ---> API Gateway Cluster ---> Service Discovery Agent (like eureka) --->  Microservice A ---> Client Side Load Balancer ---> Microservice B
Scenario 2: You have a single API Gateway
User ---> API Gateway ---> Service Discovery Agent (like Eureka) ---> Microservice A ---> Client Side Load Balancer -> Microservice B
I hope you understand why we required Load Balancer before the API Gateway in Scenario 1, as there we had multiple instances of API gateway also to handle the large traffic and to avoid the burden on the single api gateway since gateway itself can have several tasks to manage as per the requirements, so to distribute the load among them, we have load balancer.
Inside the microservices environment, you may need load balancing concept at multiple places. Like to accept the outside network you will maintain a load balancer provided by Cloud provider like AWS, eureka (Service Discovery) also acts like a load balancer if there are multiple instances of same service are  registered with it and at last we also have client side load balancing (each microservice has its own client side load balancer that maintains a local cache) when your microservices are trying to communicate within them just to avoid burden on service discovery agent(eureka) by not checking every time with it the address for the other microservices.

Note: In the flow diagram, please don't confuse the path from API
Gateway --> Service Discovery --> to Microservice as if the Gateway is
forwarding request to Service Discovery that later routes it forward.
Gateway is just checking for the services registry from the Discovery
agents and then routing it to the correct microservice (Not through
the Service Discovery agent)

A: Load Balancer :
Its main purpose is to distribute by load balancing traffic between multiple back end systems.

*

*We can configure different routes for different back end systems.

*We get a static ip address for the load balances end points (usually not available with API gateways)

*Can configure health checks (usually not available with API gateways)

In case of cloud providers, usually "Pay for idle as well"
API Gateway :
This as well routes traffic to back end systems based on URL
BUT, its main purpose is targeted towards "API management".
Below are such key features which are usually not available in "Load Balancers",

*

*Can implement rate limiting, bursting limits

*Can do request validation and request/response mapping

*Usually cloud API gateways allows to export/import cross API platform using swagger spec

*Allows caching responses
In case of cloud providers, usually "Pay per use"

A: API Gateway and Load Balancer are 2 different things.
Load Balancer -> Its a software which works at protocol or socket level (eg. tcp, http, or port 3306 etc.) Its job is to balance the incoming traffic by distributing it to the destinations with various logics (eg. Round robin).
I doesn't offer features such as authorisation checks, authentication of requests etc.
Whereas
API Gateway -> Its a managed service provided by various hosting companies to manage API operations to seamlessly scale the API infra.
It takes cares of the access control, response caching, response types, authorisation, authentication, request throttling, data handling, identifying the right destinations based on custom rules, and seamless scaling the backend.
Generally Managed API gateways by default comes with scalable infra, so putting them behind load balancer might not make sense.
About resolving the Domain, most likely always the DNS resolves to the load balancer, which in turn fetches the response from the API gateway service.

DNS -> Load Balancer -> API gateway -> Backend service

Hope I could explain and clear your confusion.

A: API gateway predominately does API management and provides various other key features such as IAM (Identity and Access Management), Rate limiting, circuit breakers. Hence, it mainly eliminates the need to implement API-specific code for functionalities such as security, caching, throttling, and monitoring for each of the microservice. Microservices typically expose the REST APIs for use in front ends, other microservices and  3rd party apps with help of API gateway.
However, normally, the API Management does not include load balancing function, so it should be used in conjunction with a load balancer to achieve the same.
In system architecture based on Azure, there is Azure Application Gateway which is a load balancer that runs on Layer 7 and provides more features than traditional load balancer ( Layer 4 ) in terms of routing traffic using routing decisions based on additional attributes of HTTP request or content of traffic. This can also be termed as an application load balancer. It shall be used in conjunction by Azure API Management (API gateway). Azure has a Traffic Manager for operating at DNS level which uses DNS to direct client requests to the most appropriate service endpoint based on a traffic-routing method and the health of the endpoints. Traffic  manager also uses the rules configured at the DNS level and enables dstribution of the the load over multiple regions and data centers. Within every region or data center, there shall be application gateways coupled with load balancers such that, the application gateways shall help in determining the application server to fetch response from and the load balancer shall help in load balancing.
System overview based on Azure :

Here are few related references:

*

*Azure Application Gateway - https://learn.microsoft.com/en-us/azure/application-gateway/application-gateway-introduction

*Azure Load Balancer- https://learn.microsoft.com/en-us/azure/load-balancer/load-balancer-overview

*Azure Traffic Manager - https://learn.microsoft.com/en-us/azure/traffic-manager/traffic-manager-overview

*Scenario Architecture - https://learn.microsoft.com/en-us/azure/traffic-manager/traffic-manager-load-balancing-azure

A: DNS is responsible for routing the request to the nearest ip address inside network for a given domain name.
Api gateway is responsible for authentication, finding the correct apis(with or without load balancer) to call and circuit braking, response consolidation.
Load balancer is resposnible for distributing incoming request to different machine having same service deployed on them, on the basis of load or maybe round robin fashion.
So one way of doing it is
DNS TO GATEWAY TO LB
NOTE : LB can be placed before gateway depending upon traffic and use case


text:
Q: Magento2.3.5 home page & admin panel is running very slow after doing cache: enable as well I have installed the Magento2.3.5 successfully with PHP 7.3 version. I am running magento on windows 10 laptop. When I open homepage & admin link it takes huge time to open. It keeps loading. Which is frustrating. Please suggest on this. I have done cache:enable from Magento too directory still it is slow. I have attached screenshots of homepage & admin pages.

A: Run this command.
   php bin/magento cache:enable

For the first time it will load slow. Later on it will load very fast. Without caching magento is a miss.

redpajama_set_name: RedPajamaStackExchange


text:
Q: WiFi dropping. Good Broadband I have sky broadband router and on test always has a good signal with stable lights (3 green). WiFi may drop even though internet is good and this could be for a period of time, intermittently or occasionally. Usually laptops work well but WiFi calling and things like Skype seem to have poor stability. My wifi phone is 1 metre from the router without obstruction but sound often distorted.I'm in the UK and have previously had BT and Plusnet routers but they have been no different. Sky set up both 2.4 and 5 and put in a booster but this did not help.The house is not in a heavily built up area, is detached and of normal brick and tiled construction.
I would do almost anything to get a stable internet/wifi calling after years of problems. Would it be worth getting and extra phone line and another router from same/different provider?


text:
Q: Node.js running Python scripts with librairies
*

*I have a Node.js app that makes GET calls every minute to an API.

*The data it receives gets stored into a MongoDB database.

*Simultaneously, the Node.js runs a Python script (with the Keras library) on that data every minute.

*Based on the output of the Python script, the Node.js app makes a POST call to the same API.

*This would all run on Docker 24/7 after I download Node.js, npm, python's keras library and mongo.

How should the Node.js app and the Python script interact? Can I have a simple node-cmd npm package to run the script from the Node.js code or is it more complex? Am I missing anything else?
Thanks!

A: Use child_process from Node.js documentation (Link)

var exec = require('child_process').exec;
var output = '';
var child = exec('python some/file.py');
child.stdout.on('data', function(data) {
    output += data;
});
child.on('close', function() {
    // Make your API call here
    console.log(result);
});


text:
Q: UIScrollView overlaps other UIElements so they are not clickable anymore Dear StackOverflowCommunity,
im currently working on a project, where I need to make a fully dynamic user interface.
For that, im building all of it programatically to make it as easy as possible.
I've now come to a problem which is as soon as I wrap my contentView(UIStackView) with an UIScrollView to make it scrollable, the scrollView is in front of all the other UIElements so that I can only scroll. I can not interact with Buttons, Sliders, Switches or anything, no event will get triggered.
I've literally done anything I could think of (working on that Problem for DAYS) but couldn't find any suiting answer whether on google directly nor on stack overflow or apple forums.
I'm pretty sure its a pretty small change that I just wasn't capable of thinking of. I really appreciate any of your help.
Structure is like this:
ViewController > UIScrollView > UIStackView > Item Wrappers (for example contains a UISwitch and a Describing Label) > Single UIElement
On User Interaction (for example choosing a different mode) the wrappers get removed and/or added to the view as the user needs.
I did only post the code that is somehow relevant for this problem (in my opinion). If you need any further information feel free to ask.
I maybe need to add:
As soon as I remove the UIScrollView and just add the StackView (named contentView in code) to the main view it all works just fine, I just can't scroll it which is a big problem as soon as I have more than like 5 element wrappers attached to the view.
    var wrappers : Dictionary<String, UIView> = [:]
var elements : Dictionary<String, [UIView]> = [:]
var constraints : Dictionary = [String: [[NSLayoutConstraint]]]()
let contentView = UIStackView()

let states = [
    "state_operating_hours",
    "state_dim",
    "state_brightness_sensor",
    "state_operating_voltage",
    "state_circuit_voltage",
    "state_load_current_led",
    "state_output_power",
    "state_temperature",
    "state_error",
    "state_sw_version",
    "state_hw_version"
]

let checkboxes = [
    "summertime_wintertime",
    "dali",
    "error_output"
]

let sliders = [
    "immediate_sensitivity",
    "immediate_dawn",
    "immediate_dim",
    "immediate_day",
    "immediate_dusk",
    "immediate_night",
    "aging"
]

let textInputs = [
    "module_name",
    "switch_delay"
]

let dropdowns = [
    "mode",
    "bt_state",
    "config_output"
]

let timePickers = [
    "phase_0",
    "phase_1",
    "phase_2",
    "phase_3"
]

let buttons = [
    "state_trigger",
    "reset_trigger",
]

let l_kind_criteria = [
    "immediate_dawn",
    "immediate_day",
    "immediate_dusk",
    "immediate_night",
    "immediate_sensitivity"
]

let d_kind_criteria = [
    "immediate_dim"
]

let t_kind_criteria = [
    "phase_0",
    "phase_1",
    "phase_2",
    "phase_3"
]

let m_kind_criteria = [
    "immediate_dawn",
    "immediate_day",
    "immediate_dusk",
    "immediate_night",
    "immediate_sensitivity",
    "phase_0",
    "phase_1"
]

let user_criteria = [
    //"access",
    //"state_trigger",
    //"reset_trigger",
    "mode",
    "summertime_wintertime"
]

let service_criteria = [
    "module_name",
    //"access",
    "state_trigger",
    "reset_trigger",
    "mode",
    "bt_state",
    "config_output",
    "aging",
    "switch_delay",
    "summertime_wintertime",
    "error_output",
    "dali"
]

override func viewDidLoad() {
    bleService.delegate = self
    bleService.requestAuthMode()
    view.backgroundColor = .lightGray
    bleService.send(aText: "c28r:#")
    bleService.send(aText: "c05r:#")
    Toast.show(message: "Statuswerte werden abgerufen..." , controller: self)
    buildLayout()
}

// Class - Functions

func buildLayout() {
    // Building the Basic Layout

    let topView = UIView()
    topView.backgroundColor = .purple
    self.view.addSubview(topView)
    topView.translatesAutoresizingMaskIntoConstraints = false

    let logoImageView = UIImageView(image: UIImage(named: "placeholder"))
    logoImageView.translatesAutoresizingMaskIntoConstraints = false
    logoImageView.frame = CGRect(x: 0, y: 0, width: view.frame.width/1.8, height: 30)
    topView.addSubview(logoImageView)

    logoImageView.leftAnchor.constraint(greaterThanOrEqualTo: view.leftAnchor, constant: 20).isActive = true
    logoImageView.topAnchor.constraint(greaterThanOrEqualTo: view.topAnchor, constant: 30).isActive = true

    topView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
    topView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    topView.heightAnchor.constraint(equalToConstant: view.frame.height/3).isActive = true
    topView.centerYAnchor.constraint(equalTo: view.topAnchor).isActive = true
    topView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true

    //Generate and add Scroll View to Main Window

    let scrollView = UIScrollView()
    scrollView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(scrollView)

    NSLayoutConstraint.activate([
        scrollView.topAnchor.constraint(equalTo: topView.bottomAnchor, constant: 20),
        scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
        scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
        scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
        scrollView.centerXAnchor.constraint(equalTo: view.centerXAnchor)
    ])

    //Add Content Stack to Scroll View

    contentView.axis = .vertical
    contentView.alignment = .fill
    contentView.spacing = 150
    contentView.distribution = .fill
    contentView.backgroundColor = .blue
    contentView.translatesAutoresizingMaskIntoConstraints = false
    scrollView.addSubview(contentView)

    NSLayoutConstraint.activate([
        contentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
        contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 20),
        contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: -20),
        contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
        contentView.widthAnchor.constraint(equalToConstant: scrollView.frame.width),
        contentView.centerXAnchor.constraint(equalTo: view.centerXAnchor)
    ])

    // programmatically creating layout elements without constraints
    // Elements that change a value are always last in their respective array

    for (index, dropdownName) in dropdowns.enumerated() {
        constraints[dropdownName] = [[]]
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.text = dropdownName

        let leadAnch = label.leadingAnchor.constraint(equalTo: contentView.leadingAnchor)
        constraints[dropdownName]!.append([leadAnch])

        let textField = UITextField()
        textField.delegate = self
        textField.translatesAutoresizingMaskIntoConstraints = false
        textField.backgroundColor = .white
        textField.layer.cornerRadius = 5

        var trailAnch = textField.trailingAnchor.constraint(equalTo: contentView.trailingAnchor)
        var widthAnch = textField.widthAnchor.constraint(equalToConstant: view.frame.width / 6)
        constraints[dropdownName]!.append([trailAnch, widthAnch])

        let pickerView = UIPickerView()
        pickerView.backgroundColor = .white
        pickerView.translatesAutoresizingMaskIntoConstraints = false
        pickerView.delegate = self
        pickerView.isHidden = true
        pickerView.dataSource = self

        trailAnch = pickerView.trailingAnchor.constraint(equalTo: textField.trailingAnchor)
        widthAnch = pickerView.widthAnchor.constraint(equalTo: textField.widthAnchor)
        constraints[dropdownName]!.append([trailAnch, widthAnch])

        let dropdownWrapper = UIView()
        dropdownWrapper.translatesAutoresizingMaskIntoConstraints = false

        dropdownWrapper.addSubview(label)
        dropdownWrapper.addSubview(textField)
        dropdownWrapper.addSubview(pickerView)

        wrappers[dropdownName] = dropdownWrapper
        elements[dropdownName] = [label, textField, pickerView]

        let commandID = bleService.getCommand(commandName: dropdownName)
        bleService.send(aText: "c\(commandID)r:#")
    }

    for (index, sliderName) in sliders.enumerated() {
        constraints[sliderName] = [[]]
        let descLabel = UILabel()
        descLabel.translatesAutoresizingMaskIntoConstraints = false
        descLabel.text = sliderName

        var leadAnch = descLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor)
        constraints[sliderName]!.append([leadAnch])

        let valueLabel = UILabel()
        valueLabel.translatesAutoresizingMaskIntoConstraints = false
        valueLabel.text = "0"
        valueLabel.backgroundColor = .white

        let widthAnch = valueLabel.widthAnchor.constraint(equalToConstant: view.frame.width/6)
        var trailAnch = valueLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor)
        constraints[sliderName]!.append([trailAnch, widthAnch])

        let slider = UISlider()
        slider.translatesAutoresizingMaskIntoConstraints = false
        slider.isContinuous = false
        slider.addTarget(self, action: #selector(sliderValueChanged), for: .valueChanged)

        leadAnch = slider.leadingAnchor.constraint(equalTo: contentView.leadingAnchor)
        trailAnch = slider.trailingAnchor.constraint(equalTo: contentView.trailingAnchor)
        let topAnch = slider.topAnchor.constraint(equalTo: descLabel.bottomAnchor, constant: 5)
        constraints[sliderName]!.append([trailAnch, leadAnch, topAnch])

        let sliderWrapper = UIView()
        sliderWrapper.translatesAutoresizingMaskIntoConstraints = false

        sliderWrapper.addSubview(descLabel)
        sliderWrapper.addSubview(valueLabel)
        sliderWrapper.addSubview(slider)

        wrappers[sliderName] = sliderWrapper
        elements[sliderName] = [descLabel, valueLabel, slider]

        let commandID = bleService.getCommand(commandName: sliderName)
        bleService.send(aText: "c\(commandID)r:#")
    }

    for (index, checkboxName) in checkboxes.enumerated() {
        constraints[checkboxName] = [[]]
        let cbLabel = UILabel()
        cbLabel.translatesAutoresizingMaskIntoConstraints = false
        cbLabel.text = checkboxName

        let leadAnch = cbLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor)
        constraints[checkboxName]!.append([leadAnch])

        let checkbox = UISwitch()
        checkbox.translatesAutoresizingMaskIntoConstraints = false
        checkbox.addTarget(self, action: #selector(checkboxClicked), for: .valueChanged)

        let trailAnch = checkbox.trailingAnchor.constraint(equalTo: contentView.trailingAnchor)
        constraints[checkboxName]!.append([trailAnch])

        let checkboxWrapper = UIView()
        checkboxWrapper.translatesAutoresizingMaskIntoConstraints = false

        checkboxWrapper.addSubview(cbLabel)
        checkboxWrapper.addSubview(checkbox)

        wrappers[checkboxName] = checkboxWrapper
        elements[checkboxName] = [cbLabel, checkbox]

        let commandID = bleService.getCommand(commandName: checkboxName)
        bleService.send(aText: "c\(commandID)r:#")
    }

    for (index, textInputName) in textInputs.enumerated() {
        constraints[textInputName] = [[]]
        let textLabel = UILabel()
        textLabel.translatesAutoresizingMaskIntoConstraints = false
        textLabel.text = textInputName

        var leadAnch = textLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor)
        constraints[textInputName]!.append([leadAnch])

        let inputField = UITextField()
        inputField.layer.cornerRadius = 5
        inputField.translatesAutoresizingMaskIntoConstraints = false
        inputField.placeholder = textInputs[index]
        inputField.backgroundColor = .white
        inputField.addTarget(self, action: #selector(textfieldChanged), for: .valueChanged)

        let topAnch = inputField.topAnchor.constraint(equalTo: textLabel.bottomAnchor, constant: 5)
        let widthAnch = inputField.widthAnchor.constraint(equalToConstant: view.safeAreaLayoutGuide.layoutFrame.width/1.1)
        leadAnch = inputField.leadingAnchor.constraint(equalTo: contentView.leadingAnchor)
        constraints[textInputName]!.append([topAnch, widthAnch, leadAnch])

        let inputWrapper = UIView()
        inputWrapper.translatesAutoresizingMaskIntoConstraints = false

        inputWrapper.addSubview(textLabel)
        inputWrapper.addSubview(inputField)

        wrappers[textInputName] = inputWrapper
        elements[textInputName] = [textLabel, inputField]

        let commandID = bleService.getCommand(commandName: textInputName)
        bleService.send(aText: "c\(commandID)r:#")
    }

    for(index, phase) in timePickers.enumerated() {
        constraints[phase] = [[]]
        let descLabel = UILabel()
        descLabel.translatesAutoresizingMaskIntoConstraints = false
        descLabel.text = "Zeitschaltung \(index+1)"

        var leadAnch = descLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor)
        constraints[phase]!.append([leadAnch])

        let enabledSwitch = UISwitch()
        enabledSwitch.translatesAutoresizingMaskIntoConstraints = false
        enabledSwitch.addTarget(self, action: #selector(changeTimerState), for: .valueChanged)

        var topAnch = enabledSwitch.topAnchor.constraint(equalTo: descLabel.topAnchor)
        var trailAnch = enabledSwitch.trailingAnchor.constraint(equalTo: contentView.trailingAnchor)
        constraints[phase]!.append([trailAnch, topAnch])

        let showPickerButton = UIButton()
        showPickerButton.translatesAutoresizingMaskIntoConstraints = false
        showPickerButton.setTitle("Zeit auswählen", for: .normal)
        showPickerButton.backgroundColor = .darkGray
        showPickerButton.layer.cornerRadius = 5
        showPickerButton.addTarget(self, action: #selector(showTimePicker), for: .touchUpInside)

        topAnch = showPickerButton.topAnchor.constraint(equalTo: enabledSwitch.bottomAnchor, constant: 4)
        trailAnch = showPickerButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor)
        constraints[phase]!.append([topAnch, trailAnch])

        let timePicker = UIDatePicker()
        timePicker.backgroundColor = .white
        timePicker.isHidden = true
        timePicker.translatesAutoresizingMaskIntoConstraints = false
        timePicker.datePickerMode = .time
        timePicker.addTarget(self, action: #selector(changeTimer), for: .valueChanged)

        topAnch = timePicker.bottomAnchor.constraint(equalTo: enabledSwitch.bottomAnchor)
        trailAnch = timePicker.trailingAnchor.constraint(equalTo: enabledSwitch.trailingAnchor)
        constraints[phase]!.append([topAnch, trailAnch])

        //Brightness Slider Value Label

        let sliderValLabel = UILabel()
        sliderValLabel.translatesAutoresizingMaskIntoConstraints = false
        sliderValLabel.text = "0"
        sliderValLabel.backgroundColor = .white

        trailAnch = sliderValLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor)
        topAnch = sliderValLabel.topAnchor.constraint(equalTo: showPickerButton.bottomAnchor, constant: 10)
        var widthAnch = sliderValLabel.widthAnchor.constraint(equalToConstant: view.frame.width / 6)
        constraints[phase]!.append([trailAnch, topAnch, widthAnch])

        //Brightness Slider

        let valueSlider = UISlider()
        valueSlider.isContinuous = false
        valueSlider.translatesAutoresizingMaskIntoConstraints = false

        topAnch = valueSlider.topAnchor.constraint(equalTo: sliderValLabel.bottomAnchor, constant: 10)
        leadAnch = valueSlider.leadingAnchor.constraint(equalTo: contentView.leadingAnchor)
        trailAnch = valueSlider.trailingAnchor.constraint(equalTo: contentView.trailingAnchor)
        constraints[phase]!.append([topAnch, leadAnch, trailAnch])

        let timePickerWrapper = UIView()
        //timePickerWrapper.translatesAutoresizingMaskIntoConstraints = false

        timePickerWrapper.addSubview(descLabel)
        timePickerWrapper.addSubview(enabledSwitch)
        timePickerWrapper.addSubview(showPickerButton)
        timePickerWrapper.addSubview(timePicker)
        timePickerWrapper.addSubview(valueSlider)
        timePickerWrapper.addSubview(sliderValLabel)

        wrappers[phase] = timePickerWrapper
        elements[phase] = [descLabel, showPickerButton, enabledSwitch, timePicker, sliderValLabel, valueSlider]

        let commandID = bleService.getCommand(commandName: phase)
        bleService.send(aText: "c\(commandID)r:#")
    }

    for buttonName in buttons {
        constraints[buttonName] = [[]]
        let button = UIButton()
        button.translatesAutoresizingMaskIntoConstraints = false

        let widthAnch = button.widthAnchor.constraint(equalToConstant: contentView.frame.width/1.1)
        let xAnch = button.centerXAnchor.constraint(equalTo: view.centerXAnchor)
        constraints[buttonName]!.append([widthAnch, xAnch])

        let buttonWrapper = UIView()
        buttonWrapper.translatesAutoresizingMaskIntoConstraints = false

        wrappers[buttonName] = buttonWrapper
        elements[buttonName] = [button]
    }
}

func changeContent(criteria: [String]) {
        for item in criteria {
            if(!contentView.contains(wrappers[item]!)) {
                contentView.addArrangedSubview(wrappers[item]!)
                for singleView in constraints[item]! {
                    for singleViewConstraint in singleView {
                        singleViewConstraint.isActive = true
                    }
                }
            }
        }
    }

func removeContent() {
    var criteria = [String]()
    switch(previousSetupMode) {
    case "d":
        criteria = d_kind_criteria
        break
    case "l":
        criteria = l_kind_criteria
        break
    case "m":
        criteria = m_kind_criteria
        break
    case "t":
        criteria = t_kind_criteria
        break
    default:
        break
    }
    for item in criteria {
        wrappers[item]!.removeFromSuperview()
    }
}

func changeView() {
    if(previousSetupMode != activeSetupMode) {
        removeContent()
    }
    switch(activeSetupMode) {
    case "d":
        changeContent(criteria: d_kind_criteria)
        break
    case "l":
        changeContent(criteria: l_kind_criteria)
        break
    case "t":
        changeContent(criteria: t_kind_criteria)
        break
    case "m":
        changeContent(criteria: m_kind_criteria)
        break
    default:
        break
    }
}

A: The problem is that you are not giving your "wrapper" views any height, so the controls are being placed outside the bounds of their parent views.
You can confirm this two ways...
1) In your
for (index, sliderName) in sliders.enumerated() {

block, add:
sliderWrapper.backgroundColor = .green

(after creating the sliderWrapper view, of course). When you run the app, you won't see the green background, because sliderWrapper has a height of Zero:

2) And / or add:
sliderWrapper.clipsToBounds = true

and you won't see the controls at all:

To solve this, you can add constraints:
        let sliderWrapper = UIView()
        sliderWrapper.translatesAutoresizingMaskIntoConstraints = false
        sliderWrapper.backgroundColor = .green

        sliderWrapper.addSubview(descLabel)
        sliderWrapper.addSubview(valueLabel)
        sliderWrapper.addSubview(slider)

        // add a topAnchor constraint from the top of descLabel to the top of sliderWrapper
        // center valueLabel vertically to descLabel
        // and a bottomAnchor from the bottom of slider to the bottom of sliderWrapper (negative if you want "padding")
        NSLayoutConstraint.activate([
            descLabel.topAnchor.constraint(equalTo: sliderWrapper.topAnchor, constant: 8.0),
            valueLabel.centerYAnchor.constraint(equalTo: descLabel.centerYAnchor),
            slider.bottomAnchor.constraint(equalTo: sliderWrapper.bottomAnchor, constant: -8.0),
        ])

Now, background is visible... controls are visible... and controls can be interacted with:


text:
Q: Matplotlib transparent overlay & pdf transparency Let's assume I have two numpy arrays (The ones I present are just examples):
import numpy as np
A = np.arange(144).reshape((12, 12))
np.random.shuffle(A)

B = np.ones((12,12))
B[0:10:4,:] = None

I want to plot A using imshow:
import matplotlib.pyplot as mplt
mplt.imshow(A, cmap = mplt.gray())

and overlay B so that the None areas are fully transparent and the one areas have an alpha of (e.g. alpha = 0.3.).
I already tried using something along the lines of:
mplt.imshow(B, cmap = mplt.get_cmap('Reds), alpha = 0.3)

but that does not work. Also tried to use masked arrays to create B, but cannot get my head around it. Any suggestions?
Thanks
EDIT:
I ended up using
my_red_cmap = mplt.cm.Reds
my_red_cmap.set_under(color="white", alpha="0")

which works like a charm (I tested Bill's solution as well, which also works perfectly).

A: If instead of None you use 0's for the transparent colors, you can take your favorite matplotlib colormap and add a transparent color at the beginning of it:
my_red_cmap = mplt.cm.Reds
my_red_cmap.set_under(color="white", alpha="0")

then you can just plot the array B with a global alpha of 0.3 whatever you want, using your custom color map, which will use a transparent white as its first value.

A: You can do the following:
import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt

x = np.arange(100).reshape(10, 10)
y = np.arange(-50, 150, 2).reshape(10, 10)
y[y<x] = -100 # Set bad values

cmap1 = cm.gray
cmap2 = cm.Reds
cmap2.set_under((1, 1, 1, 0))

params = {'interpolation': 'nearest'}
plt.imshow(x, cmap=cmap1, **params)
plt.show()

plt.imshow(y, cmap=cmap2, **params)
plt.show()

plt.imshow(x, cmap=cmap1, **params)
plt.imshow(y, cmap=cmap2, vmin=0, **params) # vmin > -100
plt.show()


text:
Q: DbContext - how do I stop my database from creating new records when I'm updating them? My database keeps creating new records when it should be updating the current one. Razor-Pages project, asp.net 2.2.
What should be happening:

*

*Retrieving email from asp.net Identity user class

*Finding match in table Companies by comparing email == email

*Updating records

*Saving changes

And instead of updating, it creates new records.
public async Task<IActionResult> OnGetAsync()
{
    var user = await _userManager.GetUserAsync(User);
    if (user == null)
    {
        return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
    }

    var email = await _userManager.GetEmailAsync(user);

    var company = _context.Companies.FirstOrDefault(b => b.Email == email);
    Firma = user.Firma;

    return Page();
}

public async Task<IActionResult> OnPostAsync()
{
    var user = await _userManager.GetUserAsync(User);
    if (user == null)
    {
        return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
    }

    var email = await _userManager.GetEmailAsync(user);

    var company = _context.Companies.First(a => a.Email == email);

    company.Navn = Input.Firma;
    company.Postnr = Input.Postnr;
    company.Sted = Input.Sted;
    company.Beskrivelse = Input.Beskrivelse;

    _context.SaveChanges();

    return RedirectToPage();
}

A: _context.Companies.Update(company);

_context.SaveChanges();


text:
Q: jQuery selectors:  $('#ID1, #ID2, #ID3') vs $('1X CLASS')  which is faster? Looking into selector performance between $('#ID1, #ID2, #ID3') vs $('1X CLASS'). Which is faster?

A: Looks like .class is working faster for this case. jQuery might not be going the getElementById route. Chrome and Safari are probably being optimizing with getElementsByClassName.
Tests @ http://jsfiddle.net/mGqyH/4/
Chrome
Chrome http://img339.imageshack.us/img339/5021/chromew.png

Safari
alt text http://img339.imageshack.us/img339/5021/chromew.png

Firefox
Firefox performance http://img94.imageshack.us/img94/1123/firefoxg.png

Document used (modified)

http://www.w3.org/TR/DOM-Level-2-Events/events.html

combined IDs selector
$("#Events, #table-of-contents, #Events-overview, #Events-flow-capture, #Events-EventTarget, #Events-EventListener")

disjoint IDs selector
$("#Events").add("#table-of-contents").add("#Events-overview").add("#Events-flow-capture").add("#Events-EventTarget").add("#Events-EventListener");

class selector
$(".selectMe")

A: Use this instead, if you want performance:
$("#id1").add("#id2").add("#id3")

There's less string parsing to do here. That should be faster than selecting by class name, unless the browser has a native implementation (some do).

A: In general, searching for id's is done by getElementbyId, which is the fastest possible way to select a DOM element. If available, getElementByClass is used to grab a node by class name.
Again, getElementById is the fastest way. Performing getElementById three times against one getElementByClass needs some benchmarking to find out the speed difference.
But if the browser does not support getElementByClass, it's even more slow.

A: Updated http://jsfiddle.net/uD7Qz/1/ with .add method.
.add method is almost as fast as $(.class), on Chrome. On FireFox it's 4x slower then $("#1, #2, #4").
Atleast those were my results.

A: Just as a guess, I'd say selecting by ID is faster, since document.getElementByID() is a built-in function to javascript, while 'getElementByClass()' is something that various custom functions have been built to solve. Ideally too, looking for $('div#id') is going to be faster because it's more specific and allows the search loop to cut out certain paths that have no chance of coming back positive.

A: jQuery selectors work on same principle as that of CSS selectors(generalized statement not an exact fact).And in CSS , id selector are more faster when compared to that of class selector.So $("#myDiv") is more faster than #(".myDivClass").


text:
Q: Help with a step in a derivation in Peskin & Schroeder In page 53 of P&S, they postulate the commutation relations for the annihilation and creation operators of spin 1/2 particles. From there, they start computing the commutation relations of $\psi$ and $\psi^{\dagger}$. But I don't get how they arrive at $$ [a_p^r,a_q^{s\dagger}]u^r(p)u^{\dagger}(q)+[b_{-p}^r,b_{-q}^{s\dagger}]v^r(-p)v^{\dagger}(-q)$$ (I omitted the rest because I think it's obvious).
It seems like they are using that $u$ and $u^{\dagger}$ commute, but it doesn't make sense since one product is a scalar ($uu^{\dagger}$) and the other a matrix ($u^{\dagger}u$). How do they get to the equation I wrote down? I do get the rest of the derivation from there, just not that particular step.
Ps: I know that the operators for spin 1/2 particles anticommute, they just do this as a pedagogical example.


text:
Q: .Net components for Mono Can anybody suggest any stable WinForms .Net components, that are compatible with Mono.
As I know DevExpress and Infragistics still have a lot of Windows specific PInvoke calls which.
UPDATE 1:
I need WinForms .Net components with standart controls(TextBox,Buttons,Checkbox, Tree) which have common Look&Feel and a theme engine. Something similar to DevExpress .Net Winforms components, but with Mono compatibility.

A: When you create a cross-platform (or Linux only) WinForms application, use GTK#.
There aren't many more options.
wxWidgets has a .NET/mono binding as well.

Then, look for custom GTK# controls.
However, this probably requires a rewrite, so why not just write a web-interface ?
e.g. make it a web-application and embed a webserver to listen on port 5000 or 9000.
Then, on start of your application, open the default webbrowser with URL http://localhost:5000


text:
Q: PHP update query with syntax error Can anyone tell me why this doesnt work, and returns syntax error please?
$sql4 = "update apiStreetCheckGeneral
         set (BBAverageSpeed, BBSuperFastBBAvailable, BBCommentary)
             values ('$averagespeed', '$superfast', '$bbcommentary')
         where PostCode='".$values['PostCode']."'";
CustomQuery($sql4);

A: This is your query:
update apiStreetCheckGeneral set (BBAverageSpeed, BBSuperFastBBAvailable, BBCommentary)
     values ('$averagespeed', '$superfast', '$bbcommentary')
     where PostCode='".$values['PostCode'].

I am not aware of update syntax that uses a column list or values.  Set each one individually:
update apiStreetCheckGeneral
     set BBAverageSpeed = '$averagespeed',
         BBSuperFastBBAvailable = '$superfast',
         BBCommentary = '$bbcommentary'
     where PostCode='".$values['PostCode']."'"

You should learn, however, to use parameterized queries especially for update statements.

A: Use query like below
$sql4 = "update apiStreetCheckGeneral
         set BBAverageSpeed = '$averagespeed',
          BBSuperFastBBAvailable = '$superfast',
          BBCommentary = '$bbcommentary'
          where PostCode='".$values['PostCode']."' ";
CustomQuery($sql4);


text:
Q: android - opengl crash on animation Helo. I'm experiencing strange behavior with my app. It crashes on litsview item flip animation with this error:
06-02 17:26:16.748 22310-23383/com.dealy.android A/OpenGLRenderer﹕ Error: Ambient Vertex Buffer overflow!!! used 286, total 284

I don't use any of OpenGL libs or smthing, so it's strange. Also, crash only occurs on Nexus 6 with android 5.1.
The code of list item here:
package com.dealy.android.adapter;

import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.animation.AnimatorSet;
import android.annotation.TargetApi;
import android.content.Context;
import android.location.Location;
import android.os.Build;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.squareup.picasso.Picasso;

import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import database.HelperFactory;
import com.dealy.android.DealyApplication;
import com.dealy.android.R;
import com.dealy.android.util.SimpleAnimationEndListener;
import dto.GeoPoint;
import dto.ImageDTO;
import special.dto.Special;
import venue.dto.Venue;

/**
 * Created by Beyka on 13.01.2015.
 */
public class SpecialAdapter extends BaseAdapter {

    private static final DecimalFormat DEFAULT_DISTANCE_FORMAT = new DecimalFormat("##0.0");

    private final AnimatorSet fbo;
    private final AnimatorSet fbi;

    private Context context;
    private LayoutInflater inflater;

    private List<Special> values;
    private SparseBooleanArray flipArray;

    private GeoPoint lastLocation;

    Tracker t;

    public SpecialAdapter(Context context, List<Special> values, GeoPoint lastLocation) {
        fbo = (AnimatorSet) AnimatorInflater.loadAnimator(context, R.animator.card_flip_right_out);
        fbi = (AnimatorSet)AnimatorInflater.loadAnimator(context, R.animator.card_flip_right_in);

        this.context = context;
        inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        this.values = values;
        flipArray = new SparseBooleanArray();

        this.lastLocation = lastLocation;
    }

    public void setLastLocation(GeoPoint lastLocation) {
        this.lastLocation = lastLocation;

        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return values.size();
    }

    @Override
    public Special getItem(int position) {
        return values.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final Holder holder;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item_special, parent, false);
            holder = new Holder(convertView);
            convertView.setTag(holder);
        } else{
            holder = (Holder)convertView.getTag();
        }

        Special special = getItem(position);

        fillHolder(holder, special, position);

        return convertView;
    }

    private void fillHolder(final Holder holder, Special special, final int position) {
        holder.front.setVisibility(flipArray.get(position, false) ? View.GONE : View.VISIBLE);
        holder.back.setVisibility(!flipArray.get(position, false) ? View.GONE : View.VISIBLE);

        t = ((DealyApplication) context.getApplicationContext()).getTracker(DealyApplication.TrackerName.APP_TRACKER);

        holder.more.setOnClickListener(new View.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onClick(View v) {
                t.send(new HitBuilders.EventBuilder().setCategory("Test Catogory").setAction("Нажатие на подробности").build());

                fbi.setTarget(holder.back);
                fbo.addListener(new SimpleAnimationEndListener() {
                    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        flipArray.put(position, true);

                        holder.front.setVisibility(View.GONE);

                        holder.back.setVisibility(View.VISIBLE);
                        fbi.start();

                    }
                });
                fbo.setTarget(holder.front);
                fbo.start();
            }
        });

        holder.goBack.setOnClickListener(new View.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onClick(View v) {
                t.send(new HitBuilders.EventBuilder().setCategory("Test Catogory").setAction("Нажатие на вернуться").build());

                fbi.setTarget(holder.front);
                fbo.addListener(new SimpleAnimationEndListener() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        flipArray.put(position, false);
                        holder.back.setVisibility(View.GONE);

                        holder.front.setVisibility(View.VISIBLE);

                        fbi.start();

                    }
                });
                fbo.setTarget(holder.back);
                fbo.start();

            }
        });

        holder.backTitle.setText(special.getName());
        holder.description.setText(special.getDescription());

        if(special.getImageLink() == "" || special.getImageLink() == null){
            for(ImageDTO image : special.getImages()){
                if(image.getWidth() >= 640){
                    Picasso.with(context).load("http://app.dev.getdealy.ru/images/" + image.getUrl()).fit().into(holder.logo);;
                }
            }

        }
        else {
            Picasso.with(context).load("http://app.dev.getdealy.ru/images/" + special.getImageLink()).fit().into(holder.logo);
        }

        Venue venue = new Venue();
        try {
            venue = HelperFactory.getHelper().getVenueDAO().getVenueById(special.getVenues().get(0));
        } catch (SQLException e) {
            e.printStackTrace();
        }

        final float[] distanceInMeters = new float[1];
        try {
            Location.distanceBetween(lastLocation.getLat(), lastLocation.getLng(), special.venue.getLat(), special.venue.getLng(), distanceInMeters);
        } catch(NullPointerException e){

        }
        double distanceInKm = distanceInMeters[0] / 1000.0;
        holder.distance.setText(context.getString(R.string.kilometers, DEFAULT_DISTANCE_FORMAT.format(distanceInKm)));
        holder.backDistance.setText(context.getString(R.string.kilometers, DEFAULT_DISTANCE_FORMAT.format(distanceInKm)));

        if(distanceInKm == 0){
            holder.distance.setVisibility(TextView.GONE);
            holder.backDistance.setVisibility(TextView.GONE);
        }

        if(special.venue.getLogoLink() != null) {
            Picasso.with(context).load("http://app.dev.getdealy.ru/images/" + special.venue.getLogoLink()).fit().into(holder.place);
            Picasso.with(context).load("http://app.dev.getdealy.ru/images/" + special.venue.getLogoLink()).fit().into(holder.backPlace);
        }
        else{
                Picasso.with(context).load("http://app.dev.getdealy.ru/images/" + special.venue.getImages().get(0)).fit().into(holder.place);
                Picasso.with(context).load("http://app.dev.getdealy.ru/images/" + special.venue.getImages().get(0)).fit().into(holder.backPlace);
        }

    }

    class Holder {
        @InjectView(R.id.front)
        View front;

        @InjectView(R.id.logoImage)
        ImageView logo;

        @InjectView(R.id.place)
        ImageView place;

        @InjectView(R.id.distanceText)
        TextView distance;

        @InjectView(R.id.more)
        Button more;

        @InjectView(R.id.back)
        View back;

        @InjectView(R.id.goBack)
        Button goBack;

        @InjectView(R.id.backTitle)
        TextView backTitle;

        @InjectView(R.id.backPlace)
        ImageView backPlace;

        @InjectView(R.id.backDistance)
        TextView backDistance;

        @InjectView(R.id.description)
        TextView description;

        @InjectView(R.id.card)
        RelativeLayout card;

        private Holder(View view) {
            ButterKnife.inject(this, view);
        }
    }
}

A: i have resolve this, the reason is : you had open the hardwareAccelerated attribute , you must close it in your manifest.xml like this

    android:hardwareAccelerated = "false"

    ......
    >

This problem is caused by more than 6.0 of Android's system automatically open the default hardware acceleration, but sometime we had no need to used it, Because most of the hardware capacity is still insufficient.
hope can help you!

A: @high sea company `s answer is right.
Thank you!!!
You can try like this:
in AndroidManifest.xml application:
<application android:hardwareAccelerated="false" ...>

in Activity :
getWindow().setFlags(
    WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
    WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);

In layout XML :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:paddingLeft="2dp"
android:layerType="software" //**close hardwareAccelerated**
android:paddingRight="2dp" >

in View:
myView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);


text:
Q: How to get all items that has added action but wasn't deleted I have an Activity table in which user's activity on actions is stored.
There is two type of actions in column type that are required to check:

*

*add_favorite

*remove_favorite
So same object can be added or removed from favorites multiple times so table has records like:

| id | type            | timestamp  | object_id | user  |
|----|-----------------|------------|-----------|-------|
| 1  | add_favorite    | 1584150783 | 4         | user1 |
| 2  | add_favorite    | 1584151341 | 5         | user1 |
| 3  | remove_favorite | 1584161259 | 4         | user1 |
| 4  | add_favorite    | 1584168758 | 4         | user1 |
| 5  | remove_favorite | 1584171635 | 10        | user1 |
| 6  | add_favorite    | 1584174201 | 11        | user1 |
| 7  | remove_favorite | 1584177194 | 5         | user1 |

First I was constructing two queries that was collecting all object_id's with add_favorite actions for the user in array. Then I was filtering this array with another one set of object_id's which had type of action removed_favorite
SELECT object_id FROM activity WHERE user='user1' AND type='add_favorite';
SELECT object_id FROM activity WHERE user='user1' AND type='remove_favorite';

But this is highly ineffective on large number of activities. Please advise me query with LEFT JOIN which would be more effective and will give the end result

A: You could use a subquery like this
SELECT object_id
FROM activity a1
WHERE a1.user = 'user1'
AND a1.type = 'add_favorite'
AND object_id NOT IN (
    SELECT object_id
    FROM activity
    WHERE user = 'user1'
        AND type = 'remove_favorite'
    )

However, I guess you want a list of effectively active (added) favorites
SELECT a1.object_id
FROM activity a1
WHERE a1.user = 'user1'
    AND a1.TIMESTAMP = (
        SELECT MAX(a2.TIMESTAMP)
        FROM activity a2
        WHERE a2.user = a1.user
            AND a1.object_id = a2.object_id
            AND a2.type IN (
                'add_favorite'
                ,'remove_favorite'
                )
        )
    AND a1.type = 'add_favorite'

Here is a demo.

A: You can simplify your query to:
SELECT object_id
FROM activity
WHERE user = 'user1' AND
      type IN ('add_favorite', 'remove_favorite');

Then I would recommend aggregation:
SELECT object_id
FROM activity
WHERE user = 'user1' AND
      type IN ('add_favorite', 'remove_favorite')
GROUP BY object_id
HAVING SUM(type = 'add_favorite') > SUM(type = 'remove_favorite');

This gets the objects that have net more adds than removes.
An alternative is to look at the last action and only choose those that are adds:
SELECT a.object_id
FROM activity a
WHERE a.user = 'user1' AND
      a.timestamp = (SELECT MAX(a2.timestamp)
                     FROM activity a2
                     WHERE a2.user = a.user AND
                           a2.type IN ('add_favorite', 'remove_favorite')
                    ) AND
      a.type = 'add_favorite'

With an index on activity(user, type, timestamp), this probably has better performance.


text:
Q: Correct way to add modified check-command for Nagios I am running Nagios® Core Version 3.5.1 on Ubuntu 14.04.5 LTS. I am adding a slightly different check_http defined as check_http_s. It appears that I can add this to any one of three different files:
a.  /etc/nagios3/conf.d/checkcommands.cfg
b.  /etc/nagios3/global/checkcommands.cfg
c.  /etc/nagios-plugins/config/http.cfg

But it turns out, that Nagios cannot find the new check command unless it is in
         C - /etc/nagios-plugins/config/http.cfg
Is this OK?
What are Files A&B for because it appears to me that they are not being used by Nagios in my case.
Thanks in advance for any guidance.

A: Configuration files are all included from the main nagios.cfg. They are included with the following directives:
cfg_file=
cfg_dir=
So, unfortunately, there isn't any good way to just tell if files are in use - you need to travel down the path of which files are included, and then see if files are included from those files!
cd /path/to/root/nagios/dir
grep -R "cfg_file\|cfg_dir" *

Hope this helps!


text:
Q: Show the selected value when using html.dropdownlistfor I am using
@Html.DropDownListFor(x => x.Selects, new SelectList(Model.Selects, "Value", "Text", Model.Select), "Select"})`

for a dropdown to show the list of US states. The text I am showing is AL Alabama,CA California,NY New York etc....See below
<option value="AL">AL Alabama</option>
<option value="CA">CA California</option>
<option value="NY">NY New York</option>
....

The value attribute has the state abbreviation. What I want to achieve is, when the selection is made by the user the selected value on the UI should show the state abbreviation and not the state name. Currently it is showing abbreviation state name. Can anyone help me?

A: The easiest solution would be to simply use your Value property twice (both as a value of an option and as an inner text):
@Html.DropDownListFor(x => x.Selects,
    new SelectList(Model.Selects, "Value", "Value", Model.Select), "Select"})

In case you would firstly like to show the state name and then only after the selection of a user change it into the state abbrevation you should handle this via Javascript.
To do this via Javascript you should firstly set the id of your drop-down-list and assign appropriate onChange function:
@Html.DropDownListFor(x => x.Selects,
    new SelectList(Model.Selects, "Value", "Text", Model.Select), "Select"},
    , new {@id="selectListId" onchange = "setText(this)"})

Then implement your function:
function setText(sel) {
   var selectedItem = sel.options[sel.selectedIndex];
   selectedItem.text = selectedItem.value;
   //or
   //$("#selectListId option:selected").text(selectedItem.value);
}


text:
Q: c++: is this getInstance() method of my singleton threadsafe? I am currently trying to write a threadsafe singleton (at least in terms of construction and destruction) using boost::mutex. I read that boost mutex can't be initialized statically(I lost the link where I read it, sorry) so to work around that I tried this, if threadsafety for construction and destruction is:
                static T& getInstance()
            {
#ifndef STATIC_VARIABLES_ARE_THREADSAFE
                boost::mutex mutex;
                boost::lock_guard lock(mutex);
#endif
                static T instance;
                return instance;
            }

is that threadsafe, or should I use boost::call_once? Will boost once give me any performance benefit over this approach?
EDIT:
Okay, my first idea was obviously not correct. To clearify the question. Can a boost::mutex safely be initialized statically? Like this:
class Singleton
{
private:
static boost::mutex m_mutex;

public:
static Singleton & getInstance()
{
    boost::lock_guard lock(m_mutex);
    static T instance;
    return instance;
}

};

Is that a working approach or is it in fact not safe to init boost::mutex statically (which is what I read)?
EDIT2:
Ah, that was the link by the way http://uint32t.blogspot.com/2007/12/you-lazy-bastard-part-1.html

A: Since each entry to the function will create its own lock, the lock will be completely useless; any number of threads can enter the function, lock different locks, and start messing with the static data at the same time.
You could create the lock at file (or class static) scope; this would ensure it's created in time, provided that you don't start threads before main(). However, this would also serialize entry to the function even after the static data is initialized.
Why not just define your static data at file (or class static) scope in the first place?

A: GCC provides thread safe initialization of static variables.
So, if you use GCC you do not need to care about proper initialization of static variables

A: You do need to use locking. However, the boost::mutex scheme you propose is broken since you allocate the mutex on the stack and multiple concurrent callers would each get their own mutex.

A: Try to use the Meyers Singleton implementation.
class MySingleton {
public:
  static MySingleton& getInstance() {
    static MySingleton instance;
    return instance;
  }
private:
  MySingleton();
  ~MySingleton();
  MySingleton(const MySingleton&)= delete;
  MySingleton& operator=(const MySingleton&)= delete;

};

MySingleton::MySingleton()= default;
MySingleton::~MySingleton()= default;

// Usage
int main() {
  MySingleton::getInstance();
}

More info...


text:
Q: Finding a node in an XML document by its attribute value I am trying to grab a value from a xml feed, but I am not sure how to get it.
Feed:
 <name>
    <namerecord nameID="0" platformID="1" platEncID="0" langID="0x0">
      Hello World
    </namerecord>
    <namerecord nameID="1" platformID="1" platEncID="0" langID="0x0">
      MyName
    </namerecord>
    <namerecord nameID="6" platformID="1" platEncID="0" langID="0x0">
      Another Record
    </namerecord>
    <namerecord nameID="12" platformID="1" platEncID="0" langID="0x0">
      Another Record Again
    </namerecord>

I am trying to grab the items from that, by target what is the value of nameID. If I target it just by like namerecord[0] its not correct in the way I need it.
I have tried numerous things like:
$test = $xml->name->namerecord->attributes('nameId, '12');

Any suggestions?

A: That's now how you handle XML:
$dom = new DOM();
$dom->load('your xml here');

$xp = new XPath($dom);

$node = $xp->query('//namerecord[@nameID=12]')->item(0);

$nameID = $node->getAttribute('nameID');


text:
Q: Retrieve text alignment from TextRenderInfo in LocationTextExtractionStrategy I've written a LocationTextExtractionStrategy handler to extract the text and graphics in C# from a PDF using iText7. All of the items are being extracted correctly but it appears that some of the text is right-aligned. The bounds of the text are correct but the text should be right-aligned in the bounds which means it appears incorrectly when rendered.
You can see the bounds and text here; the enumerators are supposed to be right-aligned:

I've compared all of the properties of the TextRenderInfo class but can't see how I can determine that the text is right aligned. The properties seem to have the same values for left and right aligned text.
// Automatically called for each chunk of text in the PDF
public void RenderText(TextRenderInfo renderInfo)
{
    // Grab the individual characters
    var chars = renderInfo.GetCharacterRenderInfos().ToList();

    // Grab the first and last character
    var firstChar = chars.First();
    var lastChar = chars.Last();

    // Get the bounding box for the chunk of text
    var bottomLeft = firstChar.GetDescentLine().GetStartPoint();
    var topRight = lastChar.GetAscentLine().GetEndPoint();

    var font = renderInfo.GetFont();
    var fontName = font.GetFontProgram().GetFontNames().GetFontName();

    // How do I know the text alignment?

    var shape = new Shapes.Text(
        $"t{_textId++}",
        new PointF(bottomLeft.Get(Vector.I1), bottomLeft.Get(Vector.I2)),
        new PointF(topRight.Get(Vector.I1), topRight.Get(Vector.I2)))
    {
        Runs = new List<Run>
        {
            new Run(renderInfo.GetText())
            {
                Bold = fontName.Contains("Bold"),
                Italic = fontName.Contains("Italic"),
                Size = renderInfo.GetFontSize()
            }
        }
    };

    _shapes.Add(shape);
}


text:
Q: Conditional Expectation v.s. a new Random Variable I am wondering if the following situation is trivial for you guys. For me, it is not. For the book, it is trivial.
Example: You write a software program over and over, and each time there is probability $p$ that it works correctly, independent of previous attempts. What is the mean and variance of $X$, the number of tries until the program works correctly?
Clearly $X$ has geometric distribution with PMF  $\:\:\:p_X(k)=(1-p)^{k-1}p, k=1,2,...$
Then $E[X]=\sum_{1}^{\infty}k(1-p)^{k-1}p$. We can go ahead and compute this series directly (I did computed it,) or we can use conditioning because we have the following formula
$$E[X]=\sum_{i=}E[X|A_i]P(A_i)$$
where $A_i's$ is a disjoint partition of the sample space. So, let $A_1=\{X=1\}$ and $A_2=\{X>1\}$. Clearly $P(A_1)=p$ and $P(A_2)=1-p$. Then $$E[X]=E[X|X=1]P(X=1)+E[X|X>1]P(X>1)=1\cdot p+(1-p)E[X|X>1].$$
Here is where it got me thinking. In the book, it argues like this. Given that $\{X>1\}$, i.e., the first try fails, we have wasted one try, and we are back to where we start, thus,
$$E[X|X>1]=1+E[X].$$
Even though it does make sense, it is not rigorous, and I had to work it out like this to see why the above equality is true.
$E[X|X>1]=\sum_{k=1}^{\infty}k\frac{P(\{X=k\}\cap \{X>1\})}{P(X>1)}=\sum_{k=2}^{\infty}k\frac{(1-p)^{k-1}p}{1-p}=\sum_{k=2}^{\infty}k(1-p)^{k-2}p=$
$\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:=\sum_{k=1}^{\infty}(k+1)(1-p)^{k-1}p=\sum_{k=1}^{\infty}k(1-p)^{k-1}p+\sum_{k=1}^{\infty}(1-p)^{k-1}p=$
$\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:=E[X]+1$
since $\sum_{k=1}^{\infty}(1-p)^{k-1}p=1.$
Well, I verified it, but I still couldn't see why the book's argument is believable.

A: As remarked both in the question and in the comments, the formula can be verified in multiple ways. I try to give a proof that gives perhaps a simpler intuition.
We can assume that $X=\min\{n\ge 1: Y_n=1\} $
where $(Y_n)_{n\ge 1}$ is a sequence of a i.i.d. Bernoulli random variables with success parameter $p$.
Now, let
$X'=\min\{n\ge 1: Y_{n+1}=1\} $
and observe that
$$
X = X' + 1
$$
provided that $X>1$.
We have
\begin{align}
\mathbb{E}[X|X>1] = \mathbb{E}[X' + 1|B_1=0] = 1+ \mathbb{E}[X'] = 1 + \mathbb{E}[X]
\end{align}
where in the second equality I used that $X'$ does not depend on $B_1$ and in the last I used that $\mathbb{E}[X]=\mathbb{E}[X']$.


text:
Q: python script always give file not found even when file exists ubuntu 20.04 On ubuntu 18.04 everything was working fine but when we upgraded to ubuntu 20.04 our python script:
import os
os.path.exists('/tmp/file.csv')

above code gives False even though the file exists.
I google it and found this by setting fs.protected_regular to 0 but that did nothing. However when I switch to root the script seems to be working. And on the server even the root user returns False.
please help.

A: Please use the correct command. os.path.exists checks for a PATH. Not a file. Use os.path.isfile

*

*os.path.exists() – Returns True if path or directory does exists.

*os.path.isfile() – Returns True if path is File.

*os.path.isdir() – Returns True if path is Directory.

*pathlib.Path.exists() – Returns True if path or directory does exists. (In Python 3.4 and above versions)


text:
Q: Dynamic deserialization of list or object I am calling an API which returns an object if there is a single item and a list of 0 or 2+ elements. I'd like to deserialize all the responses into a list.
I'd like to write a dynamic Deserializer or TypeAdapter which I can just annotate any field which might be a list or object. I am able to write the TypeAdapter for each class, but I can't figure out how to make it dynamic so that I can use the same class for all the keys.
sample inputs:
{ "fruits": [], "vegetables": { "name": "carrot" } }

{ "fruits": { "type": "apple" }, "vegetables": [ { "name": "carrot" }, { "name": "celery" } ] }

{ "fruits": [ { "type": "apple" }, { "type": "banana" } ], "vegetables": [] }

Desired POJOs:
public class FoodResponse {
  @SomeAnnotation
  private List<Fruit> fruits;
  @SomeAnnotation
  private List<Vegetable> vegetables;

}
public class Fruit {
  private String type;
}
public class Vegetable {
  private String name;
}

Do you have any idea how I might write something that can be this dynamic?


text:
Q: Send command to the shell via Makefile I'm building a Makefile to automate the start of docker on osx.
At the end of the start docker requires to launch this command on the shell in order to configure the shell: eval "$(docker-machine env dev)"
The problem is that if I try to run it on the Makefile, this has no effect on the shell.
In fact, if the launch:
make start and then make status I get error from docker.
This is my Makefile:
CURRENT_DIRECTORY := $(shell pwd)

start:
    @sh run.sh -d
    @eval $(docker-machine env dev)

start-compose:
    @docker-compose up -d

clean:
    @docker-compose rm --force

stop:
    @docker-compose stop

shutdown:
    @docker-compose stop
    @docker-machine stop dev

build:
    @docker-compose build

status:
    @docker-compose ps

cli:
    @docker-compose run --rm web bash

log:
    @docker-compose logs web

logall:
    @docker-compose logs

restart:
    @docker-compose stop web
    @docker-compose start web

restartall:
    @docker-compose stop
    @docker-compose start

.PHONY: clean start start-compose stop status shutdown build cli log logall restart restartall

Is there a way to launch the eval "$(docker-machine env dev)" command on the Makefile and that will affect the shell?

A: If I understand the question, you want make to configure a shell with some environment such that when make exits, that environment persists.
What the eval command is doing is changing the current shell, but since you are running it from make, it changes only the subshell created by make, which is then destroyed when the make target that invoke `eval is completed.
Every line make is told to run is actually invoked in a shell it creates. Once the command run from make returns, that shell is gone, along with any changes you made in it.
What you need to do is run your eval command in a shell that is used to invoke the docker command, all in the same subshell. That is, every command that a target runs that needs this environment needs to invoke the eval command first. And you have to run the commands in the same shell, instead of a separate subshell for every line.
The easiest way to do this is to string your commands together with ; so that it first sets the environment, and then runs some docker command:
status:
    eval $$(docker-machine env dev); docker-compose ps

Note the double dollar sign: $ is a special character in make, and you need to escape it as $$ so that the shell sees $.
This is a make-specific version of this answer. So, you can also invoke a script, or us && or anything else you like.
Or, if the docker environment is not configured or changed by make (for example, you don't need to tweak the environment based on make runtime variables), but is predetermined, you run make in a shell that already has the docker environment set. Then each of its subshells will also have the same environment.
There make be some way in the make you are using to collect multiple lines into the same subshell; check your documentation.

A: *

*If you don't have dependencies to track, Make is probably not the right tool.

*Make launches one shell per command (or per rule in some versions), if you need to configure the shell, you'll need to configure each instances.

*It is not possible for a process to modify its parent.  So if you wanted for the Make to modify the shell in which it has been executed, that's not possible without using the same kind of trick as docker.

*As $ is interpreted by Make, to have it passed to the shell it needs to be escaped.

*Here is a structure which could be workable (note that I combine the rules into one command), but again I don't think Make is the right tool for such kind of thing and I know nothing about docker so I may miss something relevant.
start:
    @sh run.sh -d; \
    echo $$(docker-machine env dev) > ./docker-config

start-compose:
    @eval $$(cat ./docker-config); \
    docker-compose up -d

clean:
    @eval $$(cat ./docker-config); \
    docker-compose rm --force

stop:
    @eval $$(cat ./docker-config); \
    docker-compose stop

shutdown:
    @eval $$(cat ./docker-config); \
    docker-compose stop ; \
    docker-machine stop dev

A: I solved with
@eval $$(docker-machine env dev); \
docker-compose stop; \
docker-machine stop dev

in each make command.


text:
Q: Continuos loop until condition is not met Im trying to place the user in a loop if a certain condition is met: if he gets the correct answer, random questions would be generated till the user fails then their score would be added
            System.out.println("You chose easy elimination mode");

            firstNumbereasy = randN.nextInt(9)+2; // new first random number generated
             secondNumbereasy= randN.nextInt(firstNumbereasy - 1); // new second random number generated
            System.out.println("What is " + firstNumbereasy + getRandomOperator()+ secondNumbereasy);
            b = scanner.nextDouble();
            c++;

      while (c==b) {
            c = (int) (firstNumbereasy+secondNumbereasy);
              c = (int) (firstNumbereasy-secondNumbereasy);
              c = (int) (firstNumbereasy*secondNumbereasy);
              c= (int)   (firstNumbereasy/secondNumbereasy);

              firstNumbereasy = randN.nextInt(9)+2; // new first random number generated
                 secondNumbereasy= randN.nextInt(firstNumbereasy - 1); // new second random number generated
                System.out.println("What is " + firstNumbereasy + getRandomOperator()+ secondNumbereasy);
                b = scanner.nextDouble();
                c++;}

Ive even tried using a while loop , but it doesnt loop the user to another random generated question when he meets the condition (c==b)

A: *

*What's up with c?
You've got it incrased after the question, so I assume it was meant to be Score or something.

*It's (c) assigned value AFTER the if.
It should be before the if, so it's never gonna change value from the one before the code frgment shown.

*C is set as an int and you've got clearly possibilities of division

Here's my (quickly made) code for addition only:
    System.out.println("You chose easy elimination mode");

    Scanner scanner = new Scanner(System.in);
    Random ran = new Random();
    int score = 0;
    while(true)
    {
        int c = 0;
        int firstNumbereasy = ran.nextInt(9)+2; // new first random number generated
        int secondNumbereasy= ran.nextInt(firstNumbereasy - 1); // new second random number generated
        System.out.println("What is " + firstNumbereasy +"+" +  secondNumbereasy);
        int b = scanner.nextInt();
        c = firstNumbereasy + secondNumbereasy;

        if (c!=b)
        {
            System.out.println("Score: "+ score);
            break;
        }
        else
        {
            score++;14

        }
    }

You can edit this code into a function that runs at the selection and, instead of set true and break statement use a boolean.


text:
Q: Remove background color from buttons in Listbox (Windows Phone) I have a function connected to a buttonclick in i Listbox. It sets the background color of the selected button. The problem with this is that i only want one button at a time to act as selected. With this solution every button clicked gets the green background... how can i reset the buttons that are not selected to a black background?
private void SettingsChangeRegionButton_Click(object sender, RoutedEventArgs e)
{
    Button clickedButton = sender as Button;
    clickedButton.Background = new SolidColorBrush(Colors.Green);
    RssStream choosenStream = GetRssStreamFromName(clickedButton.Content.ToString());
}

A: If you want a button to be green while it is being pressed you should change the color which is used as the background in the Pressed state.
If you just want to highlight which is the currently selected item in the list(box) then you need to change the styling of the item in the Selected state.
Sorry, if you know this but to pre-empt your next question: You can change a template by selecting an item in the objects and timeline window in blend and selecting "Edit Template" (or "Edit Additional Templates" as appropriate).


text:
Q: function only returns one value multiple times I have this function:
function get_content($text_to_match) {
    $query  = "SELECT * ";
    $query .= "FROM table_name ";
    $query .= "WHERE one_column_name LIKE '%{$text_to_match}%' OR another_column_name LIKE '%{$text_to_match}%'";
    $cont = mysqli_query($connection, $query);
    if($content = mysqli_fetch_assoc($cont)) {
        return $content;
    } else {
        return null;
    }
}

But when I call it like:

      <?php
        for ($i = 1; $i < count(get_content("text_to_match")); $i++) {
          echo '
' .
                 '
' . get_content("text_to_match")["string1"] . '
'.
                 '
' . get_content("text_to_match")["string2"] . '
' .
               '
';
        }
      ?>

I only get the first match in the DB repeated as many times as the number of found items.
Where have I gone wrong?

A: use this code then fetch data properly
 while($content = mysql_fetch_array($cont))
{
   return $content;

 }

A: Your logic is at fault. You are calling get_content function to get all matches for the loop, as well as to get individual elements out of the list. This is:

*

*bad logic - the 2nd use case doesn't make sense

*excessive - you shouldn't need to run a database query just to output an already retrieved result

What you probably want to do is:
foreach (get_content('text_to_match') as $content) {
    echo '
';
    echo '
' . $content['string1']  . '
';
    echo '
' . $content['string2'] . '
';
    echo '
';
}

A: With a few modifications in combination with tips from @Anant and @Unix One's answer, I arrived at this working solution:
Function definition
  function get_content($text_to_match, $multiple=false) {
        $query  = "SELECT * ";
        $query .= "FROM table_name ";
        $query .= "WHERE one_column_name LIKE '%{$text_to_match}%' OR another_column_name LIKE '%{$text_to_match}%'";
        $cont = mysqli_query($connection, $query);
        if ($multiple) {
          $content_array = [];
          while($content = mysqli_fetch_array($cont)) {
            $content_array[] = $content;
          }
          return $content_array;
        } else {
          if($content = mysqli_fetch_assoc($cont)) {
            return $content;
          } else {
            return null;
          }
        }
   }

Function calls
<?php
  /* multiple items */
  foreach(get_content("text_to_match", true) as $content) {
    echo '
' .
           '
' . $content["string1"] . '
' .
           '
' . $content["string2"] . '
' .
         '
';
  }
?>

<?php
  /* one item */
  echo get_content("text_to_match")["string"];
?>


text:
Q: Collapse redundant rows in data table I have a data table in the format:
myTable <- data.table(Col1 = c("A", "A", "A", "B", "B", "B"), Col2 = 1:6)
print(myTable)

   Col1 Col2
1:    A    1
2:    A    2
3:    A    3
4:    B    4
5:    B    5
6:    B    6

I want show only the highest result for each category in Col1, then collapse all others and present their sum in Col2. It should look like this:
print(myTable)

       Col1 Col2
1:        A    3
2:   Others    3
3:        B    6
4:   Others    9

I managed to do it with the following code:
unique <- unique(myTable$Col1)                                  # unique values in Col1
myTable2 <- data.table()                                        # empty data table to populate
for(each in unique){
    temp <- myTable[Col1 == each, ]                             # filter myTable for unique Col1 values
    temp <- temp[order(-Col2)]                                  # order filtered table increasingly
    sumCol2 <- sum(temp$Col2)                                   # sum of values in filtered Col2
    temp <- temp[1, ] # retain only first element
    remSum <- sumCol2 - sum(temp$Col2)                          # remaining sum in Col2 (without first element)
    temp <- rbindlist(list(temp, data.table("Others", remSum))) # rbind first element and remaining elements
    myTable2 <- rbindlist(list(myTable2, temp))                 # populate data table from beginning
}

This works, but I am trying to shorten a very large data table, so it takes forever.
Is there any better way to approach this?
Thanks.
UPDATE: Actually my procedure is a little bit more complicated. I figured I would be able to develop it myself after the basics were mastered but it seems I will need further help instead. I want to display the 5 highest values in Col1, and collapse the others, but some entries in Col1 do not have 5 values; in these case, all entries should be displayed, and no "Others" row should be added.

A: Here the data is split into groups according to the value of Col1 (by = Col1). .N is the index of the last row in the given group, so c(Col2[.N], sum(Col2) - Col2[.N])) gives the last value of Col2, and the sum of Col2 minus the last value. The newly created variables are surrounded by .() because .() is an alias for the list() function when using data.table, and the  created columns need to go in a list.
library(data.table)
setDT(df)

df[, .(Col1 = c(Col1, 'Others'),
       Col2 = c(Col2[.N], sum(Col2) - Col2[.N]))
  , by = Col1][, -1]
#      Col1 Col2
# 1:      A    3
# 2: Others    3
# 3:      B    6
# 4: Others    9

A: If it just a matter of displaying things you could the 'tables' packages :
others <- function(x) sum(x)-last(x)
df %>% tabular(Col1*(last+others) ~ Col2, .)

# Col1        Col2
# A    last   3
#      others 3
# B    last   6
#      others 9

A: do.call(
    rbind, lapply(split(myTable, factor(myTable$Col1)), function(x) rbind(x[which.max(x$Col2),], list("Other", sum(x$Col2[-which.max(x$Col2)]))))
)

#    Col1 Col2
#1:     A    3
#2: Other    3
#3:     B    6
#4: Other    9

A: I did it! I made a new myTable to illustrate. I want to retain only the 4 highest values by category, and collapse the others.
set.seeed(123)
myTable <- data.table(Col1 = c(rep("A", 3), rep("B", 5), rep("C", 4)), Col2 = sample(1:12, 12))
print(myTable)

    Col1 Col2
 1:    A    8
 2:    A    5
 3:    A    2
 4:    B    7
 5:    B   10
 6:    B    9
 7:    B   12
 8:    B   11
 9:    C    4
10:    C    6
11:    C    3
12:    C    1

# set key to Col2, it will sort it increasingly
setkey(myTable, Col2)

# if there are more than 4 entries by Col1 category, will return all information, otherwise will return 4 entries completing with NA
myTable <- myTable[,.(Col2 = Col2[1:max(c(4, .N))]) , by = Col1]

# will print in Col1: 4 entries of Col1 category, then "Other"
# will print in Col2: 4 last entries of Col2 in that category, then the remaining sum
myTable <- myTable[, .(Col1 = c(rep(Col1, 4), "Other"), Col2 = c(Col2[.N-3:0], sum(Col2) - sum(Col2[.N-3:0]))), by = Col1]

# removes rows with NA inserted in first step
myTable <- na.omit(myTable)

# removes rows where Col2 = 0, inserted because that Col1 category had exactly 4    entries
myTable <- myTable[Col2 != 0]

Owooooo!

A: Here's a base R solution and the dplyr equivalent:
res <- aggregate(Col2 ~.,transform(
  myTable, Col0 = replace(Col1,duplicated(Col1,fromLast = TRUE), "Other")), sum)
res[order(res$Col1),-1]
#    Col0 Col2
# 1     A    3
# 3 Other    3
# 2     B    6
# 4 Other    9

myTable %>%
  group_by(Col0= Col1, Col1= replace(Col1,duplicated(Col1,fromLast = TRUE),"Other")) %>%
  summarize_at("Col2",sum) %>%
  ungroup %>%
  select(-1)
# # A tibble: 4 x 2
#   Col1   Col2
#   <chr> <int>
# 1 A         3
# 2 Other     3
# 3 B         6
# 4 Other     9


text:
Q: type A is not assignable to type B with typescript 2.8 conditional types this is actually a followup on typescript 2.8 Exclude: possible to supercharge the 'partition' type? -- I'm having issues introducing conditional types in my code.
Note that conditional types are new with typescript 2.8, so currently this must be built with typescript 2.8rc.
I've reduced my current issue to this pretty small test case:
export class Option<T> {
    toVector(): Vector<T> {
        return <any>undefined;
    }
}

interface Seq<T> {
    tail(): Option<Seq<T>>;
}

class Vector<T> implements Seq<T> {

    tail(): Option<Vector<T>> {
        return <any>undefined;
    }

     // the next line breaks the compilation
    partition2<U extends T>(predicate:(v:T)=>v is U): [Vector<U>,Vector<Exclude<T,U>>];
    partition2(predicate:(x:T)=>boolean): [Vector<T>,Vector<T>];
    partition2<U extends T>(predicate:(v:T)=>boolean): [Vector<U>,Vector<any>] {
        return <any>undefined;
    }
}

The new line is the first overload for partition2. If you comment it, all builds fine.
If you compile this with --strict, it fails with a rather baffling build error:
t.ts(13,5): error TS2416: Property 'tail' in type 'Vector<T>' is not assignable to the same property in base type 'Seq<T>'.
  Type '() => Option<Vector<T>>' is not assignable to type '() => Option<Seq<T>>'.
    Type 'Option<Vector<T>>' is not assignable to type 'Option<Seq<T>>'.
      Types of property 'toVector' are incompatible.
        Type '() => Vector<Vector<T>>' is not assignable to type '() => Vector<Seq<T>>'.
          Type 'Vector<Vector<T>>' is not assignable to type 'Vector<Seq<T>>'.
            Types of property 'tail' are incompatible.
              Type '() => Option<Vector<Vector<T>>>' is not assignable to type '() => Option<Vector<Seq<T>>>'.
                Type 'Option<Vector<Vector<T>>>' is not assignable to type 'Option<Vector<Seq<T>>>'.
                  Types of property 'toVector' are incompatible.
                    Type '() => Vector<Vector<Vector<T>>>' is not assignable to type '() => Vector<Vector<Seq<T>>>'.
                      Type 'Vector<Vector<Vector<T>>>' is not assignable to type 'Vector<Vector<Seq<T>>>'.
                        Types of property 'tail' are incompatible.
                          Type '() => Option<Vector<Vector<Vector<T>>>>' is not assignable to type '() => Option<Vector<Vector<Seq<T>>>>'.
                            Type 'Option<Vector<Vector<Vector<T>>>>' is not assignable to type 'Option<Vector<Vector<Seq<T>>>>'.
                              Types of property 'toVector' are incompatible.
                                Type '() => Vector<Vector<Vector<Vector<T>>>>' is not assignable to type '() => Vector<Vector<Vector<Seq<T>>>>'.
                                  Type 'Vector<Vector<Vector<Vector<T>>>>' is not assignable to type 'Vector<Vector<Vector<Seq<T>>>>'.
                                    Types of property 'tail' are incompatible.
                                      Type '() => Option<Vector<Vector<Vector<Vector<T>>>>>' is not assignable to type '() => Option<Vector<Vector<Vector<Seq<T>>>>>'.
                                        Type 'Option<Vector<Vector<Vector<Vector<T>>>>>' is not assignable to type 'Option<Vector<Vector<Vector<Seq<T>>>>>'.
                                          Types of property 'toVector' are incompatible.
                                            Type '() => Vector<Vector<Vector<Vector<Vector<T>>>>>' is not assignable to type '() => Vector<Vector<Vector<Vector<Seq<T>>>>>'.
                                              Type 'Vector<Vector<Vector<Vector<Vector<T>>>>>' is not assignable to type 'Vector<Vector<Vector<Vector<Seq<T>>>>>'.
                                                Type 'Vector<Vector<Vector<Seq<T>>>>' is not assignable to type 'Vector<Vector<Vector<Vector<T>>>>'.

I don't really know what to do to make this work :-(

A: As I mentioned in comments, this looks like a compiler bug (or at least a design limitation).  The minimal reproduction I can find looks like this:
interface A<T> {
    bat: B<A<T>>;
}

interface B<T> extends A<T> {
    bat: B<B<T>>;
    boom: true
}

Everything's okay here.  All the type parameters are in covariant positions, which means that if Y is a subtype of X, then A<Y> is a subtype of A<X>, and B<Y> is a subtype of B<X>.  And since B<T> is a subtype of A<T>, you can deduce that, specifically, B<B<T>> is a subtype of B<A<T>>.  Therefore it is fine that the bat property of B narrows B<A<T>> to B<B<T>>.

Now watch what happens when we add a conditional type (that doesn't get immediately evaluated) to B:
interface A<T> {
    bat: B<A<T>>;
}
interface B<T> extends A<T> {
//        ^ error
// Interface 'B<T>' incorrectly extends interface 'A<T>'.
    bat: B<B<T>>;

    boom: T extends any ? true : true
}

It explodes.  boom will undoubtedly still be of type true, but somehow the deferred conditional type is causing trouble.  From the error, it's clear that the compiler is chasing down whether B<T> is compatible with A<T> by checking whether B<B<T>> is compatible with B<A<T>> by checking whether B<B<B<T>>> is compatible with B<B<A<T>>> by... uh oh.
So there's some kind of infinite regress in the type checker which bails out early... that's good, since otherwise the compiler would just hang.  But when it bails out it decides that B<T> is not compatible with A<T>, which is bad for us (although a rule like "bail out with success" is probably bad too).

So, my suggestion is to do what you did and file the issue in GitHub.  We'll see what they say about it there.
I'm not sure if there are any really easy workarounds.  I'll edit this answer if I find one.
Good luck!

A: The problem is that Seq<T>.tail returns Option<Seq<T>> while Vector<T>.tail returns Option<Vector<T>>. These two types are not compatible, as the compiler to verbosely tells us. The simplest solution, is to change Seq<T> to return an Option of the same type as the current type, whatever that type may be. This means that the implementation of tail in Vector<T> will return Option<Vector<T>> as expected, but will be compatible with the definition of tail in Seq. We can do this using the this type:
export class Option<T> {
    toVector(): Vector<T> {
        return <any>undefined;
    }
}

interface Seq<T> {
    tail(): Option<this>;
}

class Vector<T> implements Seq<T> {

    tail(): Option<this> {
        return <any>undefined;
    }

    // the next line breaks the compilation
    partition2<U extends T>(predicate:(v:T)=>v is U): [Vector<U>,Vector<Exclude<T,U>>];
    partition2(predicate:(x:T)=>boolean): [Vector<T>,Vector<T>];
    partition2<U extends T>(predicate:(v:T)=>boolean): [Vector<U>,Vector<any>] {
        return <any>undefined;
    }
}

declare var v: Vector<number>;
var d = v.tail().toVector() // will be Vector<Vector<number>>


text:
Q: microk8s cann't add windows worker node Microk8s 1.26.0
Master node - ubuntu 20.04.
After adding a windows worker node (Windows Server 2019 version 2004) to microk8s cluster with this guide:
https://microk8s.io/docs/add-a-windows-worker-node-to-microk8s
Node doesn't come up on the cluster (command microk8s kubectl get no -o wide doesn't show the windows worker node).
But kubectl works from windows worker node and I can manage cluster from windows worker node. What have I done wrong?
Calico-node.log from windows node has the following lines:
2023-01-17 09:42:32.122 [WARNING][5656] startup/node.go 74: Operation Create is not supported on Node type
2023-01-17 09:42:32.123 [ERROR][5656] startup/startup.go 201: Unable to set node resource configuration error=operation Create is not supported on Node(k8s-windows1)
2023-01-17 09:42:32.123 [WARNING][5656] startup/utils.go 49: Terminating


text:
Q: Making the SocketHandler to log in a file in python I was looking at the python SocketHandler example for how to Sending and receiving logging events across a network. All I want is to make the logger log to a file and not use StreamHandler. After looking at the code I can't find where I need to make the changes to log to a file. Can someone please tell me how i can achieve that?
If you find this trivial, I do apologize.
Thank you in advance.

A: After a lot of searching i have found an example on the internet that is close to what I was looking. You can find the example here : http://code.activestate.com/recipes/577025-loggingwebmonitor-a-central-logging-server-and-mon/.
Sorry again for all the trouble.


text:
Q: How to center boxes using Flexbox? I'm creating a local webpage but have run in to some problems - I'm trying to center my boxes, but nothing I have tried works.
I've got 2 sections - the first one is slightly aligned to the right, while the second is sligthly aligned to the left (have only pasted the code of the first section).
I have tried to use margin: auto and a lot of other things I don't remember, as I have tried to fix this problem for some time.

Services

some text

some text

some text

some text

some text

some text

some text

some text

some text

some text

.services {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  height: 420px;
  border-top: 5px solid hsla(134, 97%, 14%);
  flex-wrap: wrap;
  }

/* Box titles */

.heading {
  display: inline;
  -webkit-box-pack: start;
  -ms-flex-pack: start;
  justify-content: flex-start;
  -ms-flex-item-align: start;
  align-self: flex-start;
  position: relative;
  color: hsl(134, 97%, 14%);
  float: left;
  top: 20px;
  left: 150px;
}

.box {
  display: block;
  -ms-flex-pack: distribute;
  justify-content: space-around;
  height: 200px;
  width: 190px;
  border: 3px solid hsl(356, 97%, 29%);
  margin: 75px  40px;
  padding: 15px 15px;
  border-radius: 10px;
  color: hsl(134, 97%, 14%);
}

.box h3, .box p {
  text-align: center;
  margin-top: 10px;
}

.service-icon {
  text-align: center;
}

.service-icon i {
  font-size: 30px; line-height: normal;
}

A: The heading div is a child of the div class="services" which is "looping" the all the child elements out.
I adjusted the markup a bit.
Moved the heading out of the services div and removed the float property aswell.
Finally I gave the border to the .main-container class instead.
Did this solve your problem? :)

.main-container {
   border-top: 5px solid hsla(134, 97%, 14%);
}

.services {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  height: 420px;

  flex-wrap: wrap;
  }

/* Box titles */

.heading {
  display: inline;
  -webkit-box-pack: start;
  -ms-flex-pack: start;
  justify-content: flex-start;
  -ms-flex-item-align: start;
  align-self: flex-start;
  position: relative;
  color: hsl(134, 97%, 14%);
  top: 20px;
  left: 150px;
}

.box {
  display: block;
  -ms-flex-pack: distribute;
  justify-content: space-around;
  height: 200px;
  width: 190px;
  border: 3px solid hsl(356, 97%, 29%);
  margin: 75px  40px;
  padding: 15px 15px;
  border-radius: 10px;
  color: hsl(134, 97%, 14%);
}

.box h3, .box p {
  text-align: center;
  margin-top: 10px;
}

.service-icon {
  text-align: center;
}

.service-icon i {
  font-size: 30px; line-height: normal;
}

Services

some text

some text

some text

some text

some text

some text

some text

some text

some text

some text

JSFiddle example


text:
Q: Relation between decay probability and the energy of particle Is there any way to find the energy of a particle through its decay probability?

A: No.
If a particle can decay, it eventually will. The quantity of interest is its lifetime (or half-life, if you'd prefer; it is longer by a factor of about 1.4). The lifetime of an unstable particle is related to its "width" $\Gamma$ which is a quantity with units of energy:
$$
\tau = \frac{\hbar}{\Gamma}
$$
So, if you know the lifetime of the particle, you can find its width. This does not, however, tell you the energy (or equivalently mass) of the particle.
There is a sense in which the mass and width are two components of the same quantity (which might be guessed from the fact that they have the same units):
$$
M + i \Gamma
$$
This combined complex quantity shows up in quantum field theory. When computing the amplitude for a field excitation (i.e. particle) to travel a time interval $t$, it shows up in an exponential term
$$
e^{i(M + i \Gamma)t} = e^{iMt} e^{-\Gamma t}
$$
So, the real component (mass) determines the "frequency" at which the field excitation oscillates (and thus the energy), while the imaginary component (decay width) dampens the excitation, giving it a finite lifetime. Measuring the lifetime of the particle only gives you access to $\Gamma$, and not the mass $M$.
Here is a list (wish I could make a table) that illustrates this point, somewhat:

*

*Top quark has lifetime $2.5$ to $5 \times 10^{-25}$ s, mass $173.07$ GeV

*W boson has a similar lifetime $3.2 \times 10^{-25}$ s, mass $80.4$ GeV

*Iron has a half-life of $ > 10^{22}$ years, mass about $52$ GeV

*The neutron has a lifetime of about $12$ minutes, mass about $1$ GeV

*The proton has an infinite lifetime, mass about $1$ GeV

*Tritium has a half-life of $12$ years, mass about $3$ GeV

It's evident that there is no pattern in which the mass of the particle is related directly to its lifetime.

A: It depends on which energy (total, kinetic?) and which decay probability (at rest, the effective measured one?) you are talking about, and also on other information you may be in the possession of.
There is an influence of speed (which is related to kinetic energy) on decay probability per unit of time, due to relativistic effects. So if you know the lifetime at rest, and the effective lifetime you measure, it is possible to deduce the speed the particles are travelling at. If you know the rest mass of the particle, it is possible to compute the kinetic energy given this speed (and then also the total energy if you want to).
Furthermore more massive particles decay more rapidly, all other things being equal. If you know all (or at least the most important) interactions and decay channels relevant for the particle under consideration, it is possible to compute the lifetime, and the result will be a function of the mass (i.e. the "rest energy"). For example, the top and charm quark interact and decay in the same way, and the top decays much more quickly due to its greater mass.