text:
Q: Django-REST-framework Concrete-View-Classes not returning json? I'm working on a new app using React and DRF in which React must get the data from DRF in JSON and parse the data. But I think some of my Generic View Classes do not return JSON correctly.
For Example, a "ListCreateAPIView" class returns this:
[{"id":5,"name":"5 Storey I=1.3","Value":1399511075,"NSt":5},{"id":6,"name":"5 Storey I=0.7","Value":1344981250,"NSt":5},{"id":7,"name":"5 Storey I=1","Value":1363157800,"NSt":5}]

While a "RetrieveUpdateDestroyAPIView" class returns this:
{"id":6,"name":"5 Storey I=0.7","Value":1344981250,"NSt":5,"jRatio":"[0.2,0.4,0.4]","jEDR":"[0.02,0.1,0.5,1]","jStrDrSL":"[0.3826667,0.6046667,0.78,0.8666667]","StrDrB":0.8,"jNStrDrSL":"[0.4,0.8,2.5,5]","NStrDrB":0.75,"jNStrAccSL":"[0.25,0.5,1,2]","NStrAccB":0.5,"jPGA":"[0.141,0.374,0.550,0.822]","jRePr":"[75,475,975,2475]","NNTH":7,"jP_CL":"[ 0 , 5 , 6 , 7 ]","jMIDR":"[[[0.014488,0.021893,0.010635,0.029521,0.009106,0.013556,0.034016], [0.019524,0.022306,0.013733,0.041172,0.012122,0.019027,0.027467], \r\n[0.018057,0.019549,0.01485,0.034628,0.010172,0.022447,0.02065], \r\n[0.018057,0.015954,0.009193,0.024401,0.006838,0.022809,0.017592], \r\n[0.017192,0.012215,0.009257,0.016268,0.005854,0.019945,0.012777]], \r\n\r\n[[0.016604,0.025492], \r\n[0.026047,0.03113], \r\n[0.02794,0.02432], \r\n[0.024571,0.01748], \r\n[0.023962,0.014474]], \r\n\r\n[[0.040325], \r\n[0.044064], \r\n[0.035164], \r\n[0.024971], \r\n[0.020532]], \r\n\r\n[[1], \r\n[1], \r\n[1], \r\n[1], \r\n[1]]]","jMAcc":"[[[0.081014271,0.126595311,0.094557594,0.094250765,0.068444444,0.088719674,0.118411825], \r\n[0.06911213,0.091793068,0.097146789,0.11106422,0.056927625,0.118172273,0.103258919], \r\n[0.076614679,0.077261978,0.120961264,0.144769623,0.055780836,0.08214475,0.123833843], \r\n[0.082191641,0.08675739,0.129832824,0.13788685,0.04724159,0.071845056,0.091466871], \r\n[0.18904791,0.111108053,0.098691131,0.13933945,0.052319062,0.198410805,0.117994903]], \r\n\r\n[[0.184002039,0.156264016], \r\n[0.18011213,0.122554536], \r\n[0.24753211,0.136911315], \r\n[0.292653415,0.120941896], \r\n[0.255610601,0.127876656]], \r\n\r\n[[0.201146789], \r\n[0.173687054], \r\n[0.17719368], \r\n[0.172267074], \r\n[0.187479103]], \r\n\r\n[[1], \r\n[1], \r\n[1], \r\n[1], \r\n[1]]]"}

Notice that the data doesn't start with a bracket "[" and because of this I'm not able to parse it in React. I need to know where the problem is. Should I not use GenericViewClasses?
views.py:
class BuildingsList(ListCreateAPIView):
    queryset=Building.objects.all()
    serializer_class=BuildingSerializerList

class BuildingDetails(RetrieveUpdateDestroyAPIView):
    queryset=Building.objects.all()
    serializer_class=BuildingSerializerDetails

urls.py:
urlpatterns=[
    path('', BuildingsList.as_view()),
    path('<int:pk>/', BuildingDetails.as_view()),]

serializers.py:
class BuildingSerializerList(serializers.ModelSerializer):
    class Meta:
        model=Building
        fields=['id','name','Value','NSt']

class BuildingSerializerDetails(serializers.ModelSerializer):
    class Meta:
        model=Building
        fields='__all__'

A: The Detail-View means, it only returns One item/details of particular look-up. and moreover, the response behavior will purely depend on your Serializer classes (BuildingSerializerList and BuildingSerializerDetails).
The ListCreateAPIView is meant for listing all your Building instances.
In terms of react, the Detail-view returns a JSON object whereas in List-view it returns a JSON-Array
I would recommend you to use DRF's ModelViewset class for views, which is very handy
UPDATE-1
You can do simple CRUD operations on Sample model through REST-API by using following view class
from rest_framework.viewsets import ModelViewSet

class SampleViewset(ModelViewSet):
    serializer_class = SampleSerializer
    queryset = SampleModel.objects.all()

If you are trying to do CRUD operations by using GenericViewSet, you need to write views like this,
from rest_framework.viewsets import GenericViewSet

class SampleNew(GenericViewSet):
    queryset = SampleModel.objects.all()
    serializer_class = SampleSerializer

    def list(self, request, *args, **kwargs):
        # your list logic
        return response

    def create(self, request, *args, **kwargs):
        # your list logic
        return response

    def destroy(self, request, *args, **kwargs):
        # your list logic
        return response

    def retrieve(self, request, *args, **kwargs):
        # your list logic
        return response

Did you see the difference !!

A: Get ListCreateAPIView will return a list(jsonarray),get RetrieveUpdateDestroyAPIView will return a single object info(jsonobject) is right,that's ListCreateAPIView and RetrieveUpdateDestroyAPIView designed to be.You would better change the parse code in fontend in React.
In your case is GenericAPIView not suit your requirement,I think you want to CRUD the model Building by DRF,then the ModelViewSet is something you actually needed.
views.py
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import ModelViewSet

class BuildingViewSet(ModelViewSet):
    queryset = Building.objects.all()
    serializer_class = BuildingSerializerList
    permission_classes = (IsAuthenticated,)

    def get_serializer_class(self):
        if self.action in ['update', 'partial_update', 'retrieve']:
            return BuildingSerializerDetails
        else:
            return self.serializer_class

urls.py:
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'building', BuildingViewSet)

urlpatterns = [
    path('', include(router.urls)),
    path('admin/', admin.site.urls),
]

then
create with post http://localhost/building/
list with get http://localhost/building/ # return jsonarray
detail with get http://localhost/building/id/ # return jsonobject
update with put/patch http://localhost/building/id/
delete with delete http://localhost/building/id/

If you really want detail return a list,simple change to:
class BuildingViewSet(ModelViewSet):
    ....
    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response([serializer.data])

but it's really meaningless.


text:
Q: How to move grep inside awk script? In the below have I 3 grep commands that I would like to replace with awk's grep. so I have tried
! /000000000000/;
! /000000000000/ $0;
! /000000000000/ $3;

where I don't get an error, but testing with both the script below and
$ echo 000000000000 | awk '{ ! /000000000000/; print }'
000000000000

it doesn't skip the lines as expected.
Question
Can anyone explain why my "not grep" doesn't work in awk?
grep -v '^#' $hosts | grep -E '[0-9A-F]{12}\b' | grep -v 000000000000 | awk '{
    print "host "$5" {"
    print "  option host-name \""$5"\";"

    gsub(/..\B/,"&:", $3)
    print "  hardware ethernet "$3";"

    print "  fixed-address "$1";"
    print "}"
    print ""
}' > /etc/dhcp/reservations.conf

A: Could you please try changing your code to:
echo 000000000000 | awk '!/000000000000/'

Problem in your attempt: $ echo 000000000000 | awk '{ ! /000000000000/; print }' Since you are checking condition ! /000000000000/ which is having ; after it so that condition works well and DO NOT print anything. But then you have print after it which is NOT COMING under that condition so it simply prints that line.
awk works on pattern{action} if you are putting semi colon in between it means that condition ends before it and statement after ; is all together a new statements for awk.

EDIT: Adding possible solution by seeing OP's attempt here, not tested at all since no samples are shown by OP. Also I am using --re-interval since my awk version is old you could remove in case you have new version of awk in your box.
awk --re-interval '!/^#/ && !/000000000000/ && /[0-9A-Fa-f]{12}/{
    print "host "$5" {"
    print "  option host-name \""$5"\";"
    gsub(/..\B/,"&:", $3)
    print "  hardware ethernet "$3";"
    print "  fixed-address "$1";"
    print "}"
    print ""
}' "$host" > /etc/dhcp/reservations.conf

A: Taking a look at your code:
$ echo 000000000000 | awk '
{
    ! /000000000000/ # on given input this evaluates to false
                     # but since its in action, affects nothing
    print            # this prints the record regardless of whatever happened above
}'

Adding a print may help you understand:
$ echo 000000000000 | awk '{ print ! /000000000000/; print }'
0
000000000000

Removing the !:
$ echo 000000000000 | awk '{ print /000000000000/; print }'
1
000000000000

This is all I can help you with since there is not enough information for more.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Count column with specific condition How can i count columns that hold particular values - but have it as a grand-total.
table data:
 Code      No
  1         *
  2         -
  3         4
  4

If for example i wanted to count how many rows had * and - and space
I could do
Case when No = '*'
Then COUNT(No)
when No = '-' then count(No)
when No = '' then count(No)
else 0 end as 'Count'

but this returns 4
http://sqlfiddle.com/#!9/f73409/4
I would want this to return 3
Any help would be appreciated

A: Use IN:
select Sum(Case when No IN ('*', '-', '') then 1 else 0 end) as Count
from Table1

See Fiddle.

A: Standard SQL has a particular feature for that: the filter clause that follows aggregates.
Unfortunately, it is not very widely supported (mainly PostgreSQL).
There is an easy workaround using case however:
COUNT(CASE WHEN <condition> THEN 1 END)

This works because the implied else null clause of case and because count does not count null.
More about the filter clause and ways to mimic it: http://modern-sql.com/feature/filter


text:
Q: How do I create bar charts in R where the starting point of the bar is greater than zero? I'm trying to create a series of bar charts (to be replicated for multiple sites) that highlight the difference between the main site and the satellite locations. I can come somewhat close using geom_point, but I'd like to have them represented as bar charts, where the bar starts at the lowest point, there are labels for the main site and satellite locations, as well as the difference between them. Here is some sample code and screenshots of what I have, and an idea of what I'd like it to look like.
library(ggplot2)
library(dplyr)

site <- c("Site A", "Main Site", "Site A", "Main Site", "Site A", "Main Site")
year <- c("2013", "2013", "2014", "2014","2015", "2015" )
value <- c(57, 74, 60, 50, 60, 68)

df <- data.frame (site, year, value)

df %>%
  mutate (label = paste0(site, " (", value, ")")) %>%
  ggplot (aes (x = year, y = value, group = site, colour = site)) +
  geom_point (size = 0.5) +
  scale_y_continuous(limits = c (0,100)) +
  geom_text (aes(label = label))

A: Following up on the comment from @gregor, you can try the below (note dcast is from reshape2 and the heavy use of dplyr
df %>%
  dcast(year~site) %>%
  mutate(midpt = (`Main Site` + `Site A`)/2
         , dir = factor( (`Main Site` - `Site A`) > 0
                         , levels = c(FALSE,TRUE)
                         , labels = c("Negative", "Positive"))
         , diff = abs(`Main Site` - `Site A`)) %>%
  ggplot(aes(x = year
             , y = midpt
             , fill = dir
             , height = diff)) +
  geom_tile() +
  scale_fill_manual(values = c("Positive" = "darkgreen"
                               , "Negative" = "red3"))

If you have more than 2 sites, you would likely want a more flexible solution, probably using dplyr directly.

A: Using the comment from @Gregor I managed to come up with something that will work. Probably isn't the most elegant solution but will work for now.
df %>%
  spread(site, value) %>%
  mutate (diff = SiteA - MainSite) %>%
  mutate (AboveBelow = recode (diff," -100:-1 = 'Below';
                               0 = 'No Difference';
                               1:100 = 'Above'")) %>%
  ggplot() +
  scale_x_continuous(name = "Year", breaks = c (2013, 2014, 2015)) +
  scale_y_continuous(name = "Percentage", limits = c(0,100)) +
  geom_rect (aes (xmin = year - 0.33, xmax = year + 0.33, ymin = SiteA, ymax = MainSite, fill = AboveBelow)) +
  geom_text (aes (x = year, y = ifelse (diff < 0, MainSite + 5, MainSite - 3), label = paste0("MainSite - ", MainSite))) +
  geom_text (aes (x = year, y = ifelse (diff < 0, SiteA - 3, SiteA +5), label = paste0("SiteA - ", SiteA))) +
  geom_text (aes (x = year, y = MainSite + (diff/2), label = diff)) +
  scale_fill_manual(values = c("green", "red", "white" ))

Gives me this:


text:
Q: PHP if/switch concatenated by * I was wondering if anybody knew if there was a way to concatenate a * (all) to a string inside an if (or switch) statement. For example if you had a URL called /hello/there and /hello/whats-up ... is there anyway you could have something like the following:
if ($url="/hello/" . *) {
sayHello();
} else { sayGoodebye(); }

etc... I don't think that's the correct syntax, but if anybody knows what I'm talking about it would be a great help.
Thanks (:

A: $match = "/hello/";
if (substr($url, 0, strlen($match)) === $match) {
   sayHello();
} else {
   sayGoodbye();
}

Do not use regular expressions if you don't have to...

A: You can also check for the position of $match in the $url string:
$match = "/hello/";

if (strpos($url, $match) === 0) {
   sayHello();
} else {
   sayGoodbye();
}

A: Use regular expressions:
http://www.regular-expressions.info/php.html
So it would be something like this:
if (ereg("/hello/", $url)) {
sayHello();
} else { sayGoodebye(); }

Although that would match anything with "/hello/" in it anywhere, so if you only wanted to match strings that start with "/hello/" you'd have to modify the expression.  The point is, if you've never used regular expressions it's a good thing to invest some time into.  It'll pay off eventually because at some point you're going to need this skill.
Edit: I'll leave my original code here as reference, but please see phihag's comments and use preg_match and the preg_match compatible expression instead of ereg and the expression I used.


text:
Q: Make broken loop run again? I made a program which prints 'F pressed!' when i press the button 'F'. I don't want it to spam my console with that so I made the While-Loop break after that. How can I make the function run again and make the program not stop working? Or just make the text only appear once everytime I press the button?
import win32api

while True:
    keystate = win32api.GetAsyncKeyState(0x46)

    if keystate < 0:
        print('F pressed!')
        break
    else:
        pass

Thanks

A: How can I make the function run again and make the program not stop working?
The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop.
Therefore, you just remove break and everything is ok.
Or just make the text only appear once everytime I press the button?

If the least significant bit is set, the key was pressed after the
  previous call to GetAsyncKeyState.

Try the code sample below:
import win32api

while True:
    keystate = win32api.GetAsyncKeyState(0x46)&0x0001
    if keystate > 0:
       print('F pressed!')


text:
Q: Add formatted text to SynEdit How can I add formatted text to a SynEdit control?  I don't actually need syntax highlighting, I want to be able to control the colors of specific parts of a line.
I am currently using a TRichEdit and setting SelAttributes.Color and SelAttributes.Text in order to achieve this effect.  It works fine, but I am hoping to get away from using TRichEdit.
Can I do something similar with SynEdit, or is it not the ideal component for the job?


text:
Q: The inverse of a parametrization I have two surfaces, with parametrizations:
$$\mathbb{x}(u,v)=(u\cos v,u\sin v,\log u) \\
\mathbb{\bar{x}}(u,v)=(u\cos v,u\sin v, v).$$
I need to proof that the map $\mathbb{\bar{x}}\circ \mathbb{x}^{-1}$ is not an isometry, but I don't know how to find $\mathbb{x}^{-1}$; Any hints?
Basically, I need to find a function $\mathbb{x}^{-1}:\mathbb{R}^{3}\rightarrow\mathbb{R}^{2}$ such that $\mathbb{x}^{-1}(u\cos v, u\sin v, \log u)=(u,v).$

A: Remember that a diffeomorphism $\varphi: S \to \overline{S}$ between surfaces is an isometry  when for all $p \in S$ and all pairs $w_1, w_2 \in T_pS$ we have:
$$
\left\langle w_{1}, w_{2}\right\rangle_{p}=\left\langle\mathrm{d} \varphi_{\mathrm{p}}\left(w_{1}\right), \mathrm{d} \varphi_{p}\left(w_{2}\right)\right\rangle_{\varphi(p)}
$$
By the polarization identity, there is no loss of generality in assuming $w_1 = w_2$. Also, it's easy to show that this happens iff $\varphi$ preserves the first fundamental form (which happens iff $\varphi$ preserves lengths of curves). I shall prove that this does not happen for the diffeomorphism $\varphi = \bar{x} \circ x^{-1}: x(U) \subset S \to \overline{x}(U) \subset \overline{S}$ described here (without explictly calculating $x^{-1}$!). Indeed, let $\alpha: (-\varepsilon, \varepsilon) \to S$ be a smooth curve in $S$ such that $\alpha(0) = p$ and $\alpha'(0) = w \in T_pS$, and let's write $\alpha(t) = x(u(t), v(t))$. We have:
$$\langle w, w \rangle_p = \mathrm{I}_p(w) = E(u')^2 + 2Fu'v' + G(v')^2$$
Now, let $\overline{\alpha} = \varphi \circ \alpha : (-\varepsilon, \varepsilon) \to \overline{S}$ be the image of $\alpha$ by $\varphi$. It's clear that $\overline{\alpha}(0) = \varphi(p)$ and that $\overline{\alpha}'(0) = \mathrm{d}\varphi_p(w)$ (chain rule in action here). Furthermore,  $$\overline{\alpha}(t) = \varphi(\alpha(t)) = \overline{x}(u(t), v(t))$$
Therefore
$$\begin{aligned}   \langle \mathrm{d} \varphi_p(w), \mathrm{d} \varphi_p(w) \rangle_{\varphi(p)} &= \overline{\mathrm{I}}_{\varphi(p)}(\mathrm{d} \varphi_p(w)) \\ &= \overline{E}(u')^2 + 2 \overline{F} u' v' + \overline{G}(v')^2          \end{aligned}$$
Now, an easy calculation shows that $$E = 1 + \frac{1}{u^2}, F = \overline{F} = 0, G = u^2, \overline{E} = 1, \overline{G} = 1 + u^2$$.
So we have
$$\begin{aligned} &\langle \mathrm{d} \varphi_p(w), \mathrm{d} \varphi_p(w) \rangle_{\varphi(p)} = (u')^2 + (v')^2 + u^2 (v')^2  \\ &\langle w, w \rangle_p = (u')^2 + \left( \frac{u'}{u} \right)^2 + u^2 (v')^2 \end{aligned}$$
Therefore, if $\varphi$ were an isometry, we would then have:
$$\begin{aligned} &\langle \mathrm{d} \varphi_p(w), \mathrm{d} \varphi_p(w) \rangle_{\varphi(p)} - (v')^2 = \langle w, w \rangle_p -\left( \frac{u'}{u} \right)^2 \\ &\left\langle w_{1}, w_{2}\right\rangle_{p}=\left\langle\mathrm{d} \varphi_{\mathrm{p}}\left(w_{1}\right), \mathrm{d} \varphi_{p}\left(w_{2}\right)\right\rangle_{\varphi(p)}\end{aligned} $$
which would imply $(v')^2 = \left( \frac{u'}{u} \right)^2 $ for any smooth curve of $S$ given by $\alpha(t) = x(u(t), v(t))$. This is false, because the equality above only happens when $v = \pm\ln(u) + C$, and $\alpha$ was chosen arbitrarily. This is a classical counter example proving that the converse of the theorema Egregium is false (this can happen when the gaussian curvature is not constant, which you can easily verify is the case here - when it happens that both gaussian curvatures are equal and constant, then by Minding's theorem both surfaces are locally isometric).

Note: if you really want to know the inverse, in this case it can be explicitly calculated (under a suitable domain for $u, v$, of course). It's given by $x^{-1}(x, y, z) = \left(\sqrt{x^2 + y^2}, \arctan\left(\frac{y}{x}\right) \right)$.


text:
Q: Comparison of two Character Arrays in C++ using Comparison Operator How does the comparison operator work when doing a comparison between two character arrays?
Consider the following program,
#include <iostream>
using namespace std;

int main()
{
    char arr1[5] = { 'T','e','s','t' };
    char arr2[10] = { 't','e' };
    if (arr1 < arr2)
        cout << "Yes";
    else if (arr1 > arr2)
        cout << "No";
    else
        cout << "0";
}

The way I know is it should print Yes because the first character of arr1 has an ASCII value of 84 while the ASCII value of first character of arr2 is 116so technically it should print Yes.
However, this program gives the output of No when run on Visual Studio.
I thought that it might be comparing the addresses of character arrays. To test this, I swapped the variable names and ran this program,
#include <iostream>
using namespace std;

int main()
{
    char arr2[5] = { 'T','e','s','t' };
    char arr1[10] = { 't','e' };
    if (arr1 < arr2)
        cout << "Yes";
    else if (arr1 > arr2)
        cout << "No";
    else
        cout << "0";
}

But this again gave Yes as output, meaning the addresses of character arrays did not matter in the comparison.
Can anyone tell how is this comparison being done?

A: In the condition of the if statement
if (arr1 < arr2)

the both arrays are implicitly converted to pointers to their first elements and these addresses are compared that results in undefined behavior for the operator <.
Pay attention to if you will compare string literals like
if ( "Hello" == "Hello" )
//...

then the value of the expression can be either true or false dependent on compiler options: whether identical string literals are stored as one string literal or as separate string literals.
As for the comparison of character arrays that do not contain strings then you can use the standard algorithm std::lexicographical_compare.
Otherwise if character arrays contain strings as in your example then you can use the standard C string function strcmp.
Here is a demonstration program
#include <iostream>
#include <algorithm>
#include <cstring>

int main()
{
    char arr1[5] = { 'T','e','s','t' };
    char arr2[10] = { 't','e' };

    if (std::lexicographical_compare( arr1, arr1 + 4, arr2, arr2 + 2 ))
    {
        std::cout << "The array arr1 is less than the array arr2\n";
    }

    if ( std::strcmp( arr1, arr2 ) < 0 )
    {
        std::cout << "The array arr1 is less than the array arr2\n";
    }
}

The program output is
The array arr1 is less than the array arr2
The array arr1 is less than the array arr2

A: It definitely compares addresses and not values of array items. You should not rely on address allocations in this manner.
Anyways, you can check:

*

*string.h for strcmp() // need to terminate your char arrays with '\0'

*string::compare()

*std::lexicographical_compare()

A: Consider using string_view, it has hardly any overhead. https://en.cppreference.com/w/cpp/string/basic_string_view
note : this example compares the strings at compile time for easy testing, but it works at runtime too (without the constexpr)
#include <cassert>
#include <string_view>

int main()
{
    constexpr std::string_view cvw1{ "test" };
    constexpr std::string_view cvw2{ "te" };
    static_assert(cvw1 > cvw2);

    return 0;
}


text:
Q: OSstatus -22 Error, Disk Utility in Catalina I have an OSstatus -22 error with Catalina while trying to restore any ISO/DMG to a USB flash drive using Disk Utility. I can use the terminal option just fine, but does anyone know of a reason why this error appears? I never had it under Mojave. Been looking for a solution to flash old PowerPC images in Apple Partition Format; used to work fine without any 3rd party tools. This is the closest solution I came to: Disk Utility fails with OSStatus error 22 during cloning/recovery operation
Thanks!


text:
Q: log-in after checking the specific response from the API-POST request I am having problems with POST request function I made, The problem is that I don't know how to use that specific response of StatusCode that comes after validating a user, I made the function that sets-up the POST request but now I need to make the statement to check if the StatusCode is for example 0 the user gets logged in if its 1 it shows error.
My POST request:
func signInToAccount(username: String, password: String, completion: @escaping ([String: Any]?, Error?) -> Void) {

    let parameters = ["User": username, "Password": password]

    let url = URL(string: "https://randomurl/Signin")!

    let session = URLSession.shared

    var request = URLRequest(url: url)
    request.httpMethod = "POST"

    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
    } catch let error {
        print(error.localizedDescription)
        completion(nil, error)
    }

    request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")

    let task = session.dataTask(with: request, completionHandler: { data, response, error in

        guard error == nil else {
            completion(nil, error)
            return
        }

        guard let data = data else {
            completion(nil, NSError(domain: "dataNilError", code: -100001, userInfo: nil))
            return
        }

        do {
            guard let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] else {
                completion(nil, NSError(domain: "invalidJSONTypeError", code: -100009, userInfo: nil))
                return
            }
            print(json)
            completion(json, nil)
        } catch let error {
            print(error.localizedDescription)
            completion(nil, error)
        }
    })

    task.resume()
}

My sign-in button sender of sign-in viewController:
@IBAction func signInSegueToDashboard(_ sender: Any) {

    APICallerPOST.shared.signInToAccount(username: "admin", password: "admin123") { (result, error) in
        if let result = result {
            print("success: \(result)")
        } else if let error = error {
            print("error: \(error.localizedDescription)")
        }

        self.activityLoaderSignIn.startAnimating()

    guard let mainTabBarController = self.storyboard?.instantiateViewController(withIdentifier: "mainTabBarController") else {
        return
    }

    Timer.scheduledTimer(withTimeInterval: 2, repeats: false) {_ in

        self.activityLoaderSignIn.stopAnimating()
        mainTabBarController.modalPresentationStyle = .custom
        self.present(mainTabBarController, animated: true, completion: nil)
    }
  }
}

Now the problem is here:
I don't know how to implement a proper way of logging-in, I need for example the if statement to check for the StatusCode if its 0 then the rest of code executed and to the dashboard if its error then show the error.
APICallerPOST.shared.signInToAccount(username: "admin", password: "admin123") { (result, error) in
        if let result = result {
            print("success: \(result)")
        } else if let error = error {
            print("error: \(error.localizedDescription)")
        }

The response that comes from the POST request:
{
"StatusCode": 0,
"Result": {
    "First": "admin",
    "Last": "admin123",
    "CompleteName": "admin admin123",
    "PhoneNumber": "+000 (00) 000-000",
    "Email": "admin.admin123@gmail.com",
    "IsConnectedToCustomer": true,
    "Token": "a3311cc231994f34bfjksadf82f7a4djska3",
    "TokenExpireDate": "2023-05-19T13:49:15.383"
    }
}

Thanks in advance for those who contribute to help on this specific topic, And to all the newcomers this post will help a lot if the correct answer is found.

A: Create a decodable struct which holds your server's response
struct SignInResponse: Decodable {
    struct SignInResult: Decodable {
        let First: String
        let Last: String
        let CompleteName: String
        let PhoneNumber: String
        let Email: String
        let IsConnectedToCustomer: Bool
        let Token: String
        let TokenExpireDate: String
    }

    let Result: SignInResult?
    let StatusCode: Int
}

IMPORTANT: This requires that your server either responds with an Result object as you have posted OR (when login failed) with "Result": null or with no Result object at all. But not an empty string or something like that.
Then modify the completion closure definition of your signInToAccount function to
func signInToAccount(username: String, password: String, completion: @escaping (SignInResponse?, Error?) -> Void) { ...

Inside this function, use a JSONDecoder to decode the response from your server.
let decoder = JSONDecoder()

guard let json = try? decoder.decode(SignInResponse.self, from: data) else {
   completion(nil, NSError(domain: "invalidJSONTypeError", code: -100009, userInfo: nil))
   return
}

print(json)
completion(json, nil)

Now you can access the StatusCode property in your function call's closure.
signInToAccount (username: "admin", password: "admin123") { (result, error) in
    if let result = result {

        print ("StatusCode is", result.StatusCode)

        if let signInData = result.Result {
            print ("Complete name:", signInData.CompleteName)
        }

        print("success: \(result)")
    } else if let error = error {
        print("error: \(error.localizedDescription)")
    }
}


text:
Q: java.util.zip.ZipException: error in opening zip file while deploying war to websphere I am trying to deploy my war file to websphere 8 and it's giving me below error.
02:02:57,209 INFO  [com.liferay.portal.kernel.deploy.auto.AutoDeployScanner][Aut             oDeployDir:182] Processing MIR.war. This is attempt 169.
02:02:57,215 ERROR [com.liferay.portal.kernel.deploy.auto.AutoDeployScanner][Aut             oDeployDir:210] com.liferay.portal.kernel.deploy.auto.AutoDeployException: java.             util.zip.ZipException: error in opening zip file
com.liferay.portal.kernel.deploy.auto.AutoDeployException: java.util.zip.ZipExce             ption: error in opening zip file
        at com.liferay.portal.kernel.deploy.auto.BaseAutoDeployListener.isMatchi             ngFile(BaseAutoDeployListener.java:87)
        at com.liferay.portal.kernel.deploy.auto.BaseAutoDeployListener.isHookPl             ugin(BaseAutoDeployListener.java:43)
        at com.liferay.portal.deploy.auto.HookAutoDeployListener.deploy(HookAuto             DeployListener.java:43)
        at com.liferay.portal.kernel.deploy.auto.AutoDeployDir.processFile(AutoD             eployDir.java:193)
        at com.liferay.portal.kernel.deploy.auto.AutoDeployDir.scanDirectory(Aut             oDeployDir.java:235)
        at com.liferay.portal.kernel.deploy.auto.AutoDeployScanner.run(AutoDeplo             yScanner.java:54)
Caused by: java.util.zip.ZipException: error in opening zip file
        at java.util.zip.ZipFile.open(Native Method)
        at java.util.zip.ZipFile.<init>(ZipFile.java:150)
        at java.util.zip.ZipFile.<init>(ZipFile.java:166)
        at com.liferay.portal.kernel.deploy.auto.BaseAutoDeployListener.isMatchi             ngFile(BaseAutoDeployListener.java:72)
        ... 5 more

The war is generated by Jenkins maven build.  What's going wrong here ?


text:
Q: Font style to dropdownlist asp.net I am trying to display all the fonts available in the system with its own style. But it is not working. I am following for color it is working fine.
Problem: This code is working fine in firefox but not in IE. Is there any option to make it work.
Code:
foreach (FontFamily font in fonts.Families)
        {
            ddlFontName.Items.Add(font.Name); // Working
        }

        for (int row = 0; row < ddlFontName.Items.Count; row++)
        {
            ddlFontName.Items[row].Attributes.Add("style", "font-family:" + ddlFontName.Items[row].Value); // Not Working
        }

A: The default drop down list did not have this capability on every line. Not even the default windows drop down list can do that as it is with out custom render.
To make what you try, you need to make a custom menu, that is looks like drop down list.
In this menou that you make it out of div/ui/li set, you place inside the render style you like, make your selection then save your selection to an input.
Its a big javascript journey...
Take this as example: http://www.marghoobsuleman.com/jquery-image-dropdown


text:
Q: Pay Employee via WordPress I'm looking for a system where the employer can pay their employee via WordPress (frontend). Basically my portal job site is only providing a part-time job. After the job finished, the employee can request a payment and then the employer will send the money via our site.
Is there any plugin have such capability?
I'm currently using WP Job Manager as the main system of my site.
Thank you.

A: Have you checked extension "WC Paid Listings" on official website?
Link: https://wpjobmanager.com/add-ons/wc-paid-listings/


text:
Q: Area of an arbitrarily oriented plane How do I find the area of a plane, whose normal vector is given by
$$
a\overrightarrow{i}+b\overrightarrow{j}+c\overrightarrow{k}
$$
a,b and c are Real numbers.
I would have four 3-D coordinates which form this plane, and using these coordinates I will have to find out the area of the plane formed by the planes. I am writing code for this and will be required to perform this operation multiple times, so I am not inclined towards using the cross product
The initial idea that I had was to perform a series of rotations to transform the plane parallel to one of the XY, YZ or ZX planes. But I am not able to figure out the axes about which these have to be performed.

A: Assuming you have 4 completely different 3D points, graphically the plane looks something like this:
As seen in the image above the, the area is equal to $b \times h$, where $b$ = length between $C_2 \text{ and } C_3$, and $d$ = length between $C_3 \text{ and } C_4$.
For more complex shapes (shape of the plane), split them out into the basic shapes first, then continue with the method above. (Note: For triangles, Area = $\frac{1}{2} \times \text{ base } \times \text{ height }$): .
Hope this helps!


text:
Q: Bad argument `LOG' when configuring iptables I am trying to write a iptables sh script that later i can have updated from one spot for all my servers.  So far I have this that works.
i get this error
Bad argument `LOG'
Try `iptables -h' or 'iptables --help' for more information.

first i wipe to some defaults
iptables-restore /etc/iptables.conf
then load a file of ip ranges or just single ips
_input=/root/firewall/badips.db
_pub_if="eth0"
IPT=/sbin/iptables

$IPT -A INPUT -i lo -j ACCEPT
$IPT -A OUTPUT -o lo -j ACCEPT

egrep -v "^#|^$" x | while IFS= read -r ip
do
        $IPT -A INPUT -i ${_pub_if} -s $ip -j LOG --log-prefix " Drop BadIP "
done <"${_input}"

$IPT -I INPUTlist
$IPT -I OUTPUTlist
$IPT -I FORWARDlist

$IPT -A INPUT -i ${_pub_if} -p icmp --icmp-type 8 -m state --state NEW,ESTABLISHED,RELATED -m limit --limit 30/sec  -j ACCEPT
$IPT -A INPUT -i ${_pub_if}  -p icmp -m icmp --icmp-type 3 -m limit --limit 30/sec -j ACCEPT
$IPT -A INPUT -i ${_pub_if}  -p icmp -m icmp --icmp-type 5 -m limit --limit 30/sec -j ACCEPT
$IPT -A INPUT -i ${_pub_if}  -p icmp -m icmp --icmp-type 11 -m limit --limit 30/sec -j ACCEPT

A: If in doubt about bash behaviour: quote your untrusted inputs.
If you have a line with just a space in your badips.db file, then that line equates to:
/sbin/iptables -A INPUT -i eth0 -s -j LOG --log-prefix " Drop BadIP "

The error message doesnt pinpoint the problem because of the way iptables parses arguments initially ignoring the fact that -j is not a valid argument to -s and getting stuck on the next argument.
The current impact of malicious entries in your badips.db is "code execution with root privileges", so definitely ensure your script is handling invalid source ips/nets properly.


text:
Q: Does there exist a grammar formula in grammar book? Lots of people refer to "subject + verb + adjective" as a formula.
Does there exist this kind of grammar formulas in grammar book? In other words, is this kind of formulas a well recognized term?

A: "Grammar" by definition incorporates the structure of a language. The rules of grammar dictate how sentences are constructed. There is no single "grammar formula", although the "rules" for constructing the most basic of sentences could, I suppose, be called a "formula", and perhaps are when teaching English as a foreign language, but during my own education as a native British English speaker, I never heard the term "grammar formula".
A formula is a list of ingredients with which something is made. In a mathematical context, if an "ingredient" or element of the formula was omitted, it would be an incomplete formula.
The example "formula" you gave of "Subject + Verb + Adjective" is very basic and does not give all the "ingredients" of a complete sentence. It does not mention articles, for example, and even in the most basic sentence, the subject would require one.
At best, I would suggest "subject-verb-adjective" is a guide to the order in which these appear within a sentence.

A: I suspect you're thinking of the five basic (canonical) clause types:
S-P: Ordinary intransitive [We hesitated.]
S-P-C: Complex-intransitive [We felt happy.]
S-P-Od: Ordinary monotransitive [We sold our house.]
S-P-Od-PC: Complex-transitive [We made them happy.]
S-P-Oi-Od: Ditransitive [We gave them some food.]

A: it is neither a well recognized nor always true

subject + verb + object (for transitive verb) (I write a letter)
  subject + verb  (for intransitive verb) (He died)
  subject + verb + Complement (which a noun or an adjective) (for linking verb) (It seems delicious / I will become a politician)

All in all, the above structure sometimes is not true, due to applying inversion:

So beautiful was the girl that nobody could talk of anything else

It is noteworthy noting that a "subject", "object" , even "Complement " sometimes can be a clause  (noun, adjective, adverbial)


text:
Q: Dynamic linking: offset value used to index relocation table I'm trying to understand dynamic linking process...the call to a library function (let's call it func) passes through the plt table. I know when the symbol is not yet relocated the call of the function passes from plt table which contains an istruction (say i1) like jmp *function_in_GOT which points to the next instruction after i1 that appears like push $offset: after the control is passed to the dynamic linker that fixes up the relative GOT entry with the address of the function. offset should be the index of the entry in the relocation table but i don't understand...how this value can be find by reading the elf of the executable. Is possible with
objdump --dynamic-reloc prog

to find something? For example i wrote a very simple program that uses only printf and strcpy and output of the previous command is:
DYNAMIC RELOCATION RECORDS
OFFSET   TYPE              VALUE
08049ff0 R_386_GLOB_DAT    __gmon_start__
0804a000 R_386_JUMP_SLOT   __gmon_start__
0804a004 R_386_JUMP_SLOT   __libc_start_main
0804a008 R_386_JUMP_SLOT   strcpy
0804a00c R_386_JUMP_SLOT   printf

For example by reading with gdb the instructions starting at printf@plt:
0x8048324 <printf@plt>: jmp    *0x804a00c
0x804832a <printf@plt+6>:   push   $0x18
0x804832f <printf@plt+11>:  jmp    0x80482e4

we can see that the value for the offset is 0x18 (24 in decimal) but reading the output of objdump seems that offset of printf from the first reloc entry is 0x1c.
Some ideas?

A: This is not how PLT works, really. To understand how it does work, I recommend starting by reading this article.

A: Yes, offset is a index on the file relocation table.
From ELF specification version 1.2:
5 . Consequently, the program pushes a relocation offset (offset) on the stack. The relocation offset is a
    32-bit, non-negative byte offset into the relocation table. The designated relocation entry will have
    type R_386_JMP_SLOT, and its offset will specify the global offset table entry used in the previous
    jmp instruction. The relocation entry also contains a symbol table index, thus telling the dynamic
    linker what symbol is being referenced, name1 in this case.
But I don't know why the discrepancies in your results.


text:
Q: Can I make the following assumptions about the longest simple circuits? The longest simple circuit in $W_n$ is $\frac{3}{2}n$ when $n$ is even and $\frac{3}{2}(n-1) + 1$ when $n$ is odd.
I drew it out for a couple of graphs and it seemed to work. Can someone confirm this?

For example for $W_{10}$ the answer is $\frac{3}{2}(10) = 15$. I know the answer should be 15 based on an example question and answer that I used to practice for a test.

A: For a wheel graph $W_{2n}$ with hub $w$ and outer vertices $v_1,\ldots, v_{2n}$ we can form the circuit
$$wv_1v_2wv_3v_4w\ldots wv_{2n-1}v_{2n}$$
of length $3n$. A longer circuit is not possible because eacxh $v_i$ cannot appear more than once and between tow occurances of $w$ there must be two $v_i$.
Similarly, for a wheel graph $W_{2n+1}$ with hub $w$ and outer vertices $v_1,\ldots, v_{2n+1}$ we can form the circuit
$$wv_1v_2wv_3v_4w\ldots wv_{2n-1}v_{2n}v_{2n+1}$$
of length $3n+1$. Again alonger circuit is not possible because eacxh $v_i$ cannot appear more than once and between tow occurances of $w$ there must be two $v_i$.


text:
Q: View PDF in Browser, Edit in Acrobat I'd like to have SharePoint handle PDFs in such a way that PDFs will open in a browser, but will Edit in Acrobat. It seems that I can have one or the other:
If the DOCICON.xml is configured to show:
<Mapping Key="pdf" Value="pdficon_small.gif" OpenControl="AdobeAcrobat.OpenDocuments" />

No "Edit Document" or "Edit in Acrobat" menu appears, but I am able to view the PDF in a browser. However, if my mapping looks like this:
<Mapping Key="pdf" Value="pdficon_small.gif" OpenControl="SharePoint.OpenDocuments" />

I can edit in Acrobat beautifully, and it works with the drop-down menu per document, but it won't display the PDF in the browser, even after changing the settings in Acrobat/Reader to Edit -> Preferences -> Internet -> Display PDF in Browser but will show the popup of "Read Only" or "Edit" radio buttons.
I've also tried to fool with the client-side application, on the list and the site collection to open documents in browser by default. No change.

A: You can try to see if a permssion issue. Change the permission of the headers from the browser.
Please, go to the Central Administration, then Manage Web Application. Select the WebApp where you have the pdf files. Then Click on the Ribbon on General Settings, General Settings again.
In the PopUp, in the section Browser File Handling, click on Permissive. Click Ok and try again.
Cheers!

A: I did this by changing the entry in docicon.xml to
<Mapping Key="pdf" Value="pdficon_small.gif" OpenControl="SharePoint.OpenDocuments" />

And resetting IIS. How did I forget resetting IIS? Everything works now.
Also the other mapping setting doesn't work on those web applications using https so I had to use the SharePoint.OpenDocuments opencontrol.


text:
Q: ggplot: change the order of stacked bars based on the % component of a level within the bar I have created a stacked bar plot in ggplot as such:
antr1$Traits4<-factor(antr1$Traits4,
                      levels=c("Flight", "Avoidance", "Investigative",
                               "Defensive aggression","Active aggression"))

ggplot(antr1, aes(Receiver3, fill=Traits4)) +
  geom_bar(position="fill") +
  coord_flip() +
  scale_y_continuous("", formatter="percent") +
  scale_fill_manual(values=c("Flight"="yellow",
                             "Avoidance"="green",
                             "Investigative"="blue",
                             "Defensive aggression"="orange",
                             "Active aggression"="red"))

It works nicely. However, at the moment the bars are ordered alphabetically based on the names of the "Receiver3". I would like to reorder the stacked bars based on the percentage of the level of "Active aggression".
thanking you in advance
Matt

A: If you know the order of the levels of Receiver3 that you'd like, you can specify is via something like:
antr1$Receiver3 <- factor(antr1$Receiver3,
                    levels=c(...list the levels in the order you'd like...),
                    ordered=TRUE)

If Receiver3 has many levels so determining the correct order by hand is prohibitive, you might try something like this:
temp <- aggregate(antr1$Traits4,by=list(receiver=antr1$Receiver3),
          FUN=function(xx){
                return(sum(xx=='Active aggression')/length(xx))
          }
antr1$Receiver3 <- factor(antr1$Receiver3,levels=temp$receiver[order(temp$x)],
                     ordered=TRUE)

If you want to opposite order, change order(temp$x) to order(temp$x,decreasing=TRUE).


text:
Q: Turtling around in Python? I've found myself playing around with the turtle module in Python, and just tweaking some stuff to code written by someone else (Dmitri Kurilo). I did a pretty neat figure with it, forming beautiful curves. And because i know little about math, maybe some of you can help me decypher what's happening here! Thanks a lot, here's the code!:
import turtle, random
from math import *
def fib(n):
    for n in range(400):
        turtle.color("black")
        turtle.right(pi*19)
        turtle.forward(n)
        if n > 400:
            break

turtle.title("The Looping ball")
turtle.colormode(255)
turtle.color("white")
turtle.goto(0,0)
turtle.color("black")
turtle.speed(500)
fib(1)
turtle.getscreen()._root.mainloop()

A: import turtle, random
from math import *

The import of random is superfluous. In the end, only turtle and math.pi are used.
def fib(n):
    for n in range(400):
        turtle.color("black")
        turtle.right(pi*19)
        turtle.forward(n)
        if n > 400:
            break

Draw a figure constructed of 400 line segments, where every two segments have a 59.69 degree angle between them (the turtle module uses degrees by default), and every line segment is one unit longer than the previous one. This should almost result in a 6-angle spirangle, but because the angle between the segments is not one sixth of a full turn (60 degrees), it is slightly off.
Note that the parameter n is unused, because it is overwritten by the n in the loop. The condition n > 400 is never reached (because range(400) ranges from 0 inclusive to 400 exclusive), so the last part of the loop does nothing worth mentioning.
Now for the main part:
turtle.title("The Looping ball")
turtle.colormode(255)
turtle.color("white")
turtle.goto(0,0)
turtle.color("black")
turtle.speed(500)

Some settings for the resulting window are chosen: the title is set, the colormode is set (how you specify colour values; not used here), draw a white line to the center of the screen and leave the turtle there (it's better to use turtle.penup() and turtle.pendown() for this), and set the drawing speed as fast as possible (turtle.speed(0) would have done the same thing, and anything larger than ten is the same as turtle.speed(0)).
fib(1)

The spiral is drawn.
turtle.getscreen()._root.mainloop()

The control of the program is yielded to the main event loop of the turtle screen. If you don't do this, the window will close immediately after it has completed drawing. If you "run" the main loop, it will keep the program alive as long as the window is open.

A: A clearer version of the original program:
import turtle

def fib(num, rot=59.7, scale=1.0):
    for n in range(num):
        turtle.right(rot)
        turtle.forward(n*scale)

turtle.title('The Looping ball')
turtle.speed(2000)
turtle.pencolor('blue')
fib(400, rot=92, scale=0.75)
turtle.getscreen()._root.mainloop()

This has some of the unnecessary stuff removed and some values parameterised so the OP can play with the number of lines, rotation before each line and the length of lines.  This helps with getting a feel of how each parameter changes things.


text:
Q: Why do I get high voltage (125V) between secondary of a transformer and oscilloscope ground clip? I have a 230V to 24V step down transformer. I have not connected the secondary to ground connection of the mains power.
When I measure the voltage between one of the secondary terminals and the oscilloscope I get about 125V. Is it safe to connect the oscilloscope to the secondary to see the AC output signal of the transformer?
I examined the circuit diagram for my setup and I can see that this will not complete the circuit through the oscilloscope ground to conduct a high current, but I just need to make sure if I am making any mistake in my understanding.

A: Try this and think about the interwinding capacitance and how it couples primary and secondary: -

Another good example of this happening is on house wiring that uses cable called "twin and earth" in the UK. The twin part is two wires connected to live and neutral. If the earth is left floating you can measure 120 volts between earth wire and neutral with a high impedance meter such as a DVM.

A: Recall that multimeters in voltage mode are high impedance devices, and their behavior is thus highly sensitive to stray capacitances.
The mental model of a transformer should include the parasitic primary-to-secondary capacitance. This tiny capacitance (tens-hundreds of pF for small transformers) is plenty enough to act as a good conductor against the 10Mohm input resistance of the multimeter.
In other words: you'll always measure such voltages. The current the voltage sources produce can be determined by using a lower parallel resistance across voltmeter inputs. Say 1Mohm or 200kohm.
In transformer circuits, there is always some primary-to-secondary common mode leakage current. This current will be shunted to ground via the ground lead of the oscilloscope probe.


text:
Q: how to work with Eclipse Source Code in Eclipse itself I have download entire Eclipse Helios/Indigo version Source Code. Now I want to work on it like some modifications and all. So I imported the entire sourceCode but now I am getting n number of errors while compiling. Moreover I am trying to RunAs> Plug-in is confusing me about the output I am getting is the changed one or what.
My Problems are-
How to import entire Eclipse SOurceCode in eclipse?
How to build the Eclipse SourceCode properly?
After modification in the SC of Eclipse , how to check the changes feasility?

A: I would define a target definition for your Eclipse distribution. Include all the features (including source) in the definition. Then you can use you importer to import plugins from your target definition into your workspace with sources and work from that. Having target definition is easier because you can change your setup on-demand.
Edit: Forgot to mention that in import wizard (File -> Import -> Plug-in Development -> Plug-ins and Fragments) make sure you select "Project with source folders" under "Import as". Otherwise class files will be imported as jars and not deflated into your project. Just makes it easier to work with them this way.


text:
Q: IOS Opening PDF from my app in another app EXC_BAD_ACCESS I'm having difficulty debugging this error. I get an EXC_BAD_ACCESS error after I click on Adobe or Nook as the selected app to open the download PDF. I've gone through with the debugger and it breaks somewhere outside of the methods I wrote. Here is the code in question.
        //download protocol
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *storedEmail = [defaults stringForKey:@"email"];
    NSString *storedPassword = [defaults stringForKey:@"password"];
    NSString *projectID = self.study.ProjectID;
    NSString *urlString = [NSString stringWithFormat:@"http://service.pharmatech.com/Document/projectprotocol/%@/%@/%@", storedEmail, storedPassword, projectID];
    NSURL *url = [NSURL URLWithString:urlString];
    NSData *data = [NSData dataWithContentsOfURL:url];
    if (data) {
        NSArray       *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString  *documentsDirectory = [paths objectAtIndex:0];

        NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory, [NSString stringWithFormat:@"Protocol_%@.pdf", projectID]];
        [data writeToFile:filePath atomically:YES];

        UIDocumentInteractionController *docController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
        docController.delegate = self;
        docController.UTI = @"com.adobe.pdf";
        self.navigationController.toolbarHidden = NO;
        BOOL isValid = [docController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
        NSLog([NSString stringWithFormat:@"DISPLAYED? %d", isValid]);

        NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:NULL];
        for (int count = 0; count < (int)[directoryContent count]; count++) {
            NSLog(@"File %d: %@", (count + 1), [directoryContent objectAtIndex:count]);
        }

        [self.navigationController setToolbarHidden:YES animated:YES];

The popup shows with the apps capable of showing pdfs. After I click one the Bad Access error occurs, but not until after leaving the method this is called in, which is just a button click action.
If I run the app w/o the debugger is simply closes the my app and opens nothing. Anyone have any tips. I'm still very new to this ios stuff.
EDIT: For those who visit this later and don't read the comments, the answer is that the UIDocumentInteractionController must be an instance variable, not local.

A: It seems to be a problem with "docController", is a local variable and, i think, must be a instance variable.
Change
UIDocumentInteractionController *docController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];

for
docController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];

and in your .h declare
UIDocumentInteractionController *docController;


text:
Q: Wrong Autoprefixer compilation on linear-gradient Im using Codekit 2 (2.0.4) with Autoprefixer-
background: linear-gradient(to top, black, white);

turned into this:
background: linear, to top, black, white;

A: This problem was on old Autoprefixer version and was fixed in newest one. But it is difficult to update Autoprefixer separated of CodeKit (it is one of benefits of using Grunt).


text:
Q: How to use erlang fun recursive function? I am trying to decode frames with variable length and options (such as the TLV in ethernet frames)
In order to do that, I was thinking about doing a fun recursive function :
fun (Fields, Bin) ->
    Parse =
        fun (P, F, <<Length, Rest/binary>>) ->
                P(P, F#{first => Length}, Rest)
        end,
    Parse(Parse, Fields, Bin)
end.

So Bin is the input frame for example : 40 02 12 45 01 50
So first byte is the type of frame, 02 is the length of following data 12 45, 01 is the length is the following data 50 and so on.
But my function doesn't work as expected using the funny trick
I am returning JSON object because it's send over MQTT.

A: What you're doing there really is only reading out the length, and don't do much with the Rest. You'd need to first declare an exit condition, i.e. when the TLV is empty -> just return the accummulator; And use the pattern match to read out the values based on the Length:
parse(<<>>, Acc) -> Acc;  %% finished with the list
parse(<<Length, Rest/binary>>, Acc) ->
   <<Value:Length/binary, Carry/binary>> = Rest.
   %% Value for the tag, Carry to be passed back on the recursion.
   %% Assuming that `Acc` is a list of Values.
   parse(Carry, Acc ++ [Value]).

You can use the above to read out the values, and can do something similar for getting the type first as:
tlv(<<Type, Values/binary>>) ->
   %% Return at tuple with the Type and the values.
   {Type, parse(Values, [])}.

A: You could write the function like this:
fun(<<Type, Packet/binary>>) ->
        {Type,
         fun Parse(<<>>) ->
                 [];
             Parse(<<Length, Data:Length/bytes, Rest/binary>>) ->
                 [Data] ++ Parse(Rest)
         end(Packet)}
end.

This returns {40,[<<12,45>>,<<50>>]} for your sample data.
The outer fun takes the frame type (40 in this case), and returns it along with the list of the data fields.  The inner fun takes one length byte and the corresponding number of data bytes, and returns the data and makes a recursive call to itself - until it reaches the end of the binary.
The inner fun is a "named fun": it calls itself Parse, and is therefore able to call itself without needing to pass itself as an argument.  The name Parse is not visible outside the fun.  See this question for details and examples.


text:
Q: Algorithm to Derive All Possible Math Expressions In a Set To get a Target Value I am new to Swift Programming, and while I could figure the rest of this out for this app I have floating in my head, I'm having a hard time figuring out how to derive a algorithm that could handle this problem:
Given a set of 4 values (probably best to use Double because some can even be fractions), derive all possible combinations that return a result of a target value--in my case, 24.
For example, a+b+c+d, a+b+d+c, a+d+b+c, d+a+b+c, and all arrangements of that set, plus all possible mathematical operators such as (a*b)^(c-d) or (a+b+c)/d.
I was able to find this article, but it doesn't quite match what I'm looking for, especially as order doesn't matter for me
Number of ways to sum the items in a set to get a target value - Order matters
so for example, I could manually do each combination this way:
if a + b + c + d == 24 {
  print("\a + \b + \c + \d")
}

My goal is for the user to enter 4 values and let IOS generate a list of all possible mathematical expressions that result in 24.
Patrick

A: Here is one approach.  Start with an array of expressions and an array of values.  Initially, the expressions is just the String value of the values:
let expressions = ["1", "2", "3", "4"]
let values = [1, 2, 3, 4]

Pick two expressions (for example "1" and "2", and a binary operator ("+"), and combine them creating an expressions and values with 3 values:
expressions = ["3", "4", "(1 + 2)"]
values = [3, 4, 3]

Repeat this process combining again two of the expressions with an operation:
expressions = ["3", "(4 + (1 + 2))"]
values = [3, 7]

Finally, combine the last two expressions with "+":
expressions = ["(3 + (4 + (1 + 2)))"]
values = [10]

Once you reach a single expression, check to see if the value matches your target.

The following is a recursive function that tries all combinations of values and operations to create the expressions in search of a target:
import Foundation

// An array of tuples containing an operator name and a closure
// that performs the operation
let ops: [(name: String, function: (Double, Double) -> Double)] = [
    ("+", { $0 + $1 }),
    ("-", { $0 - $1 }),
    ("*", { $0 * $1 }),
    ("/", { $0 / $1 }),
    ("^", { pow($0, $1) })
]

func compute(expressions: [String], values: [Double], target: Double) {

    // base case of the recursion: if there is only one
    // expression and one value, check if the value is the
    // target value we're looking for and print the expression
    // and value if the target is matched
    if expressions.count == 1 {
        if values[0] == target {
            print("\(expressions[0]) = \(values[0])")
        }
    } else if expressions.count >= 2 {

        // loop through all of the expressions choosing each
        // as the first expression
        for idx1 in expressions.indices {

            // copy the expressions and values arrays so that
            // we can remove the expression and value
            // without modifying the original arrays
            // which will be needed for the next try
            var expcopy = expressions
            var valcopy = values
            let exp1 = expcopy.remove(at: idx1)
            let val1 = valcopy.remove(at: idx1)

            // loop through the remaining expressions to find
            // the second one
            for idx2 in expcopy.indices {
                // again, copy the arrays to keep from modifying
                // the originals while searching
                var expcopy2 = expcopy
                var valcopy2 = valcopy

                let exp2 = expcopy2.remove(at: idx2)
                let val2 = valcopy2.remove(at: idx2)

                // now try all possible operations to combine
                // the two expressions
                for op in ops {
                    // use the closure to compute the value
                    let value = op.function(val1, val2)

                    // combine the expressions into a new string
                    // expression with the operator in the
                    // middle and surrounded by () if this is
                    // not the top level expression
                    var exp = "\(exp1) \(op.name) \(exp2)"
                    if !expcopy2.isEmpty {
                        exp = "(\(exp))"
                    }

                    // now that we've reduced the number of
                    // expressions by 1, recurse by calling
                    // compute again on the reduced list of
                    // expressions
                    compute(expressions: expcopy2 + [exp], values: valcopy2 + [value], target: target)
                }
            }
        }
    }
}

// This helper function creates the array of expressions from
// the array of values, and then calls the main function above
// to do the real work
func search(values: [Double], target: Double) {
    compute(expressions: values.map { String($0) }, values: values, target: target)
}

Example 1:
search(values: [1, 2, 3, 4], target: 121)

Output:

(1.0 - (3.0 * 4.0)) ^ 2.0 = 121.0
((3.0 * 4.0) - 1.0) ^ 2.0 = 121.0
(1.0 - (4.0 * 3.0)) ^ 2.0 = 121.0
((4.0 * 3.0) - 1.0) ^ 2.0 = 121.0

Example 2:
search(values: [1, 2, 3], target: 1)

Output:

3.0 / (1.0 + 2.0) = 1.0
(1.0 + 2.0) / 3.0 = 1.0
3.0 - (1.0 * 2.0) = 1.0
(1.0 ^ 2.0) ^ 3.0 = 1.0
(1.0 * 3.0) - 2.0 = 1.0
2.0 - (1.0 ^ 3.0) = 1.0
(1.0 ^ 3.0) ^ 2.0 = 1.0
3.0 / (2.0 + 1.0) = 1.0
(2.0 + 1.0) / 3.0 = 1.0
(2.0 - 1.0) ^ 3.0 = 1.0
3.0 - (2.0 * 1.0) = 1.0
3.0 - (2.0 / 1.0) = 1.0
3.0 - (2.0 ^ 1.0) = 1.0
1.0 ^ (2.0 + 3.0) = 1.0
1.0 ^ (2.0 - 3.0) = 1.0
1.0 ^ (2.0 * 3.0) = 1.0
1.0 ^ (2.0 / 3.0) = 1.0
1.0 ^ (2.0 ^ 3.0) = 1.0
2.0 / (3.0 - 1.0) = 1.0
(3.0 - 1.0) / 2.0 = 1.0
(3.0 * 1.0) - 2.0 = 1.0
(3.0 / 1.0) - 2.0 = 1.0
(3.0 ^ 1.0) - 2.0 = 1.0
1.0 ^ (3.0 + 2.0) = 1.0
1.0 * (3.0 - 2.0) = 1.0
1.0 / (3.0 - 2.0) = 1.0
1.0 ^ (3.0 - 2.0) = 1.0
(3.0 - 2.0) * 1.0 = 1.0
(3.0 - 2.0) / 1.0 = 1.0
(3.0 - 2.0) ^ 1.0 = 1.0
1.0 ^ (3.0 * 2.0) = 1.0
1.0 ^ (3.0 / 2.0) = 1.0
1.0 ^ (3.0 ^ 2.0) = 1.0

Eliminating Duplicate Solutions
With 4 or more values, or even with fewer values that aren't unique, you can end up with duplicate expressions.  The way to eliminate the duplicates is to use a Set<String> to keep track of the expressions you've already found and check if that set contains your new expression before printing it as a new solution.
import Foundation

// An array of tuples containing an operator name and a closure
// that performs the operation
let ops: [(name: String, function: (Double, Double) -> Double)] = [
    ("+", { $0 + $1 }),
    ("-", { $0 - $1 }),
    ("*", { $0 * $1 }),
    ("/", { $0 / $1 }),
    ("^", { pow($0, $1) })
]

func compute(expressions: [String], values: [Double], target: Double, solutions: inout Set<String>) {

    // base case of the recursion: if there is only one
    // expression and one value, check if the value is the
    // target value we're looking for and print the expression
    // and value if the target is matched and we don't already
    // have that expression in our set of solutions
    if expressions.count == 1 {
        if values[0] == target && !solutions.contains(expressions[0]) {
            print("\(expressions[0]) = \(values[0])")
            solutions.insert(expressions[0])
        }
    } else if expressions.count >= 2 {

        // loop through all of the expressions choosing each
        // as the first expression
        for idx1 in expressions.indices {

            // copy the expressions and values arrays so that
            // we can remove the expression and value
            // without modifying the original arrays
            // which will be needed for the next try
            var expcopy = expressions
            var valcopy = values

            let exp1 = expcopy.remove(at: idx1)
            let val1 = valcopy.remove(at: idx1)

            // loop through the remaining expressions to find
            // the second one
            for idx2 in expcopy.indices {
                // again, copy the arrays to keep from modifying
                // the originals while searching
                var expcopy2 = expcopy
                var valcopy2 = valcopy

                let exp2 = expcopy2.remove(at: idx2)
                let val2 = valcopy2.remove(at: idx2)

                // now try all possible operations to combine
                // the two expressions
                for op in ops {
                    // use the op's function to compute the value
                    let val = op.function(val1, val2)

                    // combine the expressions into a new string
                    // expression with the operator in the
                    // middle and surrounded by () if this is
                    // not the top level expression
                    var exp = "\(exp1) \(op.name) \(exp2)"
                    if !expcopy2.isEmpty {
                        exp = "(\(exp))"
                    }

                    // now that we've reduced the number of
                    // expressions by 1, recurse by calling
                    // compute again on the reduced list of
                    // expressions
                    let newexp = expcopy2 + [exp]
                    let newval = valcopy2 + [val]
                    compute(expressions: newexp, values: newval, target: target, solutions: &solutions)
                }
            }
        }
    }
}

// This helper function creates the array of expressions from
// the array of values, creates a Set to hold the solutions, and
// then calls the main function above to do the real work
func search(values: [Double], target: Double) {
    // create a set to keep track of solutions found so far
    var solutions = Set<String>()

    compute(expressions: values.map { String($0) }, values: values, target: target, solutions: &solutions)

    print("\n\(solutions.count) unique solutions were found")
}

Example:
search(values: [2, 2, 1], target: 5)

Output:

1.0 + (2.0 + 2.0) = 5.0
(2.0 + 2.0) + 1.0 = 5.0
1.0 + (2.0 * 2.0) = 5.0
(2.0 * 2.0) + 1.0 = 5.0
1.0 + (2.0 ^ 2.0) = 5.0
(2.0 ^ 2.0) + 1.0 = 5.0
2.0 + (2.0 + 1.0) = 5.0
(2.0 + 1.0) + 2.0 = 5.0
2.0 + (1.0 + 2.0) = 5.0
(1.0 + 2.0) + 2.0 = 5.0

10 unique solutions were found

A: A simple approach not covered in the solutions referenced in the first few comments is to generate your candidate expressions in reverse polish notation (RPN). If you've studied CS, or owned a HP calculator, you might recall this. RPN has the advantage that it contains no parentheses and is evaluated in strict left-to-right order. Follow the link for a full description, here are a couple of examples:

Algebraic: (a+b)*c
RPN: ab+c*

Algebraic: a+(b*c)
RPN: abc*+

In outline to evaluate an RPN expression left-to-right you push any variable you find onto a stack. For any operator you pop 2 values of the stack, combine the with the operation, and push the result back onto the stack.
To generate a single expression for your problem an outline algorithm is:
while there are variables unused or fewer than (number of variables - 1) operators
   either:
      add any unused variable
   or:
      if the number of added variables is at least two greater than the
      number of added operators add any operator

That will give you a single expression, to generate all of them think recursion. At each stage you iterate through all the choices as above and for each one recurse passing in the partial expression, unused variables, etc. You can store the partial expression in an array, each element being a variable or an operator (think enum). As Swift passes arrays by value as you recurse each call can continue to add elements to the array without effecting other calls.
In pseudocode:
generate(expression: array, variables: variable collection) -> collection
   results <- empty collection
   for nextVar in variables
      add generate(expression + nextVar, variables - nextVar) to results
   if #variables in expression - #operators in expression >= 2
      for every possible operator
         add generate(expression + operator, variables) to results
   return results

When a complete expression is generated your can evaluate it and add it to solutions if the result is 24. As a possible optimisation you can evaluate as you go down the recursion to save recalculation of the partial expressions. RPN evaluation can use a stack, which you can build from an array in Swift and pass down in each recursive call. Exploring other optimisation is left to you.
If you get stuck after designing your algorithm and writing some code you can ask a new question - include a link to this one, your algorithm, your code, and your problem; someone will undoubtedly help you along.
HTH


text:
Q: time rangeseekbar in android I am using org.florescu.android.rangeseekbar.RangeSeekBar for time selection as I need to filter the result between selected time. I was fortunate enough to get this thing working for price but now I am stuck on time selection as it accepts only int, double and float values. but time is in string format
I tried https://android-arsenal.com/details/1/771 which worked. and gave me below result:-

But it fails for minute selection(As it only provides hours) and also I need to do something like:-

Please help me out

A: int SMALLEST_HOUR_FRACTION = 60;
seekbar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener() {
            @Override
            public void onRangeSeekBarValuesChanged(RangeSeekBar bar, Object minValue, Object maxValue) {
                int minHour = seekbar.getSelectedMinValue().intValue() / SMALLEST_HOUR_FRACTION;
                int minMinute = (seekbar.getSelectedMinValue().intValue() % SMALLEST_HOUR_FRACTION);
                int maxHour = seekbar.getSelectedMaxValue().intValue() / SMALLEST_HOUR_FRACTION;
                int maxMinute = (seekbar.getSelectedMaxValue().intValue() % SMALLEST_HOUR_FRACTION);
            String dep_min_time = (String.valueOf(minHour)+ ":" + String.valueOf(minMinute));
            String dep_max_time = (String.valueOf(maxHour)+ ":" + String.valueOf(maxMinute));

            dep_min_time1_txt.setText(DateUtil.TimeFormat(dep_min_time));
            dep_max_time1_txt.setText(DateUtil.TimeFormat(dep_max_time));

        }
    });


text:
Q: using NSIS to install and run every time Im doing a little research into installers, and right now at my company we are having some issues deploying from jenkins using click once. We have a test certificate(these programs are all internal) and for some reason are having some issues with the certifcate being incompatiable with certain msbuilds/.net frameworks. So im looking into alternatives.
But in that i want to keep the same architecture. How it works right now is someone clicks on a button in our task bar, clicks on the application they want, and then click once installs the updates(or installs) without further user input and starts the application. Ive heard a lot of good things about NSIS.
So far ive only seen generic application installers like you expect when you download anything from the internet. Could I do something like i described above using NSIS?

A: A very basic no interaction installer might look like this:
Name foo
OutFile foo_setup.exe
AutoCloseWindow true
RequestExecutionLevel user
InstallDir "$LocalAppData\Programs\MyApp"

Page InstFiles

Section
SetOutPath "$InstDir"
WriteUninstaller "$InstDir\uninst.exe"
; TODO: Add registry entry for Add/Remove Programs
File "MyApp.exe"
File "Data.xml" ; Support files etc
Exec '"$InstDir\MyApp.exe" -firstrun "c:\some path\file.ext"'
SectionEnd

Section Uninstall
Delete "$InstDir\MyApp.exe"
Delete "$InstDir\Data.xml"
Delete "$InstDir\uninst.exe"
RMDir "$InstDir"
SectionEnd

If you want to install for all users in %ProgramFiles% you can run into issues with Exec because the app can end up running as the wrong user if a non-administrator used some other account in the UAC dialog.


text:
Q: Maven plugin installation for eclipse Juno is failing? I'm getting the following error while installing maven plugin from the eclipse market place. Eclipse version is Juno.
An error occurred while collecting items to be installed

session context was:(profile=epp.package.jee,
phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, operand=, action=).
Problems downloading artifact:
    osgi.bundle,org.eclipse.m2e.maven.runtime,1.3.1.20130219-0923.
MD5 hash is not as expected.
Expected: 7a5ed4c4367be0a19e1c297bfbfe53b8 and
found 223b1b3e1b17bf8fb075672dfbd58dd7.

A: Run the installation again. The downloaded plugin file is corrupt, as indicated by the error message.


text:
Q: Service returning unexpected result, promise ignored The service is returning data (the raw $http response) rather than result (the processed version I want to pass back to my controller), why is the code inside promise being ignored?
///in controller
Romanize.get($scope.currentMaterial).then(function(d){
    $scope.romanized = d;
});

//service
app.factory('Romanize', ['$http', 'Position', function($http, Position){
    return{
      get: function(query){
            var url= Position.sections[Position.sectionNumber].romanizeService + "?korean=" + query;
            var promise = $http.get(url).success(function(data) {
                var parts = $(data).find("span");
                var array = [];
                for (var x = 0; x<parts.length; x++){
                    array.push(parts[x].title);
                }
                var result = array.join("");
                return result;
            });
            return promise;
        }
    };
}]);

A: success handler does not provide chain. You should use then:
var promise = $http.get(url).then(function(data) {
  var parts = $(data).find("span");
  // ...
  return result;
});


text:
Q: Why are .z.* files created for In my home folder I have realized that there are plenty of .z.* files are created. They all are empty. I have no idea which process have created them. What might be the reason all those files are created, is it safe to remove them?
$ cat .z.*
$ ls .z.*
.z.28    .z.3504  .z.6019  .z.9240   .z.12471  .z.15266  .z.18282  .z.20997  .z.24111  .z.26818
.z.40    .z.3511  .z.6020  .z.9293   .z.12495  .z.15268  .z.18285  .z.21031  .z.24129  .z.26847
.z.145   .z.3533  .z.6039  .z.9305   .z.12516  .z.15303  .z.18292  .z.21051  .z.24136  .z.26874
.z.217   .z.3584  .z.6049  .z.9316   .z.12548  .z.15337  .z.18348  .z.21099  .z.24143  .z.26900
.z.284   .z.3599  .z.6107  .z.9326   .z.12570  .z.15361  .z.18360  .z.21102  .z.24208  .z.26909
.z.342   .z.3611  .z.6125  .z.9353   .z.12587  .z.15378  .z.18370  .z.21103  .z.24265  .z.26913
.z.357   .z.3658  .z.6138  .z.9370   .z.12613  .z.15438  .z.18371  .z.21120  .z.24292  .z.26932
.z.360   .z.3668  .z.6152  .z.9396   .z.12676  .z.15452  .z.18398  .z.21141  .z.24303  .z.27007
.z.397   .z.3702  .z.6159  .z.9428   .z.12682  .z.15468  .z.18399  .z.21181  .z.24316  .z.27040
.z.406   .z.3744  .z.6173  .z.9443   .z.12685  .z.15476  .z.18419  .z.21219  .z.24339  .z.27042
.z.415   .z.3784  .z.6204  .z.9452   .z.12712  .z.15491  .z.18483  .z.21278  .z.24341  .z.27062
.z.500   .z.3818  .z.6317  .z.9467   .z.12748  .z.15561  .z.18484  .z.21299  .z.24344  .z.27076
.z.551   .z.3870  .z.6329  .z.9557   .z.12763  .z.15575  .z.18490  .z.21339  .z.24363  .z.27085
.z.605   .z.3886  .z.6339  .z.9594   .z.12782  .z.15583  .z.18494  .z.21384  .z.24373  .z.27124
.z.606   .z.3887  .z.6369  .z.9605   .z.12791  .z.15587  .z.18501  .z.21399  .z.24399  .z.27127

A: These are left-overs from z, a fancy cd replacement. You might have this as an Oh My Zsh plugin. z maintains a ~/.z file, and the numbered versions are created when that file is updated; but they are supposed to be deleted automatically.
I used to see this too, but haven't recently; things might have improved with recent versions of z.


text:
Q: MySQL group by query with additional row I have a table like below called trades
traders   qty

abc      50000
xyz      35000
pqr      25000
xxx      10000
yyy      20000
uuu      15000
abc      2000
xyz      3000
pqr      1500

I need to get the top 3 qty wise traders and all others in a separate row.
SELECT trader,SUM(qty)
FROM traders
GROUP BY trader DESC
LIMIT 3

from the above query I can get an answer like below
tr        qty

abc      52000
xyz      38000
pqr      26500

but my requirement is as below
tr        qty

abc      52000
xyz      38000
pqr      26500
other    45000   ----- with this column for all other traders except the largest 3

A: Try this query -
SELECT
  IF(t2.trader IS NULL, 'other', t1.trader) trader,
  SUM(qty) qty
FROM traders t1
  LEFT JOIN (
  SELECT trader, SUM(qty) FROM traders
    GROUP BY trader
    ORDER BY SUM(qty) DESC
    LIMIT 3) t2
  ON t1.trader = t2.trader
GROUP BY trader
ORDER BY IF(t2.trader IS NULL, 1, 0), qty DESC

+--------+-------+
| trader | qty   |
+--------+-------+
| abc    | 52000 |
| xyz    | 38000 |
| pqr    | 26500 |
| other  | 45000 |
+--------+-------+

A: Here's another one:
(select trader, sum(qty)
 from trades
 group by trader
 order by sum(qty) desc
 limit 3)
union
(select 'other', sum(qty)
 from (select trader, sum(qty) qty
       from trades
       group by trader
       order by sum(qty) desc
       limit 3, 4000000000) t);

SQL Fiddle for playing around.


text:
Q: Map Filter in React. Objects are not valid as a React child. If you meant to render a collection of children, use an array instead function Main(){
    // create an array that holds objects
    const people = [
        {
            firstName: 'Fathi',
            lastName: 'Noor',
            age: 27,
            colors: ['red', 'blue'],
            bodyAttributes: {
                weight: 64,
                height: 171
            }
        },
        {
            firstName: 'Hanafi',
            lastName: 'Noor',
            age: 26,
            colors: ['white', 'black'],
            bodyAttributes: {
                weight: 62,
                height: 172
            }
        }
    ]

    return(

                /* display person age equal to 27 using filter using ES6 arrow */
                {people.filter(person => person.age == 27)}

    )
}

I'm very new to react and the use of map instead of a normal loop function.
When I run this code it gave me this error (as displayed below)

Can you guys teach me the right way of how to display all data of a person when filtered by age equal to 27?

A: You try to return an Object and this is not possible.

function Main(){
    // create an array that holds objects
    const people = [
        {
            firstName: 'Fathi',
            lastName: 'Noor',
            age: 27,
            colors: ['red', 'blue'],
            bodyAttributes: {
                weight: 64,
                height: 171
            }
        },
        {
            firstName: 'Hanafi',
            lastName: 'Noor',
            age: 26,
            colors: ['white', 'black'],
            bodyAttributes: {
                weight: 62,
                height: 172
            }
        }
    ]

    const filterdPeople = people.filter(person => person.age == 27)

    return(

                {filterdPeople.map(person => {
                  return (

First name: {person.firstName}

Last name: {person.lastName}

Age: {person.age}

Colors: {person.colors.map(color => ({`${color}, `}))}

                      Body Attributes:
                      Weight: {person.bodyAttributes.weight}
                      Height: {person.bodyAttributes.height}

                  )
                })}

    )
}

A: You have to map the array. See this doc.
For each person, you decide how to display each field, here I used
 tags, you can display them in a table, or in a custom card.. Your choice!
Remember that inside {} brackets goes Javascript expressions while in () goes JSX, very similar to HTML tags as you can see!
Read the documents, follow a tutorial, it'll help a lot!
{people.filter(person => person.age == 27).map(person => { return(

First name: {person.firstName}

Last name: {person.lastName}

Age: {person.age}

Colors: {person.colors.map(color => ({color+" "})}

        Body Attributes:
        Weight: {person.bodyAttributes.weight}
        Height: {person.bodyAttributes.height}

)})}

A: function Main(){
    // create an array that holds objects
    const people = [
        {
            firstName: 'Fathi',
            lastName: 'Noor',
            age: 27,
            colors: ['red', 'blue'],
            bodyAttributes: {
                weight: 64,
                height: 171
            }
        },
        {
            firstName: 'Hanafi',
            lastName: 'Noor',
            age: 26,
            colors: ['white', 'black'],
            bodyAttributes: {
                weight: 62,
                height: 172
            }
        }
    ]

    return(

                /* display person age equal to 27 using filter using ES6 arrow */

                firstName
                lastName
                age
                colors
                bodyAttributes

                {people.filter(person => person.age == 27).map(item=>{
                    return(

                           {item.firstName}
                           {item.lastName}
                           {item.age}

                             {
                                 item.colors.map(color=>{
                                     return
{color}

                                 })
                             }

                           {}

W:{item.bodyAttributes.weight}

H:{item.bodyAttributes.height}

                    )
                })}

    )
}


text:
Q: At a certain breakpoint, the content from 2 masonry containers on the same page starts overlapping I am displaying the wordpress posts on my blog index page in a masonry layout. I also have the masonry activated on footer, to display the wordpress footer widgets in a masonry layout.
So basically I have 2 masonry containers on the same page.
1. One for displaying the blog posts, and
2. Other for displaying the footer widgets.
The html markup for the page looks like this:
HTML

Post 1

Post 2

Post 3

        .....
        .....

Post n

    Widget 1
    Widget 2
    Widget 3
    .....
    .....
    Widget n

Following is the url where I am trying to implement this layout.  --  http://lanarratrice-al-rawiya.com/lanarratrice/blog/
I dont want the masonry to load on the mobile devices.
1. I want the masonry on Posts to work only when the min width of the document is 837px.
2. Also I want the masonry on Footer to work only when the min width of the document is 880px.
Any media query lower than the above width(s) will not trigger the masonry layout, and I will display all my posts and widgets in a full width (taking up the full space available). To implement this I am using enquire js, that will trigger the masonry layout if it matches the media query. Following is my javascript:
JAVASCRIPT
// Masonry settings to organize footer widgets and blog posts
jQuery(document).ready(function($){
    var $container = $('#footer-widgets'),
        $maincontent = $('.blog .testmason');

    enquire.register("screen and (min-width:837px)", {

        // Triggered when a media query matches.
        match : function() {
            $maincontent.masonry({
                columnWidth: 200,
                itemSelector: '.hentry',
                isFitWidth: true,
                isAnimated: true
            });
        },

        // Triggered when the media query transitions
        // from a matched state to an unmatched state.
        unmatch : function() {
            $maincontent.masonry('destroy');
        }

    });

    enquire.register("screen and (min-width:880px)", {

    // Triggered when a media query matches.
    match : function() {
        $container.masonry({
            columnWidth: 400,
            itemSelector: '.widget',
            isFitWidth: true,
            isAnimated: true
        });
    },

    // Triggered when the media query transitions
    // from a matched state to an unmatched state.
    unmatch : function() {
      $container.masonry('destroy');
    }

    });
});

And finally this is my css that is being applied on this page:
CSS
#main {
    max-width: 100%;
    width: 100%;
}

.testmason {
    margin: 0 auto 35px;
}

#main article {
    margin: 0 20px 35px;
    width: 360px;
    float: left;
}

@media screen and (max-width: 854px) {
    #main { width: 100%; }

    #main .testmason {
        margin: 0 10px;
        width: auto!important;
        height: auto!important;
    }

    #main article {
        float: none;
        width: 100%;
        margin: 0 0 35px;
    }

    #main .index-box {
        box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.22);
        margin: 0 auto 2em;
        width: auto;
        max-width: 780px;
        max-width: 78rem;
    }

    #main .navigation {
        width: auto;
        max-width: 780px;
        max-width: 78rem;
    }
}

.index-box {
    margin: 0;
}

nav.paging-navigation {
    width: 90%;
    position: static!important;
    margin: 0 auto;
}

It seems that my javascript is working correctly, because the masonry layout is implemented. But as I resize my firefox browser window to about 846px (approx around this size), I see a broken layout. I see sometimes that the post is on top of footer. Please see this following picture attached.

To reproduce this bug you might have to shrink and expand your browser window (firefox) around 5-8 times. Sometimes if you shrink it very fast or very slow you might not see the broken layout. BTW I am using Firefox 35.0.1.
Please let me know what can I do to fix this issue. Thanks.

A: Add the $container.masonry() function on page load too.
The issue is, it registers the event on resize, but on load it fails to calculate the body heights to calculate the positions. As these post blocks are absolutely positioned, it bleeds over footer.


text:
Q: Dual-Boot Ubuntu 16.04.1 freeze on loading screen I tried to install the LTS version of Ubuntu (16.04) on my Asus win10 64 bit.
I made a usb bootable with ubuntu (and rufus application) I did the partition on my hard drive.
And when I launch The installation of Ubuntu right after I restart, whether I select Install Ubuntu or Try Ubuntu, it freezes on the loading screen, where you can see the dots under the name Ubuntu. It freezes and nothing happens, even after one hour. I have to restart the computer in the hard way.
I don't understand why it is not working, everywhere on tutorials or the docs, it seems that it should word.
I even updated pilots, but none of that worked.

A: As the comment suggested, you need to disable legacy boot using the options in the BIOS. That seemed to work for me facing this same issue with both Ubuntu 18.04 and 16.04 on a Dell Inspiron 15 5000, trying to dual boot with Windows 10.
To be specific the BIOS has two options relevant to Legacy Boot on the same tab where you select the boot preferences and add/delete boot options. Those are the ones you would want to modify (disable).
Also note that I had to reset these options in the BIOS back to their original settings after successfully installing Ubuntu because otherwise it prompts a system repair and fails to boot into Windows.


text:
Q: Regression for data over the course of two years I have a quick question regarding an analysis that I am doing.  I am looking at metrics for years 2013 and 2014. What I want to do is a build a growth model using growth rates.
Suppose that I have a growth variable that I am trying to predict which is defined as Y% = (Y2014 - Y2013)/(Y2013) and two other independent variables, X1% and X2%, which are growth variables as well. In addition to this I also have a factor variable so my model is the following Y% ~ X1% + X2% + Factor.
I want to run this regression in R, but I wanted to make sure that my model is adequate. Is there anything I should be careful about? Are there any other ways to go about this? The question I am trying to answer is "Does growth in one variable(%X1, %X2) lead to growth in the my dependent variable(%Y).
I am not looking carry out a super formal analysis or anything like that. I just came on here to make sure that I am on the right path.


text:
Q: Why does not this plot get bigger as expected? From a previous question, I got that plt.figure(figsize = 2 * np.array(plt.rcParams['figure.figsize'])) will increase the plot size by 2 times. With below code, I want to plot 4 subplots in the grid 2x2.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
%config InlineBackend.figure_format = 'svg' # Change the image format to svg for better quality
don = pd.read_csv('https://raw.githubusercontent.com/leanhdung1994/Deep-Learning/main/donclassif.txt.gz', sep=';')

fig, ax = plt.subplots(nrows = 2, ncols = 2)
plt.figure(figsize = 2 * np.array(plt.rcParams['figure.figsize'])) # This is to have bigger plot

for row in ax:
    for col in row:
        kmeans = KMeans(n_clusters = 4)
        kmeans.fit(don)
        y_kmeans = kmeans.predict(don)
        col.scatter(don['V1'], don['V2'], c = y_kmeans, cmap = 'viridis')
        centers = kmeans.cluster_centers_
        col.scatter(centers[:, 0], centers[:, 1], c = 'red', s = 200, alpha = 0.5);

plt.show()

Could you please explain why plt.figure(figsize = 2 * np.array(plt.rcParams['figure.figsize'])) does not work in this case?

A: I post @JohanC's comment to remove this question from unanswered list.

It could be written as fig, axes = plt.subplots(nrows=2, ncols=2, figsize=2 * np.array(plt.rcParams['figure.figsize'])). Just calling plt.figure without storing the result creates a dummy new figure, without changing fig and without creating the axes on that new figure won't have the desired result.


text:
Q: Add content asynchronously (threading + ajax) Ok what id like to do is to load a page that displays 90% of content, and load the last 10% asynchronously.
As im rendering the page i programatically create an update panel which i pass to a thread. When this thread finishes it then updates the updatepanel on the main thread.
public void test(object parameter)
{
    Thread.Sleep(2000);
    var updpanel = (UpdatePanel)parameter;
    updpanel.ContentTemplateContainer.Controls.Add(new LiteralControl("HI"));
    updpanel.Update();
}
protected void Page_Load(object sender, EventArgs e)
{
    var th = new Thread(new ParameterizedThreadStart(test));
    var updpanel = new UpdatePanel() { UpdateMode = UpdatePanelUpdateMode.Conditional };
    ContentPlaceHolder1.Controls.Add(updpanel);
    th.Start(updpanel);
}

Failing this, in a single threaded approach, do i just keep polling the page to see if it has finished or not?

A: One thing to keep in mind is, even though ASP.Net development seems like it's closely related to windows development, there's a big difference:  your code to handle a request, most of the time, is executed in a fraction of a second and done...  In this example, once the main thread has completed, the generated page has already been sent to the requestor, leaving your secondary thread running in the background of your server, working on a page that has already been sent out.
What you'll probably need to do is generate the 90% of the page, and then send it out.  On your page, you will need to use ajax to, on page load (for the client), request the other 10% from the server... You'll probably want to do the javascript with a library like jquery, and on the server end setup a web service to handle the requests.

A: You cannot use threading this way on the server. Your second thread will probably not complete until after the page have been processed and the request lifecycle is complete.
Depending on what you are trying to achieve: do you need to process data in parallel server-side you should look into Asynchronous Pages in ASP.Net 2.0.
Another approach would be to render the page ("90%" as you call it) and use ajax on the client to request additional data.


text:
Q: What is the difference between Owner and Parent of a control? I am bit curious about the two properties of a Delphi VCL control.
Each component has 2 properties as Owner and Parent at runtime. Can anyone help me to understand the difference between both? And how are they used by windows for displaying control or form?

A: Owner
Owner is a property introduced in TComponent, and Owner itself has type TComponent. The Owner is used primarily to manage the lifetime of designed components. That is, components that you place on the form designer (or indeed other design surfaces) and whose lifetime is managed entirely by the framework. The documentation says:

Indicates the component that is responsible for streaming and freeing this component.

When a form is created, the streaming framework parses the .dfm file and instantiates the components that are listed within. These components are typically created with Owner specified to be the form.
At the other end of a component's life is destruction. When a component is destroyed, it also destroys all of the components which it owns. Consider, for the sake of a concrete example, a TButton that sits on a TForm, placed there at design time. The streaming framework creates the button setting its Owner to be the form. The form, as a descendent of TComponent maintains a list of all the components that it owns. When the form is destroyed it walks over that list of owned components and destroys them. The button is destroyed in this manner.
There are many nuances to this:

*

*Components don't need to be owned by the form. For instance, components created at run time are owned by whatever component you pass to the constructor.

*Components need not have an owner, you can pass nil to the constructor. In this case, the programmer remains responsible for destroying the component.

*Ownership can be changed during the lifetime of a component.

Because the streaming framework instantiates components, the constructor of TComponent is declared virtual:
constructor Create(AOwner: TComponent); virtual;

If you derived from a TComponent descendent, and you wish for that derived component to be placed on a design surface, then you must respect this virtual constructor. If you define a constructor in your TComponent descendent then it must override this virtual constructor.
It is worth pointing out that Win32 has a completely different concept of a window's owner, that should not be confused with the VCL concept of the same name. The Windows documentation says:

Owned Windows
An overlapped or pop-up window can be owned by another overlapped or
  pop-up window. Being owned places several constraints on a window.
   - An owned window is always above its owner in the z-order.
   - The system automatically destroys an owned window when its owner is destroyed.
   - An owned window is hidden when its owner is minimized.
Only an overlapped or pop-up window can be an owner window; a child
  window cannot be an owner window.

In VCL terms, this concept is exposed by the PopupParent property. That property was introduced after Delphi 7 so will not be available to you. In Delphi 7, the framework sets the window owner, and gives no easy mechanism to override the framework's choice. If you do need to influence window ownership then you must override CreateParams and set Params.WndParent. Unfortunately, there are a number of problems with the VCL handling of ownership in Delphi 7 and it is sometimes necessary to grub around in these somewhat gory details.
To show how easy it is to get confused, the VCL documentation says:

WndParent: The window handle of the parent window. This is the same as the Handle property of the parent control.

This is simply wrong. For a top-level window, this is the owner rather than the parent.
Parent
Parent is a property defined in TControl and has type TWinControl. This property is used, broadly, to expose the Win32 concept of parent and child controls. The Windows documentation says:

A window can have a parent window. A window that has a parent is called a child window. The parent window provides the coordinate system used for positioning a child window. Having a parent window affects aspects of a window's appearance; for example, a child window is clipped so that no part of the child window can appear outside the borders of its parent window. A window that has no parent, or whose parent is the desktop window, is called a top-level window.

Essentially, the VCL Parent property maps directly onto the Win32 parent concept.
Note however, that Parent is defined in TControl. Now, TControl is not windowed, so a TControl is not a child control in the Win32 sense, because a Win32 window's children are themselves windows. So, a TControl with a defined Parent is a child in the VCL sense, known as a non-windowed child control. These non-windowed controls paint themselves as part of their parent's paint handlers. The canonical example of such a control is TLabel.
Note that when a windowed control, that is a TWinControl descendent, is destroyed, it also destroys all of its children.
A TWinControl descendent can enumerate its children using the ControlCount and Controls[] properties. These enumerate both windowed and non-windowed children.