text:
Q: No postback after user confrim in jquery dialog box I am newsiest on jQuery. I need to show the  dialog box to get the user response. If the use click confirm, I need to update the database on sever. I found the example jQuery dialog Confirm-JSFiddle and followed the code. However, after the user click confirm, it is not postback to server. Would someone tell me how to fix it.
There is my jQuery script code:
           $(document).ready(function() {
               $("#dialog-confirm").dialog({
                   autoOpen: false,
                   modal: true
               });
           });

           $(function() {

               $("#dialog-confirm").dialog({
                   autoOpen: false,
                   modal: true,
                   buttons : {
                       "Confirm" : function() {
                           $(this).dialog("close");
                           return true;
                       },
                       "Cancel" : function() {
                           $(this).dialog("close");
                           return false;
                       }
                   }
               });

               $("#Button1").on("click", function(e) {
                   e.preventDefault();
                   $("#dialog-confirm").dialog("open");
               });

           });

There is the code on vb.net
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim i As Integer = 0
End Sub

There is the button on aspx page
  <asp:button id="Button1" runat="server"  text="test" visible="true" />

A: You're just need one step to do postback by using appendTo function to bind with target form:
$("#Button1").on("click", function(e) {
    e.preventDefault();
    $("#dialog-confirm").dialog("open");
    $("#dialog-confirm").parent().appendTo($("form:first"));
});

<asp:Button id="Button1" runat="server"  text="test" visible="true" OnClick="Button1_Click" />

Of course, if you're using dynamic client ID (without ClientIDMode="Static" attribute at asp:Button), you need to use ClientID instead of button's server ID:
$("#<%= Button1.ClientID %>").on("click", function(e) {
    e.preventDefault();
    $("#dialog-confirm").dialog("open");
    $("#dialog-confirm").parent().appendTo($("form:first"));
});

Or you can embed appendTo into dialog setting (with jQuery 1.10 and above):
$("#dialog-confirm").dialog({
    autoOpen: false,
    modal: true,
    buttons : {
        "Confirm" : function() {
            $(this).dialog("close");
            return true;
        },
        "Cancel" : function() {
            $(this).dialog("close");
            return false;
        }
    },
    appendTo: "form" // append this setting
});

If appendTo doesn't work with your page, try __doPostBack method (but not guaranteed to work with all browsers):
__doPostBack('<%= Button1.UniqueID %>', '');

Similar issues:
jQuery UI Dialog with ASP.NET button postback
jQuery modal form dialog postback problems


text:
Q: Using ES6 Symbols with typescript I am trying to run this simple line of code —
let FUNJECTOR_KEY = Symbol.for('funjector')

But I keep getting the error —  Cannot find name 'Symbol'.
I am new to typescript, so I am not sure if I need to include something?
In my case I don't want to use a poly fill as explained here — Using es-6 symbols in typescript

A: TypeScript compiler transpiles TS into JS. TSC cannot find the declaration for Symbol in es5 mode. So your error is purely in compile-time. You don't need polyfill for runtime.
To address this, you can either change your compiling target to es6, so that Symbol is defined in standard library. Or you can manually add the definition (source).
declare class Symbol {
    /** Returns a string representation of an object. */
    toString(): string;

    /** Returns the primitive value of the specified object. */
    valueOf(): Object;

    /**
      * Returns a new unique Symbol value.
      * @param  description Description of the new Symbol object.
      */
    constructor(description?: string);

    /**
    * Returns a Symbol object from the global symbol registry matching the given key if found.
    * Otherwise, returns a new symbol with this key.
    * @param key key to search for.
    */
    static for(key: string): Symbol;

    /**
      * Returns a key from the global symbol registry matching the given Symbol if found.
      * Otherwise, returns a undefined.
      * @param sym Symbol to find the key for.
      */
    static keyFor(sym: Symbol): string;
}

// Well-known Symbols
declare module Symbol {
    /**
      * A method that determines if a constructor object recognizes an object as one of the
      * constructor's instances.Called by the semantics of the instanceof operator.
      */
    const hasInstance: Symbol;

    /**
      * A Boolean value that if true indicates that an object should be flatten to its array
      * elements by Array.prototype.concat.
      */
    const isConcatSpreadable: Symbol;

    /**
      * A Boolean value that if true indicates that an object may be used as a regular expression.
      */
    const isRegExp: Symbol;

    /**
      * A method that returns the default iterator for an object.Called by the semantics of the
      * for-of statement.
      */
    const iterator: Symbol;

    /**
      * A method that converts an object to a corresponding primitive value.Called by the
      * ToPrimitive abstract operation.
      */
    const toPrimitive: Symbol;

    /**
      * A String value that is used in the creation of the default string description of an object.
      * Called by the built- in method Object.prototype.toString.
      */
    const toStringTag: Symbol;

    /**
      * An Object whose own property names are property names that are excluded from the with
      * environment bindings of the associated objects.
      */
    const unscopables: Symbol;
}

Caveat:
  Some type checking does not work on symbol. For example, you cannot declare a property computed to symbol on interface.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Scrambling and descrambling javascript array with salt So i made a javascript string scrambler with md5.
var MD5 = function(d){var r = M(V(Y(X(d),8*d.length)));return r.toLowerCase()};function M(d){for(var _,m="0123456789ABCDEF",f="",r=0;r<d.length;r++)_=d.charCodeAt(r),f+=m.charAt(_>>>4&15)+m.charAt(15&_);return f}function X(d){for(var _=Array(d.length>>2),m=0;m<_.length;m++)_[m]=0;for(m=0;m<8*d.length;m+=8)_[m>>5]|=(255&d.charCodeAt(m/8))<<m%32;return _}function V(d){for(var _="",m=0;m<32*d.length;m+=8)_+=String.fromCharCode(d[m>>5]>>>m%32&255);return _}function Y(d,_){d[_>>5]|=128<<_%32,d[14+(_+64>>>9<<4)]=_;for(var m=1732584193,f=-271733879,r=-1732584194,i=271733878,n=0;n<d.length;n+=16){var h=m,t=f,g=r,e=i;f=md5_ii(f=md5_ii(f=md5_ii(f=md5_ii(f=md5_hh(f=md5_hh(f=md5_hh(f=md5_hh(f=md5_gg(f=md5_gg(f=md5_gg(f=md5_gg(f=md5_ff(f=md5_ff(f=md5_ff(f=md5_ff(f,r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+0],7,-680876936),f,r,d[n+1],12,-389564586),m,f,d[n+2],17,606105819),i,m,d[n+3],22,-1044525330),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+4],7,-176418897),f,r,d[n+5],12,1200080426),m,f,d[n+6],17,-1473231341),i,m,d[n+7],22,-45705983),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+8],7,1770035416),f,r,d[n+9],12,-1958414417),m,f,d[n+10],17,-42063),i,m,d[n+11],22,-1990404162),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+12],7,1804603682),f,r,d[n+13],12,-40341101),m,f,d[n+14],17,-1502002290),i,m,d[n+15],22,1236535329),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+1],5,-165796510),f,r,d[n+6],9,-1069501632),m,f,d[n+11],14,643717713),i,m,d[n+0],20,-373897302),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+5],5,-701558691),f,r,d[n+10],9,38016083),m,f,d[n+15],14,-660478335),i,m,d[n+4],20,-405537848),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+9],5,568446438),f,r,d[n+14],9,-1019803690),m,f,d[n+3],14,-187363961),i,m,d[n+8],20,1163531501),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+13],5,-1444681467),f,r,d[n+2],9,-51403784),m,f,d[n+7],14,1735328473),i,m,d[n+12],20,-1926607734),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+5],4,-378558),f,r,d[n+8],11,-2022574463),m,f,d[n+11],16,1839030562),i,m,d[n+14],23,-35309556),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+1],4,-1530992060),f,r,d[n+4],11,1272893353),m,f,d[n+7],16,-155497632),i,m,d[n+10],23,-1094730640),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+13],4,681279174),f,r,d[n+0],11,-358537222),m,f,d[n+3],16,-722521979),i,m,d[n+6],23,76029189),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+9],4,-640364487),f,r,d[n+12],11,-421815835),m,f,d[n+15],16,530742520),i,m,d[n+2],23,-995338651),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+0],6,-198630844),f,r,d[n+7],10,1126891415),m,f,d[n+14],15,-1416354905),i,m,d[n+5],21,-57434055),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+12],6,1700485571),f,r,d[n+3],10,-1894986606),m,f,d[n+10],15,-1051523),i,m,d[n+1],21,-2054922799),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+8],6,1873313359),f,r,d[n+15],10,-30611744),m,f,d[n+6],15,-1560198380),i,m,d[n+13],21,1309151649),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+4],6,-145523070),f,r,d[n+11],10,-1120210379),m,f,d[n+2],15,718787259),i,m,d[n+9],21,-343485551),m=safe_add(m,h),f=safe_add(f,t),r=safe_add(r,g),i=safe_add(i,e)}return Array(m,f,r,i)}function md5_cmn(d,_,m,f,r,i){return safe_add(bit_rol(safe_add(safe_add(_,d),safe_add(f,i)),r),m)}function md5_ff(d,_,m,f,r,i,n){return md5_cmn(_&m|~_&f,d,_,r,i,n)}function md5_gg(d,_,m,f,r,i,n){return md5_cmn(_&f|m&~f,d,_,r,i,n)}function md5_hh(d,_,m,f,r,i,n){return md5_cmn(_^m^f,d,_,r,i,n)}function md5_ii(d,_,m,f,r,i,n){return md5_cmn(m^(_|~f),d,_,r,i,n)}function safe_add(d,_){var m=(65535&d)+(65535&_);return(d>>16)+(_>>16)+(m>>16)<<16|65535&m}function bit_rol(d,_){return d<<_|d>>>32-_}

var hex = {
    a: 10,
    b: 11,
    c: 13,
    d: 14,
    e: 15,
    f: 16
}

function scrambleText(text, salt) {
    if(text.length > 32) throw "No more than 32 chars.";

    var strs = text.split("");
    var final = "";

    var hash = MD5(salt);
    var hashlength = hash.length, i = 0;

    while(i < hashlength) {
        if(!strs.length) break;
        var num = (hex[hash[i]] || parseInt(hash[i])) * 2 % strs.length;
        final += strs[num];
        strs.splice(num, 1);
        ++i;
    }
    return final
}

I can scramble strings but how do I unscramble the scrambled text assuming I know the salt?
I tried an attempt but it's not doing a good job
function unscrambleText(text, salt) {
    var strs = text.split("");

    var hash = MD5(salt);
    var hashlength = hash.length, i = strs.length - 1, c = 0;;

    var final = [];

    while(i >= 0) {
        var num = (hex[hash[i]] || parseInt(hash[i])) * 2 % (strs.length - i);
        final[num] = strs[c];

        final += strs[num];
        strs.splice(num, 1);
        --i;
        ++c;
    }
    return final
}

Can you guys help me solve this problem? I have been trying for hours.
I take the md5 of the string called "salt" then use it as a reference to scramble the string. I only use strings to simplify the problem. In my actual code, I have an array of image datas that I want to scramble, then be able to descramble it
example of image

A: Here's a silly script to scramble/unscramble text.
The hash function is from here: Simple (non-secure) hash function for JavaScript? Apparently, it's a JavaScript version of a Java hash function.
The script takes the "salt", hashes it, and uses each character in the hash as an offset to shift the letters up or down the ascii table. So it's essentially ROT n where n is one of the values of the hashed salt. "Rotten" is probably a pretty good description of this scramble function :D.

const hash = (str) =>
  str.split("").reduce((hash, char) => {
    hash = (hash << 5) - hash + char.charCodeAt(0);
    return hash & hash;
  }, 0);

const offset = (num, i) =>
  parseInt(num.toString().charAt(i % num.toString().length));

const scramble = (st, sa, d = 1) =>
  st
    .split("")
    .map((c, i) => String.fromCharCode(c.charCodeAt(0) + offset(sa, i) * d))
    .join("");

const unscramble = (str, salt) => scramble(str, salt, -1);

const salt = "This is my salt";
const str = "My text to 'scramble'.";

const scram = scramble(str, hash(salt));
const unscram = unscramble(scram, hash(salt));

console.log("scrambled:", scram);
console.log("unscrambled:", unscram);


text:
Q: How do I disable this red warning appearing in every new conversation in iMessage? Every time I get a text-message from a new number, I get this big, red message:

WARNING: Apple will never ask you to open Terminal or execute a command on your Mac, click a link, visit a website, send or change your credentials, send or reply to an e-mail or text message, call someone, receive a call, or download and run an application on your phone or your Mac. If such a message claims to be from Apple and asks you to write back or take any similar action, it is a phishing message designed to compromise your account. Do not reply and immediately tap below to report it. If you are unsure, stop and contact the IS&T HelpLine before doing anything else.

Notably, there's no where to 'tap below' under the message; and I have no idea what the "IS&T HelpLine" is.
How do I disable this? I'd almost think it were some sort of reverse-psychology phishing worm, because I'm very sure this isn't default iMessage behaviour … except that I can't think of a way that this behaviour benefits a hostile actor? -_-

A: Turns out that this is Apple internal messaging, intended for employees.
It appears that, if the machine has a directory named AppleInternal in the root directory, certain Apple-employee-specific features of the OS — including the above one — are silently enabled, without explanation.

I've no idea how this happened to my machine, but I rm -rf'd /AppleInternal, rebooted Messages.app, and the message has stopped appearing.


text:
Q: using curl to get a json output and struggling to make that output into a pandas dataframe Using the pandas json_normalise function I'm given this - raise NotImplementedError. Using DataFrame.from_dict(swaps, orient='columns') I'm given - ValueError: DataFrame constructor not properly called!
from subprocess import run
import pandas as pd

#using curl and subprocesses
swaps = run('curl --location --request POST https://www.rmb.co.za/rates-service/rates/historical \
    --form productType="Swaps" \
    --form top="13"', shell=True)

Is there something I'm missing?

A: You can use subprocess.run and try to capture the text, convert it to JSON and then to a DataFrame.
Or you can use requests to make your life a lot easier:
import requests

# This is equivalent to your curl command
response = requests.post("https://www.rmb.co.za/rates-service/rates/historical", data={
    "productType": "Swaps",
    "top": "13"
})
# Raise an exception if the request did not succeed
response.raise_for_status()

df = pd.DataFrame(response.json())


text:
Q: Многопоточность Java - блок if Всем привет, вопрос такой, можно ли избавиться от блока if в данном случае, чтоб выводило с такими же таймингами?
public class AffableThread extends Thread {
private final Object object;

AffableThread(String name, Object object) {
    this.setName(name);
    this.object = object;
}

@Override
public void run() {
    synchronized (object) {
        while (true) {
            System.out.println(getName());

                try {
                    if(getName().equals("Понг")) {
                        Thread.sleep(5000);
                    } else {
                        Thread.sleep(1000);
                    }
                } catch (InterruptedException interruptedException) {

                }

            object.notify();

            try {
                object.wait();
            } catch (InterruptedException e) {}

        }
    }
}
}

Main
public class Main {
    public static void main(String[] args) {
        Object object = new Object();
        AffableThread thread1 = new AffableThread("Пинг", object);
        AffableThread thread2 = new AffableThread("Понг", object);
        thread1.start();
        thread2.start();
    }
}

A: Избавится можно разными способами.
Я предложу такой.
public class AffableThread extends Thread {
private final Object object;
private long delay;

AffableThread(String name, Object object) {
    this.setName(name);
    this.object = object;
    this.delay = name.equals("Понг") ? 5000 : 1000;
}

@Override
public void run() {
    synchronized (object) {
        while (true) {
            System.out.println(getName());

                try {
                    Thread.sleep(this.delay);
                } catch (InterruptedException interruptedException) {

                }

            object.notify();

            try {
                object.wait();
            } catch (InterruptedException e) {}

        }
    }
}
}


text:
Q: Constructing IRI from prefix and data in JSON-LD I have a problem to construct IRI for the object using a prefix and a data value when converting  non-edited JSON data into JSON-LD. The example code I have running is:
{
    "@context" :
    { "prefix" : "http://www.gerastree.at/",
      "rdfs" : "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
      "@vocab" : "http://example.com/" ,
      "load" : "prefix:load"
       "items" : "prefix:item"

    },
    "@type" : "tree",
    "@id" : "prefix:t1" ,
    "items" :
    [
        { "@id" : "prefix:t2",
          "@type" : "item",
          "load" : "some111"
         },
        { "@id" : "prefix:t3",
          "@type" : "item",
          "load" : "some2222"
         }
    ]
}

but when I change the @id values from "prefix:t1" to the plain data values I have in the original JSON (i.e. to just "t1", "t2" and "t3") the objects are not dealt with anymore.
The code which is not proper JSON-LD (at least not read by riot)
{
    "@context" :
    { "prefix" : "http://www.gerastree.at/",
      "rdfs" : "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
       "@vocab" : "http://example.com/" ,
       "load" : "prefix:load"
       "items" : "prefix:item"

    },
    "@type" : "tree",
    "@id" : "t1" ,
    "items" :
    [
        { "@id" : "t2",
          "@type" : "item",
          "load" : "some111"
         },
        { "@id" : "t3",
          "@type" : "item",
          "load" : "some2222"
         }
    ]
}

The value "t1" etc. are unique and I would like to use them with a prefix as IRI to link the data with other data. Is there a way to produce the IRI with some addition to the context without changing the program which produces the JSON data or edit the file.
I found a solution (based on the solution of Json-LD > Define a "person" for easy reuse as values on different keys for WebPage schema) but do not understand why it works.
{
    "@context" :
    { "prefix" : "http://www.gerastree.at/",
      "rdfs" : "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
       "@base" : "http://example.com/" ,
      "load" : "prefix:load",
     "items" : "prefix:item"

    },
    "@type" : "tree",
    "@id" : "t1" ,
    "items" :
    [
        { "@id" : "t2",
          "@type" : "item",
          "load" : "some111"
         },
        { "@id" : "t3",
          "@type" : "item",
          "load" : "some2222"
         }
    ]
}

I do not think this is a duplicate of Any way to specify the default URI for the @id of a @type or the values of a property? .
What additions and changes to the context are necesary?

A: I found the explanation why my third version works as desired with some more reading of the JSON-LD recommendations and experimentation.
@vocab is applied to properties and objects  only
@base is used to complete IRI for the subject.
not really obvious but flexible enough for my application.


text:
Q: Remove Lazy loading on first image in Wordpress i want to remove lazy loading on the first image in Wordpress, for every posts, pages and home.
I don't use any plugins for lazy loading image, i need a solution for the default lazy loading add by wordpress.
I found this script for functions.php, but it is for WP Rocket plugin, and i haven't this plugin.
So i modified it in this:
function add_responsive_class($content){
    if ( is_single() || is_page() || is_front_page() || is_home() ) {
        $content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
        $document = new DOMDocument();
        libxml_use_internal_errors(true);
        $document->loadHTML(utf8_decode($content));

        $imgs = $document->getElementsByTagName('img');
        $img = $imgs[0];

        if ($imgs[0] == 1) { // Check if the post has images first
            $img->setAttribute('class','aligncenter size-full remove-lazy');
            $html = $document->saveHTML();
            return $html;
        }

        else {
            return $content;
        }
     }
     else {
         return $content;
     }
}
add_filter ('the_content', 'add_responsive_class');

Now, i need to remove the lazy load only on image with class "aligncenter size-full remove-lazy".
I try with this, after the above code, but i have an error and it doesn't work:
function remove_lazy_loading_for_specific_class( $attributes ) {
    $attributes[] = 'class="aligncenter size-full remove-lazy"';
    return $attributes;
}
add_filter( 'wp_img_tag_add_loading_attr', 'remove_lazy_loading_for_specific_class' );

How can I do that? Thanks

A: Not sure if this would be helpful but instead of all of this why not give this image an ID or a class and remove the lazy attribute that WordPress adds by default using the removeAttribute() method.

A: I solved only with this :)
function add_responsive_class($content){
    if ( is_single() || is_page() || is_front_page() || is_home() ) {
        $content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
        $document = new DOMDocument();
        libxml_use_internal_errors(true);
        $document->loadHTML(utf8_decode($content));

        $imgs = $document->getElementsByTagName('img');
        $img = $imgs[0];

        if ($imgs[0] == 1) { // Check if the post has images first
            $img->removeAttribute( 'loading' );
            $html = $document->saveHTML();
            return $html;
        }

        else {
            return $content;
        }
     }
     else {
         return $content;
     }
}
add_filter ('the_content', 'add_responsive_class');


text:
Q: Cannot find module "node-sass" react I am trying to build react app and I want to use scss to style my app.
Challenge is that even though I already installed node-sass, but I still get this error.
./src/styles/styles.scss (/usr/local/lib/node_modules/react-scripts/node_modules/css-loader/dist/cjs.js??ref--6-oneOf-5-1!/usr/local/lib/node_modules/react-scripts/node_modules/postcss-loader/src??postcss!/usr/local/lib/node_modules/react-scripts/node_modules/resolve-url-loader??ref--6-oneOf-5-3!/usr/local/lib/node_modules/react-scripts/node_modules/sass-loader/dist/cjs.js??ref--6-oneOf-5-4!./src/styles/styles.scss)
To import Sass files, you first need to install node-sass.
Run `npm install node-sass` or `yarn add node-sass` inside your workspace.
Require stack:
- /usr/local/lib/node_modules/react-scripts/node_modules/sass-loader/dist/getDefaultSassImplementation.js
- /usr/local/lib/node_modules/react-scripts/node_modules/sass-loader/dist/getSassImplementation.js
- /usr/local/lib/node_modules/react-scripts/node_modules/sass-loader/dist/index.js
- /usr/local/lib/node_modules/react-scripts/node_modules/sass-loader/dist/cjs.js
- /usr/local/lib/node_modules/react-scripts/node_modules/loader-runner/lib/loadLoader.js
- /usr/local/lib/node_modules/react-scripts/node_modules/loader-runner/lib/LoaderRunner.js
- /usr/local/lib/node_modules/react-scripts/node_modules/webpack/lib/NormalModule.js
- /usr/local/lib/node_modules/react-scripts/node_modules/webpack/lib/NormalModuleFactory.js
- /usr/local/lib/node_modules/react-scripts/node_modules/webpack/lib/Compiler.js
- /usr/local/lib/node_modules/react-scripts/node_modules/webpack/lib/webpack.js
- /usr/local/lib/node_modules/react-scripts/scripts/start.js

I also tried to delete node_modules and reinstalled node-sass but it didn't work. Any advice?

A: This happens to me sometimes and seems like issue with npm. Try installing node-sass using yarn
yarn add node-sass

A: I'm not going to answer this question directly!
But point to an important matter! node-sass is deprecated!
sass package is used now in react-scripts. And the whole sass compiler or pre-processor is followed in the Dart sass project!
sass package is a distribution of Dart sass!
You can check more details and illustration in the following answer:
https://stackoverflow.com/a/68327656/7668448

A: This really seems like issue with npm (it happend not always), but if you already use npm to your project, it would be better to use:
npm cache clear --force

instead of relocating all dependencies on yarn.


text:
Q: Why findViewById() doesn't work as getActivity().findViewById() here?     /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_detail,
                    container, false);
            // The detail Activity called via intent.  Inspect the intent for forecast data.
            Intent intent=getActivity().getIntent();
            TextView text=(TextView)rootView.findViewById(R.id.text1);
            String b=intent.getStringExtra(Intent.EXTRA_TEXT);
            text.setText(b);

            return rootView;
        }
    }

In this code when I am using
TextView text=(TextView)getActivity().findViewById(R.id.text1)

Then my app crashes and Logcat says that
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference

This is the XML file associated with this code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.sunshine.app.DetailActivity$PlaceholderFragment" >

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>

A:
In this code when I am using TextView text=(TextView)getActivity().findViewById(R.id.text1)
Then my app crashes and Logcat says that Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference

findViewById() on an Activity starts from the root view (what is referred to as the "decor view") and traverses the tree of available widgets and containers, looking for an ID match. Hence, findViewById() called on an Activity will only find views that are part of the overall activity view hierarchy.
However, your inflate() call does not attach the inflated RelativeLayout to the activity view hierarchy. This is expected. Those views will be attached to the activity view hierarchy when the fragment itself is attached, sometime after you return from onCreateView(). As a result, when you call findViewById() on the activity from inside onCreateView(), it cannot find your TextView, because that TextView is only being managed by the fragment and is not yet part of the activity view hierarchy.
findViewById() on a View or ViewGroup starts from that View or ViewGroup and traverses the tree of available widgets and containers, looking for an ID match. The RelativeLayout has access to your TextView, so when you call findViewById() on the RelativeLayout that you inflate, it works.

A: It's because fragment_detail.xml layout contains your TextView with id text1, not Activity layout.


text:
Q: how to pass C++ callback function into C# COM method I have a COM server, done in C#, where one of the methods takes a callback function.
   [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.AutoDual)]
    public class REDIServer
    {
        public bool Connect([MarshalAs(UnmanagedType.FunctionPtr)] ref CallBackFunction callback)
        {
            // send callback deeper into C# code
            return _service.Connect(callback);
        }

When generating tlb code out of that dll so I can use it in my C++ client, it looks like this:
  virtual HRESULT __stdcall Connect (
    /*[in,out]*/ long * callback,
    /*[out,retval]*/ VARIANT_BOOL * pRetVal ) = 0;

And finally, when I try to use the Connect() call from C++, I am using it like this:
void Callback()
{
    cout << "got a callback\n";
}

int main()
{
    HRESULT hr = CoInitialize(NULL);

    try
    {
        REDIXLServer::_REDIServerPtr ptr(__uuidof(REDIXLServer::REDIServer));

        VARIANT_BOOL ret;
        hr = ptr->Connect((long *) &Callback, &ret);
    }
    catch (_com_error & e)
    {
        cout << e.ErrorMessage() << endl;
    }

The program crashes on the Conect() call.  I am getting a message box "Managed Debugging Assistant 'InvalidFunctionPointerInDelegate has detected a problem.... Invalid function pointer was passed into the runtime to be converted to a delegate...."
So what am I doing wrong?   Thank you

A: First of all, if doing interop with native COM clients, I would suggest using COM events instead of callbacks
Additionally, I would suggest not using [ClassInterface(ClassInterfaceType.AutoDual)] as it generates a lot of cruft in generated tlh/tli files. Instead of that, define an interface and implement it in your class.
public delegate double FunctionCallback(int arg);

[ComVisible(true)]
[Guid("5F11C485-0AA8-461D-BB56-32D620D17311")]
public interface ITestServer
{
  double Connect([MarshalAs(UnmanagedType.FunctionPtr)] FunctionCallback callback, int arg);
}

[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class TestServer : ITestServer
{
  public double Connect(FunctionCallback callback, int arg)
  {
    Console.Out.WriteLine("In server, calling callback...");
    return callback(arg);
  }
}

You don't need to send the callback by ref (ref CallBackFunction) as you will not be changing it to point to different implementation, and since Callback is same as &Callback you can't dereference it anyway - this is why it crashes.
In your native client, callback will be modeled as long:
double Connect (long callback, long arg );

When sending a function pointer just cast it to long:
double triple(int arg) {
    return arg * 3.0;
}

double halve(int arg) {
    return arg / 2.0;
}

int main() {
    CoInitialize(NULL);
    server::ITestServerPtr svr(__uuidof(server::TestServer));
    printf("tripled: %g\n", svr->Connect((long)triple, 5));
    printf("halved: %g\n", svr->Connect((long)halve, 5));
    return 0;
}


text:
Q: How to display max value from row subtotals? (Power BI) Below is a simplified chart in Excel for ease of Q&A.
What I have is a matrix in Power BI that shows the average value as a subtotal.
The desired output is highlighted in yellow, which contains the greatest average from all columns.

A: With DAX Mesaures
_avgA :=
CALCULATE ( AVERAGE ( factTbl[typeA] ), ALL ( factTbl ) )

_avgB :=
CALCULATE ( AVERAGE ( factTbl[typeB] ), ALL ( factTbl ) )

_avgC :=
CALCULATE ( AVERAGE ( factTbl[typeC] ), ALL ( factTbl ) )

_greatestAvg :=
MAXX (
    UNION ( ROW ( "allAvg", [_avgA] ), ROW ( "avg", [_avgB] ), ROW ( "avg", [_avgC] ) ),
    [allAvg]
)

_A :=
VAR _1 =
    SUM ( factTbl[typeA] )
RETURN
    IF ( HASONEVALUE ( factTbl[ID] ), _1, [_avgA] )

_B :=
VAR _1 =
    SUM ( factTbl[typeB] )
RETURN
    IF ( HASONEVALUE ( factTbl[ID] ), _1, [_avgB] )

_C :=
VAR _1 =
    SUM ( factTbl[typeC] )
VAR _2 =
    IF ( HASONEVALUE ( factTbl[ID] ), _1, [_greatestAvg] )
RETURN
    _2


text:
Q: How to select only top layer using Select OpenLayers? I use this  part of code to make all layers selectable:
this.selectFeaturesClick = new Select({
  style: selectFeatureStyle,
  condition: click,
  multi: false,
  filter: (feature: FeatureLike) => {
    console.log(feature);

    return (
      !this.drawingService.editFeaturePoint &&
      feature.getGeometry().getType() !== LayerType.point
    );
  },
});

The issue is I got all layers selected after click. How to make only top layers selected?
This console.log(feature); showesme two messages by count of visible layers.

A: Either specify the layer in the layers option
  layers: [topLayer],

or test the layer in the filter function
  filter: (feature, layer) => {
    return (
      !this.drawingService.editFeaturePoint &&
      feature.getGeometry().getType() !== LayerType.point &&
      layer === topLayer
    );
  },


text:
Q: SSL Certificate on Load Balancer I have a load balancer in front of multiple websites, one of which needs an SSL certificate. When I install the SSL certs for that one site on the load balancer, it breaks the HTTPS protocol for all the other sites.
How can I get SSL for this site without disrupting HTTPS for the other sites? Can I just get an SSL cert for the whole load balancer? The URLs are different and do not share top level domains.
Thanks in advance!

A: Depending on the website(s) behind the load balancer, it sounds like you might need a wildcard cert for *.yourwebsite.com , or something similar if all URLs behind the balancer share a common URL.
You could also generate a cert for one of the specific sites with something like Lets Encrypt.

A: You can use Let's Encrypt to generate a single certificate that's valid for many domains. The downside is that you will need to regenerate the certificate whenever you add a new domain. Depending on how frequently you do this, you may run into rate limiting from Let's Encrypt...
Here's how you'd request a cert with multiple domains:
certbot certonly --webroot -w /var/www/example/ -d www.example.com -d example.com -w /var/www/other -d other.example.net -d another.other.example.net

Here's how you would add another domain to an existing certificate:
certbot --expand -d existing.com -d example.com -d newdomain.com

Finally, please use Let's Encrypt's test servers/API until you have finalized your scripts/commands, otherwise you may hit the rate limit sooner... just add --staging to your certbot commands.
I hope this helps!

*

*Relevant discussion at Let's Encrypt

*CertBot Documentation

*Let's Encrypt Rate Limits

*Let's Encrypt Staging Environment

A: What you want is SNI and SSL stripping. You should run a virtual host for each SSL domain on your webserver which will then balance the stripped traffic the same way the unencrypted traffic is balanced.


text:
Q: Why the size of my database file is always 4KiB build through the Room library? I build the database through the Room by this guide. This is my build code:
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                        NodesRoomDatabase.class, "nodes_database.db")
                        .build();

And I insert information by DAO:
public void insert(NodesData nodesData) {
    new InsertAsyncTask(nodesDao).execute(nodesData);
}

private static class InsertAsyncTask extends AsyncTask<NodesData, Void, Void> {
    private NodesDao asyncDao;

    public InsertAsyncTask(NodesDao asyncDao) {
        this.asyncDao = asyncDao;
    }

    @Override
    protected Void doInBackground(NodesData... nodesData) {
        asyncDao.insert(nodesData[0]);
        return null;
    }
}

After database build and insert something. I can find nodes_database.db, nodes_database.db-shm and nodes_database.db-wal under data/data/<package name>/databases/ but the size of nodes_database.db is always only 4 KiB and has a empty table. But I can query all the contents of the database by using the Stetho debugging.
The file size image
Device: Oneplus 5, Android Oreo 8.1
So, what's wrong with my codes?

A: It's how SQLite works. If you want to query your database outside Android make sure to export both the .db and the .db-wal file.


text:
Q: I tried implementing server-side rendering, but broke my API in the process I have very basic application at the moment that I wanted to try to implement SSR with.
problem 1
Previously I would send index.html (that had a script tag with my bundle.js inside) to requests made to '/' and that would render on the client.
Now I'm rendering the app on the server for every request made to '/' and now, expectantly, when I make GET requests to '/api/users/' my isomorphic rendering function is executed (even though this is an API request and should not be rendering anything).
I understand why, because of where I placed this function in the middleware is such that all requests made to the app will run that middleware.
My question is: How can I ignore this function unless a browser is requesting it? Is that even the right question? It sounds like I'm asking for a hack, which means I'm misunderstanding something.
problem 2
This is the cause of another problem I am having when the client requests bundle.js. Because each request is rendering the app and sending html back, requests to get the bundle are receiving an HTML response, which when parsed by the browser errors out as expected (Unexpected token '<').
I think I've designed my server poorly, and maybe someone can give me some insight or point me to a good place to start learning.
server.js
require('babel-register')
var express = require('express')
// TODO setup global error handling
var path = require('path') // built-in middleware
var mongoose = require('mongoose')

const isomorphic = require('./isomorphic')

// change promise library of mongoose to bluebird
mongoose.Promise = require('bluebird')

// create the api and auth
var api = require('./api/api')
var auth = require('./auth/routes')

// make app
var app = express()

// setup the app middleware
require('./middleware/appMiddleware')(app)

// get the api and auth
app.use('/api', api)
app.use('/auth', auth)

// serve static assets
app.use(express.static('dist'))

// serverside rendering
app.use(isomorphic)

// give the bundle
// app.get('/dist/bundle.js', function(req, res) {
//   res.sendFile(path.resolve('dist/bundle.js'), function(err) {
//     if (err) {
//       res.status(500).send(err)
//     }
//   })
// })

module.exports = app

Note app.get('/dist/bundle.js', function... is commented out because I believe app.use(express.static('dist)) should be handling that. Right?
isomorphic.js
var React = require('react')
var ReactDOMServer = require('react-dom/server')
var StaticRouter = require('react-router-dom').StaticRouter
var ServerStyleSheet = require('styled-components').ServerStyleSheet
var fs = require('fs')
var _ = require('lodash')
var baseTemplate = fs.readFileSync('./index.html') // TODO change to async function maybe
var template = _.template(baseTemplate)
var sheet = new ServerStyleSheet()
var something = sheet.collectStyles(App)
var css = sheet.getStyleTags()
var App = require('../src/js/App').default

const isomorphic = (req, res) => {
  var context = {}
  var body = ReactDOMServer.renderToString(
    React.createElement(StaticRouter, { location: req.url, context },
      React.createElement(App)
    )
  )

  console.log('hello?');

  if (context.url) {
    // TODO if there is a redirect
  }

  res.write(template({body: body}))
  res.end()
}

module.exports = isomorphic

Please let me know if you need to see any other files.
update 1
I added a check in isomorphic.js that looks like this:
if (req.url !== '/') {
    next()
} else {
    ...
}

And I uncommented the app.get('/dist/bundle.js') code.
Now everything seems to be half working, however:
That if check seems to be bad practice because the user could request routes that exist on the client that are not the root.
React's server render does match the checksum on the client, therefore negating the SSR.
And the app.use(express.static('dist')) appears to be doing absolutely nothing. The 'dist' directory is one level up from my server.js file, so I've changed it to '../dist' but it still 404s (with that .get commented).
update 2
I have figured out why express.static('dist') was not working.
One, I changed it from express.static('dist') to express.static(path.join(__dirname, '../dist/')) to be sure it going to the correct path.
Two, in my index.html, the script tag was originally
<script src="dist/bundle.js"></script>

when apparently it should have been this (I got lucky and guessed this could have been the issue)
<script src="bundle.js"></script>


text:
Q: Boundaries of unit testing between my code and a library or sub-component Background: I am new to testing in general, and have been studying it in context of JavaScript, specifically React.js, front-end development (actually new to this as well). For the question, I have these 2 similar cases:
Case 1: My code and a library
I'm using UI library and aside from its decent design, I want to leverage its form validation utilities. I want to test this validation, but not sure how to do it.

*

*Option 1: Just test for the behaviors I expect
It would be testing if my field (which is a sub-module of the library itself) receives the library-specific classes for fields with errors as expected, and if these errors prevent from calling the submit handler I passed to the form (also sub-module of the library).

*

*Problem A with Option 1
I am very likely to be duplicating tests that are already covered by the library itself. (e.g. I am testing if the field receives the error classes when the input is invalid when the library itself has tested if it does so, given the right configuration.)

*Problem B with Option 1
It slightly couples the test code to the library, i.e. I have to use library-specific classes and markup to evaluate my code.
Okay, this is actually a side-question, is this a bad thing for a test? Is this making the test brittle, or is what they call 'contract' that is actually necessary for unit tests?

*Option 2: Test which sub-module is used and what configuration is passed

*

*Problem A with Option 2
This is much more brittle, I think, It's almost like repeating the implementation (i.e. repeating the type sub-module used, and the configuration passed to it.)

*Problem B with Option 2
Same as Option 1's Problem A -- coupling test to the library's API, specifically its configuration API. (Again, not sure if this is just test being brittle, or contract being written)

Case 2: My code and its sub-component
I have my good 'ol to do app. Its to do list component has addTodo() method and it passes to its sub-component to do field. I want to test its feature to add todo item, but not sure on how to do this either.

*

*Option 1: Again, just test for the behaviors I expect
Test `to do app` that if input and submit with sub-component `to do field`, another `to do item` is added. (This is implemented by passing `addTodo()` method from `to do app` to `to do field` as onSubmit handler)

*

*Problem A with Option 1
If I'll do this, is there still a point in unit testing the to do field alone? If I already unit-tested to do field that it calls any onSubmit handler upon submitting, wouldn't this to do app test case indirectly repeating to do field's test case??

*Option 2: Test if correct sub-component is used and what configuration is passed (Similar to Case 1's option 2)
Its specs would look like this:

*

*Unit test to do app to assert...

*

*that to do app's addTodo() method adds a todo item properly

*that to do app renders to do field sub-component

*and that to do app passes addTodo() to as onSubmit handler to to do field

*then also unit test to do field to assert that...

*

*that to do field calls the onSubmit, which is received from parent component, during submit

The Question
Which of these options are better, especially if I favor BDD over TDD? Also, please correct me if you noticed I misunderstood anything. Thank you.

A: You are testing a user interface.  This is exactly what functional testing was created to do. You want to test the behavior of the interface you've created, specifically:

*

*When the screen is first loaded, is the submit button visible/selectable?  If it shouldn't be, you can test for that.

*Enter invalid data into your text field.  Use all the different types of invalid data that you have configured to check.  The submit button should probably be visible/selectable, but clicking it should generate some kind of error message.  Check that the error message displays as you expect it to.

*Enter valid data into your text field.  The submit button should be visible/selectable, and clicking on it should produce the correct result.  Check that the correct result is displayed.

Using functional testing like this prevents coupling to your library.  Changing the library should result in these tests passing.  Even dropping the library and rolling your own validation routines should result in these tests passing.
If you haven't chosen a functional testing tool, you may want to consider Selenium.  It will enable you to write and run functional tests.

A: I think you have outlined approaches in your Case 2 above. What you are getting at is the distinction between unit and integration tests. (I actually find that the language of TDD vs. BDD is not that helpful here.) In a "unit test" test, the behavior of a specific piece of code is validated; and an integration tests, the interaction between different pieces of code is validated.
Let's say that the React validation library changes in such a way that it breaks your app. If you upgrade your library, you'd like a test to fail in this case. And ideally, you wouldn't want all your tests to fail.
Like you say, you can write specific tests that validate individual the behaviors of your code, such as:
a. if I enter bad data a css class gets applied to an input, and
b. if there's a css class on an input the submit button is disabled.
   If your library does this, it's tested there, right?
c. if the submit button is disabled the form cannot be submitted, etc.

These very specific behavior tests are nice when they fail, as it's clear what's going on. The downside is that sometimes the chain, or coupling between them, can have flaws: a step can be left out, or the contract with an external tool can change slightly and then go undetected with the unit test. Or it can just be hard for the reader to piece them all together.
And a callout to (b) above. If a your code is dependent on a specific library behavior, you need to figure out how you will maintain trust in it. If it's the main behavior of the library, maybe you can just trust it; but if it's a less central piece of behavior, you may want to write your own (redundant) test. I seldom find that testing that a configuration setting is correct raises my confidence much, but people do in fact do this.
Consider a higher level example (perhaps via Selenium) that tests that the system behaves within the context of the app: entering a specific value in an input box shows an error and will not submit to the server. It's nice as it's not tied to implementation details: if a css class is changed globally, the test stays green if the app still works. The downside is that the test is covering a wide swatch of behavior, so it will be more brittle than a unit test. If any of the units tests above fail, this integration test will also probably fail. This can turn people off to these tests, but in fact, this is the only test that will catch some subtle change in your external library that you missed when upgrading.
I recommend a testing strategy include a thoughtful combination of different types of tests, balancing the benefits of these two specific approaches.

A: Unit testing refers to testing individual units or components of your code in isolation from the rest of the application. The goal is to verify that each unit or component is working correctly on its own, and to identify any issues early in the development process.
In the context of testing a library or sub-component, the boundaries of unit testing depend on the specific design of your code and the library or sub-component being used. Here are some general guidelines for testing in these cases:
Case 1: My code and a library
Option 1: Just test for the behaviors you expect
This option involves testing the expected behavior of your code when interacting with the library or sub-module. To avoid duplication of tests, you may want to focus on testing the specific behaviors of your code that are unique to your application, rather than testing the behavior of the library itself. It is generally acceptable for unit tests to depend on the API of the library or sub-module being tested, but you should be mindful of how much the test code depends on the specific implementation details of the library or sub-module.
Option 2: Test which sub-module is used and what configuration is passed
This option involves testing the specific implementation details of the library or sub-module being used. This can be more brittle, as it is more sensitive to changes in the implementation of the library or sub-module. You should consider whether testing the specific implementation details adds value to your testing strategy.
Case 2: My code and its sub-component
Option 1: Test for the behaviors you expect
This option involves testing the expected behavior of your code when interacting with the sub-component. To avoid duplication of tests, you may want to focus on testing the specific behaviors of your code that are unique to your application, rather than testing the behavior of the sub-component itself.
Option 2: Test if correct sub-component is used and what configuration is passed
This option involves testing the specific implementation details of the sub-component being used. This can be more brittle, as it is more sensitive to changes in the implementation of the sub-component. You should consider whether testing the specific implementation details adds value to your testing strategy.
When deciding which approach to take, it can be helpful to consider the following questions:
What are the most important behaviors or features of my code that I want to test?
How much does my code rely on the library or sub-component being tested?
How much does the implementation of the library or sub-component being tested change over time?
How much do I care about the specific implementation details of the library or sub-component being tested?
By answering these questions, you can determine the most appropriate approach for testing your code in the context of a library or sub-component.


text:
Q: C++ Range-adaptors/views and iterator invalidation rules I have not found any direct reference to range/range-adaptor/range-view specific invalidation rules when modifying the underlying container.
Intuition suggests it would be exactly the same as pointer/iterator invalidation rules -- which are specified within the containers section of the standard.
The current container invalidation wording is as follows:

"...invalidates all the references, pointers, and iterators referring
  to the elements in the sequence, as well as the past-the-end
  iterator."

Which raises the question: Do all ranges necessarily "refer to the elements of the sequence", or, could they be accessing elements through the interface of the container?
It seems to me that most range adaptors already access a sequence without referring directly to the elements of that sequence (i.e. lazy views just build up iterator adaptors).
What seems to matter is the underlying range at the base of the view pyramid, so to speak.

We all learn at some point, that you cannot do std::vector::push_back while iterating that same vector, because the memory may move and invalidate the iteration.  But, we also learn, that you can use std::vector::operator[] access with push_back, so long as you are careful with checking your size() bounds correctly.
It seems to me the same rules would apply to ranges/adaptors/views.
So: is it possible to force some equivalent to std::ranges::views::all (or, perhaps take_view) over a random access container to use array indexing (or some equivalent indirect/lazy element access), and to not use iteration directly?

Something to allow this:
std::vector<People> people = ...;
for (auto& person : std::ranges::views::lazy_all(people)) { // or ranges::lazy_take_view(people, people.size())
  if (person.has_new_child()) {
    people.push_back(person.get_new_child());
  }
}

A: I'm currently playing with C++20 ranges and while implementing my own view I came up with the same question: what are the rules for iterator invalidation for views?
As far as I can see, ranges heavily use meta-programming and under the hood they construct a hierarchy of state machines. Actual types of these state machines are often hidden [1], so we may have difficulties to assume their restrictions. Iterator invalidation is a part of these restrictions, so to specify when and how iterators are invalidated when we construct a view hierarchy can be quite challenging if not impossible. Even if we manage to describe these rules they could be impossible to memorise, not to mention to use efficiently.
Ranges V3 library has the following recommendation:

View validity
Any operation on the underlying range that invalidates its iterators or sentinels will also invalidate any view that refers to any part of that range. Additionally, some views (e.g., views::filter), are invalidated when the underlying elements of the range are mutated. It is best to recreate a view after any operation that may have mutated the underlying range.

https://github.com/ericniebler/range-v3/blob/master/doc/index.md
The restriction given above just slashes away all concerns and although it is stricter than the rules for the standard containers it establishes a simple rule to memorise about any view iterators invalidation. At the same time it gives freedom to change a view implementation without touching that rule.
So, I suppose, it is safe to assume that ranges in C++20 standard are subject to the same limitations.
[1] My observation are based on MSVC implementation for ranges where range adapters can actually spawn different types based on strategies. So when you pipeline std::views::take(), for example, you may suddenly end up with std::span().

A: Each range adaptor or view has its own rules for how it interacts with the underlying range. And the standard spells out these interactions, if sometimes obliquely.
ranges::ref_view for example is explicitly stated to work as if it holds a pointer to the range. And its begin/end functions behave as if they call that range's begin/end functions, as well as forwarding any other functionality to the range it was given. So its interactions are pretty clear, since its iterators are the exact same type as those of the underlying range.
For a range like ranges::filter_view, it's a bit more difficult to track down. filter_view's iterator behavior is based on the behavior of filter_iterator. That type behaves as if it stores an iterator to the underlying range (due to the exposition-only iterator member). So a filter_iterator will be invalidated whenever the underlying range's iterators are. And there is no exposition member of filter_view that holds an iterator, so you might expect that calling begin will always get a fresh, valid filter_iterator.
But it won't. There is a major caveat buried in the description of filter_view::begin. A semantic component of the behavior of a range's begin function is that it must execute in amortized constant time. Finding the start of a filtered list is a linear-time operation. Therefore, filter_view::begin is required to only do this linear-time operation once and then internally cache the result.
Which means it does store an iterator, even if it's not clear that it does. So if you invalidate whatever the begin filter_iterator is using, you have invalidated the filter_range's begin iterator and must construct a new one.
In summary, if you want to know the iterator invalidation behavior for a view, you must read through the entire description of that view. But this is true of containers as well; there isn't a nice, neat section of the standard which spells out exactly when iterators, references, and pointers are invalidated. Cppreference has a nice list, but the standard leaves it up to the definition of each function in the class.


text:
Q: The /src folder in eclipse is empty from a downloaded project I downloaded a Java project of my professor: on macOS, the /src folder contains the Java code, while on Windows it's empty, I don't understand why. How can I solve it?

A: You need to click on src/java (second from above).


text:
Q: PencilKit in SwiftUI I'm trying to use PencilKit in SwiftUI.

*

*How can I detect in the updateUIView-function, which Binding-variable was updated? For example I don't want to clear the canvas when changing the color.

*And is there a better way to clear the canvas than toggling a boolean? Toggling a boolean forces the updateUIView-function to execute.

import SwiftUI
import UIKit
import PencilKit

struct ContentView: View {
    @State var color = UIColor.black
    @State var clear = false

    var body: some View {
        VStack{
            PKCanvas(color: $color, clear:$clear)
            VStack(){
                Button("Change to BLUE"){ self.color = UIColor.blue }
                Button("Change to GREEN"){ self.color = UIColor.green }
                Button("Clear Canvas"){ self.clear.toggle() }
            }
        }
    }
}

struct PKCanvas: UIViewRepresentable {
    class Coordinator: NSObject, PKCanvasViewDelegate {
        var pkCanvas: PKCanvas

        init(_ pkCanvas: PKCanvas) {
            self.pkCanvas = pkCanvas
        }
    }

    @Binding var color:UIColor
    @Binding var clear:Bool

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIView(context: Context) -> PKCanvasView {
        let canvas = PKCanvasView()
        canvas.tool = PKInkingTool(.pen, color: color, width: 10)

        canvas.delegate = context.coordinator
        return canvas
    }

    func updateUIView(_ canvasView: PKCanvasView, context: Context) {
        // clears the canvas
        canvasView.drawing = PKDrawing()

        // sets a new color
        canvasView.tool = PKInkingTool(.pen, color: color, width: 10)
    }
}

A: This will do the trick:
    func updateUIView(_ canvasView: PKCanvasView, context: Context) {
        if clear != context.coordinator.pkCanvas.clear{
            canvasView.drawing = PKDrawing()
        }
        canvasView.tool = PKInkingTool(.pen, color: color, width: 10)
    }

A: I observed similar pattern many times, and here we get intercommunication between SwiftUI-value-declarative-state-managed world and xKit-OOP-imperative-action-managed world... and there are attempts either to put everything from one to another, or vice versa...
I've got a mind that probably it would be better to keep each nature for each and have some mediator or actor between two... so for your use-case I'd think that I would go different way, say (scratchy, not tested, for consideration):
struct ContentView: View {
    //@State var color = UIColor.black // < both these have nothing to ContentView
    //@State var clear = false

    let pkActor = PKCanvasActor() // < mediator, reference type

    var body: some View {
        VStack{
            PKCanvas(actor: pkActor)
            VStack(){
                Button("Change to BLUE"){ self.pkActor.use(color: UIColor.blue) }
                Button("Change to GREEN"){ self.pkActor.use(color: UIColor.green) }
                Button("Clear Canvas"){ self.pkActor.clear() }
            }
        }
    }
}

somewhere here
func makeUIView(context: Context) -> PKCanvasView {
    let canvas = PKCanvasView()
    self.actor.canvas = canvas // but think to avoid cycle reference

and pure-OOP part
class PKCanvasActor {
  var canvas: PKCanvasView

   func use(color: Color) {
      // do anything with canvas color
   }

   func clear() {
      canvas.drawing = PKDrawing()
   }

   // ... any more actions
}

Of course there simple approach I proposed for similar scenario in SwiftUI Button interact with Map... but above way looks more preferable for me.
Remark: one might say the Coordinator is for this purpose, but its life-time is managed by SwiftUI-internals and it participate in those internal workflows, so I'd avoid intruding into those relationships...


text:
Q: how to call a javascript function from codebehind in asp.net protected void addSchoolButtonClick(object sender, ImageClickEventArgs e)
    {

        Page.ClientScript.RegisterStartupScript(GetType(), "MyKey1", "SchoolSearchPopUp();", true);

        /*Some code*/
    }

I am developing a website in asp.net.At a Hyperlink onclick event i want to call a javascript function"SchoolSearchPopUp()".this function is for creating a new popup window and it is working correctly.But my problem is ,a javascript function is calling or pop window opens only after executing the rest of the code in that function and that code need's some data that occurs as a result of popup.How can i create the popup before executing the rest of code in  that function.

A: Change your postback trigger to something within the popup.

A: I don't think javascript can be called from code behind.  C# is running from the server and java is all client side.  There's a good explanation to a similar question here: http://forums.asp.net/t/1117189.aspx
If you need to execute a javascript function, you could try changing the hyperlink to a button and making use of the OnClientClick property.  This executes script client side rather than calling a method on the server.
     <asp:button id="Button1"
                 text="Click Here"
                 onclientclick="SchoolSearchPopUp()"
                 runat="server" />

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx

A: You will need to write JavaScript on the page to handle the click of the button first and then call to the page method on the server.
Add an OnClientClick attribute to your button element and run your JavaScript method from there:
<asp:Button ID="TestButton" OnClientClick="SchoolSearchPopup()" Text="Click Me" OnClick="addSchoolButtonClick" runat="server"/>

<script type="text/javascript">
    function SchoolSearchPopup()
    {
        alert("Popup");
    }
</script>

A: If you want to execute some javascript before your postback you will need to register your hyperlink's click event to a js method, then submit your post to the server after performing whatever client side logic you are looking to run. (not the other way around, using RegisterStartupScript)
Example:
$("#myHyperLink").click(function() {

    // do page logic, in your case show a modal window
    $("#myModalDivContainer").show();

    // submit your post to the server... replace targetClientID with ID of server control you're posting to
    __doPostBack('targetClientID', '');

   // NOTE: If you want to perform an AJAX request instead simply use some jQuery here instead. it's up to you how to handle the request from this point :)

});

Hope this helps!


text:
Q: Using a comma to avoid using "and" In my writing I often use a comma and the past progressive tense (I think) to make sentences more concise.
For example:

The new design was more intuitive and user-friendly, reducing user errors.

Is this grammatically correct? Are there better alternatives?

A: This is grammatically correct. In fact, replacing the comma with an and will remove the validity of the sentence.
"Reducing user errors" is a phrase. It has no subject, only a verb. This phrase shows another thing that the design does. The main thing the design does is that it is more intuitive and user-friendly. The phrase shows another thing that it does as a result of being more intuitive and user-friendly, in this case. This is a very good sentence. I would say that you continue using this format because it works very well.


text:
Q: How to add headings in netlogo There seems to a method called subtract headings in Netlogo but method called add headings? For example :if I wish to add 340 and 25. Is there a available command to achieve this?

A: If you wish to rotate right by 25 degrees from 340, you could simply use mod arithmetic to bring the total back to a heading range. See my answer to your related question Rotating a turtle through cone of vision for what you really want.
set heading (340 + 25) mod 360


text:
Q: Overwrite a file? I have a file named config.yml in a directory I need to be able to edit it and then overwrite it. When ever I would edit it and save it with the same name it would ask to overwrite and I would say yes but it had overwritten a config.yml in another place not the one I had wanted. I need help because I need to overwrite the right config file.
Thanks

A: You should cd into the directory before opening the file and make sure that it's saving the file to the right place


text:
Q: MySql performance problems This query I have takes a whooping 45 seconds to execute. I have indexes on all fields that are being search.
SELECT SQL_CALC_FOUND_ROWS g.app_group_id, g.id as g_id, p.`id` as form_id,
       a.`user`   as activity_user,a.`activity` as app_act ,a.*
FROM grouped g
INNER JOIN
(SELECT max(id) as id, app_group_id FROM grouped GROUP BY app_group_id) g1
ON g1.app_group_id = g.app_group_id AND g.id = g1.id
INNER JOIN form p
on p.id = g.id
    INNER JOIN
    (SELECT a.id, a.date_time, a.user, a.activity FROM log a) a
    ON g.id = a.id
WHERE p.agname like '%blahblah%' and p.`save4later` != 'y'
      and a.activity = 'APP       Submitted' or a.activity = 'InstaQUOTE'
ORDER BY app_group_id DESC limit 0, 100

In my explain it shows im using Using temporary; Using filesort
Indexes are:
activity table: PRIMARY activity_id INDEX date_time INDEX id INDEX activity INDEX user
form table: PRIMARY id INDEX id_md5 INDEX dateadd INDEX dateu INDEX agent_or_underwriter INDEX
grouped table: UNIQUE id INDEX app_group_id INDEX agent_or_underwriter save4later
Any advice is much appreciated
Thank you very much

A: To start with, try this one:
SELECT
  g.app_group_id,
  g.id AS g_id,
  p.id AS form_id,
  a.user AS activity_user,
  a.activity AS app_act,
  a.id,
  a.date_time
FROM grouped g
INNER JOIN
  (SELECT MAX(id) AS id, app_group_id FROM grouped GROUP BY app_group_id) g1
  ON g1.app_group_id = g.app_group_id AND g.id = g1.id
INNER JOIN form p
  ON p.id = g.id
INNER JOIN log a
  ON g.id = a.id
WHERE p.agname LIKE '%blahblah%'
  AND p.save4later != 'y'
  AND a.activity IN('APP       Submitted', 'InstaQUOTE')
LIMIT 0, 100

I removed an unnecessary subquery. Also removed ORDER BY. I guess you could do without sorting, and that must speed the query up a lot.
I also removed SQL_CALC_FOUND_ROWS, because, as I mentioned earlier, it should be faster to issue a separate COUNT(*) query.

A: Your where clause has an "Or" on the "a.Activity".  Without ( ) around both activity, it is going through EVERYTHING, all P, G, G1 aliases.  I am guessing that might be your bigger issue.
Additionally, I would ensure you have an index on your "Form" table with the ( Save4Later ) column indexed
I would update the query like this:
SELECT STRAIGHT_JOIN SQL_CALC_FOUND_ROWS
      g.app_group_id,
      g.id as g_id,
      QualifyPages.Form_id,
      a.`user` as activity_user,
      a.`activity` as app_act,
      a.*
   FROM
      ( select p.ID as Form_ID
           from  FORM p
           WHERE p.`save4later` != 'y'
             AND p.agname like '%blahblah%' ) QualifyPages

         JOIN Grouped g
            on QualifyPages.Form_ID = g.ID

            INNER JOIN
            ( SELECT app_group_id,
                     max(id) as MaxIDPerGroup
                 FROM
                    grouped
                 GROUP BY
                    app_group_id ) g1
             ON g.app_group_id = g1.app_group_id
            AND g.id = g1.MaxIDPerGroup

           INNER JOIN
            ( SELECT a.id, a.date_time, a.user, a.activity
                 FROM log a
                 WHERE a.activity = 'APP       Submitted'
                    or a.activity = 'InstaQUOTE' ) a
               ON g.id = a.id
   ORDER BY
      g.app_group_id DESC
   limit
      0, 100


text:
Q: vba conditional formatting with standard deviations - run time error with incorrect StDev I am trying to move some of my conditional formatting to VBA but apply it to ranges that may change every time I run the macro. I think I have defined my ranges, variables, formulas and formats correctly (never done vba format.conditions so syntax could be wrong there). When I run the code it stops on the line
With checkrange.FormatConditions _
.Add(xlCellValue, xlGreater, Formula1:="=R" & cfcll.Row & "C" & q & "+ " & devone & ")")

with run-time error 5, invalid procedure or call.
The full section of code is as follows:
Dim cflastrow As Long
Dim cfrange As Range
Dim cfcll As Range
Dim checkrange As Range
Dim q As Long
Dim devone As Long
Dim devtwo As Long
Dim devthree As Long
Dim devfour As Long

cflastrow = finwb.Sheets("strt_Dash_Final").Cells(Rows.Count, 52).End(xlUp).Row
Set cfrange = finwb.Sheets("Strt_Dash_Final").Range("AV6:AV" & cflastrow)

For Each cfcll In cfrange
    If cfcll.value <> "" Then
        For q = 4 To 38
            Set checkrange = finwb.Sheets("Strt_Dash_Final").Range(Cells((cfcll.Row + 1), q), Cells((cfcll.Row + (cfcll.value - 2)), q))
            devone = Application.WorksheetFunction.StDev_P(checkrange)
                With checkrange.FormatConditions _
                    .Add(xlCellValue, xlGreater, Formula1:="=R" & cfcll.Row & "C" & q & "+ " & devone & ")")
                    With .Font
                    .ThemeColor = xlThemeColorDark1
                    .TintAndShade = 0
                    .ThemeFont = xlThemeFontMinor
                    End With
                    With .Interior
                    .Pattern = xlSolid
                    .PatternColorIndex = xlAutomatic
                    .Color = 255
                    End With
                End With
                With checkrange.FormatConditions _
                    .Add(xlCellValue, xlGreater, "=" & Cells(cfcll.Row, q).value & "+ 2*stddev(" & checkrange & ")")
                    With .Font
                    .Color = 255
                    .TintAndShade = 0
                    .ThemeFont = xlThemeFontMinor
                    End With
                    With .Interior
                    .Pattern = xlSolid
                    .PatternColorIndex = xlAutomatic
                    .Color = 49407
                    End With
                End With
                With checkrange.FormatConditions _
                    .Add(xlCellValue, xlGreater, "=" & Cells(cfcll.Row, q).value & "- stddev(" & checkrange & ")")
                    With .Font
                    .ThemeColor = xlThemeColorAccent3
                    .TintAndShade = -0.499984741
                    .ThemeFont = xlThemeFontMinor
                    End With
                    With .Interior
                    .Pattern = xlSolid
                    .PatternColorIndex = xlAutomatic
                    .ThemeColor = xlThemeColorAccent3
                    End With
                End With
                With checkrange.FormatConditions _
                    .Add(xlCellValue, xlGreater, "=" & Cells(cfcll.Row, q).value & "- 2*stddev(" & checkrange & ")")
                    With .Font
                    .ThemeColor = xlThemeColorDark1
                    .TintAndShade = 0
                    .ThemeFont = xlThemeFontMinor
                    End With
                    With .Interior
                    .Pattern = xlSolid
                    .PatternColorIndex = xlAutomatic
                    .Color = 5287936
                    End With
                End With
        Next q
    ElseIf cfcll.value = "" Then
        'nada
    End If
Next cfcll

Also, despite the range 'checkrange' definitely being correct (checked buy using checkrange = 5 and all values went to 5) devone always comes out as '1' when it should be something like 1.23.....
My theory is that I may not be using R1C1 correctly in the formula context but I saw it used this way in a couple of other examples so am now really not sure. Any help, as always, is greatly appreciated!

A: In
With checkrange.FormatConditions _
.Add(xlCellValue, xlGreater, Formula1:="=R" & cfcll.Row & "C" & q & "+ " & devone & ")")

the formula will be =R5C4+ 1) if cfcll.Row is 5 and q is 4 and devone is 1.
As you see there is a closing parenthesis to much.
With checkrange.FormatConditions _
.Add(xlCellValue, xlGreater, Formula1:="=R" & cfcll.Row & "C" & q & "+ " & devone)

How to debug? Put the formula in a string variable first
sFormula = "=R" & cfcll.Row & "C" & q & "+ " & devone & ")"

then you would have seen this.
For users having non English Excel versions:
The formulas set for FormatConditions with VBA must be in the language of the Excel. They must not be in US-English as usual in VBA. So R1C1 will be Z1S1 in German Excel for example. Thats weird and annoying.
And to your devone: It is Dimed as Long which is a integer type. So not a wonder that it does not contains Double values.


text:
Q: Sql Delete Query Based on Condition Suppose I have two table. One is Car_Window and another is Product. Now I want to write a delete statement that should delete all data from Product

Where the Car_Window.Id = Product.Makeid and Car_Window.Year = Product.Year and Car_Window.Model != product.Model

Any help would be appreciated.
Thanks in Advance.

A: DELETE  a
FROM    product a
        INNER JOIN car_window b
            ON a.makeID = b.ID AND
                a.Year = b.year
WHERE   b.Model != a.Model


text:
Q: Prove almost sure convergence related to i.i.d random variables I have following question and stuck at the 1st one.

$\left\{X_n\right\}$ are i.i.d. random variables with non-zero finite mean. Let $S_n=X_1+X_2+\dots+X_n$. Prove
  1. $|X_n|/n \xrightarrow{a.s.}0$;
  2. $(\max_{1\le k \le n}|X_k|)/n \xrightarrow{a.s.} 0$
  3. $(\max_{1\le k \le n}|X_k|)/(1+S_n) \xrightarrow{a.s.} 0$

I tried to use Borel-Cantelli lemma and Markov inequality, but failed.
1st Try:
It's equivalent to show for any $\epsilon > 0$, we have $P(|X_n|/n > \epsilon \text{ i.o.})=0$
$$\sum_{n=1}^{\infty} P(|X_n|/n > \epsilon) \le \sum_{n=1}^{\infty}E[|X_n|]/n\epsilon=\infty$$
I figured it didn't work probably because i.i.d. condition was not used.
2nd Try: $$\begin{align}P(|X_n|/n > \epsilon \text{ i.o.}) &= \lim_{m \rightarrow \infty}P(\bigcup_{n=m}^\infty |X_n|/n > \epsilon) \\ &= \lim_{m \rightarrow \infty}1-P((\bigcup_{n=m}^\infty |X_n|/n > \epsilon)^c) \\ &=\lim_{m \rightarrow \infty}1-\prod_{n=m}^\infty P(|X_1|/n \le \epsilon)\end{align}$$ Stuck again.

A: The Markov inequaltiy is too weak in this case. Instead, use the fact that the $X_n$ are all identically distributed and the integral comparison test.
$$\sum \limits_{n = 1}^\infty P(|X_n|/n > \varepsilon) = \sum \limits_{n = 1}^\infty P(|X_1|/\varepsilon > n) \le 1 + \int_0^\infty P(|X_1|/\varepsilon > x) \, dx$$
Now note that for any nonnegative random variable $Y$ the equation
$$\begin{align*}
\int_0^\infty P(Y > x) \, dx &= \int_0^\infty \int_0^\infty I\{y > x\} \, dP^Y(y) \, dx = \int_0^\infty \int_0^\infty I\{y > x\} \, dx \, dP^Y(y)\\
&= \int_0^\infty y \, dP^Y(y) = E[Y]
\end{align*}$$
holds.

A: I guess following is the answer.
$$\begin{align}P(|X_n|/n > \epsilon \text{ i.o.}) &= \lim_{m \rightarrow \infty}P(\bigcup_{n=m}^\infty |X_n|/n > \epsilon)\\ &= \lim_{m \rightarrow \infty}P(\bigcup_{n=m}^\infty |X_1|/n > \epsilon)\\ &= \lim_{m \rightarrow \infty}P(|X_1|/m > \epsilon) \\ & \le \lim_{m \rightarrow \infty} E(|X_1|)/n \epsilon \rightarrow 0\end{align}$$


text:
Q: How to reference a range of cells in UDF c#, ExcelDNA, in my UDF,
I want to pass a range of cells,  MyUDF(A1:A2)
I tried MyUDF(object param1), if I type in myUDF(A1:A2), the MyUDF is never called
I also tried MyUDF(string param1), MyUDF(string[] param1) neither works.
What type of the parameter should be? thanks

A: The format public static object MyUDF(object param1) {...} should work fine, and your formula with =MyUDF(A1:A2) will pass in an object array with the values in those cells.
If you want to allow the argument to be a reference to the passed in range, you'd declare it as
public static object MyUDF(
    [ExcelArgument(AllowReference=true)] object param1) {...}

The extra attribute tells Excel to pass in the actual reference when called as =MyUDF(A1:A2) - the reference will be of type ExcelDna.Integration.ExcelReference, from where you can get the values or make further calls to the Excel API to get the address or anything.


text:
Q: Reshape columns of matrix into multidimensional matrix I have solar data in a huge (17GB) matrix, call it A. Each column represents one station that collected the one-second data over the year and a half period. The stations are physically in a grid format on the ground and correspond (roughly) to the column numbers. I represented the layout using station numbers in a 9x9 matrix (call it B) like this:
38     0    40     0    42     0    44     0    49
 0    28     0     0    30     0     0    33     0
37     0     5    10    15    20    25     0    48
 0     0     4     9    14    19    24     0     0
36    27     3     8    13    18    23    32    47
 0     0     2     7    12    17    22     0     0
35     0     1     6    11    16    21     0    46
 0    26     0     0    29     0     0    31     0
34     0    39     0    41     0    43     0    45

The zeros are blank spots. Now, I'd like to represent each row in my huge matrix, A, as one slice of a new multidimensional matrix (call it NewMat), with the columns of A being "mapped" onto the 9x9 matrix above.
I have the following in a loop:
for mm = 1:length(A) % rows

    for i = 1:length(HeaderStatNums) % column headers

        [j k] = find(B == HeaderStatNums(i));

        NewMat(j,k,mm) = A(mm,i+1); % This maps to the new matrix. (The i+1 is just
                                    %  a shift
    end
end

This works, but due to the size of my original matrix I cannot create a copy of A in NewMat without running out of memory. I have 16GB physical and about 15GB virtual. Thus, I can only copy portions of A into NewMat. One solution would be to load and unload the MAT file where the matrix is stored, but that's clunky. Any ideas?

A: One of the comments on the question says that the reason for all of this is to generate frames of a movie. Since that is the goal, I can think of a couple different options:

*

*Generate a movie for some limited time span instead of the entire time span of your data set. That will use less memory.

*Write each frame's data to a file as you loop, but don't keep frames in memory. Then you can use another function to load and show the frames. That way you won't ever have two copies of the data in memory at once.


text:
Q: MS Edge showing file origin as "about:blob" I have a rest service to download a file, and I have a small problem with Edge. When I sent GET request to get the file the browser, displays the following confirmation dialog.

The 'From' attribute should point to whatever the current host name, but instead, it says 'about:blob'.
I feel like I'm missing some headers but cannot figure out which one.
Here are my request and response headers (as captured from the dev tools):
 *  REQUEST  *
Accept: application/json
Accept-Encoding: gzip, deflate
cache-control: no-cache
Connection: Keep-Alive
content-type: application/json
Cookie: JSESSIONID=XXXXXXXX
DNT: 1
Host: localhost:8080
Origin: http://localhost:8080
pragma: no-cache
Referer: http://localhost:8080/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393

 *  RESPONSE  *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: origin, content-type, accept, authorization, x-requested-with, content-encoding, Cookie
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT
Access-Control-Allow-Origin: http://localhost:8080
Cache-Control: no-cache, no-store, must-revalidate
Connection: keep-alive
Content-Disposition: attachment; filename="C:UsersmikhailDocumentsdesktop.ini"
Content-Length: 402
Content-Type: application/json
Date: Tue, 04 Apr 2017 03:42:11 GMT
Pragma: no-cache
Server: WildFly/10
x-filename: C:\Users\mikhail\Documents\desktop.ini
X-Powered-By: Undertow/1

Any idea how to tell Edge to use the hostname instead?

A: The issue resolved in Edge browser version 40.15


text:
Q: UML : is it okay to use only Association in a class diagram ? I feel confused about the three relationships Association, Aggregation and  Composition in UML. I need to finish a project soon, until it became less unclear in my head, is it okay to use only Associations ?

A: Yes, of course it's okay. Both aggregation and composition are types of association. So what you create might not have all the detail it could have but it will still be correct. You can always add details later.
Remember that UML diagrams are models and not complete descriptions of the actual software.
I like to add that in many cases, there really is no clear or objective answer to the question if a given relationship is aggregation, composition or just association.
For more details, you could check this article.

A: Here's why this is so confusing:

c-sharpcorner.com | Dependency, Generalization, Association, Aggregation, Composition in OOP
            |  Ownership  | Lifetime dependency |
Association | none/anyone |        none         |
Aggregation |  one owner  |        none         |
Composition |  one owner  |      on owner       |

Those are some very clear definitions. We depict them this way:

eclipse.org | Papyrus Guide > User Guide > Starter Guide | 7.4.6 Relationships
However when you see

Does that guarantee there is no ownership or merely not insist on ownership? Composition is an Association after all. Now try to read this:
        4  1     1  1
  [Tire]---◆[Car]♢---[Spare Tire]
              | 1
              | 1
       [Cup of Coffee]

And tell me if the names or the UML give you a better understanding of what is going on. If you can't trust me to always use the narrowest relationship depiction possible the symbols stop being important.
Keep that in mind when you diagram. I'm not saying you always have to be 100% faithful, most people aren't, but take responsibility for that and somehow let us know when you are being serious about the symbols and when you aren't. Otherwise this becomes a write once, read never exercise.

A: Essentially, when you have an association, you're stating that at least one instance of A can be dynamically linked to at least one instance of B. You aren't constrained by the type of link existing between the two, other than it's a dynamic link, at class/instance level (i.e., an attribute, not a local variable in a method, that would be a dependency relationship instead). This is useful, for instance, when an instance simply makes use of another instance in a delegation.
When you use an aggregation, you're semantically stating that the instance of A is aggregating (e.g., "part of") at least an instance of B. This is a specialized version of an association, used for instance to model a container and the items it contains (the items of a list).
Composition is the most specialized kind of aggregation (and, by extension, of association). Semantically it expresses that A not only aggregates B, but that the instance cannot exist without its parts. Using a real-life example, it's like saying a LivingPerson needs a Brain and a Heart.
Of course, this is a matter of refining the model. If you are okay with just modeling the association and not going into much detail (usually in the early stages of the design/development, a practice recommended by Robert C. Martin), just go for associations only. If an aggregation or composition is semantically very relevant for the model, then you're somewhat forced to use them. The same goes for a lot of other UML elements (the stereotypes of a dependency, cardinalities...) The key part is that the model is clear enough to be understandable, yet concise enough to provide a clear understanding of the idea being modeled.


text:
Q: react-native - *.js importing *.ts file How to allow *.js files to import *.ts files in react-native but without rename of any of two files?
we want to import below src/lib/setGlobalStyle.ts file from the src/App.js
//MIT LICENSE from: https://github.com/Ajackster/react-native-global-props

import React from 'react'
import { StyleProp, ViewStyle } from 'react-native'

export function setGlobalStyle(obj, customProps) {
 const oldRender = obj.prototype.render;
  const initialDefaultProps = obj.prototype.constructor.defaultProps;
  obj.prototype.constructor.defaultProps = {
    ...initialDefaultProps,
    ...customProps,
  }
  obj.prototype.render = function render() {
    let oldProps = this.props;
    this.props = { ...this.props, style: [customProps.style, this.props.style] };
    try {
      return oldRender.apply(this, arguments);
    } finally {
      this.props = oldProps;
    }
  };
}

but below import which is inside App.js only works when we rename the setGlobalStyle.ts file to setGlobalStyle.js:
import * as Utils from './lib/setGlobalStyle'

and of course the setGlobalStyle.ts currently does not contain any TypeScript types, that is because we had to remove all and rename it to .js so we can continue on the project until this gets an answer.
note: the reason why we need TypeScript is to allow IDE autocomplete of the parameters (i.e. the customProps argument).

A: JSDoc-support in Javascript allows you to import type definitions directly. I know that's not the same as importing the actual module (but I think that is madness if the type definitions exist):
/**
 * @param {import("./mymodule").customProps } customProps
 */
export function setGlobalStyle(obj, customProps) {
    customProps. // has full auto-completion


text:
Q: Spacing with li element I want to have spacing within li block. Basically Count should be on right end on the li block, I tried word-spacing but that's effecting User Name as well:

   User Name
   Count

A: add float: right to count. text-align wont work here.

A: Use float:right instead of text-align:right.

   User Name
   Count

A: Use this code

ul li:after {
      content: " Count";
  }


text:
Q: Ajax get jquery I'm trying to send an ajax request by get through jquery
data is dynamic, when it have many items I get the following error:

The head of the requirement is very large

How can I solve that?
there is a limit characters for these requests?

A: There's not any structural limits on GET request length. However there are limits on your server configuration, sometimes web apps, client browser that specify how long a GET request can be!

Note: Servers ought to be cautious about depending on URI lengths above 255 bytes, because some older client or proxy implementations might not properly support these lengths.

So if your GET request is longer than 255 bytes, It's advised to use POST requests instead.


text:
Q: Datepart Function with If condition I wrote this query to insert data to Att_process Table checkin_time field.
If the CHECKINOUT Table CHECKTIME Field Hours Value < 12,  it should insert in to CHECKINOUT Table checkin_time Field.
And if it is greater than 12 it should insert in to CHECKINOUT Table checkout_time Field
But it doesn't work, can you help me to figure this out and also i don't know how to put this on a trigger, if you can help me, I will really appreciate it.
IF (DATEPART(HOUR,CHECKTIME) < 12)
BEGIN
    INSERT INTO Att_process(USERID,checkin_time)
    SELECT CHECKINOUT.USERID,CHECKINOUT.CHECKTIME
    from CHECKINOUT
    where DATEPART(HOUR,CHECKTIME) < 12;
END
ELSE
BEGIN
    INSERT INTO Att_process(USERID,checkout_time)
    SELECT CHECKINOUT.USERID,CHECKINOUT.CHECKTIME
    from CHECKINOUT
    where DATEPART(HOUR,CHECKTIME) >= 12;
END

A: Plz try this
INSERT INTO Att_process(USERID,checkin_time,checkout_time)
SELECT USERID,
    (CASE WHEN DATEPART(HOUR,CHECKTIME) < 12 THEN CHECKTIME END),
    (CASE WHEN DATEPART(HOUR,CHECKTIME) >= 12 THEN CHECKTIME END)
FROM CHECKINOUT

A: U can use this trigger just change the script accordingly
CREATE TRIGGER trgAfterInsert ON [dbo].[CHECKINOUT]
FOR INSERT
AS
     DECLARE @uid INT;
     DECLARE @checkin DATETIME;
     SELECT @uid = i.USERID
     FROM [CHECKINOUT] i;
     SELECT @checkin = i.CHECKTIME
     FROM [CHECKINOUT] i;
     IF(DATEPART(HOUR, @checkin) < 12)
         BEGIN
             INSERT INTO Att_process
                                    (USERID, checkin_time
                                    )
             VALUES
                    (@uid, @checkin
                    );
         END;
     ELSE
         BEGIN
             INSERT INTO Att_process
                                    (USERID, checkout_time
                                    )
             VALUES
                    (@uid, @checkin
                    );
         END;


text:
Q: iOS send data using socket connection I have implemented socket connection in iOS.
What I want to do is to send string of data to the connected device...
(I am able to receive data when someone sends to my device)
I have tried this code but data is getting received on other device, when I close my app.
- (IBAction)connectToServer:(id)sender {

    NSLog(@"Setting up connection to %@ : %i", _ipAddressText.text, [_portText.text intValue]);
    CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (__bridge CFStringRef) _ipAddressText.text, [_portText.text intValue], &readStream, &writeStream);

    messages = [[NSMutableArray alloc] init];

    [self open];
}

- (void)open {

    NSLog(@"Opening streams.");

    outputStream = (__bridge NSOutputStream *)writeStream;
    inputStream = (__bridge NSInputStream *)readStream;

    [outputStream setDelegate:self];
    [inputStream setDelegate:self];

    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

    [outputStream open];
    [inputStream open];

    _connectedLabel.text = @"Connected";
}

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {

    NSLog(@"stream event %lu", streamEvent);

    switch (streamEvent) {

        case NSStreamEventOpenCompleted:
            NSLog(@"Stream opened");
            _connectedLabel.text = @"Connected";
            break;

        case NSStreamEventHasBytesAvailable:
            if (theStream == inputStream)
            {
                uint8_t buffer[1024];
                NSInteger len;

                while ([inputStream hasBytesAvailable])
                {
                    len = [inputStream read:buffer maxLength:sizeof(buffer)];
                    if (len > 0)
                    {
                        NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];

                        if (nil != output)
                        {
                            NSLog(@"server said: %@", output);
                            [self messageReceived:output];
                        }
                    }
                }
            }
            break;

        case NSStreamEventHasSpaceAvailable:
            NSLog(@"Stream has space available now");
            break;

        case NSStreamEventErrorOccurred:
            NSLog(@"error: %@",[theStream streamError].localizedDescription);
            break;

        case NSStreamEventEndEncountered:
            [theStream close];
            [theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
            _connectedLabel.text = @"Disconnected";
            NSLog(@"close stream");
            break;

        default:
            NSLog(@"Unknown event");
    }
}

 /* Sends data to other device */
 - (IBAction) sendMessage {

    NSLog(@"sendMessage");
    NSString *response  = [NSString stringWithFormat:@"msg:%@", _dataToSendText.text];
    NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
    NSLog(@"[data length] %lu",(unsigned long)[data length]);
    [outputStream write:[data bytes] maxLength:[data length]];

 }

Where I am making mistake?

A: After doing hard research i found adding \n at the end of string message indicates my buffer has received whole string.
now start sending a file, so it worked...
To send a String over Sockets, you must mark the end of the string. ie; Add a \n

A: To mark a string with start and end of string there are ASCII control characters to do so, the octets are \002 & \003 respectively. I would recommend using these control characters instead of just adding a line break, your text could have line breaks and that could create problems.


text:
Q: The server list from source engine games only show very few servers Both Gmod and TF2 only show me like 10 servers, yet games like tabletop simulator shows all server available, so i know there is a problem with source games.
I tried lowering max ping and clear download cache, but nothing happens.

A: All source games use the same algorythm of discovering servers:

*

*the game asks valve's masterserver for a server list, receiving a list of IP addresses

*the game now sends an A2S_INFO UDP packet to each server in a list, at a maximum rate of 250-5000 pings per minute.

*every servers responds with an UDP response packet containing some useful information
Why this happens
Most likely, your internet connection have issues with UDP packets: packet loss, extreme delaying, restrictive filter, etc etc. - packets between you and internet servers lost.. somehow.
What you can do
1. Decrease server query rate
Rate is guessed by steam client, but it's also configurable in
Settings -> In-game -> In-Game Server browser: Max pings / minute

2. Hit refresh servers button again
With my 3G connection it takes multiple clicks, and from 5 to 30 seconds before servers in TF2 client start to appear.
3. Troubleshoot network issues
Anti-virus, firewall or other software may interfere, try disabling it.
Bad hardware (notably your router) can interfere - try connecting to internet directly (if your pc connected  to isp through router)
If none helps, you can call your ISP's customer support.


text:
Q: Custom taxonomy page uses index.php Read a couple of tutorials (here's one) but I don't understand why I can't make it work. I'm trying to create a page for custom taxonomy terms. Like mysite.com/tag/term or mysite.com/category/term but for my taxonomy.
This is what I've done so far:

*

*I registered the new taxonomy
add_action( 'init', 'register_taxonomy_author' );

function register_taxonomy_author() {
     register_taxonomy(  'author', 'post',   //Let WordPress know that the artist   taxonomy has posts
array(
    'hierarchical' => false,
    'label' => 'Authors', // This tells WordPress how to label the various user interface outlets for the artist taxonomy
    'query_var' => true,
    'rewrite' => array( 'slug' => 'author', 'with_front' => false ))
    );
}

*Added a new file called taxonomy-author.php and copied+pasted the codes from category.php into it.

Now, when I try to view the taxonomy terms (Admin Panel > Posts > Authors > View) I get directed to mysite.com/author/term, which is great. But that page uses index.php instead of taxonomy-author.php. What did I miss? Codex states that index.php should be at the bottom, yet it ignores both taxonomy-author.php and my archive.php.

A: Sorry I forgot you can do this. Anyway the problem was that author was a reserved name. I have no idea why it worked for s_ha_dum though, but changing the name would be the safest option.


text:
Q: maps on my own server with google maps api I want to make a website that displays my map, has panning, zooming and other features.
The google API seems to be the right thing for me. Just one question : Can i use the google javascript api with my own map images on my own server. I dont want to use the actual google maps, just its capability to display zoomable/scrollable maps in a browser

A: No, I don't think so.
You may also want to look at OpenStreetMap. I have seen custom map-images being used with its interface.

A: Technically this may be possible using the Overlays section (Ground overlays allow image overlays on the map) of the API and hooking half a dozen events to handle the redrawing at different zoom levels, tiling, hiding the real information about whatever location Google Maps thinks it is showing, etc.
But it is definitely not designed for such purposes and I'm not sure if it would be legal to use it in that way, would have to read the license.
There are other alternatives out there that would be able to achieve this functionality without the level of work needed to get Google Maps to cooperate I believe.

A: I think you'll find that the Google maps interactivity code is geared towards working with Google map servers for the underlying map. However, you could put your own layers over their maps and then serve up your own content so long as it used the same mapping co-ordinates.


text:
Q: SQL Server Express and SharePoint We have a client that would like to use SQL Server Express with SharePoint instead of forking out a minimum or $7000 for SQL Standard. I know SQL Standard is the best option here, but the price tag is a big barrier to entry for this client.
SQL Express has a 10Gb database limit. Does this mean that each database (as in .mdf file) cannot exceed 10Gb or that the total combined size of all databases in a SQL instance cannot exceed 10Gb? From what I could find online it seems it's per database not per instance, but I'd like to verify this.
If it is per database, could we then set up a different SharePoint site for each document library the client wants to host? This would be cumbersome of course, but I would presume that each SharePoint site would have it's own database, which would in turn give each document library a cap of roughly 10Gb. This way they could host more than 10Gb of documents total in SharePoint, but no single document library could exceed 10Gb.
I'm open to other suggestions and thoughts on this subject, but primarily I would like to know if my solution above would be workable.

A: Its per database...The size limits are different for various years though.

*

*Microsoft SQL Server 2005 Express edition has a database size limit to 4GB

*Microsoft SQL Server 2008 Express edition has a database size limit to 4GB

*Microsoft SQL Server 2008 R2 Express edition has a database size limit to 10GB

*Microsoft SQL Server 2012 Express edition has a database size limit to 10GB

*Microsoft SQL Server 2014 Express edition has a database size limit to 10GB

A: This screencast (link only, can't copy video content here) shows how to overcome the 10GB SQLEXP limit by using the file system.