Convert escaped Unicode character back to actual character

Question: I have the following value in a string variable in Java which has UTF-8 characters encoded like below
Dodd\u2013Frank

instead of
Dodd–Frank

(Assume that I don't have control over how this value is assigned to this string variable)
Now how do I convert (encode) it properly and store it back in a String variable?
I found the following code
Charset.forName("UTF-8").encode(str);

But this returns a ByteBuffer, but I want a String back.
Edit:
Some more additional information.
When I use System.out.println(str); I get
Dodd\u2013Frank

I am not sure what is the correct terminology (UTF-8 or unicode). Pardon me for that.
Comment: Wrong, \u2013 is not an UTF-8 character, it is an escaped Unicode character. UTF-8 is a way of encoding UTF characters.
Comment: Have a look at [StringEscapeUtils.unescapeJava()](http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/StringEscapeUtils.html#unescapeJava(java.lang.String))
Comment: the question is unclear to me. When you `System.out.println(yourString);` do you see (1) `Dodd\u2013Frank` or (2) `Dodd–Frank` ?
Comment: `org.apache.commons.lang3.StringEscapeUtils` is deprecated, but moved to `commons-text` as `import org.apache.commons.text.StringEscapeUtils` which is not deprecated.
Comment: @jlordo and SirDarius I have updated the question with details.
Comment: Check the Apache Doc: https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/StringEscapeUtils.html
Comment: Just wanted to understand, why not `"Dodd\u2013Frank".chars().forEach(a -> System.out.print((char) a));` ?
Answer: try
str = org.apache.commons.lang3.StringEscapeUtils.unescapeJava(str);

from Apache Commons Lang
Comment: This might solve your issue in a simple case, but be careful.  If you are trying to use this solution, for example, on a JSON encoded string with UTF8 chars that you want unescaped, it will unescape things that you DONT want touched:  For example, if this String is inside a piece of JSON

"\u003ca href=\"http:\/\/twitter.com\" rel=\"nofollow\"\u003eTwitter Web Client\u003c\/a\u003e"
Comment: If `Java` itself provides the functionality of parsing the value then why should we use any third party tool ?
Comment: @BhavikAmbani Then please explain how, because your answer definitly does not.
Comment: @BhavikAmbani nope, when he prints out his string, he sees `Dodd\u2013Frank`, when we print your string we see `Dodd-Frank`. (before any conversion), his String is `"Dodd\\u2013Frank"`, your String is `"Dodd\u2013Frank"`
Comment: @BhavikAmbani in your own example, try `System.out.println(string);` before calling `getBytes();` and see what happens ;)
Comment: How come ? My answer solves the problem which is specified in the question asked, that convert unicode into readable string format.
Comment: @jlordo I have pasted that also you can check that this prints the perfect output, which I have taked from the console
Comment: str = org.apache.commons.text.StringEscapeUtils.unescapeJava(str);

as commons.lang3 is deprecated.
Answer: java.util.Properties
You can take advantage of the fact that java.util.Properties supports strings with \uXXXX escape sequences and do something like this:
Properties p = new Properties();
p.load(new StringReader("key = " + yourInputString));
System.out.println("Escaped value: " + p.getProperty("key"));

Inelegant, but functional.
To handle the possible IOExeception, you may want a try-catch.
Properties p = new Properties();
try {
   p.load(new StringReader("key = " + input));
} catch (IOException e) {
   e.printStackTrace();
}
System.out.println("Escaped value: " + p.getProperty("key"));

Comment: won't handle newlines
Comment: As written, true, though this solution could be applied to one line at a time.
Comment: Yeah, I am just warning people as I faced that. I actually replaced new lines with some special string, converted and converted back, worked like a charm, but not perfect for production code.
Comment: Works. Another approach is to read in one line at a time using a `BufferedReader` or `BufferedInputSteam` similar and apply this algorithm to one line at a time.
Answer: try

str = org.apache.commons.text.StringEscapeUtils.unescapeJava(str);

as org.apache.commons.lang3.StringEscapeUtils is deprecated.
Answer: Suppose you have a Unicode value, such as 00B0 (degree symbol, or superscript 'o', as in Spanish abbreviation for 'primero')
Here is a function that does just what you want:
public static String  unicodeToString( char  charValue )
{
    Character   ch = new Character( charValue );

    return ch.toString();
}

Answer: I used StringEscapeUtils.unescapeXml to unescape the string loaded from an API that gives XML result.
Answer: UnicodeUnescaper from org.apache.commons:commons-text is also acceptable.
new UnicodeUnescaper().translate("Dodd\u2013Frank")
Comment: `UnicodeUnescaper().translate(...)` needs a `writer` presumably a `StringWriter` - you may as well just use `import org.apache.commons.text.StringEscapeUtils.unescapeJava` from `commons-text`.
Answer: In case you cannot add a dependency to your project, or you simply don't want to, here is a relatively simple implementation using a regular expression.
import java.util.regex.Pattern;

public final class UnicodeUnescape {

    private static final Pattern UNICODE_ESCAPE_PATTERN =
            Pattern.compile("(?<!\\\\)\\\\u(\\p{XDigit}{4})");

    public static String unescape(String input) {
        return UNICODE_ESCAPE_PATTERN.matcher(input).replaceAll(match -> {
            char c = (char) Integer.parseInt(match.group(1), 16);
            return Character.toString(c);
        });
    }

    private UnicodeUnescape() {}
}

Though this is obviously not the most efficient implementation. Also, this will only handle Unicode escape sequences, unlike StringEscapeUtils#escapeJava(String) from Apache Commons Text.
Note that Matcher#replaceAll(Function) was added in Java 9.
Remove (?<!\\\\) from the regex if literals like \\u2013 should still be "unescaped" into \–.

Here's some very basic, non-exhaustive unit tests:
import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

class UnicodeUnescapeTests {

    @Test
    @DisplayName("Unicode sequence is unescaped")
    void testUnescape() {
        var unescaped = UnicodeUnescape.unescape("Dodd\\u2013Frank");
        assertEquals("Dodd–Frank", unescaped);
    }

    @Test
    @DisplayName("surrogate pair is unescaped")
    void testUnescapeSurrogatePair() {
        var unescaped = UnicodeUnescape.unescape("Dodd Frank \\uD83C\\uDF09");
        assertEquals("Dodd Frank ", unescaped);
    }

    @Test
    @DisplayName("escaped Unicode sequence is unchanged")
    void testEscapedUnicodeSequence() {
        var unescaped = UnicodeUnescape.unescape("Dodd\\\\u2013Frank");
        assertEquals("Dodd\\\\u2013Frank", unescaped);
    }
}

Output (from Gradle):
UnicodeUnescapeTests > escaped Unicode sequence is unchanged PASSED
UnicodeUnescapeTests > surrogate pair is unescaped PASSED
UnicodeUnescapeTests > Unicode sequence is unescaped PASSED

Answer: You can convert that byte buffer to String like this :
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.ByteBuffer

public static CharsetDecoder decoder = CharsetDecoder.newDecoder();

public static String byteBufferToString(ByteBuffer buffer)
{
    String data = "";
    try
    {
        // EDITOR'S NOTE -- There is no 'position' method for ByteBuffer.
        //                   As such, this is pseudocode.
        int old_position = buffer.position();
        data = decoder.decode(buffer).toString();
        // reset buffer's position to its original so it is not altered:
        buffer.position(old_position);
    }
    catch (Exception e)
    {
        e.printStackTrace();
        return "";
    }
    return data;
 }

Comment: decoder is object of CharsetDecoder class in java.nio package.Sorry to update that.See the edited answer.Thanks for reminding me.:)
Answer: Perhaps the following solution which decodes the string correctly without any additional dependencies.
This works in a scala repl, though should work just as good in Java only solution.
import java.nio.charset.StandardCharsets
import java.nio.charset.Charset

> StandardCharsets.UTF_8.decode(Charset.forName("UTF-8").encode("Dodd\u2013Frank"))
res: java.nio.CharBuffer = Dodd–Frank

Comment: In the source "\u2013" is alread converted to the UTF-8 character. What would be a correct representation of the problem is "\\u2013" as the text to be converted contains the backslash and each character individually.
Comment: Tried this, but what is actually decoding the UTF-8 character is the fact that it is given directly in the String. What your example does, is to take a UTF-8 String, encode that, decode that, and - luckily - we get the same output as the input.
Comment: curious, what is a string example would fail to convert for this solution?


Working by subdomain in asp.net mvc

Question: I have a website by this domain www.example.com that give some services to users
i want to have a subdomain like this www.external.example.com for giving provided service on www.example.com but just in different view
In other word i want to all controller and action that is accessible on example.com accessible and work in external.example.com too
I just want this subdomain to detect and change my layout(masterpage) to show diffrent view to user
a thing like this in _viewstart.cshtml
@{

    // indecate which layout must show
    if (request from external.example.com)
    {
        // for external load
        Layout = "~/Views/Shared/_ExternalLayout.cshtml";
    }
    else
    {
            // for normal load
            Layout = "~/Views/Shared/_Layout.cshtml";
    }
}

how can do this?
Answer: Find the subdomain:
var url = Request.Url;

string subdomain = string.Empty;

if (url.HostNameType == UriHostNameType.Dns)
{
    string host = url.Host;
    if (host.Split('.').Length > 2)
    {
        int lastIndex = host.LastIndexOf(".");
        int index = host.IndexOf(".");
        subdomain = index.Equals(lastIndex) ? string.Empty : host.Substring(0, index);
    }
}

Then, write some code to select the proper layout:
switch(subdomain)
{
    case "external":
        Layout = "~/Views/Shared/_ExternalLayout.cshtml";
        break;

    default:
        Layout = "~/Views/Shared/_Layout.cshtml";
        break;
}

Working by subdomain in asp.net mvc


When Wifi disconnect, how does Socket on Android server side know that?

Question: I developed an Android app, which works in Wifi AP mode as a Socket server. Some clients setup Wifi connection and socket connection with my app. When the socket is connected, I disconnect the Wifi connection from the client, however there is no exception nor the read method of socket return -1 in my server app. My questions are:

How to detect the broken wifi connection
How to detect which client's wifi connection is broken

Thanks.
Answer: Use this in a Thread
<code>public static boolean checkNetworkConnection(Context context)
{

   final ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

   final android.net.NetworkInfo wifi =connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
   final android.net.NetworkInfo mobile =connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

   if(wifi.isAvailable()||mobile.isAvailable())
       return true;
   else
       return false;
}
</code>
Comment: Thanks. But in my situation, there are several Wifi connections with my AP. getNetworkInfo() method returns which one of them?
Comment: @yinhao try WifiManager wifi = (WifiManager)(this.getSystemService(Context.WIFI_SERVICE)); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); the wifiInfo has some state
Comment: Thanks again for your reply. However there are several Wifi connections. getConnectionInfo return which one? I think this method is used on Wifi Client side instead of AP server side. Because on client side, there is only one Wifi connection.


Froala - get HTML

Question: I'm trying to get the current HTML from an element using Froala 2.4
My main reason is to be able to compare the original HTML from the new HTML to see if the user has changed anything, and if that case trigger a save-event.
Here's my current code
console.log($(this).froalaEditor('html.get'))
console.log($(this).data('froala.editor')._original_html);

And here's the output

TestStringEdited

TestStringOriginal

The problem is that I want to only retrieve this from the first outout:
 TestStringEdited

(I don't want the Paragraph-tag to be included, in this example)
I could make a short function to take care of that for me, but it seems like I'm missing something really obvious regarding the way I get the string from Froala.
Help really appreciated!
Comment: I have updated my answer supposing you need to get rid only of top-level `` tags.
Answer: You probably need to store the contents of your editor somewhere:
var html = $(this).froalaEditor('html.get'); //
TestStringEdited

And then just strip out HTML tags, if I got you right. The simplest way is jQuery .text() method:
var text = $( html ).text(); // TestStringEdited

update
You need to strip only upper-level
 tags right? Here is a function that implements filtering that tags with help of jQuery. But you can rewrite it and make an array of exclusion tags, or call it recursively on each child element of content. And also, you can use regular expressions as an alternative.
function stripParagraphs( html ) {
  var r = '';

  $( html ).each(function() {

    // test each higher-level tag to be

    if ($( this ).prop( 'tagName' ) === 'P') {
      r += $( this ).html(); // add contents of
 to result

    } else {
      r += this.outerHTML; // add the whole element to result
    }
  })

  return r;
}

Live example.
one more update
Strip all top-level tags.
function stripTopLevelTags( html ) {
  var r = '';
  $( html ).each( function() {
    r += $( this ).unwrap().html();
  });
  return r;
}

Live example
Comment: That is a working alternative for this situation in particular, I'll edit the question a bit in a minute! I still need it to be HTML.
Comment: Thanks for the update, I will stick with it for now, (It is not always a p-tag), I updated it to one row using this: alert($(html).first().remove().html());  I'll accept your answer in a few hours unless a better solution comes up! Thanks a lot!
Comment: @Tompina well, that line doesn't work for more than one top-level elements but you know better :) Good luck!

Froala - get HTML


IFrame positioning Dynamically

Question: Currently working on IFrame but I am facing serious issue: I am creating a Iframe where i am placing  my Chat service so that I could use this service on other projects and want to have fixed position in my other projects that is right bottom of other projects page:
here is how I am using my script in other projects:
index.html
    <!DOCTYPE>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Collaborative Text Editor</title>

    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
    <link href="/css/app.css" rel="stylesheet"></link>

My Paragraph

this line of code

here src is for testing purpose and IFrame styles is not working plus I want a fixed position always that is the right bottom of div concluding this:
I want a script with IFrame that has fixed position i.e want to embed this script on other pages or website with static position that is right bottom
any help will be highly appreciated.
Comment: If you want it in a fixed position, why aren't you setting the `position` property?
Answer: First you forgot to add a position property.
Try this code:

IFrame positioning Dynamically


Why is my .wav file not running?

Question: Without using structures, I'm trying to create a wave file that generates a tone at 900 Hz for five seconds. When I run it, however, it doesn't run or even give me the sample rate or the number of bytes. Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main () {
    FILE* fp;
    fp = fopen("sine.wav", "wb");
    if (fp == NULL) {
        printf("File does not exist.\n");
        return EXIT_FAILURE;
    }
    char ChunkID[4] = "RIFF", Format[4] = "WAVE", Subchunk1ID[4] = "fmt", Subchunk2ID[4] = "data";
    unsigned int ChunkSize, Subchunk1Size, Subchunk2Size;
    unsigned short int AudioFormat, NumChannels, BlockAlign, BitsPerSample;
    int SampleRate, ByteRate;
    Subchunk1Size = 16;
    AudioFormat = 1;
    NumChannels = 1;
    SampleRate = 44100;
    ByteRate = 2 * SampleRate;
    BitsPerSample = 16;
    BlockAlign = NumChannels * BitsPerSample / 8;
    Subchunk2Size = 10 * ByteRate;
    ChunkSize = Subchunk2Size + 41 - 8;
    fwrite(ChunkID, 4, 1, fp);
    fwrite(&ChunkSize, 4, 1, fp);
    fwrite(Format, 4, 1, fp);
    fwrite(Subchunk1ID, 4, 1, fp);
    fwrite(&Subchunk1Size, 4, 1, fp);
    fwrite(&AudioFormat, 2, 1, fp);
    fwrite(&NumChannels, 2, 1, fp);
    fwrite(&SampleRate, 4, 1, fp);
    fwrite(&ByteRate, 4, 1, fp);
    fwrite(&BlockAlign, 2, 1, fp);
    fwrite(&BitsPerSample, 2, 1, fp);
    fwrite(Subchunk2ID, 4, 1, fp);
    fwrite(&Subchunk2Size, 4, 1, fp);
    int i, amplitude = 37000;
    short int audio;
    float w, freq = 900 * 4;
    w = 2.0 * M_PI * freq;
    for(i = 0; i < 5 * SampleRate; i++) {
        if (i < 5 * SampleRate / 4)
            w = 900 * 4;
        else
            w = 0;
        w *= 2.0 * M_PI;
        audio = amplitude * sin(w * i / SampleRate);
        fwrite(&audio, 2, 1, fp);
    }
    fclose(fp);
    return EXIT_SUCCESS;
}

Comment: Does the produced file contain the bytes you expect (have you tried looking at it with a hex editor?)
Answer: The most obvious problem is the Subchunk1ID which you have as "fmt".
That should be "fmt ", note the space at the end.
Comment: That fixed everything! Thank you!

Why is my .wav file not running?


Fixing a old wood wall

Question: 1961 house. Recently bought. The house appraiser told me that I had post-and-plank type walls and could get a fun "barn" look by removing the finish. So I did a test and stripped a part of a wall. The wood was covered with tar paper, wood laths, two layers of gypsum board, and white "brick" prefinished panels on top.
The thick wooden planks have shrunk, leaving gaps that are about a quarter inch wide. Through the gaps, you can see another layer of tar paper (behind that is insulation, and the exterior brick wall). The gaps seem to be a problem, insulation-wise. Even though I was told that one does not need to insulate the inside of a plank-and-post wall, the temperature inside the gaps is about 53°F, and 63°F in front of the wall (outside temperature today is 5°F). So there is an airdraft problem.
On the pictures you can also see that some of the planks have a broken corner  (like the vertical plank on the right) or are cracked.
So if I want to go with a bare wall / barn look, that leaves me with a few questions:

How do I fill the gaps?
How do I fix the broken/chipped planks?
Should I sand / apply some sort of protective finish to the wood?

1) I looked at ressources on how to fix gaps in old wooden floors and it seems that my best option for the gaps is cotton rope for the smaller gaps and oakum for the larger ones. Would that do the trick for a wall?
2) For the broken and cracked planks, I am thinking of filling the holes with a paste made with glue and sawdust from the wood laths that I removed. Another option is colored epoxy filler, or maybe just leave it like that.
3) For the finish, I really don't know if it is even necessary. It's a wall in a living room. But guests or children could get a splinter from touching the wall, so maybe a light sanding and some sort of protective finish would be better.
Thank you.

Addendum: the finished wall:
[
Comment: If nothing else, wood planks like that have a 0 finish rating and probably aren't going to meet any sort of standards for smoke-developed or flame-spread either...
Comment: The rough wooden planking is not suitable as a finished interior wall. Drywall is far preferable.
Comment: I love it. but not sure the amount of work to make it draft free is worth it. How about non exterior walls do they have planking as well, if so i would expose those.
Comment: Alaska man: the non-interior walls do not have planking. Supposing I only plug the gaps with rope, it could still take a while.
Comment: Please check and make sure what you are pulling out isn't asbestos as well. We are updating our home built in the late 70s and we know they used asbestos in drywall and insulation til the mid-late 70s.
Answer: In my opinion, I would put the wall back as it was.
Part of the whole charm of the barn look is the roughness, textures, cracks etc., the things that sounds like you want to fix. Even if you could get an "upscale" barn look by doing what the questions surround, would severely change the look you have now.
Gluing cracks will change the color of the wood, it will run and drip. Mixing sawdust in the glue will leave a mess on the surface, it never goes in the gap clean, and will require sanding. The planks have a great patina. Patina (aged look) is a color that can only be achieved by time, and is highly sought after. It can be faked, but is expensive. Sanding this patina will remove the saw marks and the patina and pretty much render the wood to an almost new condition. IN doing that you would be better and simpler in some ways to just install new wood planks. Shiplap is a big trend now.
When the appraiser discerned the type of building you had, there was no way to know how cut up the paneling was or what condition it was behind the drywall. One could only hope it is in good shape, well enough to salvage. What I see is where a window may have been filled in or a repair made a long time ago, or perhaps the builder ran short of material, or changed their mind about having a window there. It happens all the time.
Comment: Epilogue: I ended up putting the wall back as it was.
Comment: To remove the splinters you are concerned about, you could lightly wire brush the surface by hand only going in one direction with the grain, or use a stiff bristle scrub brush to knock off the surface splinters without harming the color. The surface can be sealed with a clear water based finish that has no sheen, like a flat or matte finish. Do a test sample to make sure it dries the way you want. Water based finishes typically do not change the look of the wood as long it is a flat or matte sheen.
Comment: Do you have a finished picture?
Comment: Jack: I edited my post to add pictures.
Comment: I see, you put it back to the drywall, not the wood. Still looks good, and you know you have solid backing there for fastening...
Answer: What you are doing is like removing plaster to expose the underlying brick wall. That's rather fashionable these days but may not be a great solution in terms of energy efficiency and comfort. Read over this opinion piece on the topic and I think you will see the parallels with your situation:

Old townhouse party walls are made of soft, porous brick sloppily laid up because the masons knew the walls would be covered with plaster.

Once stripped, the exposed brick both collects dust and sheds its own mortar and brick particles.

If the bare brick is covered with a sealer to retard exfoliation, the sealer imparts a plastic-looking sheen that detracts from the desired natural, rustic appearance of the brick.

The plaster acts as an extra layer of insulation and protection in case of a fire in the row house next door.

Worst of all, the lack of plaster greatly increases sound transmission from the adjacent building. If your neighbor also exposes the brick on his or her side of the party wall, you can conduct a conversation through the bricks.
Comment: Thank you. In my case I have to mention that there is no adjacent building.

Fixing a old wood wall


How can I control a circuit breaker remotely?

Question: We have a house in the country that largely sits abandoned. We have a large family, and we like to go visit for the weekends. When we leave the house, we turn off the circuit breakers to prevent high electrical bills. But lately, some family members have decided to "live" at the house.
    The problem: they do not take responsibility for the electrical bill. Legally we have no right to prevent the family members from staying at the house, but we want a way to limit electricity usage to those who have pay for the electricity.
What I would like is a way to have remote control of the circuit breakers. I would like to be able to have a "remote kill switch" for the electricity and the circuit breakers seem like the right place to do it. But another method to turn off the electricity, and ensure that it cannot be turned on, would work too.
Is there a way to install a "meter after the meter" or something like this?
What should we be asking our electrician to install and where?
Comment: You've got an inter-personal problem with your family members who are sticking you with the electric bill. I recommend that you try to fix that problem NOW (by talking to the offenders) before it turns into an all-out feud. If it's already a feud, then perhaps you just need to turn off the electric to the house.
Comment: Shut off the electricity completely. Buy yourself a generator to take with you when you want to use the house.
Comment: A cheap energy monitor would give you awareness of the costs over time. If you go for an online energy monitoring system, you could get printed reports to bill your family with. http://gigaom.com/cleantech/10-energy-dashboards-for-your-home/
Comment: Why do you have no legal right to prevent them from staying there? Who is on the title?
Answer: Install a lock on the panel, or main shutoff. Then only give keys/combination, to those family members that pay their share.  Check with your local government before installing the lock, as it may not be legal in some jurisdictions.

Search for a circuit breaker lockout. A lockout is a device that easily attaches to a breaker, and prevents the breaker from being turned on. A combination or pad-lock can be installed, which will prevent unauthorized users from turning the breaker on.
Comment: +1, I'd expect a separate shutoff that doesn't prevent the circuit breakers from tripping or the power company from servicing the meter would be within code. You'd have to rewire to go from the meter to the lockable shutoff to the panel, so this will require an electrician with permits.
Answer: If other family members are living in the house, why are you responsible for the utilities.  Give them fair warning to put the power in their name by X date and issue a shut down order to the company for that date.  If they want power, they can pay for it.
Comment: Exactly.  Treat them like renters.  You could draw up a contract, if needed.
Comment: In a lot of states it's illegal to just shut off power to renters.  You can get them evicted, but during that process are required to keep service for water, power and other utilities in areas you are responsible for.
Comment: Illegal to shut it off.  Not illegal to tell the power company that it's going to be put in their name.  All of my tenants pay their own power bills.
Answer: What you propose is possible.
But an arrangement that is liable to be more satisfactory overall is to have a "pay as you go" meter installed which can accept coin payment. You can get units made to serve a whole house and also ones designed to control a range or commercial dryer etc. See below.
Have you got a good feel for the sort of charges involved and what causes them? You MAY be able to avoid family discord by limiting power to some equipment only.
Assume power costs $US0.20 / kWh. It may be as little as half that in some areas and more in a few.

Say D =- dollars per kWh = 0.2 in this case.
 So Kpd = KWh per dollar = 1/D = 5 in this case. ie 5 kWh per dollar.

For an appliance raed at W wAtts.

 - Hours of use per kWh = 1000/W

 - Hours of use per $ = 1000 / W / D   = 1000/WD
 or for D= $0.20 as above
 Hours of use for $1 = 5000/W

Then:

A 20 Watt CFL bulb takes 1000/P = 1000/20 = 50 hours
 Or hours of use per $ = 5000/20 = 250 hours.
 That's about 10 days non stop of 60 days at 4 hours/day.
A small to medium watertank takes about 6000 Wh = 6 kWh to reheat.
 Think of this as  a 6000 Watt appliance operating for 1 hour.
 From above hours per $ = 5000/6000 = 50 minutes so 1 hour reheat !~= $1.20.
 That would provide 2 generous showers or 5 -10 careful showers or a bath plus general dishes cleaning and ablutions.
Rangetop element is say 1 kW to 3 kW = 5000/1000 = 5 hours to 5000/3000 = 1.66 hours per dollar. ie most stovetop cooking will cost under $1/day.
Range = ? - say 5 kW or 5000/5000 = $1/hour. Roast dinner will not run on full most of the tome so probably under $1 / meal for range in oven use.
Microwave oven 650 Watts = 5000/65- = 7+ hours per $1.
 ie Microwave over will cost << $1 /day.

Heating is the cost generator.
 1 bar heater = 1000 W = 5000/1000 = 5 hours per $.
 Some larger fixed heaters may be 2 kW or more.
Dehumdifier? - lock it up.
 Air conditioner? -  throw it out :-)
A mix and match approach with metering may work.
Answer: I'd install an alarm system, only give out the temporary pin to trusted family, and change the pin anytime you think the place is being abused. Tell the rest of the family about it, and tell them that they'll be charged for any false-alarms and utilities or else you'll have them cited for trespassing. And finally, for any family visiting, let them know they will owe you for any power used after their visit if they don't turn the alarm back on.
Basically, you want the threat of a police visit rather than the annoyance of them having to break your lock. This also means that you can leave some minimal heat/ac running to prevent the pipes from freezing or other damage to the house.
Comment: "Legally we have no right to prevent the family members from staying at the house,…", that could pose a serious issue for calling the police on them.


result from Await DisplayAlert Xamarin.Forms

Question: Xamarin has awaitable DisplayAlert method which returns Task<bool>.
I have static class Helpers where i want to write code like this:
public static bool DisplayAlert(string title, string message, string accept, string cancel){
    //return answer from Page.DisplayAlert(title, message, accept, cancel);
}

This method will be called from other parts of the app like:
public ... SomeMethod(){
    // some code
    bool result = DisplayAlert(...);
    // some code
}

I want to avoid async/await in SomeMethod. (How you can wait a response from a user asynchronously?!!!!!!)
I tried  await Page.DisplayAlert(...), task.Wait() and another. But Task was executed asynchronously with no return value. Or application freezes forever without displaying DisplayAlert.
How to do it? What's the best practice?
Answer: If you want SomeMethod to remain Synchronous, this is one option:
public async static Task<bool> DisplayAlert(string title, string message, string accept,
string cancel){
 return await Page.DisplayAlert(title, message, accept, cancel);
}

// SomeMethod will run Synchronously
public boolean SomeMethod(){
  bool result = StaticClass.DisplayAlert(..).Result;
  return result;
}

EDIT: Fixed some syntax
Comment: In the Mobile world you very rarely want syncronous calls, you should never block your UI in any case
Comment: Thanks, but this code will deadlock (((  use async all the way down seems illogical to me...
Comment: Not deadlock, it will wait syncronsly until DisplayAlert returns a result. That's not definition of a deadlock.
Comment: i tried but there is deadlock. [link](https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html)
Comment: Alright ok, so why do you want `SomeMethod` to be sync ?
Comment: Where do you call this method
Comment: For example, ```SomeMethod``` is called into the button click. But you're right SomeMethod no need to be sync.


For creating common widgets, which one is best Statless, stateFull or simple function with named params?

Question: If a widget has the same style all over the project. We make it common so that we can easily use that with a minimal number of lines. But which one should I use to create a common widget.
Let's assume I have a text widget and text form field widget with the same style. Which one should I use?
What if the text widget has a dynamic string?
and
what if the text widget has a simple String?

Stateless widget / stateful widget  or
Simple Function with named params
Comment: It purely depends on the usage of the widgets.  Can you explain the purpose of your widgets a bit!
Answer: According to flutter team, Widgets are better than helperMethods, refer to the video Widgets vs HelperMethods,
StatelessWidgets are lighter than StatefulWidget so as long as you can use StatelessWidget over the StatefulWidget pick the StatelessWidget, but some widget might not work if it was in a StatelessWidget such as the TextField
if you try to put a TextField inside a StatelessWidget it will clear it's value everytime you open the keyboard or a dialog pops up, so
StatelessWidgets are the best but sometimes it wont work
StatefulWidget are the second bes option
helperMethods are good only if you have a widget with a shared style inside a single screen


My Android app crashes with "Found invalid root: 0x2"

Question: I need some help interpreting a stack trace!
I am writing an OpenGL game for Android, and I am almost done.  I just updated to Android 5.1.1 on a Nexus 5.
The app uses the bullet physics library, as built by LibGDX, which is native code.
After updating, my app has started crashing intermittently.
Here is the top of the crash stack:
<code>09-06 23:34:23.664: E/art(1778): Tried to mark 0x2 not contained by any spaces
09-06 23:34:23.664: E/art(1778): Attempting see if it's a bad root
09-06 23:34:23.666: E/art(1778): Found invalid root: 0x2
09-06 23:34:23.666: E/art(1778): Type=RootJavaFrame thread_id=14 location=Visiting method 'com.spher.cblast.world.Signal com.spher.cblast.activities.BulletLevelScene.updateBoard(float)' at dex PC 0x01a8 (native PC 0xa392ace3) vreg=9
09-06 23:34:23.666: A/art(1778): art/runtime/gc/collector/mark_sweep.cc:381] Can't mark invalid object
09-06 23:34:23.904: A/art(1778): art/runtime/runtime.cc:289] Runtime aborting...
09-06 23:34:23.904: A/art(1778): art/runtime/runtime.cc:289] Aborting thread:
09-06 23:34:23.904: A/art(1778): art/runtime/runtime.cc:289] "GLThread 972" prio=5 tid=14 Runnable
09-06 23:34:23.904: A/art(1778): art/runtime/runtime.cc:289]   | group="" sCount=0 dsCount=0 obj=0x12c22bc0 self=0xb4a26c00
09-06 23:34:23.904: A/art(1778): art/runtime/runtime.cc:289]   | sysTid=1812 nice=0 cgrp=default sched=0/0 handle=0xb491b280
09-06 23:34:23.904: A/art(1778): art/runtime/runtime.cc:289]   | state=R schedstat=( 28691639167 2902450009 24576 ) utm=2811 stm=58 core=0 HZ=100
09-06 23:34:23.904: A/art(1778): art/runtime/runtime.cc:289]   | stack=0xb353e000-0xb3540000 stackSize=1036KB
09-06 23:34:23.904: A/art(1778): art/runtime/runtime.cc:289]   | held mutexes= "abort lock" "mutator lock"(shared held)
09-06 23:34:23.904: A/art(1778): art/runtime/runtime.cc:289]   native: #00 pc 00004e64  /system/lib/libbacktrace_libc++.so (UnwindCurrent::Unwind(unsigned int, ucontext*)+23)
09-06 23:34:23.904: A/art(1778): art/runtime/runtime.cc:289]   native: #01 pc 00003665  /system/lib/libbacktrace_libc++.so (Backtrace::Unwind(unsigned int, ucontext*)+8)
09-06 23:34:23.904: A/art(1778): art/runtime/runtime.cc:289]   native: #02 pc 00256429  /system/lib/libart.so (art::DumpNativeStack(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, int, char const*, art::mirror::ArtMethod*)+84)
09-06 23:34:23.904: A/art(1778): art/runtime/runtime.cc:289]   native: #03 pc 00238fe7  /system/lib/libart.so (art::Thread::Dump(std::__1::basic_ostream<char, std::__1::char_traits<char> >&) const+158)
09-06 23:34:23.904: A/art(1778): art/runtime/runtime.cc:289]   native: #04 pc 0022881d  /system/lib/libart.so (art::AbortState::DumpThread(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, art::Thread*)+32)
09-06 23:34:23.904: A/art(1778): art/runtime/runtime.cc:289]   native: #05 pc 00228a87  /system/lib/libart.so (art::AbortState::Dump(std::__1::basic_ostream<char, std::__1::char_traits<char> >&)+354)
09-06 23:34:23.904: A/art(1778): art/runtime/runtime.cc:289]   native: #06 pc 00228c7f  /system/lib/libart.so (art::Runtime::Abort()+82)
09-06 23:34:23.904: A/art(1778): art/runtime/runtime.cc:289]   native: #07 pc 000a7371  /system/lib/libart.so (art::LogMessage::~LogMessage()+1360)
09-06 23:34:23.904: A/art(1778): art/runtime/runtime.cc:289]   native: #08 pc 0012d81b  /system/lib/libart.so (bool art::gc::accounting::HeapBitmap::AtomicTestAndSet<art::gc::collector::MarkSweepMarkObjectSlowPath>(art::mirror::Object const*, art::gc::collector::MarkSweepMarkObjectSlowPath const&)+442)
09-06 23:34:23.904: A/art(1778): art/runtime/runtime.cc:289]   native: #09 pc 0012d8ef  /system/lib/libart.so (art::gc::collector::MarkSweep::MarkObjectParallel(art::mirror::Object const*)+142)
09-06 23:34:23.904: A/art(1778): art/runtime/runtime.cc:289]   native: #10 pc 0012eaeb  /system/lib/libart.so (art::gc::collector::MarkSweep::MarkRootParallelCallback(art::mirror::Object**, void*, art::RootInfo const&)+26)
09-06 23:34:23.904: A/art(1778): art/runtime/runtime.cc:289]   native: #11 pc 0023d86f  /system/lib/libart.so (art::ReferenceMapVisitor<art::RootCallbackVisitor>::VisitQuickFrame()+806)
09-06 23:34:23.905: A/art(1778): art/runtime/runtime.cc:289]   native: #12 pc 0023dcb9  /system/lib/libart.so (art::ReferenceMapVisitor<art::RootCallbackVisitor>::VisitFrame()+224)
09-06 23:34:23.905: A/art(1778): art/runtime/runtime.cc:289]   native: #13 pc 00231959  /system/lib/libart.so (art::StackVisitor::WalkStack(bool)+276)
09-06 23:34:23.905: A/art(1778): art/runtime/runtime.cc:289]   native: #14 pc 002336b3  /system/lib/libart.so (art::Thread::VisitRoots(void (*)(art::mirror::Object**, void*, art::RootInfo const&), void*)+994)
09-06 23:34:23.905: A/art(1778): art/runtime/runtime.cc:289]   native: #15 pc 0012db67  /system/lib/libart.so (art::gc::collector::CheckpointMarkThreadRoots::Run(art::Thread*)+126)
09-06 23:34:23.905: A/art(1778): art/runtime/runtime.cc:289]   native: #16 pc 00233c2f  /system/lib/libart.so (art::Thread::RunCheckpointFunction()+182)
09-06 23:34:23.905: A/art(1778): art/runtime/runtime.cc:289]   native: #17 pc 0008774f  /system/lib/libart.so (art::JniMethodStart(art::Thread*)+390)
09-06 23:34:23.905: A/art(1778): art/runtime/runtime.cc:289]   native: #18 pc 000c5de3  /data/dalvik-cache/arm/data@email@example.com@email@example.com (Java_com_badlogic_gdx_physics_bullet_dynamics_DynamicsJNI_btDiscreteDynamicsWorld_1stepSimulation_1_1SWIG_11__JLcom_badlogic_gdx_physics_bullet_dynamics_btDiscreteDynamicsWorld_2FI+78)
09-06 23:34:23.905: A/art(1778): art/runtime/runtime.cc:289]   at com.badlogic.gdx.physics.bullet.dynamics.DynamicsJNI.btDiscreteDynamicsWorld_stepSimulation__SWIG_1(Native method)
09-06 23:34:23.905: A/art(1778): art/runtime/runtime.cc:289]   at com.badlogic.gdx.physics.bullet.dynamics.btDiscreteDynamicsWorld.stepSimulation(btDiscreteDynamicsWorld.java:71)
09-06 23:34:23.905: A/art(1778): art/runtime/runtime.cc:289]   at com.spher.cblast.activities.BulletLevelScene.updateBoard(BulletLevelScene.java:1010)
</code>
I am calling the native bullet 'stepSimulation' method.
Somehow, the garbage collector appears to be finding an invalid root, whatever that means.  The stack trace is always the same.
Any thoughts would be greatly appreciated!
Comment: are you doing xml parsing? if yes post ur code
Comment: Hi, no I am not doing XML parsing.  I have loaded 3D models into bullet, and am updating the scene according to the physics world.  It works great most of the time :-(
Comment: this error is generally comes because of an invalid character string in your data stream.
Comment: An invalid character in an XML stream generally causes a XMLStreamError exception (or similar) to be thrown.  I am getting a crash with:  A/libc(1778): Fatal signal 6 (SIGABRT), code -6 in tid 1812 (GLThread 972)
Answer: I believe I have eliminated my crash.
My call flow went from:
updateBoard(Java) --> Bullet::stepSimulation(native) --> collisionCallback(Java)
Inside the Java collisionCallback, I was dereferencing some objects, causing garbage.
I modified the code to no longer discard the objects in the collisionCallback, and I have not seen the crash since.


How to convert Mongo db type from String to Object type for existing document

Question: I am using Spring, mango db and mongock. When I started working on project hen Mongo entity has one column (Address) of type String. But now its type is changed to string to Address object. Like below code.
Now this solution is working for new entity perfectly fine but when try to get existing
Old Code :
<code>@Document(collection = PersistenceConstants.TALENT_COLLECTION)
    public class Talent extends AbstractMongoEntity<String>{
        private String address;
    }
</code>
New Code :
<code>@Document(collection = PersistenceConstants.TALENT_COLLECTION)
    public class Talent extends AbstractMongoEntity<String>{
        private Address address;
    }

{"city","", "country":"India"}
</code>
But when trying to fetch old records, system throws
<code>No converter found capable of converting from type [java.lang.String] to type
</code>
Could someone tell me , what is work around to fix this issue.
Comment: I think you should migrate all Talent Document to new Talent2 Document with correct format, after that use it instead of Talent Document. :)
Answer: this is basically what Mongock is for. You are facing a data migration issue.
So the solution is to create a Mongock ChangeLog(the migration unit) to transform the old talent documents in MongoDB to the new Document structure. Then you're safe to work with your new Talent repository as all your documents would have the new structure.
The steps would be something like.

Extract all your documents from talent collection
Check the address field of all the documents, if it's a string, transform it to your new structure.
Bulk update for all those amended documents.

Then you need to take into account the possibility of failure. Mongock now supports transactions, so if you are using them, you are fine.
If not, you need to design your changelog taking some considerations. This link gives you some context.
Also worthy to take a look to Mongock's documentation.
Mongock latest version at this moment is 4.1.15


Android application name error

Question: I tried to build an android application, when I use non-english langues like persian as name of application it causes this error AndroidManifest.xml file missing and no manifest builds but when I use english it works successful, why?
Comment: Can you post the error?
Comment: Can you post your AndroidManifest.xml file? At least the relevant part..
Comment: @Arman: I posted it before `AndroidManifest.xml file missing`
Comment: @krsteeve: I said it creates no manifest file, what do you mean by posting it?
Comment: That's the only one? Can you post your manifest file? Have you tried cleaning your project?
Comment: @Amir you must have an AndroidManifest.xml ... it will be at the top level of your project, beside the `src` and `bin` folders
Comment: As I build the project it shows me that error in console when I retry building same project with english name it works fine
Comment: @krsteeve: my problem is that I have no manifest file if I had it there was no error
Comment: @AmirSadegh what the guys are confused about your explanation. Is that AndroidManifest is generated by the programmer and compiled by the SDK. If there's an error the SDK won't generate your app, but the AndroidManifest.xml should still exist because you have to create it yourself manually.
Answer: at the top of every XML file in Android you'll see
<?xml version="1.0" encoding="utf-8"?>

So first I ask you: is persian included in utf-8 encoding?
I had a quick look on this link http://www.utf8-chartable.de/ and it seems to be me that's a no but I'm no language expert and that table might show persian as one of it related or base languages (like portuguese uses latin set)
If persian is not available in the utf-8 your best option to try to get this name in the app name is to create a strings_per.xml (inside the /values/ folder) and in there you put a different encoding and the string you need for the app name.
note that I tried to isolate the problematic variable in its own file because I'm not sure it would be a good idea to mix it with the rest of the manifest.
Answer: Farsi IS included in UTF8.
You need to add a string in strings.xml in /res/values.
Then define a farsi name there.
Your string.xml will look like this:

<string name="app_name">اسم اپ</string>
<string name="title_tab1">تماس با ما</string>
<string name="action_settings">Settings</string>

And you will reference it in you manifest.xml like this:
android:label="@string/app_name"
But remember: Farsi characters are not perfectly shown in android 2.2 and 2.3.
The characters are displayed separately. For later androids this is not an issue.

Android application name error


enabling notifications

Question: I would like to enable notifications in my iphone app. So, I modify in app ID:

After that, I generate again Development and Distribution Provisioning Profiles and installed in my xcode.
My app is a tabbed based application, the first tab is UITableViewController
I add this lines:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];

   return YES;
}

So, I suppose I should have my app in the list of app installed with notifications in my iphone, but it isnt.
Did I miss some step?
Answer: First enable your remote notification in app delegate. See below :
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];

    // Let the device know we want to receive push notifications
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
        (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];

    return YES;
}

Comment: I thy this, without the self.window lines because of the other solution, but still doesnt work. Is it possible to add this to a UITableController? where should I add this?
Comment: u have get any alert msg like this http://cdn2.raywenderlich.com/wp-content/uploads/2011/05/Basic-App-2-Allow-Notifications-333x500.jpg
Comment: if no, check your bundleId is matching with ur provisioning profile.
Comment: No, I dont get this alert, but I check the bundleID<->provisioning profile, its ok
Comment: no, u don't want to alert this one. which automatically ask When the app starts and registers for push notifications, it shows a message to inform the user that this app wishes to send push notifications.
Comment: yes, I undertood what you were saying after write the comment, so, I deleted my coment because I realized I was wrong
Answer: Yep. According to this and this you should add the registerForRemoteNotificationTypes method in your didFinishLaunchingWithOptions, which should the look something like this:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];

    return YES;
}

Depending on which Types you registered your app will appear in the notifications section and you can turn on and off the different types (sound, badge, banner).
Hope that helps.
Comment: I change the lines I had before for this and still doesnt work. Can I add this liens in a UITableViewController?
Comment: No. This method definetely belongs into your AppDelegate.m. The method is - as the name says - called, when the app did finish launching, but only when in the AppDelegate, so put it there and it should work.

enabling notifications


Flutter Cannot resolve symbol 'embedding' and Cannot resolve symbol 'FlutterActivity'

Question: error shown in Flutter Android project folder in mainactivity
package com.malik.database_demo;

import io.flutter.embedding.android.FlutterActivity;

public class MainActivity extends FlutterActivity {
}

Comment: Did you run `flutter pub get`?
Comment: flutter pub get for what ?
Comment: For `get`ing the Flutter dependencies.
Comment: Its not the dependencies issue although i have run it anyway i am in Android project folder in mainactivity and this errors always shows up
Comment: What does it look like if you run `flutter doctor -v`?
Comment: all is ok and no issues found
Answer: Currently you are probably trying to directly edit the MainActivity class from your Flutter project. (By expanding android -> Navigation to 'MainActivity.java' or 'MainActivity.kt' and editing it).
I have observed that when we try to edit the native side code this way, Flutter is not able to recognize the android part.
What you can do is open the 'android' part of your flutter project and then edit it.
To achieve this :

Click File -> Open -> Navigate to your current Flutter project -> Expand it and find the android part (refer the example below)

[1 = Your current Flutter project,2 = The android part of your flutter project]

Click on that android part and click Open. Wait for the indexing and all to complete and then I dont think it will give those errors.

GLHF :)
Comment: This is something we get from experience.Thanks, Sarvesh Bhava
Comment: yes no errors at the same current new window , but backing to the main project tab it still ask for jar file and the errors still tuned ! ,, i think it is jar issue ..
Comment: Thanks it's really helpful for someone new in flutter.
Answer: I added flutter.jar as a library. This seemed to work.
I'm not sure if there are some unintended consequences yet!
Answer: A little update on Servesh Dalvi's response: if you're using any of the latest  versions of android studio like Android Studio Giraffe you might want to open your android part of your flutter project like the attached screenshot shows, by clicking on the android part directory, scroll down to Flutter, and select 'open Android module in Android Studio.
Answer: What solved my problem is by navigating to the android part of the application as mentioned earlier in the first answer where the indexing of the gradle files was performed and then when I re opened the project view of the application then the error was still not resolved.
Then I run the following commands

flutter clean

flutter pub get

flutter run

And then Invalidated the caches from the

Menu>> File >>Invalidated caches

and finally restarted the Android Studio and boom the error was solved there were no errors.
These were the steps that resolved my error.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: I have updated the answer to the most simple form that it can be.
Answer: In my case this occurred after I updated the IntelliJ IDE. None of the above solutions worked, including opening in AS and rebuilding, invalidating caches, Flutter Clean, etc. The solution for me was to delete the android folder from the Flutter project and then re-add the Android platform as follows:
flutter create . --platforms=android


How to compare 2 columns with similar data (eg. not same order, with comma)

Question: I'm dealing with a dirty database, that has not normalized data, and has a column with a name like
"john kevin smith"  that I need to compare with another column (from other table) that could have "Kevin john smith" or "smith, kevin john" or the same as the original, and based on that I need to figure out if they point to the same record.
I'm trying to figure out how to do this with SQL Server 2012.
I have been testing with the JaroWinkler function without luck, I also tried with the fnSplit function, but that doesn't seem to do the trick, I believe I might have to first somehow normalize them, then separate them all and then compare between each other, but I'm drawing a blank on the process.
Any suggestions?
UPDATE:
with a split function and some replaces I'm able to "normalize" the columns, and receive the results in a table function like this:

now I just need to figure out how to compare with another set of values, as I'll get something similar when executing to the column I want to compare with.
Answer: For comparison you can just use the EXISTS clause.
Sample data
CREATE TABLE TEST(
    VAL_A varchar(200),
    VAL_B varchar(200)
);

INSERT INTO TEST (VAL_A, VAL_B) VALUES
('john kevin smith', 'Kevin john smith'),
('john kevin smith', 'Kevin, john smith'),
('Alpha beta gamma', 'beta delta alpha');

Query:
SELECT VAL_A, VAL_B
FROM TEST
WHERE NOT EXISTS (
    SELECT value FROM [dbo].[fn_Split](VAL_A, ' ')
    EXCEPT
    SELECT value FROM [dbo].[fn_Split]((REPLACE(VAL_B,',','')), ' ')
)
OR
NOT EXISTS (
    SELECT value FROM [dbo].[fn_Split]((REPLACE(VAL_B,',','')), ' ')
    EXCEPT
    SELECT value FROM [dbo].[fn_Split](VAL_A, ' ')

This will return the matching rows.
+-------------------+-------------------+
| VAL_A             | VAL_B             |
+-------------------+-------------------+
| john kevin smith  | Kevin john smith  |
| john kevin smith  | Kevin, john smith |
+-------------------+-------------------+

in the output, you can notice that alpha,beta,gamma,delta combination is not appearing as those are not matching. You can change NOT EXISTS to EXISTS if you want non matching rows.
CHECK DEMO HERE
You can use the joins if the other column is coming from another table. Also use the REPLACE statements accordingly.
Comment: wow, I wish I could upvote this more than once, great response! thank you!!
Answer: You can use STRING_SPLIT()

A table-valued function that splits a string into rows of substrings,
  based on a specified separator character

SELECT a.Value
FROM STRING_SPLIT('john kevin smith', ' ') a
INNER JOIN STRING_SPLIT('Kevin john smith', ' ') b on a.Value = b.Value

Demo here
Comment: actually, SQL Server 2012 does not support String_Split(), I've thought of it :(
Answer: Just an idea.. what you could do is to do a find and replace of all spaces with a comma for that field in each of the table. Place the results of each table into a separate #temp table.  Once you have done that.. do a string_split (of fnSplit) depending on SQL version and order then alphabetically.
Now join these tables based on the column value and see where you get at
Comment: I don't entirely understand this


Is it possible to change color of single word in UITextView and UITextField

Question: Is it possible to change color of single word in UITextView and UITextField ?
If i have typed a word with a symbol infront (eg: @word) , can it's color be changed ?
Comment: [NSAttributedString](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSAttributedString_Class/Reference/Reference.html) and [its usage](http://stackoverflow.com/questions/3482346/how-do-you-use-nsattributedstring).
Answer: Yes you need to use NSAttributedString for that, find the RunningAppHere.
Scan through the word and find the range of your word and change its color.
EDIT:
- (IBAction)colorWord:(id)sender {
    NSMutableAttributedString * string = [[NSMutableAttributedString alloc]initWithString:self.text.text];

    NSArray *words=[self.text.text componentsSeparatedByString:@" "];

    for (NSString *word in words) {
        if ([word hasPrefix:@"@"]) {
            NSRange range=[self.text.text rangeOfString:word];
            [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
        }
    }
    [self.text setAttributedText:string];
}

EDIT 2 : see the screenshot
Comment: but how to take that particular word in Textfield into a string ??
Comment: Thank you so much Anoop,It changed to red color,But the following words are also in red.

:- iphone @Words nithin anoop      {in this sentence except iphone,everything is red }
Comment: actually problem is, when i type---iphone @word then hit the button, and then type again----nithin Anoop; it is also in red color
Comment: i have uploaded my project in the link... please check there.
Comment: - Brother i have a doubt,hope you will help me
Please check this question - http://stackoverflow.com/questions/14211732/iphone-instragram-integration-issue
Comment: @AnoopVaidya this solution is wrong, because it affects only the first occurrence of each word
Comment: @pkacprzak: As per discussion (Single word) with OP, he wanted this only. If you want every words to be changed, if not much work, you could do it easily.
Comment: Is it possible set color of a particular word in `Storyboard` not from code?
Comment: @János: Don't think so.
Comment: I have a doubt can't we hide @ from @word ?
Comment: Hi @Mounika: Yes you can. But according to the question asked, I answered as above. For your question, you can replace `@"@"` with `@""` after the above codes to change the color. Isn't it so simple?
Comment: @AnoopVaidya my requirement is i want to hide @ pattern while showing text to user & get back while editing text.
Comment: @Mounika: You can use delegates to show based on color, or other way is to store both the strings (attributedString with red color without @ and other normal string with @) & do the process. Just a bit of programming logic required to achieve this.
Comment: @AnoopVaidya Thanks i fixed it :)
Comment: Hi @AnoopVaidya your solution is great. Is it also possible to give a word a different background color ? I want to implement something like search tags in ios mail app. For instance when you select a quick filter then the filter appears in the searchbar as a separate component but you can still type ahead to search and also remove this tag by keyboard back button.
Comment: @user3752049: You can do it quite easily, just use `NSBackgroundColorAttributeName` as key and put color in value.
Comment: @AnoopVaidya Thanks! I figured the color part but couldn't figure out how to add interactive labels/views to searchbar textfield. I'll probably have to create all custom components. Thanks for your help!
Comment: What if our word doesnt have a symbol?!
Comment: @Reza.Ab: There should be some distinguishing thing, word, symbol etc so that you can identify what text is needed to change
Comment: Okay like, If the word im looking forward to change its color is "Closed" it clearly has no symbol, so I cant make its color different?
Comment: If you want to make "Closed" you can, just get is location & length and color it. If you want to color only one, or all or some logic you can. *Eventually you have something to identify this word*.
Comment: @AnoopVaidya this code is working except for the case when the string contains duplicate words prefixing with "@"
Answer: this is a swift implementation from @Anoop Vaidya answer,this function detect any word between {|myword|} , color these words in red and remove the special characters, hope this may help someone else:
 func getColoredText(text:String) -> NSMutableAttributedString{
    var string:NSMutableAttributedString = NSMutableAttributedString(string: text)
    var words:[NSString] = text.componentsSeparatedByString(" ")

    for (var word:NSString) in words {
        if (word.hasPrefix("{|") && word.hasSuffix("|}")) {
            var range:NSRange = (string.string as NSString).rangeOfString(word)
            string.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: range)
            word = word.stringByReplacingOccurrencesOfString("{|", withString: "")
            word = word.stringByReplacingOccurrencesOfString("|}", withString: "")
            string.replaceCharactersInRange(range, withString: word)
        }
    }
    return string
}

you can use it like this:
self.msgText.attributedText = self.getColoredText("i {|love|} this!")

Comment: @Philip can you explain what do you got
Answer: Modified @fareed's answer for swift 2.0 and this is working (tested in a playground):
func getColoredText(text: String) -> NSMutableAttributedString {
    let string:NSMutableAttributedString = NSMutableAttributedString(string: text)
    let words:[String] = text.componentsSeparatedByString(" ")
    var w = ""

    for word in words {
        if (word.hasPrefix("{|") && word.hasSuffix("|}")) {
            let range:NSRange = (string.string as NSString).rangeOfString(word)
            string.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: range)
            w = word.stringByReplacingOccurrencesOfString("{|", withString: "")
            w = w.stringByReplacingOccurrencesOfString("|}", withString: "")
            string.replaceCharactersInRange(range, withString: w)
        }
    }
    return string
}

getColoredText("i {|love|} this!")

Comment: hey, I'm attempting to slightly modify this to work with an array of strings but currently having some difficulties, I was wondering if you could help me out? I asked the question [here](http://stackoverflow.com/q/33472171/5222077)
Answer: @fareed namrouti implementation rewritten in Swift 3
func getColoredText(text: String) -> NSMutableAttributedString {
    let string:NSMutableAttributedString = NSMutableAttributedString(string: text)
    let words:[String] = text.components(separatedBy:" ")
    var w = ""

    for word in words {
        if (word.hasPrefix("{|") && word.hasSuffix("|}")) {
            let range:NSRange = (string.string as NSString).range(of: word)
            string.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: range)
            w = word.replacingOccurrences(of: "{|", with: "")
            w = w.replacingOccurrences(of:"|}", with: "")
            string.replaceCharacters(in: range, with: w)
        }
    }
    return string
}

Answer: -(void)colorHashtag
{
NSMutableAttributedString * string = [[NSMutableAttributedString alloc]initWithString:textView.text];

NSString *str = textView.text;
NSError *error = nil;

//I Use regex to detect the pattern I want to change color
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"#(\\w+)" options:0 error:&error];

NSArray *matches = [regex matchesInString:textView.text options:0 range:NSMakeRange(0, textView.text.length)];

for (NSTextCheckingResult *match in matches) {
    NSRange wordRange = [match rangeAtIndex:0];
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:wordRange];
}

[textView setAttributedText:string];
}

Answer: To expound on Jamal Kharrat's answer, and to rewrite it into SWIFT, here is how to do it in a UITextView:

Set your UITextView to "Attributed" in the storyboard
Right-click & drag to ViewController icon at the top of the view (XC 6), and set the delegate
Create an IBOutlet for your UITextView (we'll call it "textView")
Make your class conform to UITextViewDelegate

Here is Jamal's function written in SWIFT:
func colorHastag(){
    var string:NSMutableAttributedString = NSMutableAttributedString(string: textView.text)
    var str:NSString = textView.text
    var error:NSError?
    var match:NSTextCheckingResult?

    var regEx:NSRegularExpression = NSRegularExpression(pattern: "#(\\w+)", options: nil, error: &error)!
    var matches:NSArray = regEx.matchesInString(textView.text, options: nil, range: NSMakeRange(0, countElements(textView.text)))

    for (match) in matches {
        var wordRange:NSRange = match.rangeAtIndex(0)
        string.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueColor(), range: wordRange)
    }

    textView.attributedText = string
}

Now, you'll need to call this function. To do this every time the user types a character, you can use:
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    self.colorHastag()
    return true
}

You'll notice that I changed the color to blue. You can set it to any color. Also, you can strip out the :Type for every variable. You'll also want to set becomeFirstResponder() and also handle resignFirstResponder() for a good user experience. You could also throw in some error handling. This will only convert hashtags to blue. You will need to modify or add a regEx to handle the @.
Comment: it will break when the specail character inside the word
Answer: The solution is this:
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];

NSArray *words=[txtDescription.text componentsSeparatedByString:@" "];

for (NSString *word in words)
{
    if ([word hasPrefix:@"@"] || [word hasPrefix:@"#"])
    {
        [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ ", word]
                                                                                attributes:@{NSFontAttributeName: [UIFont fontWithName:FONT_LIGHT size:15],
                                                                                NSForegroundColorAttributeName: [ImageToolbox colorWithHexString:@"f64d5a"]}]];
    }
    else // normal text
    {
        [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ ", word]
                                                                                attributes:@{NSFontAttributeName: [UIFont fontWithName:FONT_LIGHT size:15],
                                                                                NSForegroundColorAttributeName: [ImageToolbox colorWithHexString:@"3C2023"]}]];
    }
}

if([[attributedString string] hasSuffix:@" "]) // loose the last space
{
    NSRange lastCharRange;
    lastCharRange.location=0;
    lastCharRange.length=[attributedString string].length-1;

    attributedString=[[NSMutableAttributedString alloc] initWithAttributedString:[attributedString attributedSubstringFromRange:lastCharRange]];
}

[txtDescription setAttributedText:attributedString];

Answer: Yes it is possible. However I have found it can be a headache trying to use NSMutableAttributesString with a Swift Range. The code below will get you around having to use the Range class and return you an attributed string with the words highlighted a different color.
extension String {
    func getRanges(of string: String) -> [NSRange] {
        var ranges:[NSRange] = []
        if contains(string) {
            let words = self.components(separatedBy: " ")
            var position:Int = 0
            for word in words {
                if word.lowercased() == string.lowercased() {
                    let startIndex = position
                    let endIndex = word.characters.count
                    let range = NSMakeRange(startIndex, endIndex)
                    ranges.append(range)
                }
                position += (word.characters.count + 1) // +1 for space
            }
        }
        return ranges
    }
    func highlight(_ words: [String], this color: UIColor) -> NSMutableAttributedString {
        let attributedString = NSMutableAttributedString(string: self)
        for word in words {
            let ranges = getRanges(of: word)
            for range in ranges {
                attributedString.addAttributes([NSForegroundColorAttributeName: color], range: range)
            }
        }
        return attributedString
    }
}

Usage:
// The strings you're interested in
let string = "The dog ran after the cat"
let words = ["the", "ran"]

// Highlight words and get back attributed string
let attributedString = string.highlight(words, this: .yellow)

// Set attributed string
textView.attributedText = attributedString

Answer: After setting an attributedtext you can set typingAttributes of UITextView with the values you want for you input field.
NSDictionary *attribs = @{
    NSForegroundColorAttributeName:[UIColor colorWithHex:kUsernameColor],
    NSFontAttributeName:[UIFont robotoRegularWithSize:40]
};
self.textView.typingAttributes = attribs;


Dynamic model name on the JSON value from the Backend

Question: I have a Json from backend like this:
var infoArray = [
        {
            "field" : "text",
            "placeholder" : "Name",
            "modelName" : "userName"
        },{
            "field" : "date",
            "placeholder" : "DOB",
            "modelName" : "userDob"
        },{
            "field" : "text",
            "placeholder" : "Location",
            "modelName" : "userLocation"
        }
    ];

It's already set that there can be at most 10 text fields and 4 date
  fields i can get.

Since ModelName is coming from backend so i am trying to put that in the simple ng-repeat but that seems not working
Here is Plnkr Link

Indeed i found one solution by myself and the code seems to be bulky
  for that.

Here is plnkr Link

And one more thing i have to consider is that i have to use the modelName to get the values from the user and then sent it back.

Could anyone please suggest the optimized solution or modification over my code.
Thanks !
Answer: what you tried is almost correct. just need to remove the curly brackets in ng-model

       <input type="{{info.field}}" placeholder="{{info.placeholder}}" ng-model="info.modelName" ng-init="callFunc(info)" />

Demo
Comment: Yes, I tried that! But the thing is that on the basis of the modelName i have to take user inputs and again sent the json back![link](https://plnkr.co/edit/Uq3zW6ApnfvcgBlZUfd7?p=preview)  I am able to achieve that with my bulky solution!
Comment: but the changes you done via inputs will affect to the main array. console the main array on submit click and check
Comment: Yes ! It's Working fine .Thanks :)
Comment: @Niraj Sazzie no prob. make sure to check as right answer if this helped
Answer:
You can do this in the following manner:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.answers={};
  $scope.infoArray = [
        {
            "field" : "text",
            "placeholder" : "Name",
            "modelName" : "userName"
        },{
            "field" : "date",
            "placeholder" : "DOB",
            "modelName" : "userDob"
        },{
            "field" : "text",
            "placeholder" : "Location",
            "modelName" : "userLocation"
        }
    ];

    $scope.print=function(){
      console.log(answers);
    }

});
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>

    <link rel="stylesheet" href="style.css" />

       <input type="{{info.field}}" placeholder="{{info.placeholder}}" ng-model="answers[info.modelName]"/>

   <button ng-click="print()">Print</button>
   {{answers.userName}}
   {{answers.userDob}}
   {{answers.userLocation}}

Remove curly braces from ng-model and in your javascript file create a new object as in my example i have created an answers object. and in the ng-model use in this way : `

   <input type="{{info.field}}" placeholder="{{info.placeholder}}" ng-model="answers[info.modelName]"/>

 `
Now , if you want to access model values then you can do in this way:
   {{answers.userName}}
   {{answers.userDob}}
   {{answers.userLocation}}

Hope , this solves your problem. Thanks :)
Comment: You understand the way i am trying to achieve from code. But it's saying **Error: answers is not defined** I figured out that `console.log($scope.answers)` Thanks :)


Definition of Hermitian conjugate in bra-ket notation

Question: The Hermitian conjugate of an operator $A:H_1\rightarrow H_2$ between Hilbert spaces is the linear map $A^\dagger:H_2\rightarrow H_1$ such that
$$
       (A^\dagger h_1,h_2)_{H_2} = (h_1,A h_2)_{H_1}
$$
I am now trying to write this in bra-ket notation ($H_1=H_2=$space of states):
$$
   (A^\dagger \vert \psi\rangle,\vert \phi \rangle) = (\vert \psi\rangle,A \vert \phi \rangle) \\
    ?=\langle\psi\vert A \vert\phi\rangle
$$
I do not know how to write the LHS.
I expected to find something like
$$
    \langle \psi\vert A^\dagger\vert\phi\rangle=\langle\phi\vert A\vert\psi\rangle^*
$$
Which is the definition given in physics books.
Answer: Mathematically if $\lvert \phi \rangle \in H$ is your ket, then the bra
$\langle \phi \rvert$ is an element of $H^*$, the dual of $H$ defined by
$$
\langle \phi \rvert:H \to \mathbb{C}: \lvert \psi \rangle \mapsto \langle \phi \rvert \psi \rangle= (\lvert \phi \rangle, \lvert \psi \rangle).
$$
Then we find
$$
\langle \psi \rvert A^\dagger \lvert \phi \rangle = (\lvert \psi \rangle, A^\dagger \lvert \phi \rangle) = (A\lvert \psi \rangle, \lvert \phi \rangle) = (\lvert \phi \rangle, A\lvert \psi \rangle)^* = \langle \phi \rvert A \lvert \psi \rangle^*.
$$


Weird behavior of InterpolationOrder option of Interpolation

Question: When trying to recreate an InterpolationFunction produced by NDSolve I faced very strange problem with InterpolationOrder option of Interpolation. Consider the following InterpolationFunction (an example function from the Documentation):
ifun = First[
  x /. NDSolve[{x'[t] == Exp[x[t]] - x[t], x[0] == 1}, x, {t, 0, 10}]]

Now let us to try to reconstruct it. Here is the data:
Needs["DifferentialEquations`InterpolatingFunctionAnatomy`"]
data = Transpose@{InterpolatingFunctionGrid[ifun],
   InterpolatingFunctionValuesOnGrid[ifun]};

And here is InterpolationOrder:
interpolationOrder = InterpolatingFunctionInterpolationOrder[ifun]
(*=> {3}*)

Now we try to construct the InterpolatingFunction:
Interpolation[data, InterpolationOrder -> interpolationOrder];

and get error Message:

Interpolation::inord: Value of option InterpolationOrder -> {3} should
  be a non-negative machine-sized integer or a list of integers with
  length equal to the number of dimensions, 1. >>

But if we specify InterpolationOrder by hands, it is OK:
Interpolation[data, InterpolationOrder -> {3}]
(*=> InterpolatingFunction[{{0.,0.516019}},<>]*)

Can anyone explain why InterpolationOrder -> interpolationOrder does not work while InterpolationOrder -> {3} works although interpolationOrder must be replaced with {3} BEFORE calling Interpolation according to the standard evaluation sequence?
P.S. The problem occurs in Mathematica 7.0.1 and 8.0.1 but not in Mathematica 5.2.
UPDATE
I have found one workaround for this bug:
Interpolation[data,
 ToExpression@ToString[InterpolationOrder -> interpolationOrder]]

works as expected.
It seems that expressions generated by evaluation of Rule[InterpolationOrder,interpolationOrder] and Rule[InterpolationOrder,{3}] has different internal structure in spite of the fact that they are identical:
ByteCount // Attributes
ByteCount[InterpolationOrder -> interpolationOrder]
ByteCount[InterpolationOrder -> {3}]
Order[InterpolationOrder -> interpolationOrder,
 InterpolationOrder -> {3}]

(*=>
{Protected}
192
112
0
*)

Answer: It seems that I have found the reason for this behavior. It is because InterpolatingFunctionInterpolationOrder function returns PackedArray:
Developer`PackedArrayQ@InterpolatingFunctionInterpolationOrder[ifun]
(*=> True*)

We can convert {3} into PackedArray ourselves:
Interpolation[data,
  InterpolationOrder -> Developer`ToPackedArray@{3}];

(*=> gives the error Message*)

So the reason is that Interpolate does not support PackedArray as a value for InterpolationOrder option. The workaround is to unpack it manually:
Interpolation[data,
 InterpolationOrder -> Developer`FromPackedArray@interpolationOrder]
(*=> InterpolatingFunction[{{0.,0.516019}},<>]*)

Answer: Very strange behaviour indeed. Something like
a = {3};
Interpolation[data, InterpolationOrder -> a]

works fine, and both ??interpolationOrder and OwnValues[interpolationOrder] seem to indicate that interpolationOrder is just equal to {3}. Even weirder is that this does seem to work
interpolationOrder = 2 InterpolatingFunctionInterpolationOrder[ifun]/2
Interpolation[data, InterpolationOrder -> interpolationOrder]

Comment: Division by 2 results in unpacking because rational numbers cannot be packed. See my answer for further details.


LWJGL 2 Mouse doesnt give out dx/dy when grabbed

Question: I currently am making a game with a FPS type interface. Mouse.setGrabbed(true) and i'm trying to use that but now Mouse.getDX() and Mouse.getDY() does not work anymore and return 0. How can I get the values while the mouse is grabbed?
Answer: According to the LWJGL 2 documentation, when grab is true, getX() and getY() will return the delta coordinate values for the mouse.
Source: http://legacy.lwjgl.org/javadoc/org/lwjgl/input/Mouse.html#setGrabbed(boolean)
Comment: I'm not looking for the values from those methods though I am trying to find the result of Mouse.getDX() which is how much the mouse moved.
Comment: Again, when `grabbed` is set to true, `getX()` returns the same value as `getDX()` when not grabbed and `getY()` returns the same value as `getDY()` when not grabbed.  Grabbing sets the position to the middle of the screen on each input poll.


Javascript function repeat old call, when call it the second times

Question: I want to pass value to a js function many times, but at the after call, js function will execute with old parameter, then execute again with new value
I have the html:
Delete
Delete

Here is the javascript:

The first click on the badge, value is 1,'abc', but the second click on the second link,the values still be 1,'abc',after that, it will call again with new value 2, 'def'.
Comment: Working fine for me
Comment: After success call ajax, i receive error message because the post of the first id was deleted, but after that i see both post was deleted
Answer: You can add a version to script source link like this

change 1500 to version number you like
Comment: after debugging, i saw that the js function was repeated with old value, and new value ever since
Answer: You might have cached JS file on your browser with the same file name. You can try ctrl + f5 to reload ignoring cached content.
Comment: Thankyou, but there are another ways to do that without refreshing my page ?
Comment: You can stop caching from your browser settings. you might find this helpful - http://devtoolsecrets.com/secret/performance-disable-the-browser-cache.html
Comment: Another approach can be adding a version number to file, which might be helpful in production.
Comment: after debugging, i saw that the js function was repeated with old value, and new value ever since
Comment: can you be more descriptive about your #deleteModal contents? Share the snippet maybe?
Comment: It is just a bootstrap 4 modal with id deleteModal
Answer: Finally, i realized that $('#deleteBtn').onclick add a EventListener to the element.
It is called every time when #deleteBtn is clicked, so multiple event listeners are attached to deleteBtn. That's why my ajax was called multiple times.
Solution (just move event out of the function):


dplyr & tibble - Create a new column according to values in a list column

Question: I have a tibble dataframe as follows:
data = tibble(X = c("a", "b", "c", "d","c"),
          Y = c("a1", "b1", "c1", "d1","c1"),
          Z = c("a2", "b2", "c2", "d2","c2"),
          all = list(c("a"), c("b"), c("c", "c1"), c("d", "d2"), c("c", "b2")))

I want to create a new column "result" such that for each row :
- if the "Y" value is in "all" => result equals the Y value
- if the "Z" value is in "all" => result equals the Z value
- else result equals "none"
I've tried the following code with the dplyr syntax.
data %>%
mutate(result = case_when(Y %in% all ~ Y,
                          Z %in% all ~ Z,
                          TRUE ~ "none"))

It doesn't work as expected and returns:
# A tibble: 4 x 5
  X     Y     Z     all       result
  <chr> <chr> <chr> <list>    <chr>
1 a     a1    a2    <chr [2]> none
2 b     b1    b2    <chr [1]> none
3 c     c1    c2    <chr [2]> none
4 d     d1    d2    <chr [2]> none

When I'd like to obtain :
# A tibble: 4 x 5
  X     Y     Z     all       result
  <chr> <chr> <chr> <list>    <chr>
1 a     a1    a2    <chr [2]> none
2 b     b1    b2    <chr [1]> none
3 c     c1    c2    <chr [2]> c1
4 d     d1    d2    <chr [2]> d2

EDIT
One problem is to unlist the values in the column list as stated by Ronak Shah. But even with this solution, the behavior is like working on the column list will consider all the values of the column and not only those of a row.
Here is what I obtain with the proposed solution and the edited data :
data %>%
    mutate(result = case_when(Y %in% flatten_chr(all) ~ Y,
                              Z %in% flatten_chr(all) ~ Z,
                              TRUE ~ "none"))

# A tibble: 5 x 5
  X     Y     Z     all       result
  <chr> <chr> <chr> <list>    <chr>
1 a     a1    a2    <chr [1]> none
2 b     b1    b2    <chr [1]> b2
3 c     c1    c2    <chr [2]> c1
4 d     d1    d2    <chr [2]> d2
5 c     c1    c2    <chr [2]> c1

When it should return :
# A tibble: 5 x 5
  X     Y     Z     all       result
  <chr> <chr> <chr> <list>    <chr>
1 a     a1    a2    <chr [1]> none
2 b     b1    b2    <chr [1]> none
3 c     c1    c2    <chr [2]> c1
4 d     d1    d2    <chr [2]> d2
5 c     c1    c2    <chr [2]> none

Comment: `data %>% rowwise() %>% mutate(result = case_when(Y %in% unlist(all) ~ Y,  Z %in% unlist(all) ~ Z,TRUE ~ "none"))` Should do what you want
Answer: all column actually is a list, you cannot directly compare the values in list column.
For example,
 "a" %in% list(c("a", "b"))
#[1] FALSE

You need unlist or flatten_chr to make it work.
"a" %in% unlist(list(c("a", "b")))
#[1] TRUE

"a" %in% flatten_chr(list(c("a", "b")))
#[1] TRUE

So, now you can do
library(tidyverse)

data %>%
  mutate(result = case_when(Y %in% flatten_chr(all) ~ Y,
                            Z %in% flatten_chr(all) ~ Z,
                            TRUE ~ "none"))

#  X     Y     Z     all      result
#  <chr> <chr> <chr> <list>    <chr>
#1 a     a1    a2    <chr [2]> none
#2 b     b1    b2    <chr [1]> none
#3 c     c1    c2    <chr [2]> c1
#4 d     d1    d2    <chr [2]> d2

EDIT
You could add rowwise to compare the values for each row.
data %>%
  rowwise() %>%
  mutate(result = case_when(Y %in% all ~ Y,
                            Z %in% all ~ Z,
                            TRUE ~ "none"))

# A tibble: 5 x 5
#  X     Y     Z     all       result
#  <chr> <chr> <chr> <list>    <chr>
#1 a     a1    a2    <chr [1]> none
#2 b     b1    b2    <chr [1]> none
#3 c     c1    c2    <chr [2]> c1
#4 d     d1    d2    <chr [2]> d2
#5 c     c1    c2    <chr [2]> none

Comment: @Meshuggahat We can add `rowwise`, updated the answer.
Comment: It doesn't seems to work as I expect either. This my bad I didn't put the correct data for reproducibility.

It seems that any operation on the "all" column operates in ALL the values of the column and not only the values of a row. I'll edit my post to be clearer.
Answer: I  have used ifelse and mapply and any to go through the list and generating the values based on the given conditions as shown below
data$result <- ifelse(unlist(mapply(
  data$all,data$Z,
  FUN =  function(x, y) {
    any(x%in% y)
  }
)), data$Z, ifelse(unlist(mapply(
  data$all, data$Y,
  FUN =  function(x, y) {
    any(x%in% y)
  }
)), data$Y, "none"))

#View Data
data

alternatively:

library(dplyr)

data %>%
  mutate(result = ifelse(unlist(mapply(
    all,Z,
    FUN =  function(x,y) {
      any(x%in% y)
    }
  )), Z, ifelse(unlist(mapply(
    all,Y,
    FUN =  function(x, y) {
      any(x%in% y)
    }
  )), Y, "none")))

This produces


What's a good progression/path for self-educating from pre-algebra and beyond?

Question: I never got very far in my math studies; I took zero math in college and had terrible teachers in high school. Fast forward to today and I'm a professional developer who's starting to feel that my lack of a solid grounding in math is holding me back. I can hold my own with basic concepts, etc. but I'd like to start a formal self-education regiment in math. When I take something on, I take it seriously. When I taught myself my programming, I watched lectures from Stanford/MIT/UC Berkeley, read every book, did every exercise etc. I thrive on self-education.
And to my question: can someone recommend some really great resources/books for learning math starting from pre-algebra and beyond? I'd love it if someone could map out a good, structured progression for someone like me who likes math for its own sake, but also wants to use it as a tool for computer science.
Any help would be greatly appreciated.
Comment: Read Peter Eccles An introduction to Mathematical Reasoning or How to Prove it by Daniel Velleman. Personally, you won't really need that much Maths for computer science. I doubt it is holding you back.
Comment: @LuxuryMode, I would suggest you not to learn math completely from the begging, but start out with something you can use as professional developer. I think **Introduction to Algorithms** by Cormen,...can give you move motivation. This books shows that what we actually need for CS is a little bit of probability, a bit of graph theory etc.
Comment: @simplicity thanks a lot! You're probably, right. Just an insecurity that I have. I guess it's hard to accurately assess what you don't know also...
Comment: Thanks @com. I think what I'll do is sort of on the side learn maths in a formal way, but focus on algorithms as a main area.
Comment: Does this answer your question? [Looking for a good precalculus/algebra reference](https://math.stackexchange.com/questions/44240/looking-for-a-good-precalculus-algebra-reference)
Comment: Does this answer your question? [Learning mathematics as if an absolute beginner?](https://math.stackexchange.com/questions/22513/learning-mathematics-as-if-an-absolute-beginner)
Answer: Although I couldn't provide the sequence you request, I can point two references that can be of great help in gaining a bic-picture view of higher mathematics: The Princeton Companion to Mathematics and Mathematics: Its Content, Methods and Meaning.
Here is a description of the first out of Tim Gowers's web page:
"This is a book I am editing with the help of June Barrow-Green and Imre Leader, which could be thought of as "Mathematics: A Very Long Introduction". It has the aim of being a genuinely useful reference work in mathematics. This is a difficult aim, since mathematics is hard enough to explain at the best of times, and even more so if one has limited space. Is there any point in trying to summarize algebraic geometry in ten pages, for example? Probably not, but the articles in the PCM don't try to summarize , so much as to provide an initial overview and perspective. I like to think of them as "prequels" to textbooks -- things you would read to get an idea of why you were bothering to learn some concept that your lecturer seems to take for granted is interesting. Strenuous efforts have gone into making the book as accessible as possible, which I hope will have been worth it when it comes out, all going well, some time in the first half of 2008."
Hopefully that sounds enticing. (The second book runs somewhat along the same lines).
You mentioned OCW resources, I am sure you will know how to use those after you've gained your motivation and are ready to dive right into the subjects!
Answer: http://khanacademy.com
This is a well known website with videos on multiple subjects, but mainly math. They are meant to help students, but really can be for anyone, and the site might help you because you can watch it on your own without a strict curriculum (which fits because you aren't going to school or something for this).
Hope that's interesting!