text:
Q: WP8 Gzip compression WP8 does not support Gzip compression, but there is 3rd party libraries that will allow you do so, i have tried many but i am not able to make it work. this is my latest try:
var handler = new HttpClientHandler();
        if (handler.SupportsAutomaticDecompression)
        {
            handler.AutomaticDecompression = DecompressionMethods.GZip |
                                             DecompressionMethods.Deflate;
        }

        Uri myUri = new Uri("http://www.web.com");

        HttpClient client = new HttpClient(handler);

        client.BaseAddress = myUri;

        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Add("ubq-compression", "gzip");

        HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, myUri);
        req.Content = new StringContent(finalURL, Encoding.UTF8);

        HttpResponseMessage rm = client.SendAsync(req).Result;
        string rst = await rm.Content.ReadAsStringAsync();

the API return to me an array of bytes but the the first 300 are not Gziped but everything else is
i need to unzip everything that comes after the 300 bytes.
i am using the http://www.nuget.org/packages/Microsoft.Net.Http
// i am splitting the array
byte[] hJ = res.Take(300).ToArray();
byte[] bJ = res.Skip(300).ToArray();
bj is what need to be decompressed.
i am trying this
MemoryStream stream = new MemoryStream();
                    stream.Write(bj, 0, bj.Length);
                using (var inStream = new MemoryStream(bj))
                {
                    var bigStreamsss = new GZipStream(inStream, CompressionMode.Decompress, true);

                    using (var bigStreamOut = new MemoryStream())
                    {
                        bigStreamsss.CopyTo(bigStreamOut);
                        output = Encoding.UTF8.GetString(bigStreamOut.ToArray(), 0, bigStreamOut.ToArray().Length);
                    }

                }

but it is always failing on this line "
                        var bigStreamsss = new GZipStream(inStream, CompressionMode.Decompress, true);
"
Any help would be much appreciated

A: If you are using the compression header there's nothing you need to do. The server compresses and the client decompresses automatically and you don't have to worry about anything. However it sounds like you're using some proprietary content compression standard where you only compress some of it. If that's the case don't mess with any compression settings on the http client, and instead use a 3rd party uncompress library. Just seek 300 bytes on the response stream, then pass that stream to the library. You should be able to use my inflater from my gzip library, that you can find here: https://github.com/dotMorten/SharpGIS.GZipWebClient/blob/master/src/SharpGIS.GZipWebClient/GZipDeflateStream.cs
It's extremely light-weight (it's just this one file). First call
myResultStream.Seek(300, SeekOrigin.Begin);
If the stream isn't seekable, you will need to read the first 300 bytes first though.
Then use my class to decompress the rest:
Stream gzipStream = new SharpGIS.GZipInflateStream(myResultStream);
You can now read the gzipStream as if it was an uncompressed stream.
However I really don't understand why you don't use standard http compression and let the server compress everything including the first 300 bytes. It's much easier and better for the all the kittens out there.

A: You can use http://www.componentace.com/zlib_.NET.htm library (available through nuget):
part of request handler:
            try {
                var request = (HttpWebRequest)callbackResult.AsyncState;
                using (var response = request.EndGetResponse(callbackResult))
                using (var stream = response.GetResponseStream()) {
                    bool zip = false;
                    if (response.Headers.AllKeys.Contains("Content-Encoding") &&
                        response.Headers[HttpRequestHeader.ContentEncoding].ToLower() == "gzip") zip = true;
                    using (var reader = zip ?
#if NETFX_CORE
                        new StreamReader(new GZipStream(stream, CompressionMode.Decompress))
#else
                        new StreamReader(new zlib.ZOutputStream(stream), false)
#endif
                        : new StreamReader(stream)) {
                        var str = reader.ReadToEnd();
                        result = new ObjectResult(str);
                    }
                }
            }
catch (WebException e) {...}


text:
Q: Regular Expression to validate price I need a regular expression that validate price in the format like:
0.07 //valid
0.0 //Invalid
20 //valid
All the above Expressions are that which I want to achieve
^\d{0,8}(\.\d{1,4})?$

I use the above Expression which also accepts 0.0 which is invalid in my case.
Thank you.

A: Why not just use that RegEx, but then also check for value > 0
I presume you also don't want a negative price - which other 'number checking' methods will most likely consider valid

A: You could use a negative lookahead that asserts that what follows from the start of the line is not zero or times a zero followed by an optional part that matches a dot and only zeroes.
^(?!0*\.0+$)\d*(?:\.\d+)?$
Explanation

*

*^ Assert the start of the line

*(?! Negative lookahead

*

*0*\.0+$ Match zero or more times a 0 followed by a dot and one or more times a 0 until the end of the string

*) Close lookahead

*\d* Match zero or more times a digit

*(?: Non capturing group

*

*\.\d+ Match a dot followed by one or more digits

*)? Close non capturing group and make it optional

*$ Assert the end of the line

A: In C#, I would advice to use standard libraries to validate decimal values, like using Decimal.TryParse.
You may then implement something like:
public static bool IsValid(string price) {

    var result = Decimal.TryParse(price, out decimal d);

    if (result && d != 0) {
        return true;
    }

    return false;

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create local SQL database from AS/400 Schema I want to create local a database in SQL Server 2008 R2 using AS/400 schema...how can i do that..i don't know what is AS/400 schema in SQL...i tried to search on internet but not able to find any helpful link.
Please help me.

A: You would need to extract the file structures from the AS/400 and manually create, I know of no automated method, the corresponding SQL tables.


text:
Q: File data changed after encrypting then decrypting I encrypted a file using DES then After decrypting it successfully at the server and using
System.IO.File.WriteAllBytes(@"c:\test\" + fileName, decryptedFile);

method the file data changed a little it the text is "Encrypting and Decrypting usind DES blah blah blah blah"
the text in the end file after decrypting is " k$nlng and Decrypting usind DES blah blah blah blah"
and i also tried this:
using (BinaryWriter binWriter =
                        new BinaryWriter(File.Open(@"C:\Test\" + fileName, FileMode.Create)))
                {
                    binWriter.Write(decryptedFile);
                }

the text still not the same
encrypting by :
public byte [] DESEncrypt(byte [] fileBytes)
    {
        CryptoStreamMode mode = CryptoStreamMode.Write;

        // Set up streams and encrypt
        MemoryStream memStream = new MemoryStream();
        CryptoStream cryptoStream = new CryptoStream(memStream,
            cryptoProvider.CreateEncryptor(cryptoProvider.Key, cryptoProvider.Key), mode);
        cryptoStream.Write(fileBytes, 0, fileBytes.Length);
        cryptoStream.FlushFinalBlock();

        // Read the encrypted message from the memory stream
        byte[] encryptedMessageBytes = new byte[memStream.Length];
        memStream.Position = 0;
        memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length);
        MessageBox.Show("encrypted DES");
        return encryptedMessageBytes;
    }

decrypting by:
static public byte[] DESdecrypt(byte [] fileBytes)
    {

        ICryptoTransform decryptor = cryptoProvider.CreateDecryptor();
        byte[] originalAgain = decryptor.TransformFinalBlock(fileBytes, 0, fileBytes.Length);

        return originalAgain;
    }

Thanks

A: hard to say,  not an expert on the subject but compare your bytes before encrypting and after encrypting and decrypting. If they are identical no issues with the process. WriteALLBytes might not be the only thing.  think MIME type . a similar issue is i had to specifically say what type of file i am saving.

A: You are passing the same value for your "key" and "iv" value.  Each time you call the function, your "iv" value gets updated (thus, your key gets changed).
So you basically are doing this:
key = "key"
Encrypt (key, key)
-- key has now changed.
What you need to do is:
key = "key"
iv = copy of key
Encrypt (key, iv)


text:
Q: What is the best practice for creating a module? I've seen this done two ways:

*

*The module is assigned a global variable which is then appended to directives, controllers, and services:
var app = angular.module('myApp', [ ]);

app.directive('myDirective' function() {
   // directive stuff here
});

*Or the the module is used as-is like:
angular.module('myApp', [ ])

.directive('myDirective' function() {
   // directive stuff here
});

So why would you do it one way or the other?


text:
Q: C++ Singleton Threading problem I have a C++ singleton that runs as a separate thread.  This singleton is derived from a base class provided by a library and it overrides the method onLogon(...).  The onLogon method is synchronous, it wants to know right away if we accept the logon attempt.
Problem is we need to pass the logon information via message to a security server.  We can register a callback with the security server listener (a separate thread) to get the results of the logon authentication message we sent.  My question is how do I block in the onLogon method such that I can have the thread woken up by the callback I've registered with the security server listener thread, and how can I then access the response returned from the security server in a thread-safe way (ie, I need to be able to handle multiple concurrent logon requests).
I'm totally stumped.

A: Use an empty semaphore.  After you send the credentials to the security server, take the semaphore.  Since it will be empty it will block execution.  Then have the callback function post to the semaphore.  That will then resume execution on the original thread.
Since callbacks typically allow an anonymous value to be passed as a parameter, you can register a pointer to a data structure that can be filled with the response.

A: I ended up going with boost::promise and boost::unique_future.  It's was perfect for what I needed.
http://www.boost.org/doc/libs/1_43_0/doc/html/thread/synchronization.html#thread.synchronization.futures


text:
Q: Counting the occurrences of the string As input, we have some ids which are strings. How do we calculate what identifier has appeared most frequently and how many times?
Example
Input:
cat
dog
cat
dog
dog
dog
dog
fly
spider
spider
cat
cat

Output:
dog 5

A: If you are looking for one string only:
grep -cxF dog

or
echo "dog: $(grep -cxF dog)"

An efficient solution for a complete list:
> awk '{a[$0]++}; END {for (val in a) print val ": " a[val];}' file
spider: 2
cat: 4
fly: 1
dog: 5

A: Rearrange the data with sort and count the matching occurences using uniq -c
sort < input.txt | uniq -c

A: You can use the commands  sort & uniq -c to count the occurrences of all the strings like this:
$ sort sample.txt | uniq -c
      4 cat
      5 dog
      1 fly
      2 spider

If you just want the one string "dog" you can use grep either before or after.
after
$ sort sample.txt | uniq -c | grep dog
      5 dog

before
$ grep dog sample.txt  | uniq -c
      5 dog

How it works
The command uniq -c will count all the unique strings that it's presented, but the list needs to be in sorted order first. Hence why we use the sort command prior to doing the tally.
The command grep is for selecting things in the output that are of interest. You can thing of grep as a filter that can act either inclusively or exclusively depending on what you want from the output.
The sort command can sort data based on rules. In this case we're letting it behave in its default mode, so it's sorting the data based on an alphanumeric set of sorting rules.


text:
Q: Is it correct to say "there be..."? I'm currently reading Tolkien's The Lord of the Rings. One sentence says:

[...] where there be mountains of gold, they say.

English is not my mother tongue, but I've found the same expression somewhere else, probably in song lyrics as well. I would like to know if it is correct to use (apart from literature context) and what it means and how it is different from "where there are mountains of gold". Thank you!

A: Yes, "there be" is from the past.  And nowadays only used when imitating the past.  Searching "there be" in Shakespeare's plays returns 86 matches ...

I think there be six Richmonds in the field
  King Richard III: V, iv


text:
Q: How to resolve the 'cannot get security labeling handle: No such file or directory' error? For a reason that completely escapes me, recently whenever I try to install a package or upgrade a package with APT or dpkg I get the error:
dpkg: error processing archive ... (--install):
 cannot get security labeling handle: No such file or directory

where ..., of course, depends on the name of the Debian package archive (or .deb) being installed. If you're wondering whether it is something I've done to cause this well I don't think so, but I haven't run this Ubuntu 16.04.1 installation directly for quite some time. Rather I periodically chroot into this Ubuntu system from my Fedora system (if what I am saying is unclear, I mean I am running Fedora 25, but I chroot into this Ubuntu system) and run sudo apt-get update && sudo apt-get upgrade -y && sudo apt-get autoremove -y in order to keep this Ubuntu installation up-to-date.

A: Based on Naftuli Kay's answer the following command helped me solve this issue:
mount /sys/fs/selinux -o remount,ro


text:
Q: How do I install 3rd party libraries for an Angular 2 application using the ng-cli tool? There used to be this page https://github.com/angular/angular-cli/wiki/3rd-party-libs for installing 3rd party libs. It is no longer available. I was using angular-cli: 1.0.0-beta.25.5 and this page helped me to install bootstrap.
Now, since I've upgraded to @angular/cli: 1.0.0-beta.32.3, and with this wiki page gone, I am wondering if the previous instructions no longer apply? Meaning, did ng-cli somehow managed to allow installation of 3rd party packages magically without manual user intervention.
I'd appreciate if someone may clarify why https://github.com/angular/angular-cli/wiki/3rd-party-libs no longer exists and how we are supposed to add 3rd party libs now (if those previous instructions are obsolete and where the new instruction is or how adding third party libs is supposed to happen).
For example, how would I go about adding popular third party libraries such as bootstrap or lodash using the latest ng-cli? If I recall correctly, lodash presents a problem in that it requires the installation of typings.


text:
Q: Regular expression check for numbers with a series of patterns I have a condition where in i need to omit series of numbers with following pattern using javascript.
If 4 digit number

*

*Only numbers and length should be 4

*Atleast 3 distinct digits (Eg: of non allowed digits: 1113, 4443)

*No 3 consecutive digits both in case of  ascending and descending series (Eg: of not allowed digits: 1231, 4321)

If 5-6 digit number

*

*Only numbers and length should be 5-6

*Atleast 4 distinct digits (Eg: of non allowed digits: 11113, 44443)

*No 3 consecutive digits both in case of  ascending and descending series (Eg: of not allowed digits: 12341, 43211)

As far as I am aware you cannot check the ascending and descending number, you can only listen to them like
If 4 digit
^[0-9]{4}$ AND NOT IN
(?:012|210|123|321|234|432|345|543|456|654|567|765|678|876|789|987|111|222|333|444)

If 5-6 digit
^[0-9]{5,6}$ AND NOT IN
(?:0123|3210|1234|4321|2345|5432|3456|6543|4567|7654|5678|8765|6789|9876|1111|2222|3333|4444|5555|6666)

I dont know how to fill "AND NOT IN" in regular expression.
Is there a better way?

A: This kind of thing seems too complex for a regex, since even if you could write it, would you understand it without a bunch of comments?
Instead, try breaking it down:
// assuming var number as string;
var i, l = number.length, prev = -999, dist, prevdist = 0,
    digits = [0,0,0,0,0,0,0,0,0,0], dcnt = 0;
main:
switch(l) {
case 4:
case 5:
case 6:
    for( i=0; i<l; i++) {
        digits[number[i]]++;
        dist = prev-number[i];
        if( prevdist == dist && Math.abs(dist) == 1) {
            alert("Three consecutive digits ("+number.substr(i-2,3)+")");
            break main;
        }
        prev = number[i];
        prevdist = dist;
    }
    for( i=0; i<10; i++) {
        if( digits[i]) dcnt++;
    }
    if( dcnt < (l == 4 ? 3 : 4)) {
        alert("Need at least "+(l == 4 ? 3 : 4)+" distinct digits");
        break main;
    }
    alert("Valid");
    break main;
default:
    alert("Length must be between 3 and 5");
    break main;
}

A: I think the consecutive digits test is much better to do in javascript.  Here's a function that tests for any sequence of consecutive digits up or down.  You pass how many you want to test for:
function checkConsecutiveChars(str, limit) {
    var lastDigit = str.charCodeAt(0), num = 1, val, delta;
    for (var i = 1; i < str.length; i++) {
        val = str.charCodeAt(i);
        ++num;
        if (num === 2) {
            // calc delta and remember it
            delta = val - lastDigit;
            // see if we have a two char sequence now
            if (Math.abs(delta) !== 1) {
                // not sequential, start over
                num = 1;
            }
        } else {
            // see if consecutive sequence continues and exceeds limit
            if (val === (lastDigit + delta)) {
                if (num >= limit) {
                    return(false);
                }
            } else {
                // sequence stopped
                num = 1;
            }
        }
        lastDigit = val;
    }
    return(true);
}

Working example: http://jsfiddle.net/jfriend00/Nym8Y/

You can check for how many unique digits there are with this function:
function checkDistinctDigits(str, minDistinct) {
    var digits = new Array(10);
    var uniqueCnt = 0, val;
    for (var i = 0; i < str.length; i++) {
        val = str.charCodeAt(i);
        if (val >= 48 && val <= 57) {
            if (!digits[val - 48]) {
                ++ uniqueCnt;
                digits[val - 48] = true;
            }
        }
    }
    return(uniqueCnt >= minDistinct);
}

Working example: http://jsfiddle.net/jfriend00/cpXnW/


text:
Q: How to button Invisible (hide) after specific time period (e.g. 7days) my-account > my-orders on woocommerce? I added a button that only appears when it is in a specific order status.
Because it is not a button to set up in Commerce, I have to hide that button seven days after I place an order. Could you help me?
Best,

// Add button when order status is 'completed'

add_filter( 'woocommerce_my_account_my_orders_actions', 'add_my_account_my_orders_custom_action', 10, 2 );
function add_my_account_my_orders_custom_action( $actions, $order ) {
 if ( $order->has_status( 'completed' ) ) {
     $action_slug = 'specific_name';

     $actions[$action_slug] = array(
         'url'  => 'https://www.cjlogistics.com/ko/tool/parcel/reservation-return',
         'name' => 'Withdraw',
     );
    }
    return $actions;
}

A: Please find below code snippet that will show the withdraw button for seven days after the completion of order. Hope the code is easy to understand. Need to find the current date and the order completed date and based on this we need to find the difference between the two dates (i.e. Number of days)
add_filter( 'woocommerce_my_account_my_orders_actions', 'add_my_account_my_orders_custom_action', 10, 2 );
function add_my_account_my_orders_custom_action( $actions, $order ) {
    if ( $order->has_status( 'completed' ) ) {
        $action_slug = 'specific_name';

        /*This is the logic to get difference between order completed date and the current date*/
        $date1 = $order->get_date_completed(); // Order completed date
        $date2 = date('Y-m-d'); //current date
        $diff = abs(strtotime($date2) - strtotime($date1));
        $days = floor(($diff)/ (60*60*24));

        /*If order completed days is less then 7 then show the Withdra button */
        if($days < 7){
            $actions[$action_slug] = array(
                'url'  => 'https://www.cjlogistics.com/ko/tool/parcel/reservation-return',
                'name' => 'Withdraw',
            );
        }
    }
    return $actions;
}


text:
Q: Is it possible to trigger different HTTP methods on a single page with only one form on it? Until now, I have dealt with PUT and DELETE HTTP methods with jQuery AJAX (or XMLHttp) and HiddenHttpMethodFilter including GET and POST in Spring (currently I'm working with Spring 3.2.0). I have one general question about using these methods.
Basically, I want to perform basic database operations like INSERT, EDIT, UPDATE and UPDATE on the same page (JSP) using a single form. In this scenario, is it possible to trigger these methods at appropriate actions?
For example, when a user presses the delete button, the DELETE method should be raised, when he presses the update button, the PUT method should be triggered, on pressing the insert button, the POST method should be invoked and while retrieving data, the GET method should be used and accordingly an appropriate method which is mapped in the controller should be invoked (again on the same page with a single form <form:form>...</form:form>).
Of course, it is possible by means of AJAX but using AJAX everywhere is not appropriate.
Maybe I'm missing some important aspects of RESTFul APIs. Apparently, it is not possible (unknowingly). What is the actual answer?

EDIT:
Suppose, I wanted to deal with the PUT method then the Spring form would look like the following.
<form:form id="mainForm" name="mainForm" method="put" action="Temp.htm" commandName="tempBean" enctype="multipart/form-data">
    <input type="submit" id="btnSubmit" name="btnSubmit" value="Submit"/>
</form:form>

and its generated HTML would look like the following.
<form id="mainForm" name="mainForm" action="Temp.htm" method="post" enctype="multipart/form-data">
    <input type="hidden" name="_method" value="put"/>
    <input type="submit" id="btnSubmit" name="btnSubmit" value="Submit"/>
</form>

The hidden <input type="hidden" name="_method" value="put"/> field is automatically added to be dealt with the PUT method by the HiddenHttpMethodFilter

If I now needed to raise the DELETE method then the form and its generated HTML should respectively be modified as follows.
<form:form id="mainForm" name="mainForm" method="delete" action="Temp.htm" commandName="tempBean" enctype="multipart/form-data">
   <input type="submit" id="btnSubmit" name="btnSubmit" value="Submit"/>
</form:form>

Generated HTML
<form id="mainForm" name="mainForm" action="Temp.htm" method="post" enctype="multipart/form-data">
    <input type="hidden" name="_method" value="delete"/>
    <input type="submit" id="btnSubmit" name="btnSubmit" value="Submit"/>
</form>

How likely is it to do so dynamically at run time?

A: You could do something like:
<form id="mainForm" name="mainForm" action="Temp.htm" method="post" enctype="multipart/form-data">
    <input type="hidden" name="_method" value="delete"/>
    <input type="submit" name="btnUpdate" value="Update"/>
    <input type="submit" name="btnDelete" value="Delete"/>
    <input type="submit" name="btnCreate" value="Create"/>
</form>

Then on your processing page just check to see which button submitted the form.


text:
Q: Оптимизация использования дисплея в Elementary OS Как совместить окно приложения и верхнюю строку в Elementary OS. необходимо потому что, экран ноутбука маленький хотелось бы больше. Буду благодарен даже если подскажите в какую сторону капать.

A: В любом браузере есть F11 для полноэкранного режима - удобно когда работаете со одной вкладкой. В фаерфоксе давлением мышки ввех можно достать открытые вкладки.
В старом фаерфоксе был флаг в about:config для сокрытия декорации. Браузеры Opera, Chrome, Yandex, Vivaldi скрывают заголовок когда развернуты.
Для оригинального гнома 3 есть расширение https://extensions.gnome.org/extension/1287/unite/
но я не уверен что оно запустится на элементари.

A: Честно говоря, точно не знаю как это можно реализовать. Но могу подсказать с направлением.
1. Вы можете поискать как поставить global menu как тут: https://www.reddit.com/r/elementaryos/comments/31er5c/global_menu_in_elementary/
Если все правильно настроите ,то меню настроек типа "Файл, Настройки и тп" переместится на верхний bar. Вам останется лишь сменить тему window manager на какую-нибудь минималистичную.
2. Сменить window manager на какой-нибудь awesome wm.
3. Поискать минималистичные темы типа xenlism


text:
Q: XSLT - Remove nodes when current node is equal to previous node I need to write XSLT for an xml which contains in below format.
<books>
<book>
 name
 name
 name
 name
</book>
</books>

I need to eliminate the duplicate child nodes in some conditions.

*

*Only if(current node == previous node) then it should be removed.

ie.. if previous node (element) is   and current node (element) is also , Then one node should be removed.
output for the above be,
`<a>name</a>`

`<b>name</b>`

please help me to do this.

A: In XSLT 2 or 3 you can easily group adjacent sibling elements by their node name with for-each-group select="*" group-adjacent="node-name()" and simply output the first item in each group (which is equal to the context item .):
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="3.0">

  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:output method="xml" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="book">
      <xsl:copy>
          <xsl:for-each-group select="*" group-adjacent="node-name()">
              <xsl:copy-of select="."/>
          </xsl:for-each-group>
      </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/6qVRKw4/1

A: As I understood, you want to omit a leaf element (without children elements)
if it has a previous sibling, which:

*

*is also a leaf element,

*has the same name,

*has the same text content.

So the most intuitive solution (I think) is to write an empty template,
matching just these nodes:
<xsl:template match="*[not(*)][preceding-sibling::*[1][not(*)]
  [name() = current()/name()][text() = current()/text()]]"/>

A brief description of the match attribute:

*

**[not(*)] - Every element without any child element (leaf element).

*[ - Start of the second predicate.

*

*preceding-sibling::*[1] - Take the first preceding sibling.

*[not(*)] - It must not have any child element.

*[name() = current()/name()] - It must have the same name as the
"starting" element.

*[text() = current()/text()] - It must have the same text as the
"starting" element.

*] - End of the second predicate.

Of course, the script must contain also an identity template.
For a working example, with a bit extended source, see http://xsltransform.net/jxN8Nqm
If requirement concerning the same text is not necessary, delete the respective
predicate fragment.


text:
Q: getting response from twitch api The issue is quite strange for me. It seems that function getChannels should return json, but instead I get undefined. I've put log function right before return statement and it shows me that the data is present.
Please take a look at my pen - https://codepen.io/blooblyboo/pen/VXgdXx
Right above getChannels() I call that function with the given name.
$(this).addClass('current');
  if($(this).find('span.all').length > 0){//output channels to corresponding list
    var ul = $(this).find('ul');
    var list = JSON.parse(localStorage.getItem('channels')), len = list.length, channels = [];
      while(len != 0){
        var channel = getChannels(list[--len]);
        // console.log(channel)
      }
  }
});

function getChannels(channelName){//take list from storage and request all of it's items from twitch
  function Channel(name, display_name, bio, logo, _id){
    this.name = name;
    this.display_name = display_name;
    this.bio = bio;
    this.logo = logo;
    this._id = _id;
  }
    var url = 'https://api.twitch.tv/kraken/users/'+channelName+'?client_id=v1oygovy27vh6tml1vb6edbtlsehkx', result;
    $.ajax({
       url: url,
       data: {
          format: 'json'
       },
       error: function() {
          console.log('Couldn\'t get any');
       },
       success: function(data) {
         var channel = new Channel(data.display_name, data.bio, data.logo, data.name, data._id);
         console.log(channel);
         return channel;
       }
    });
}


text:
Q: String concatenation: binary syntax v. operator <> In elixir, are the following equivalent:
 str1 = "hello "
 str2 = "world"

 result = str1 <> str2
 result = <<str1::binary, str2::binary>>

??

A: Yes. The <>/2 operator is a macro that transforms the code into the <<>> special form.
quote do str1 <> str2 end
|> Macro.expand(__ENV__)
|> Macro.to_string()

Output:
"<<str1::binary, str2::binary>>"

A: Yes, they're equivalent.
In Elixir, the string type is a UTF-8 encoded binary, so "hello" is <<"h", "e", "l", "l", "o">> or <<104, 101, 108, 108, 111>>.
The string concatenation operation is actually a binary concatenation operator so
str1 <> str2 == <<str1::binary>> <> <<str2:binary>> == <<str1::binary, str2::binary>>


text:
Q: Comparing two text cells in different sheets I'm trying to compare two text cells (like abcDEF) from different sheets. One sheet is fixed but the other is not.
My code is:
Private Sub Worksheet_Change(ByVal Target As Range)

Dim i As Long, LastRow As Long, n As Long
Dim Project As String
Dim Responsible As String, Site As String, Sample As String, _
    Description As String, Parameter As String, Method As String
Dim j As Long

Application.EnableEvents = False

' Find LastRow in Col A into the Sheet2
LastRow = Sheet2.Range("A" & Rows.Count).End(xlUp).Row

' Select all Col A in Project
For Each Value In Sheet2.Range("A2:A" & LastRow)
   Project = Project & "," & Value
Next Value

Sheet1.Range("A2").ClearContents: Sheet1.Range("A2").Validation.Delete

' Create the Data Validation List
With Range("A2").Validation
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween,     Formula1:=Project
    .IgnoreBlank = True
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = ""
    .InputMessage = ""
    .ErrorMessage = ""
    .ShowInput = True
    .ShowError = True
End With

' Select the sheet coinciding with the cell "A2" value
For j = 3 To Sheets.Count

    If Sheets(j).Range("A2").Text = Sheets(1).Range("A2").Text Then
        'Write 4 in sheet1 cell C6 when the two values are coinciding.
        Sheet1.Range("C6") = 4
    End If

Next j
End Sub

The problem is the If... line, probably is the range definition. I've tried .Text and .Value and neither works.

A: What you may want to use is
If StrComp(Sheets(j).Range("A2").Value2, Sheets(1).Range("A2").Value2, _
    vbTextCompare) = 0 Then
'added the underscore since I made it two lines for neatness

vbTextCompare is case-insensitive, vbBinaryCompare is case-sensitive. There are several resources online about string comparison that can help you.
Also, I noticed you're using Worksheet_Change and changing the value of a cell on Sheet1. My guess is that your Worksheet_Change is for Sheet1, yes? If that's the case, then every time you modify Sheet1, the sub gets called again (and again and again... until it crashes). To prevent that, you want to add
Application.EnableEvents = False

to the start of the sub, then
Application.EnableEvents = True

at the end. This way any changes you make to the worksheet won't trigger the Worksheet_Change sub.

A: you can use EXACT(text1,text2) function


text:
Q: C# dynamically set property When Property is a class? Hi i have a Number of Properties and My properties like
public XYZ()
{
    xyz = new xyz1();
    xyz2 = new xyz2();
}
public xyz1 xyz1 { get; set; }
public xyz2 xyz2 { get; set; }
}

public class xyz1
{
    public string fName { get; set; }
    public string lnameget; set;}
}
public class xyz2
{
    public string city { get; set; }
    public string state
}

While i am setting my property on runtime i am getting exception object reference set to null.
XYZ model = new XYZ();
PropertyInfo propertyInfo = model.GetType().GetProperty("fName");
propertyInfo.SetValue(model, Convert.ChangeType(item.InnerText, propertyInfo.PropertyType), null);

Please help me

A: model has no fName property, but model.xyz1 does.


text:
Q: how to apply css class to mvccontrib grid I am using mvccontrib grid in asp.net mvc(C#) application.
How can i apply css class to the grid thats created for the mvccontrib grid Attributes?
I am looking to construct like:

....

By default, the mvccontrib grid has the class "grid". I need to change it to my custom css class

A: Html.Grid(x).Columns(col => {}).Attributes(@class => "usertable");

By the way MvcContrib's Grid should have full intellisense so you should see all the available methods when you type "." (dot).


text:
Q: Rails Devise/Invitable I have a Rails app with devise and devise_invitable (links to official docs on overriding controllers), I have made a devise_invitable invitations_controller.rb to display a list of currently invited users within devise/invitations/new.html.erb. Both devise and devise_invitable views are in app/views/devise and app/views/devise/invitations respectively and my devise/devise_invitable controllers are in app/controllers/users/. Rails throws an undefined method 'each' for NilClass in the invitations/new view in my loop:
# app/views/devise/invitations/new.html.erb
<% @invited_users.each do |invited| %>
  omitting code...
<% end %>

# app/controllers/users/invitations_controller.rb
class Users::InvitationsController < Devise::InvitationsController
  def new
    super
    # This is not empty, returns multiple records in console
    @invited_users = User.where.not(invitation_sent_at: nil)
  end
end

# config/routes.rb
...
devise_for :users, controllers: { registrations: 'users/registrations',
                                  invitations: 'users/invitations' }
...
end

The weird thing is that when I change the app/views/devise folder name to app/views/users, the error is gone and it displays current invited users but this creates a larger problem which is that the app now uses both devises/devise_invitable's default views.

A: Turns out that the culprit was my super statement, the render was being called so it never actually got to the @invited_users, I just moved it below


text:
Q: Same query different database different result I try to change database from 'MySQL' to 'PostgreSQL' but i have problem some of my query
SELECT
    SUM( CASE WHEN b.DISPLAYNAME IS NULL THEN 0 ELSE 1 END ) AS NUMMENUDETAIL,
    A.DISPLAYNAME AS GROUPNAME,
    b.displayname,
    D.NAME,
    min( A.ROLEID ) AS ROLEID
FROM
    usermenu A
    LEFT JOIN usermenu B ON A.ID = B.GROUPID,
    userrole C,
    position D,
    positiondetail E
WHERE
    ( A.GROUPID IS NULL )
    AND D.id = E.position_id
    AND A.ROLEID = E.userrole_id
    AND A.ROLEID = C.ID
    AND B.ROLEID = E.userrole_id
    AND B.ROLEID = C.ID
    AND b.displayname = 'Transaction Listing Report'
GROUP BY
    A.DISPLAYNAME,
    b.displayname
    LIMIT 10

i use this query into "MySQL" it pass
but when i use in "PostgreSQL" it error, They want my to GROUP BY d.name
then if i GROUP BY it may have different result
How can i fix this ?

A: This query does not comply with the SQL standard, so it is unsurprising that it does not work on all databases. The standard requires that all columns in the SELECT list that do not appear only inside aggregate functions must be in the GROUP BY clause.
You can have the same effect by using the (again, non-standard) DISTINCT ON clause in PostgreSQL.


text:
Q: NameError undefined local variable or method `primary_abstract_class' for # I'm trying to run rails with jruby
rails : 6.1.4.4 | jruby : 9.3.3.0 | ruby  : 2.6.8
I get this error for when i try to use any Model(s)
In rails console
User.all.limit(1)
Traceback (most recent call last):
        4: from (irb):2:in `evaluate'
        3: from app/models/user.rb:1:in `<main>'
        2: from app/models/application_record.rb:1:in `<main>'
        1: from app/models/application_record.rb:2:in `<class:ApplicationRecord>'
NameError (undefined local variable or method `primary_abstract_class' for #<Class:0x558123>)
Did you mean?  primary_class?

I have a User Model
app/models/user.rb
class User < ApplicationRecord
end

app/models/application.rb
class ApplicationRecord < ActiveRecord::Base
  primary_abstract_class
end

A: As already mentioned primary_abstract_class is introduced in Rails 7.
In Rails < 7 the ApplicationRecord is generated with:
# app/models/application_record.rb
class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true
end


text:
Q: Filtering out sublist from list based on contents of entire sublist? So here is what I have:
lst = [["111","101","000"],["1001","1100","1111"],["00","11","00"]]

And I want to filter out the sublists that contain only strings of "0"*len(string) and "1"*len(string). The result should look like this:
[["111","101","000"],["1001","1100","1111"]]

A: Here's one way to do it with regular expressions:
import re

[[y for y in x if not (re.match('1+$', y) or re.match('0+$', y))] for x in lst]

And here is a better clever way inspired by the answer here:
[[y for y in x if not (y == len(y) * y[0])] for x in lst]

A: Break up the task into smaller parts. Then combine to get the solution:
# check that a string is all 0 or all 1
def check_string(s):
    size = len(s)
    return s in ('0'*size, '1'*size)

# check that a list contains only strings that satisfy check_string
def check_list(l):
    return all(check_string(s) for s in l)

lst = [["111","101","000"],["1001","1100","1111"],["00","11","00"]]

result = [l for l in lst if not check_list(l)]

Then we have
>>> print(result)
[['111', '101', '000'], ['1001', '1100', '1111']]

A: With generator expressions:
lst = list([x for x in lst if not all([y == y[0]*len(y) for y in x])])

Note: This is better than @Tum's answer because it takes the list as a whole (e.g., ["111","101","000"]) rather than individually accepting or rejecting each value (e.g., accepting "101" but rejecting "111" and "000", leaving ["101"]

A: You can do so using the filter function as follows:
import re

orig_list = [["111","101","000"], ["1001","1100","1111"], ["01","10"]]

def checker(item):
    for idx in item:
        if re.search(r'^1*$', idx) or re.search(r'^0*$', idx):
            return True
    return False

new_list = list(filter(checker, orig_list))
print(new_list)

Output:
[['111', '101', '000'], ['1001', '1100', '1111']]

A: One more solution:
[lst[j] for j in set([k for k, i in enumerate(lst) for m in i if m[0]*len(m) != m])]

In this case think about m[0]: if you have empty string what does it mean in your case? You can exclude it also.


text:
Q: Getting server settings from Microsoft Outlook 2010 I would like to read the mail server settings from Microsoft Outlook 2010.
Outlook has a mail account configured that uses a Microsoft Exchange server.
When I click "File", "Information", then "Account settings" Account" and then "Edit", I see the name of the exchange server and the user's login name (which is his email address).
I have also been told the password.
Additionally, a proxy is being used on this network.
Now I would like to configure a custom built mail program in such a way that it works like Microsoft Outlook 2010.
I'm using all parameters that I could find and which I have been told, but I don't see the SMTP or POP settings in Outlook 2010.
These are the settings that I can see within Outlook 2010:

How could I get the other settings like SMTP and POP settings?
Or am I totally wrong somewhere in my thinking?
Thank you.

A: Firstly, on the screenshot you have an Exchange account, not POP3/SMTP, so obviously you cannot extract any POP3/SMTP settings from there.
Account settings for all account types (Exchange, POP3/SMTP, IMAP4/SMTP, etc.) are stored in the profile sections accessible through Extended MAPI (C++ or Delphi), namely through the IOlkAccountManager interface. You can play with that interface in OutlookSpy (click IOlkAccountManager button).
Profile sections are accessible directly through the registry, but the format is not documented.
If using Redemption is an option (I am its author), it exposes all Outlook accounts and their settings through the RDOAccounts and RDOAccount objects.


text:
Q: Implementing Composition pattern with least boilerplate in C#? I've looked at many posts here and I'm not entirely clear on the answer to this question.
I want to be able to implement an interface with composition and have all the methods be called on the component:

*

*Create an interface for the Component (i.e. Car).

*Create a class, implementing the Component (i.e. SimpleCar)

*Create another class which implements the Component interface (i.e. create a DeluxeCar which implements the methods by calling them on a SimpleCar member) by calling them on a Component member.

Now the caveat, the important part is I want to be able to do part 3 without writing all the wrapper methods to make DeluxeCar call the methods on SimpleCar. Preferable only needing to add a C# decorator or some C# template magic.
Two solutions I've seen:
 1. ExtensionMethods - I believe you can implement a CarComposite interface and place extension methods on it (Similar to what's done here in C. Lawrence Wenham's answer: Multiple Inheritance in C#). However, I don't think that you can make the Composite interface also implement the Component interface. At least I haven't been able to get a working example. Perhaps I am wrong  though.
 2. Aspect Oriented Programming. Use PostSharp or another AOP framework to do step 3. I haven't been able to find example code on how to do this. Further I would really like to avoid PostSharp as I don't like the license and want a completely free solution. I think PostSharp states you can't do this with their free version anyways (See AspectInheritance http://www.postsharp.net/purchase). A working example for Spring.Net would help a lot.
Can someone please provide an example of #3 please in using standard C# libraries or Spring.net?
Update
h.alex's suggestion is interesting but still doesn't do what I need. Your use of the abstract class is a bit limiting. Imagine having a Boat interface in addition to the Car interface. Then you want to create an AmphibiousVehicle which implements both Boat and Car. In C# there is no multiple inheritance so you can't inherit both the AbstractCar and AbstractBoat class. You are forced to add even more boilerplate and create an AbstractAmphibiousVechicle abstract class as well. This might be fine if you don't have too many different classes. But sometimes you want to create many different classes and mix and match these behaviours. This is pretty common in video games. You might have a ton of different aspects that you want to be able to do with a game object (Push it, Throw it, Collect it, etc.). You will be forced to make many different abstract classes this way, each having a lot of boilerplate.
I want something like this that PostSharp has, but I'd really like to know if there is a framework with a less restrictive license which can do the same. Is this something that can be easily done in Spring.net for example?
http://doc.postsharp.net/postsharp-3.0/##PostSharp-3.0.chm/html/T_PostSharp_Aspects_CompositionAspect.htm
http://doc.postsharp.net/postsharp-3.0/Default.aspx#PostSharp-3.0.chm/html/20c81e23-af91-4688-a672-b0f3cce793a9.htm

A: So, I believe you are asking about inheritance.
Well, the vanilla way one could do it is this:
public interface ICar
{
    void ShiftGearUp();
    void ShiftGearDown();
    void SwitchLightsOn();
    void SwitchLightsOff();
    void Brake();
    void Accelerate();
}

public class Car : ICar
{
    public virtual void ShiftGearUp() { }
    public virtual void ShiftGearDown() { }
    public virtual void SwitchLightsOn() { }
    public virtual void SwitchLightsOff() { }
    public virtual void Brake() { }
    public virtual void Accelerate() { }
}

public class DeluxeCar : Car
{
    public override void SwitchLightsOn()
    {
        //calls the implementation in the Car class.
        base.SwitchLightsOn();
        //implement custom behavior.
        this.AdjustCabinAmbientLighting();
    }

    private void AdjustCabinAmbientLighting() { }
}

In this way you only override the behavior you want to change.
But, there is a world famous rule which says prefer composition over inheritance.
It would make us form the solution in this way:
public interface ICar
{
    void ShiftGearUp();
    void ShiftGearDown();
    void SwitchLightsOn();
    void SwitchLightsOff();
    void Brake();
    void Accelerate();
}

public abstract class AbstractCar : ICar
{
    protected ITransmission Transmission;
    protected ILights Lights;
    protected IEngine Engine;
    protected IBrakes Brakes;

    public void ShiftGearUp()
    {
        this.Transmission.ShiftUp();
    }

    public void ShiftGearDown()
    {
        this.Transmission.ShiftDown();
    }

    public void SwitchLightsOn()
    {
        this.Lights.SwitchOn();
    }

    public void SwitchLightsOff()
    {
        this.Lights.SwitchOff();
    }

    public void Brake()
    {
        this.Brakes.Brake();
    }

    public void Accelerate()
    {
        this.Engine.Accelerate();
    }
}

public class Car : AbstractCar
{
    public Car()
    {
        this.Lights = new AcmeLights();
        //todo
        //this.Engine = init engine object;
        //this.Brakes = init brakes object;
        //this.Transmission = init transmission object;
    }
}

public class DeluxeCar : AbstractCar
{
    public DeluxeCar()
    {
        this.Lights = new FancyLights();
        //todo
        //this.Engine = init engine object;
        //this.Brakes = init brakes object;
        //this.Transmission = init transmission object;
    }
}

public interface ITransmission
{
    void ShiftUp();
    void ShiftDown();
}

public interface ILights
{
    void SwitchOn();
    void SwitchOff();
}

public interface IEngine
{
    void Accelerate();
}

public interface IBrakes
{
    void Brake();
}

public class AcmeLights : ILights
{
    private LightSwitch Switch;

    public void SwitchOn() { this.Switch.On(); }
    public void SwitchOff() { this.Switch.Off(); }
}

public class FancyLights : ILights
{
    private LightSwitch Switch;
    private CabinAmbientLightingController AmbientLightingController;

    public void SwitchOn()
    {
        this.Switch.On();
        this.AmbientLightingController.AdjustLightLevel();
    }

    public void SwitchOff()
    {
        this.Switch.Off();
        this.AmbientLightingController.AdjustLightLevel();
    }
}

public class LightSwitch
{
    public void On() { }
    public void Off() { }
}

public class CabinAmbientLightingController
{
    public void AdjustLightLevel() { }
}

Edit: then you can use an dependency injection tool of your choosing to inject the dependencies of the Car and Deluxe car through their constructors. This is "AOP", maybe.
Edit:
For that purpose maybe you can use Dynamic Proxy. The famous tutorial is this. Might be a bit of a learning curve (and possibly not the best solution for this problem, but I don't know any others) - but all in all its a great framework and an interesting read.
What I would do, and please mind that my DynProxy is a little rusty, is declare an empty class, like
public class RocketCar
{

}

and then generate a class proxy without target and use interceptors to forward the calls. So, we should write a generic interceptor to which we can inject dependencies (like in the two concrete Cars above). So, we would have only one such class and configure and use it as needed. I believe this should be possible to code within a day, or two :)
The idea is the "Class which does not implement the interface" section here.
We would make the RocketCar implement IRocket and ICar.
But!
To implement many interfaces in one class is not imo the best way to do things! You are breaking the SRP.
If we have all these interfaces anyway, why not make the client code reference them by the individual interfaces? After all, if an RocketCar implements ICar, then it's Accelerate method must not be aware it is a part of a different car. In other words, the RocketCar must act in such a way that it is possible for us to substitute the RocketCar with any other ICar implementation wherever it is used. Otherwise we are breaking the LSP.
So, it is good to have the ICar and the IRocket in seperate classes. The specific implementations of these can have concrete type references to each other which model their interaction.
I am not saying you should never have classes implement multiple interfaces, but that should be an exception rather than the rule.


text:
Q: Azure PowerShell - Send Message to VM I'm creating some scripts in Azure Automation Accounts using PowerShell and I am wanting to send a popup to users on an Azure VM. If possible, it would be a popup that sends a response back to the script.
For further details: I'm writing a script to check the VM for a tag which holds the working hours of the user, then shuts the VM down two hours after their end time (easy enough). But just in case the user is working late / has been called out, I want to send a message for them to save their work. If the popup can send a response to PowerShell, then I'd a like a popup saying "OK" or "Delay by 1 hour". In either case the script will proceed after five minutes in case they don't respond. The script will run hourly, so no need to do more than "Continue" if the response is delay.
Thank you in advance.

A: •   You can create an interactive toast notification for your purpose when the evening time of logging off and shutting down systems is reached. To find templates of such interactive toast notifications and configure them, kindly refer to the below documentation link. Also, you can send the toast notification to the remote computers to be run as a powershell script by configuring it with the help of task scheduler at a specific point of time.
https://learn.microsoft.com/en-us/windows/apps/design/shell/tiles-and-notifications/adaptive-interactive-toasts?tabs=builder-syntax
The above link helps you in designing the toast notification and its content like message, image, notification alignment, etc. You can also use the below github link's 'Toast_Notify.ps1' powershell script to modify and configure the required notification to be sent on the remote computers: -
https://github.com/byteben/Toast/blob/master/Toast_Notify.ps1
•   Also, find the below sample of the toast notification created using the above script itself in which you must modify the 'XML' content in the script to get the desired toast notification.
 <?xml version="1.0" encoding="UTF-8"?>
 <ToastContent>
  <ToastTitle>We want to bring to your attention some important information. Please review the details below before contacting the Service Desk</ToastTitle>
   <Signature>Sent on behalf of the ICT Service Desk</Signature>
  <EventTitle>Major IT Issues - Flooding</EventTitle>
   <EventText>We are currently experiencing problems with all our systems. We are drinking coffee with our feet up and will provide an update shortly. Thank you for your patience</EventText>
    <ButtonTitle>Details</ButtonTitle>
    <ButtonAction>https://byteben.com</ButtonAction>
    </ToastContent>

Toast Notification image: -

Powershell command script to execute the above script: -
 PowerShell.exe -File "Toast_Notify.ps1" -XMLOtherSource \\MyFileServer\Toast Notifications Custom Message\CustomMessage.xml '

For detailed information on the above, kindly refer to the below link: -
https://byteben.com/bb/deploy-service-announcement-toast-notifications-in-windows-10-with-memcm/


text:
Q: Compiler error says "Function is not declared in this scope" but the function is public I'm setting up an IRQ on a Raspberry Pi Pico in C++ but when I compile my code it tells me the callback function is "Not declared in this scope". I've been beating my head against the wall for hours because the function is declared and it's public.
#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/gpio.h"

uint64_t time_between_triggers;
uint16_t times_triggered;

void shaft_speed_init(uint8_t _gpio_number, uint8_t _precision, uint8_t _counts_per_turn){
    gpio_set_irq_enabled_with_callback(2, GPIO_IRQ_EDGE_RISE, true, &_shaft_speed_gpio_callback);

}

void _shaft_speed_gpio_callback(uint16_t _gpio, uint32_t _event_mask) {
    uint64_t trigger_time;
    static uint64_t prev_trigger_time;

    trigger_time = to_us_since_boot(get_absolute_time());
    time_between_triggers = time_between_triggers + (trigger_time - prev_trigger_time);
    prev_trigger_time = trigger_time;
    times_triggered++;
}

[main] Building folder: variable_rate_planter
[build] Starting build
[proc] Executing command: /usr/bin/cmake --build /home/taylor/Documents/Programs/Pi-Pico/variable_rate_planter/build --config Debug --target all --
[build] [2/8  12% :: 0.017] Performing build step for 'PioasmBuild'
[build] ninja: no work to do.
[build] [3/8  25% :: 0.026] Performing build step for 'ELF2UF2Build'
[build] ninja: no work to do.
[build] [4/8  37% :: 0.043] No install step for 'PioasmBuild'
[build] [5/8  50% :: 0.052] No install step for 'ELF2UF2Build'
[build] [6/8  62% :: 0.083] Completed 'PioasmBuild'
[build] [6/8  75% :: 0.095] Completed 'ELF2UF2Build'
[build] [7/8  87% :: 0.201] Building CXX object CMakeFiles/vrp.dir/main.cpp.obj
[build] FAILED: CMakeFiles/vrp.dir/main.cpp.obj
[build] /usr/bin/arm-none-eabi-g++ -DCFG_TUSB_DEBUG=1 -DCFG_TUSB_MCU=OPT_MCU_RP2040 -DCFG_TUSB_OS=OPT_OS_PICO -DLIB_PICO_BIT_OPS=1 -DLIB_PICO_BIT_OPS_PICO=1 -DLIB_PICO_DIVIDER=1 -DLIB_PICO_DIVIDER_HARDWARE=1 -DLIB_PICO_DOUBLE=1 -DLIB_PICO_DOUBLE_PICO=1 -DLIB_PICO_FIX_RP2040_USB_DEVICE_ENUMERATION=1 -DLIB_PICO_FLOAT=1 -DLIB_PICO_FLOAT_PICO=1 -DLIB_PICO_INT64_OPS=1 -DLIB_PICO_INT64_OPS_PICO=1 -DLIB_PICO_MALLOC=1 -DLIB_PICO_MEM_OPS=1 -DLIB_PICO_MEM_OPS_PICO=1 -DLIB_PICO_PLATFORM=1 -DLIB_PICO_PRINTF=1 -DLIB_PICO_PRINTF_PICO=1 -DLIB_PICO_RUNTIME=1 -DLIB_PICO_STANDARD_LINK=1 -DLIB_PICO_STDIO=1 -DLIB_PICO_STDIO_USB=1 -DLIB_PICO_STDLIB=1 -DLIB_PICO_SYNC=1 -DLIB_PICO_SYNC_CORE=1 -DLIB_PICO_SYNC_CRITICAL_SECTION=1 -DLIB_PICO_SYNC_MUTEX=1 -DLIB_PICO_SYNC_SEM=1 -DLIB_PICO_TIME=1 -DLIB_PICO_UNIQUE_ID=1 -DLIB_PICO_UTIL=1 -DPICO_BOARD=\"pico\" -DPICO_BUILD=1 -DPICO_CMAKE_BUILD_TYPE=\"Debug\" -DPICO_COPY_TO_RAM=0 -DPICO_CXX_ENABLE_EXCEPTIONS=0 -DPICO_NO_FLASH=0 -DPICO_NO_HARDWARE=0 -DPICO_ON_DEVICE=1 -DPICO_TARGET_NAME=\"vrp\" -DPICO_USE_BLOCKED_RAM=0 -I/home/taylor/pico/pico-sdk/src/common/pico_stdlib/include -I/home/taylor/pico/pico-sdk/src/rp2_common/hardware_gpio/include -I/home/taylor/pico/pico-sdk/src/common/pico_base/include -I/home/taylor/Documents/Programs/Pi-Pico/variable_rate_planter/build/generated/pico_base -I/home/taylor/pico/pico-sdk/src/boards/include -I/home/taylor/pico/pico-sdk/src/rp2_common/pico_platform/include -I/home/taylor/pico/pico-sdk/src/rp2040/hardware_regs/include -I/home/taylor/pico/pico-sdk/src/rp2_common/hardware_base/include -I/home/taylor/pico/pico-sdk/src/rp2040/hardware_structs/include -I/home/taylor/pico/pico-sdk/src/rp2_common/hardware_claim/include -I/home/taylor/pico/pico-sdk/src/rp2_common/hardware_sync/include -I/home/taylor/pico/pico-sdk/src/rp2_common/hardware_irq/include -I/home/taylor/pico/pico-sdk/src/common/pico_sync/include -I/home/taylor/pico/pico-sdk/src/common/pico_time/include -I/home/taylor/pico/pico-sdk/src/rp2_common/hardware_timer/include -I/home/taylor/pico/pico-sdk/src/common/pico_util/include -I/home/taylor/pico/pico-sdk/src/rp2_common/hardware_uart/include -I/home/taylor/pico/pico-sdk/src/rp2_common/hardware_divider/include -I/home/taylor/pico/pico-sdk/src/rp2_common/pico_runtime/include -I/home/taylor/pico/pico-sdk/src/rp2_common/hardware_clocks/include -I/home/taylor/pico/pico-sdk/src/rp2_common/hardware_resets/include -I/home/taylor/pico/pico-sdk/src/rp2_common/hardware_pll/include -I/home/taylor/pico/pico-sdk/src/rp2_common/hardware_vreg/include -I/home/taylor/pico/pico-sdk/src/rp2_common/hardware_watchdog/include -I/home/taylor/pico/pico-sdk/src/rp2_common/hardware_xosc/include -I/home/taylor/pico/pico-sdk/src/rp2_common/pico_printf/include -I/home/taylor/pico/pico-sdk/src/rp2_common/pico_bootrom/include -I/home/taylor/pico/pico-sdk/src/common/pico_bit_ops/include -I/home/taylor/pico/pico-sdk/src/common/pico_divider/include -I/home/taylor/pico/pico-sdk/src/rp2_common/pico_double/include -I/home/taylor/pico/pico-sdk/src/rp2_common/pico_int64_ops/include -I/home/taylor/pico/pico-sdk/src/rp2_common/pico_float/include -I/home/taylor/pico/pico-sdk/src/rp2_common/pico_malloc/include -I/home/taylor/pico/pico-sdk/src/rp2_common/boot_stage2/include -I/home/taylor/pico/pico-sdk/src/common/pico_binary_info/include -I/home/taylor/pico/pico-sdk/src/rp2_common/pico_stdio/include -I/home/taylor/pico/pico-sdk/src/rp2_common/pico_stdio_usb/include -I/home/taylor/pico/pico-sdk/lib/tinyusb/src -I/home/taylor/pico/pico-sdk/lib/tinyusb/src/common -I/home/taylor/pico/pico-sdk/lib/tinyusb/hw -I/home/taylor/pico/pico-sdk/src/rp2_common/pico_fix/rp2040_usb_device_enumeration/include -I/home/taylor/pico/pico-sdk/src/rp2_common/pico_unique_id/include -I/home/taylor/pico/pico-sdk/src/rp2_common/hardware_flash/include -I/home/taylor/pico/pico-sdk/src/common/pico_usb_reset_interface/include -mcpu=cortex-m0plus -mthumb -Og -g -ffunction-sections -fdata-sections -fno-exceptions -fno-unwind-tables -fno-rtti -fno-use-cxa-atexit -MD -MT CMakeFiles/vrp.dir/main.cpp.obj -MF CMakeFiles/vrp.dir/main.cpp.obj.d -o CMakeFiles/vrp.dir/main.cpp.obj -c /home/taylor/Documents/Programs/Pi-Pico/variable_rate_planter/main.cpp
[build] In file included from /home/taylor/Documents/Programs/Pi-Pico/variable_rate_planter/main.cpp:4:
[build] /home/taylor/Documents/Programs/Pi-Pico/variable_rate_planter/shaft_speed.h: In function 'void shaft_speed_init(uint8_t, uint8_t, uint8_t)':
[build] /home/taylor/Documents/Programs/Pi-Pico/variable_rate_planter/shaft_speed.h:9:70: error: '_shaft_speed_gpio_callback' was not declared in this scope
[build]     9 |     gpio_set_irq_enabled_with_callback(2, GPIO_IRQ_EDGE_RISE, true, &_shaft_speed_gpio_callback);
[build]       |                                                                      ^~~~~~~~~~~~~~~~~~~~~~~~~~
[build] ninja: build stopped: subcommand failed.
[proc] The command: /usr/bin/cmake --build /home/taylor/Documents/Programs/Pi-Pico/variable_rate_planter/build --config Debug --target all -- exited with code: 1 and signal: null
[build] Build finished with exit code 1

A: Your function _shaft_speed_gpio_callback appears to be defined after the point in the code where it's used. You need to add a function declaration (a.k.a "prototype") so the compiler knows what the name refers to:
// Add this
void _shaft_speed_gpio_callback(uint16_t _gpio, uint32_t _event_mask);

// The rest of your code as provided
void shaft_speed_init(uint8_t _gpio_number, uint8_t _precision, uint8_t _counts_per_turn){
    gpio_set_irq_enabled_with_callback(2, GPIO_IRQ_EDGE_RISE, true, &_shaft_speed_gpio_callback);
}

void _shaft_speed_gpio_callback(uint16_t _gpio, uint32_t _event_mask) {
    // ...
}


text:
Q: Developing NodeJS app using Docker with live reload I'm developing a NodeJS app which uses webpack server.Webpack server is configured to take care of automatic file reloads. I want this to be mounted as a volume so that there is no need to rebuild the image every time I change the code. I want the node_modules folder to be available within the image so that I don't have to get the modules each time I start the container.
Actually the source code and node_modules should be at the same hierarchy level. But the problem is when I do a volume mount of my source code, node_modules (since it is part of the image) will be missing as volume mounted path will be used.
Is there any way I can get this thing working?

A: I know this problem well!
When you mount a volume it deletes the files inside the directory mounted inside the container (well, technically it does not delete them but for our purposes it does). This is because the files are part of the BUILD and not part of the RUN.
There are 3 fixes:
1 - Instead of doing an npm install at build time, do it at runtime - e.g. when you execute the docker run command. Container files created at runtime inside the mounted directory WILL BE available from the host.
ENTRYPOINT npm install (something like that)

2 - Copy the files somewhere else during the build (e.g. /temp/node_modules) and then copy them back at runtime
ENTRYPOINT scriptToCopyFilesBackIntoNodeModules.sh

Either of the first two should be used if you need access from the host. If you need access from another container use volumes_from - this just simply works without any of the above workarounds.
container1:
    volumes: /node_modules

container2:
    volumes_from: container1

It is something like that - the above syntax is docker-compose syntax.


text:
Q: Android - ScrollView is not scrolling i'm having problem with scrollview. It isn't working.
I read somewhere that you should only have one child view in ScrollView and maybe that's the problem, but i need a few horizontal lines. And i'm representing them in one view. You can see in my code two views inside RelativeLayout which is inside ScrollView.
UPDATE:
    <?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:background="@drawable/url"
        >

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="2000dp"
        android:layout_alignParentTop="true">

        <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="fill_parent">

             <com.android.volley.toolbox.NetworkImageView
                android:id="@+id/slika"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_above="@+id/textView1"
                android:layout_marginBottom="37dp"
                android:layout_alignParentLeft="true"
                android:layout_alignParentRight="true"
                android:layout_alignParentTop="true"
                android:src="@drawable/ic_horor_filmovi_ikonica" />

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@+id/slika"
                android:layout_alignParentBottom="true"
                android:layout_alignRight="@+id/slika"
                android:layout_marginBottom="64dp"
                android:text="Orginalni naslov:"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <TextView
                android:id="@+id/naslov"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@+id/textView1"
                android:layout_alignRight="@+id/slika"
                android:layout_alignTop="@+id/textView1"
                android:layout_marginTop="26dp"
                android:text="Large Text"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@+id/naslov"
                android:layout_alignRight="@+id/naslov"
                android:layout_below="@+id/naslov"
                android:layout_marginTop="18dp"
                android:text="Početak prikazivanja filma:"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <TextView
                android:id="@+id/datum_prikazivanja_filma"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@+id/textView2"
                android:layout_alignRight="@+id/textView2"
                android:layout_marginBottom="10dp"
                android:layout_below="@+id/textView2"
                />

            <TextView
                android:id="@+id/textView3"
                android:layout_marginTop="10dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@+id/datum_prikazivanja_filma"
                android:layout_alignRight="@+id/datum_prikazivanja_filma"
                android:layout_below="@+id/datum_prikazivanja_filma"
                />

            <View
                 android:id="@+id/view"
                 android:layout_alignLeft="@+id/textView3"
                 android:layout_alignRight="@+id/textView3"
                 android:layout_width="fill_parent"
                 android:layout_height="1dp"
                 android:background="#c0c0c0"
                 android:layout_below="@+id/textView3"/>

            <ImageButton
                android:id="@+id/Button1"
                android:background="@drawable/circle"
                android:drawableLeft="@drawable/ic_horor_filmovi_ikonica"
                android:drawableStart="@drawable/ic_horor_filmovi_ikonica"
                android:layout_marginTop="16dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/view"/>

            <TextView
                android:id="@+id/ime1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/Button1"
                android:layout_alignLeft="@+id/Button1"
                android:layout_alignRight="@+id/Button1"
                android:text="Ime"/>

            <ImageButton
                android:id="@+id/Button2"
                android:background="@drawable/circle"
                android:drawableRight="@drawable/ic_horor_filmovi_ikonica"
                android:drawableEnd="@drawable/ic_horor_filmovi_ikonica"
                android:layout_marginTop="16dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/view"/>

            <TextView
                android:id="@+id/ime2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/Button2"
                android:layout_alignLeft="@+id/Button2"
                android:layout_alignRight="@+id/Button2"
                android:text="Ime"/>

            <ImageButton
                android:id="@+id/Button3"
                android:background="@drawable/circle"
                android:drawableLeft="@drawable/ic_horor_filmovi_ikonica"
                android:drawableStart="@drawable/ic_horor_filmovi_ikonica"
                android:layout_marginTop="16dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/view"/>

            <TextView
                android:id="@+id/ime3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/Button3"
                android:layout_alignLeft="@+id/Button3"
                android:layout_alignRight="@+id/Button3"
                android:text="Ime"/>

            <View
                 android:id="@+id/view2"
                 android:layout_width="fill_parent"
                 android:layout_height="1dp"
                 android:background="#c0c0c0"
                 android:layout_below="@+id/ime3"/>

            <TextView
                android:id="@+id/textView4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@+id/view2"
                android:layout_alignRight="@+id/view2"
                android:layout_below="@+id/view2"
                android:layout_marginTop="18dp"
                android:text="Opis filma:"
                android:layout_centerHorizontal="true"
                android:textAppearance="?android:attr/textAppearanceLarge" />

        </RelativeLayout>
    </ScrollView>
</RelativeLayout>

A: It looks like your ScrollView height is set to fill_parent. First off, you should always use match_parent. Second, your scroll view will never scroll unless it is actually larger than its parent view.
So try setting the height of your ScrollView to WRAP_CONTENT that way it can expand to the full size of your RelativeLayout.

A:
I read somewhere that you should only have one child view in ScrollView

Yes.
ScrollView should always hold one child and that's exactly what you're doing.
Understanding the problem
Take a look at the child of your ScrollView, it's your RelativeLayout.
At it's very beginning, you define it to have a width that matche's it's parent (ScrollView) and a height large enough to wrap_content:
   <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
   </RelativeLayout>

How do you expect to scroll anything if it configured to be the same size as your ScrollView?
Solution
You need to use something like this instead:
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="2000dp"
    android:id="@+id/scrollView2"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="New Text"
            android:id="@+id/textView114"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="127dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="New Text"
            android:id="@+id/textView117"
            android:layout_below="@+id/textView114"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="268dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="New Text"
            android:id="@+id/textView118"
            android:layout_below="@+id/textView117"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="1200dp" />
    </RelativeLayout>
</ScrollView>


text:
Q: How to limit web services usage in Java application? Suppose I have a Java server application, which implements a few web services. Suppose also, I can authenticate application users.
Now I would like to add some limits per user to the service usage: e.g. rate limit (requests per second), maximum request size, etc.
Is there any "ready-to-use" library in Java to do that?

A: You can do that with Apache CXF by configuring an interceptor. This page has an example of the high level configuration.  This page has details on interceptors.  You can get as fancy as you wish with your validation.  I do not know off hand how to get the authenticated user.

A: I'm yet to see something like that available. But if you're using Java EE integrated security you can bootstrap it implementing your own LoginModule where you can do those checks without touching your web service code.
See http://docs.oracle.com/javase/6/docs/technotes/guides/security/jaas/JAASLMDevGuide.html

A: If you have a authentication/authorization service that all your calls go through then this per user restriction could be incorporated into it. I am not aware of a framework that allows you to do without custom coding.
Ideally this kind of logic is best configured outside of the service itself. I know camel provides in built throttling for number of requests. You can define your own throttling policy to map the number of per user requests.

A: You need to create a Simple interceptor class. There is a onPreExecute() method where you can put your custom check. I have used it with Spring.


text:
Q: For loop stops iterating in recursive function I'm attempting to solve the dependency hell problem on Hackerrank using Python 2.7.
I have formed a dictionary which lists all the dependencies. This is how the dictionary looks:
d = {1: [1, 8], 2: [0], 3: [1, 7], 4: [1, 7], 5: [1, 2], 6: [1, 2], 7: [0], 8: [2, 3, 4]}

The first number in each of the lists is just the number of elements in that list. The next numbers are the indices of the dependencies. Each number is the index for a software (i.e. software #1).
I've tried to create a recursive function that given an index, would list all the SW that need to be installed for the intended SW to be installed. I'm not worrying about the order at this point. This is the function:
def listSW(p,d,L):
    L.append(p)
    if d[p][0] > 0:
        for i in xrange(1,d[p][0]+1):
            return listSW(d[p][i],d,L)
    else:
        return L

Where L is a list (initially empty) where I'm dumping the indices of everything that needs to be installed and p is the software we intend to install.
The problem is that in the for loop only i = 1 is ever considered. So if I run the function for p = 8 I get:
[8, 3, 7]

When I intend to get:
[8, 3, 7, 4, 7]

What am I doing wrong?

A: def listSW(p,d,L):
    L.append(p)
    if d[p][0] > 0:
        for i in xrange(1,d[p][0]+1):
            listSW(d[p][i],d,L)
    return L

But I prefer not mixing return and updating a list so, I would do :
def buildList(p,d,L=[]):
    def patchList(p,d,L):
        L.append(p)
        for i in d[p][1:]:
            patchList(i,d,L)
    patchList(p,d,L)
    return L


text:
Q: Unreachable remote address in Apache Spark I'm trying to setup a cluster using Apache Spark 1.4.1 in 3 Ubuntu machines (named cloud-server-3 to 5). I have created my own clusters using Spark before but this time I can't seem to get it running.
I did the following for each machine.

*

*Downloaded the last prebuilt version of Spark with Hadoop 2.6, placed
it in /var/www/spark and added SPARK_HOME to environment variables.

*Installed the openjdk-7-jdk and added JAVA_HOME to environment variables.

*Shared the SSH keys between every machine using ssh-keygen and ssh-copy-id.

*Created the conf/spark-env.sh file with the master IP and the local IP in every machine.

And now the problems start.
I can create masters and slaves in every machine and can create a master in a machine and a slave in the same machine by using its name, IP or just localhost and connect them. But I can't connect different machines.
The weirdest thing is that if I put my slaves in the conf/slaves file and run start-all.sh where I want the master, the master goes up it starts the worker on the other machine but then the worker can't connect back to the master. I keep getting for master in cloud-server-3 and slave in cloud-server-5
"15/08/20 18:48:01 INFO Worker: Connecting to master akka.tcp://sparkMaster@cloud-server-3:7077/user/Master...
15/08/20 18:48:01 WARN Remoting: Tried to associate with unreachable remote address [akka.tcp://sparkMaster@cloud-server-3:7077]. Address is now gated for 5000 ms, all messages to this address will be delivered to dead letters"
I tried disabling the firewalls, confirmed that the machines can ping each other, confirmed that I can SSH every machine without password and edited /etc/hosts and added the IPs and names of every machine. Do you guys have any ideas?


text:
Q: Understanding replaced leds brightness behaviour (keyboard backlight) I've followed this tutorial to replace some broken leds on my keyboard. The leds I used are:
Emitted Color : White
Size (mm) : 3mm
Lens Color : Water Clear
Color Temperature (K): 6500 ~ 7000
Forward Voltage (V) : 3.0 ~ 3.4
Forward Current (mA): 20
Reverse Current (uA) : <= 30
Luminous Intensity Typ Iv (mcd) : 6000(Typical) ~ 8000(Max)
Viewing Angle : 20 Degree
Pin Length: 28.5mm and 26.5mm

They should be ok according to that tutorial (I haven't been able to find the exact specs of the ones that came with the keyboard).
Polarity was not specified on the board so I used a voltmeter and made sure the voltage was reported as +3.xx volts. Anyway, I've solder them and it worked, the type of white is a bit different but close enough.
Problem is, backlight can be turned off or made brighter/dimmer, I usually keep it at mid brightness (and at mid brightness all looked fine).

*

*If I lower the brightness, replaced leds brightness do not change

*If I raise the brightness, replaced leds get dimmer!

*If I turn of backlight, replaced leds stay on

I plan to keep it at mid brightness 99% of the time so that's not really a problem but I'd like to know why it behaves that way. If I got the polarity wrong they should just stay always off right? Brightness variation is done by changing the current right? Maybe the replaced leds have a lower minimum current? This could explain why they don't get dimmer as the others and don't turn off, but then why do they get dimmer when I rise the brightness setting? Could they be receiving too much current and get dimmer as result of being in the process of breaking? If that's so, why do they regain normal brightness when I set it to medium again?
Thanks, as you might have noticed I know very few of electronics.
EDIT:
I've measured volts/amps with all brightness settings:
v.o  = volts across an original led
v.r  = volts across a replaced led
ma.r = milliamps through a replaced leds

brightness       v.o  v.r  ma.r
max              1.3  0.8  0.01
mid              3.3  1.8  0.15
min              4.2  2.3  0.54
off              4.6  2.4  0.59

At this point I wanted to know the current through an original led so I desoldered one, and discovered that I indeed got the polarity wrong as @Jasen suggested in the comments. I've re-soldered everything and 2 of the 3 replaced leds behaved as intended, the remaining one stayed off. So I did not have 3 broken leds, but 2 broken leds (that worked when replaced correctly) and a broken "slot", and guess what "slot" I used to figure out polarity at my first try? The broken one.
Now, I would be happy with just one broken led, but I must have done something wrong during the last session of tests/soldering because now the keyboard does not work any more, every key repeat itself lot of times. Damn me the moment I thought I could not live with 3 keys not lighting up.
Fun fact, the keyboard worked with the 3 replaced leds with inverted polarity.
To give this question an answer, the correct guess was that of @Jasen, it would have worked if I tried it first with any slot but the broken one. If you want to write a small answer I'll accept it, otherwise I'll answer my own question.

A: Turned out I got the polarity wrong and installed the leds backward. I wasn't aware of the existence of PWM so I assumed the polarity from the first positive measure I got with my cheap voltmeter.


text:
Q: WPF - How to get ONLY one column of data from a group of data For the data retrieval part from Database:
    public DataTable GetMagazineDetails()
    {
        using (var conn = new SqlConnection(ConnectionHelper.ConnectionString))

        using (var command = new SqlCommand("usp_GetMagazineDetails", conn))

        using (var adapter = new SqlDataAdapter(command))
        {
            command.CommandType = CommandType.StoredProcedure;
            temp_table = new DataTable("[COMPANY].[Magazines]");
            adapter.Fill(temp_table);

            return temp_table;
        }

    }

For the xaml.cs part where I want it to bind to a DataGrid, particularly one column:
        DataTable temp_table = usp_GetMagazineDetails.GetMagazineDetails();

        grd_MagazineListing.ItemsSource = temp_table.DefaultView;

My question is... How do I retrieve only one column of data out from the temp_table variable that I have created here. Is it possible? Or is there another way to approach it? Thank you very much guys :) Truly appreciate any help given.

A: It is possible, you could do this.
List<string> columnValues = new List<string>(); // Modify and use respective data type.

foreach (DataRow row in temp_table.Rows)
{
    columnValues.Add(row["columnname"].ToString()); // Use either 'columnname' or 'index'
}

Other option, use Linq
columnValues = temp_table.AsEnumerable()
                         .Select(row=>row["columnname"].ToString())
                         .ToList();

Now your binding should be
grd_MagazineListing.ItemsSource = columnValues;


text:
Q: Product measure definition and normal definition of Lebesgue measure When we define Lebesgue measure in $\mathbb{R}^n$, we usually make outer measure using rectangles and take induced measure by Caratheodory's method. Let $\mu_n$ be Lebesgue measure defined by this way.
Also, we can define Lebesgue measure by product measure. With $(\mathbb{R}^n,\mathcal{M}_n,\mu_n)$ and $(\mathbb{R}^m,\mathcal{M}_m,\mu_m)$, we define outer measure $(\mu_n\times\mu_m)^*$ with measureable Rectangles. Then also by Caratheodory method we get a measure on  $\sigma(\mathcal{M}_n\times \mathcal{M}_m)$, and by completion we get Lebesgue measure exactly same as above.
Now, think about 'original' Caratheodory method. We can get measure on $(\mu_n\times\mu_m)^*$-measurable sets, not only on $\sigma(\mathcal{M}_n\times \mathcal{M}_m)$, if we give up uniqueness. My question is this: Is $(\mu_n\times\mu_m)^*$-measurable sets are exactly same as Lebesgue measurable set on $\mathbb{R}^{n+m}$? If yes, then measure defined on $(\mu_n\times\mu_m)^*$-measurable sets is exactly same as Lebesgue measure? If answer of second question is also yes, then is there exist measure defined on Lebesgue measurable set which is different from Lebesgue measure, coincide with Lebesgue measure at  $\sigma(\mathcal{M}_n\times \mathcal{M}_m)$?


text:
Q: Rails in what order do model callbacks happen for nested parent/ child models? I know that the general order in which models are saved is the deepest child first, and then gradually up to the parent. But I'm wondering with respect to other callbacks, does it happen something along the lines of:
ChildA - before validation
ChildB - before validation
Parent - before validation

ChildA - after validation
ChildB - after validation
Parent - after validation

ChildA - before save
ChildB - before save
Parent - before save

...

OR along the lines of:
ChildA - before validation
ChildA - after validation
ChildA - before save
...

ChildB - before validation
ChildB - after validation
ChildB - before save
...

Parent - before validation
Parent - after validation
Parent - before save
...

The reason this is important is that I have callbacks that adjust attributes, and the adjustability of an attribute on a model depends on the attributes of other models.
One example is that I want the Parent to auto-set its status attribute to be Complete if ChildA and child B'sstatusattributes are bothCompleteand the children are bothvalid`.
I tried to test this using puts statements, but apparently, that leads to some weird behaviour (see this question: Nested form validation statements repeating multiple times), and I'm afraid it's not representative.
I definitely read the Rails Guides, but maybe I'm blind because I didn't see a reference to this anywhere...

A: While putting this kind of state machine logic in callbacks might be tempting, it makes for a hard to understand code. Consider instead having a dedicated method gathering and mutating your data in a more straightforward way.
This would also help with data consistency and tests, as described in this blog post.

A: Interesting question. By default callback defined in the parent is run first. prepend: true option allows you to tune that behaviour.
See "Ordering callbacks" section in Rails API. It's also worth checking "Inheritable callback queues" section, since redefining a method is not the same as using macros.
P.S. All stated above is valid at least for version 4.2.5.2

A: By experimenting with rails I have encountered that the parent is validated first and then child but no rails core member have pronounced about this.
That's why you can move logic to parent:
class Sale
  has_many :details
  before_validation :evaluate_details
  # validations

  def evaluate_details
    self.details.each do |detail|
      detail.generate_info
      detail.items.each do |item|
        item.dance
      end
    end
  end
end

class Detail
  belongs_to :sale
  has_many :items
  # validations

  def generate_info
    # Do things
  end
end

class Item
  belongs_to :detail
  # validations

  def dance
    # Dancing
  end
end

This prevents multiple executions and manages the execution order.
PD: Also you can avoid the before_validation callback and call the method manually.


text:
Q: Plotting a tomographic map of a 3-D data? Regarding my former question I posted, my idea was quite vague and I was a bit confused how I can illustrate my quantities.
I have three dimensional data set. In one of the dimension, I have a probability distribution regarding each point in that axis. For example a point with (X_0,Y_0) coordinate has a probability that for given Z_0 has P(Z_0)=0.21 and Z varies between [0,1.5]. For instance, I would like to plot a tomographic map at Z=0.8.
How could I add probability distribution which is a 2-D array- e.g. one column Z between [0,1.5] and the other column p(z)- to each point and then make a 3D plot plus a tomography map at one given Z ?
I gridded my data in a 3D array. Then I counted the number of points in the x-y plane. In the z direction, I added the probability of z in each point in each cell from 0 to 1.5 and then I normalized it to the number of points in each grid cell in the x-y plane.
Now I don't know how I can make a contour plot which I would like to project the probability of z, stored in each cell at z=0.8 for a slice perpendicular to the z direction with the upper and lower limits of [0.75,0.85]. Any suggestion???
nx=200;ny=200
z=np.arange(0.0001,1.501,0.001)
xi = np.linspace(min(Xpos)-1, max(Xpos)+1, nx)
yi = np.linspace(min(Ypos)-1, max(Ypos)+1, ny)

mesh=np.zeros((nx-1,ny-1,len(z)),float)
print "gridding data:"
print mesh.shape
NP_mesh=[[0]*(ny-1)]*(nx-1)
NP_mesh=np.asarray(NP_mesh)
num_gal=0
for ii in range(len(Xpos)):
    num_gal+=1
    for i in range(nx-1):
        for j in range(ny-1):
            if ((Xpos[ii]>=xi[i]) and (Xpos[ii]<xi[i+1]) and (Ypos[ii]>=yi[j]) and (Ypos[ii]<yi[j+1])):
               NP_mesh[i,j]+=1.0
               for k in range(len(z)):
                   mesh[i,j,k]+=PDF[ii,k+1]

new_mesh=np.zeros((nx-1,ny-1,len(z)),float)
for i in range(nx-1):
    for j in range(ny-1):
        if (NP_mesh[i,j]!=0):
       new_mesh[i,j,:]=mesh[i,j,:]/float(NP_mesh[i,j])


text:
Q: Lost character/s during encrypt-decrypt using  I am using "wincrypt.h" to based algorithms to encrypt a character string and then decrypt the encrypted string to the original.
Something like :
Original -> Encrypt -> Decrypt -> Original

The problem is the Decrypted Original comes out short in length in some case(some words), the problem is not length of the string or a or more character related, that I have checked. The problem I think is with key(its simply a random character string), If I use a different key, it affects a totally different word/string.
Here is the code:
    BOOL SetupCryptoClient()
    {
        // Ensure that the default cryptographic client is set up.
        HCRYPTPROV hProv;
        HCRYPTKEY hKey;
        // Attempt to acquire a handle to the default key container.
        if (!CryptAcquireContext(&hProv, NULL, MS_DEF_PROV, PROV_RSA_FULL, 0))
        {
            // Some sort of error occured, create default key container.
            if (!CryptAcquireContext(&hProv, NULL, MS_DEF_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET))
            {
                // Error creating key container!
                return FALSE;
            }
        }
        // Attempt to get handle to signature key.
        if (!CryptGetUserKey(hProv, AT_SIGNATURE, &hKey))
        {
            if (GetLastError() == NTE_NO_KEY)
            {
                // Create signature key pair.
                if (!CryptGenKey(hProv, AT_SIGNATURE, 0, &hKey))
                {
                    // Error during CryptGenKey!
                    CryptReleaseContext(hProv, 0);
                    return FALSE;
                }
                else
                {
                    CryptDestroyKey(hKey);
                }
            }
            else
            {
                // Error during CryptGetUserKey!
                CryptReleaseContext(hProv, 0);
                return FALSE;
            }
        }

        // Attempt to get handle to exchange key.
        if (!CryptGetUserKey(hProv,AT_KEYEXCHANGE,&hKey))
        {
            if (GetLastError()==NTE_NO_KEY)
            {
                // Create key exchange key pair.
                if (!CryptGenKey(hProv,AT_KEYEXCHANGE,0,&hKey))
                {
                    // Error during CryptGenKey!
                    CryptReleaseContext(hProv, 0);
                    return FALSE;
                }
                else
                {
                    CryptDestroyKey(hKey);
                }
            }
            else
            {
                // Error during CryptGetUserKey!
                CryptReleaseContext(hProv, 0);
                return FALSE;
            }
        }

        CryptReleaseContext(hProv, 0);
        return TRUE;
    }

    BOOL EncryptString(TCHAR* szPassword,TCHAR* szEncryptPwd,TCHAR *szKey)
    {
        BOOL bResult = TRUE;
        HKEY hRegKey = NULL;
        HCRYPTPROV hProv;
        HCRYPTKEY hKey;
        HCRYPTKEY hXchgKey;
        HCRYPTHASH hHash;
        DWORD dwLength;
        // Get handle to user default provider.
        if (CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, 0))
        {
            // Create hash object.
            if (CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash))
            {
                // Hash password string.
                dwLength = sizeof(TCHAR)*_tcslen(szKey);
                if (CryptHashData(hHash, (BYTE *)szKey, dwLength, 0))
                {
                    // Create block cipher session key based on hash of the password.
                    if (CryptDeriveKey(hProv, MY_ENCRYPT, hHash, CRYPT_EXPORTABLE, &hKey))
                    {
                        // Determine number of bytes to encrypt at a time.
                        dwLength = sizeof(TCHAR)*_tcslen(szPassword);
                        // Allocate memory.
                        BYTE *pbBuffer = (BYTE *)malloc(dwLength);
                        if (pbBuffer != NULL)
                        {
                            memcpy(pbBuffer, szPassword, dwLength);
                            // Encrypt data
                            if (CryptEncrypt(hKey, 0, TRUE, 0, pbBuffer, &dwLength, dwLength))
                            {
                                // return encrypted string
                                memcpy(szEncryptPwd, pbBuffer, dwLength);

                            }
                            else
                            {
                                bResult = FALSE;
                            }
                            // Free memory
                            free(pbBuffer);
                        }
                        else
                        {
                            bResult = FALSE;
                        }
                        CryptDestroyKey(hKey);  // Release provider handle.
                    }
                    else
                    {
                        // Error during CryptDeriveKey!
                        bResult = FALSE;
                    }
                }
                else
                {
                    // Error during CryptHashData!
                    bResult = FALSE;
                }
                CryptDestroyHash(hHash);
                // Destroy session key.
            }
            else
            {
                // Error during CryptCreateHash!
                bResult = FALSE;
            }
            CryptReleaseContext(hProv, 0);
        }
        return bResult;
    }

    BOOL DecryptString(TCHAR* szEncryptPwd,TCHAR* szPassword,TCHAR *szKey)
    {
        BOOL bResult = TRUE;
        HCRYPTPROV hProv;
        HCRYPTKEY hKey;
        HCRYPTKEY hXchgKey;
        HCRYPTHASH hHash;
        TCHAR szPasswordTemp[32] = _T("");
        DWORD dwLength;
        // Get handle to user default provider.
        if (CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, 0))
        {
            // Create hash object.
            if (CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash))
            {
                // Hash password string.
                dwLength = sizeof(TCHAR)*_tcslen(szKey);
                if (CryptHashData(hHash, (BYTE *)szKey, dwLength, 0))
                {
                    // Create block cipher session key based on hash of the password.
                    if (CryptDeriveKey(
                        hProv, MY_ENCRYPT, hHash, CRYPT_EXPORTABLE, &hKey))
                    {
                        // we know the encrypted password and the length
                        dwLength = sizeof(TCHAR)*_tcslen(szEncryptPwd);
                        // copy encrypted password to temporary TCHAR
                        _tcscpy(szPasswordTemp,szEncryptPwd);
                        if (!CryptDecrypt(
                                hKey, 0, TRUE, 0, (BYTE *)szPasswordTemp, &dwLength))
                            bResult = FALSE;
                        CryptDestroyKey(hKey);  // Release provider handle.
                        // copy decrypted password to outparameter
                        _tcscpy(szPassword,szPasswordTemp);
                    }
                    else
                    {
                        // Error during CryptDeriveKey!
                        bResult = FALSE;
                    }
                }
                else
                {
                    // Error during CryptHashData!
                    bResult = FALSE;
                }
                CryptDestroyHash(hHash); // Destroy session key.
            }
            else
            {
                // Error during CryptCreateHash!
                bResult = FALSE;
            }
            CryptReleaseContext(hProv, 0);
        }
        return bResult;
    }

And this is how I call it :
TCHAR szEncrypt[32] = _T("");
EncryptString( myString, szEncrypt, szKey );

TCHAR szDecrypt[32] = _T("");
DecryptString( szEncrypt, szDecrypt, szKey);

Note: The code is not mine.
EDIT: using key "Mz6@a0i*" turns Kolaris to Kolari

A: The encrypted string can contain a zero byte, in fact the chances are 1/256 for any individual byte to be zero. You're assuming the encrypted result is a string which ends on a zero byte. Even if the TCHAR is 16 bits rather than 8, your chances are still 1/65536.
You need to pass the length of the encrypted result.


text:
Q: check if a tablet no matter the operating system of the device I want to check if a device is a tablet to disable a certain portion of code that should only work if the device is andorid or IOS, that is, even if the table is Android or IOS if it is not a phone, that code should not be executed. Anyone have any possible solution? I read this: What is the best way to detect a mobile device?
I already read that but it does not fit what I need, since it does not matter if it is an Android or IOS mobile device or if it is a mobile device or not what I want to know is if it is simply a Tablet.
Is there currently something to verify?