Q:

What is the meaning of "We are a civic society" attributed to Steve Bannon

In a radio program back in November 2015 that featured US President (then candidate) Donald Trump - his current chief strategist Steve Bannon made these following remarks -

BANNON: Well I got a tougher — you know, when two thirds or three
  quarters of the CEOs in Silicon Valley are from South Asia or from
  Asia, I think — on, my point is, a country’s more like, [inaudible], a
  country’s more than an economy. We’re a civic society.

What do those last words mean exactly -  We are a civic society.
I read the definition according to the Wikipedia article Civic Society but I am not certain if that is what Steve Bannon is referring to in this context. Does he mean Asian immigrants and/or South Asian immigrants are not contributing to a "civic society" ?
The reason this statement is a bit confusing is that it has not been used before by people of the so-called alt-right movement and secondly because he is clearly not referring to
Civic nationalism. So hopefully the answer(s) would clarify whether this is a oft-used term by alt-right nationalists.

A:

In this context what Bannon means is that the United States is, or should be, a "nation" that is a cultural community of people who share a national identity.
In particular, he has a vision of the United States has a Christian nation, guided by European concepts of civilization. This ideology, sometimes called "white nationalism" or "alt-right" is one that he has expressed in his management of Breitbart News. For example, the New York Times quoted him on February 10, 2017 as saying:

We, the Judeo-Christian West, really have to look at what he [
  Vladimir Putin, who is influenced by Evola follower Aleksandr Dugin ]
  is talking about as far as Traditionalism goes — particularly the
  sense of where it supports the underpinnings of nationalism.

The New York Times mentions this quote in a November 21, 2016 story about "White Nationalism". The original interview is available in audio form here.
The phrase is intended, in part, to evoke the more moderate connotations of the notion of civic nationalism, while actually really referring to something else. Self-described of the Alt-Right, such as Emile Durand, for example, has embraced ethnic or racial nationalism as a natural outgrowth of the milder civic nationalism and have interpreted Bannon's turn of phrase in that interview as an expression of support for racial nationalism.
On the other hand, others in the Alt-Right movement see the phrase "civic society" as a sincere effort to evoke mere "civic nationalism" when only racially based nationalism will do, rather than as a dog whistle.
The phrase is also responsive to world views such as those of Frank Gaffney Jr., a good friend of former National Security Advisor Michael Flynn, who stated the following views about Muslims in an interview:

They essentially, like termites, hollow out the structure of the civil
  society and other institutions, for the purpose of creating conditions
  under which the jihad will succeed.

Thus, by referring to civic society, he is also indirectly alluding to the belief that immigrants undermine civil society. Civil society is a nuanced as complex concept, as the link explains, but can be summed up in the sense referred to here as the grass roots cultural and institutional base of values and communities that allow our political economy to function properly. Outsiders, in his view, threaten this underlying fabric of our society that makes everything else work.

A:

Language is contextual, and as such it is impossible to know what is
meant by a given phrase without considering the context. This quote has been widely repeated out of context, and the original interview from Nov 5, 2015 is very hard to track down. I found it at mp3musicsite and will provide the actual transcript so you can get the flow of the conversation. I think in context his meaning is quite clear.
At 16:24 in the interview, Steve Bannon asked Trump the following question about the H1B visa controversy:

What do you think about this situation where you have American
  companies, particularly technology companies, that are letting go
  highly-trained American IT workers, blowing them out, having them
  train their replacements and hiring foreign workers. Just generally
  what's your sense of that?

Trump responds,

No good, it's no good, I mean we have to do something about it. And,
  you know, people are coming in and they're taking jobs, and they're
  getting paid less money, and they're -- you know, a lot of things are
  happening, a lot of bad things. You know, having... and a lot of it
  has to do with borders, a lot of it has to do with [inaudible].

Trump then launches into a clarification his his position:

You know one of the things I did say, though, and I feel strongly
  about this. When somebody's going to Harvard, Yale, Princeton, Penn,
  Stangord, all the great... and they graduate, and not only graduate
  but do great, and we throw them out of the country, and they can't get
  back in, I think that's terrible. We've gotta keep, we've got to be
  able to keep great people in the country. We've got to create, you
  know, job creators.
One man went to -- I thnk it was Harvard, I think there was a story a
  month ago -- went to Harvard, did well, wanted to stay in the country,
  wasn't allowed to, went back to his home in India, started up a
  company, now its a very very successful company with thousands of
  people. He wanted to do that here.
We have to be careful of that Steve. We have to keep our talented
  people in this country. I think you agree with that, do you agree with
  that?

At this point Steve Bannon responds to Trump's question:

Well I got a tougher — you know, when two thirds or three quarters of
  the CEOs in Silicon Valley are from South Asia or from Asia, I think —
  on, my point is, a country’s more like, [inaudible], a country’s more
  than an economy. We’re a civic society.

Steve makes three clear statements: (1) a lot of CEOs in Silicon Valley are from asia; (2) a country is more than an economy; (3) the USA is a civic society.
The first statement is a response to Trump's statement that we are sending all the talented foreigners home. Steve is saying that, as evidenced by all the CEOs, we actually are keeping many talented immigrants. Or, "it's not as bad as you make it sound."
The second statement is a response to Trump's focus on the economic aspect. He does not deny that the economy is important, but he says we have to consider more than just economics.
He clarifies what he means by this in the third statement. Civics is defined as "the study of the rights and duties of citizenship." So he is saying that we have a duty to each other, to consider the welfare of our fellow citizens. We have to be about more than just corporate profits. Just having a healthy economy is not enough if our fellow citizen is impoverished in obtaining it -- my rights do not trump your rights.
That of course raises the question of whether our fellow citizens have a right to work and make a decent wage. I think Steve is arguing that they do, at least insofar as they are citizens and participants in the common wealth of the nation.
He then starts to say "I want to see..." but then Trump interrupts to talk about how to improve immigration and we never get to hear what Steve's solution to the H1B problem is.
This statement has been widely interpreted as being about immigration and xenophobia, which is clearly it is not. It is about the H1B policy and the effect it has on the economy and on people. Trump had just finished talking about immigration being a good thing, and Steve does not challenge that.


Q:

Dropping IE6 Support; What Do We Gain? ... HTML / CSS / JavaScript Functionality & Techniques

The web development community is at the tipping point of ditching Internet Explorer 6 support - even Microsoft is counting down it's demise http://ie6countdown.com/!
This raises a very interesting question... What do we gain?
We've been weighed down by the ball and chain that is IE6 for so long it's really interesting to consider all the good stuff we've neglected...
With IE7 as the new baseline for backwards compatibility, how will this impact web development? What HTML, CSS or JavaScript functionality / techniques can we now expect from our browsers?
For example, I'm really looking forward to being able to use CSS Chained Classes.
.class1.class2.class3 {
  background: #fff;
}

Content here.

P.S This question was inspired by CSS Differences in Internet Explorer 6, 7 and 8 from Smashing Magazine.

A:

From a web developer standpoint, there is surprisingly little in the way of extra functionality. Many standard APIs present in other browsers are still missing. The gain comes more in the shape of a lot of small improvements in IE7 compared to IE6.

Improved but imperfect PNG transparency support
Native XMLHttpRequest (not useful: ActiveX is still required for file: URLs)
Some CSS layout fixes
Much better CSS support, as laid out in the article linked in the question

Some things that haven't improved between IE 6 and 7:

The JScript engine is still very slow relative to modern browsers, the JSCript API is missing many methods introduced by Mozilla that were copied in other browsers and later standardized, and JScript retains many quirks and bugs
Many CSS layout issues are still present
Some new CSS bugs were introduced


Q:

draggable inside a sortable with jquery

I have a sortable list of divs using the jquery UI. It works fine.
However, I would like to have certain images inside the divs be draggable. The divs keep taking priority though every time I try to drag an image. The sortable div gets dragged instead.
Ok, so I figured I need to catch the mouseenter and mouseleave events on the image and temporarily disable the sortable divs while it was hovering. That didn't work (Maybe I didn't do it the right way though)
Does anyone know how to get this to work?
Sorry if this has been asked before, but I didn't find anything when I searched.
EDIT: Took a bit of time to find the exact place. Anyway here is the current sortable code.
var oldColumn = '';
var systemColumnCounter = $(".systemColumn").length;
$(".systemColumn").sortable({
    /*
    accept-option mit neuer Version von JqueryUI
    */
    accept: '.none',
    placeholder: 'systemElementPlaceHolder',
    connectWith: '.systemColumn',
    dropOnEmpty: true,
    items: 'div.systemElement',
    forceHelperSize: true,
    start: function(event, ui){
        oldColumn = ui.item.parent();
        $("body").myPopup("hideAll");

    },
    sort: function(event, ui){
        $(this).ElementBorderRemove();
        $(".systemElementPlaceHolder").addClass("systemBorderColor");
        $(".systemElementPlaceHolder").height(ui.helper.height());
    },
    stop: function(event, ui){
        var counter = 0;
        var elementBefor = '';
        var elementAfter = '';
        var Item = ui.item;
        var myColumn = Item.parent();

        if(oldColumn.children().length == 0)
        {
            oldColumn.append('Column is empty.');
        }

        myColumn.children().each(function(){
            if($(this).hasClass("columnEmptyMessage") && myColumn.children().length > 1)
            {
                $(this).remove();
            }

            if($(this).attr("id") == ui.item.attr("id"))
            {
                if(counter > 0)
                {
                    elementBefor = myColumn.children().eq(counter-1).attr("id");
                }

                if(counter < (myColumn.children().length - 1))
                {
                    elementAfter = myColumn.children().eq(counter+1).attr("id");
                }
                return false;
            }
            counter++;
        })

        serialStr = elementBefor + '|' + elementAfter + '|' + myColumn.attr("id") + '|' + ui.item.attr("id");
        if(!ui.item.hasClass("systemNewElement"))
        {
            $.ajax({
                url: "includes/administration.action.php",
                type: "POST",
                data: "action=elementItemSort&items="+serialStr,
                dataType: "html",
                cache: false,
                success: function(data){
                    //alert(data);
                },
                error:function(x,e){
                },
                complete: function(data){
                }
            });
        }
    }
});

The html has a couple of divs with class systemColumn and the stuff inside is sortable... This part works.

A:

You might want to consider only having part of your div (part that the img is not contained in) as the only place on that div you can click to start the sorting by using the "handle" option http://docs.jquery.com/UI/API/1.8/Draggable#option-handle.
You could have the left hand side of the div have some kind of "move" cursor image so the user sees it and knows to click there in order to move the div to sort it. This removes complexity in your code and also removes confusion on the users end.


Q:

Delphi: Odd behaviour loading DLLs with LoadLibrary

I'm building a plugin system with Delphi (some of you have been helping me with this task).
To search for the DLL files, I'm using a TSearchRec, which search's in the exe path for dll files, and then I'm using LoadLibrary to access them.
Then, if a certain function is exposed (using GetProcAddress), I load it as a plugin. If not, FreeLibrary is executed, and moves on for the next file.
While testing, I noticed that when the TSearchRec found the "borlndmm.dll", which happened to be in that path, it loads, and searches for my plugin function, which of course is not found, but when if executes FreeLibrary, I get an Access Violation.
Other no-plugin dll's in the same path, like libmariadb.dll, are freed securely without errors.
Of course this is easily fixed, by having my plugin dll's in its own path, without any other dll files, which will be better even for performance reasons, as it doesn't have to load any library that it's not supposed to.
But I would like to understand why it happens.
Any ideas?
Thank you
Nuno Picado

A:

The reason why you run into problems with some DLLS is because LoadLibrary executes code in the DLL it loads - specifically, the DLL's initialization code. In Delphi projects, this includes the unit initialization sections.  In the case of borlandmm.dll, the dll initialization code inserts itself into your host exe process's runtime library, replacing your default memory manager with the memory manager in the DLL.  This is not intended to be a reversible action - it can't remove itself in the DLL shutdown code (in part because DLL shutdown code is not guaranteed to execute in all circumstances).
So, be careful using LoadLibrary because you are basically executing arbitrary code before you even know what the DLL is.  If you really must take a peek into a large number of arbitrary DLLs of unknown origin, a safer way would be to load the DLL as a resource image instead of as an executable image. This loads the file into memory but does not execute the DLL initialization code.  See LoadLibraryEx() and the LOAD_LIBRARY_AS_IMAGE_RESOURCE flag.
As you mentioned in an earlier comment, there are a number of things you can do to reduce the number of DLLs you need to load to exactly the DLLs that the user/administrator wants your application to load, instead of loading everything you can find.

Require the DLL file name have a custom extension or file name pattern. (Plugin*.mod for example)
Only load DLLs from a special subdirectory. This works well with directory level access control, since on most systems bin directories are not writable by ordinary users. Someone would have to have admin rights to put a DLL into the special subdirectory.
Only load DLL files that are named in a user-defined config file.
Any combination of the above

A:

That DLL implements a shared memory manager. It is designed to be used with load time linking only. It is loaded by the loader, and never unloaded until the process ends. Once it is loaded, it assumes responsibility for all future heap allocations and deallocations with the process. So it changes the behaviour of the host process. It cannot be loaded dynamically.
The moral of the story is not to load random DLLs into your process. Only load DLLs that either you or your program's users specifically ask to be loaded.


Q:

Access an object node with a variable in jQuery

I've a jQuery object (counts) like this :
Object {men: 299, womens: 175, children: 173}

I just want to retrieve the value to display it in a span (the data-filter attributes are the same as the object keys)
$( "a.type_select" ).each(function() {
    var theType = $(this).attr('data-filter');
    var theCounter = counts.theType;
    $(this).children('span.count').html(' ('+theCounter+')');
});

How can I do this ?
Thanks !

A:

counts.theType access the key theType of the object counts.
It is important to know that object key can also be accessed by string. You just need to use bracket. for example :
counts['men']; // 299

That being said, you can pass a variable to the bracket :
counts[theType]

That will return what you want.


Q:

Shrink and expand table width as screen width changes

I want to be able to shrink the width of my table as the screen width decreases and expand the width of the table when the screen width increases.
I know that I can use @media() in both CSS and JavaScript but I'm trying to find a simpler way to do this.
The current issue that I am having is that another div outside of the parent div of my table is overlapping the table when the screen width shrinks.
Here is the CSS for my table:
#course_table {
  margin: auto;
  font-family: "Lato","Helvetica Neue",Helvetica,Arial,sans-serif;
  border-collapse: collapse;
  padding: 12px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.3);
  border-radius: 4px;
  width: 100%;
}

A:

sample code with vw unit

body { margin: 0;}
* { box-sizing: border-box; }

Table { border-collapse: collapse; margin: 0;   }
td    { border: 1px solid grey; padding: 2px 10px; }
thead { background-color: turquoise;}

table tr td:nth-child(1) { width: 30vw }
table tr td:nth-child(2) { width: 10vw }
table tr td:nth-child(3) { width: 60vw }

A	B	C

1	2	3

PS: using magic words is not prohibited here...


Q:

How did humanity miss the Sol Relay

i've been wondering this for a while, Mass Technology was discovered on Mars before the First Contact War which was started after the Mass Relay in the Sol system was activated (Turians encroached on a human colonized world, we fought back) since it would have been unlikely that the Turians would have been unaware of humanity if they moved an active Mass Relay to the Sol System (can not remember if that even possible without Reaper assistance)
however, before Mass Technology was found on Mars humanity in Mass Effect was probably doing what we are doing now and that's sending probes into space, using high powered telescopes to look around discovering new planets and such
so i am wondering, how did humanity keep missing the Mass Relay in the Sol System

A:

It appears you are a little bit mistaken - while there were Prothean Ruins (and technology) on Mars, the only Mass Relay in the System was orbiting Pluto; The so-called "Charon Relay" was discovered in 2149, only a year after the Prothean Ruins were discovered on Mars.
Given the level of advancement of humanity before the Prothean Ruins were uncovered, it was not unreasonable to assume that the Charon Relay was missed due to it being misclassified as an icy-moon. After the discovery on Mars, it became clear that both a) there were other sentient beings in the universe, and b) they were capable of constructing structures the size of very small moons, Humanity took a closer look at Pluto / Charon and said, "Huh. Fancy that.".
The Turians were not found on the other end of the Charon Relay, and the first contact war didn't happen until 8 years later in 2158, after Humanity was well on its way with colonization efforts (and had discovered and activated several more relays).


Q:

Dashboard body does not resize with change in DT length

The dashboard page will not expand when more rows are shown from the DTOutput. The output is visible, but looks like it is no longer contained within the dashboard page.
ui <- function() {
 dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
   mainPanel(width = 12,
             fluidRow(DTOutput(outputId = "table"))
  )))}

server <- function(input, output) {
 data <- data.frame(1:100)
 output$table <- renderDT(
  data
 )
}

shinyApp(ui = ui, server = server)

Screenshot of issue.
The gray background for the dashboard page ends around row 15.

A:

This can be fixed by adding some CSS to the document:
section.content {
  overflow-y: hidden;
}

MWE:
library(shiny)
library(shinydashboard)
library(DT)
library(htmltools)
ui <- function() {
  dashboardPage(
    dashboardHeader(),
    dashboardSidebar(),
    dashboardBody(
      tags$head(tags$style("section.content { overflow-y: hidden; }")),
      mainPanel(width = 12,
                fluidRow(DTOutput(outputId = "table"))
      )))}

server <- function(input, output) {
  data <- data.frame(1:100)
  output$table <- renderDT(
    data
  )
}

shinyApp(ui = ui, server = server)


Q:

Unable to set socket options IPV6 multicast : No such device error

I am working on linux Ubuntu 14.04 and trying to multicast using IPv6. I have a link local address of fe80::9a90:96ff:fe98:a985. Running the following code :
int main (int argc, char *argv[]) {
  int sd;
  struct in6_addr localInterface;
  /* Create a datagram socket on which to send/receive. */
  sd = socket(AF_INET6, SOCK_DGRAM, 0);

  if(sd < 0) {
    perror("Opening datagram socket error");
    exit(1);
  }
  else {
    printf("Opening the datagram socket...OK.\n");
  }

  /* Set local interface for outbound multicast datagrams. */
  /* The IP address specified must be associated with a local, */
  /* multicast capable interface. */
  inet_pton (AF_INET6, "fe80::9a90:96ff:fe98:a985", &(localInterface.s6_addr));

  if(setsockopt(sd, IPPROTO_IPV6, IPV6_MULTICAST_IF, (char *)&localInterface, sizeof(localInterface)) < 0)
    {
      perror("Setting local interface error");
      printf ("%d\n", errno);
      exit(1);
    }
  else {
    printf("Setting the local interface...OK\n");
  }

}

gives the error : Setting local interface error : No such device
I have tested multicast to work with IPv4 and also successfully tested that IPv6 works by pinging a local node using ping6 command.

A:

With a few adjustments I was able to modify your program to get it to send multicast packets (that show up in WireShark) on my Mac (running OS/X 10.10.5).  I haven't tried it under other OS's, but it should more or less work on other OS's as well.
Note that the program has hard-coded the interface number to 4, since that is what en0 is on my computer; the interface number will likely be different on your computer, and for a generally useful program you'd want to discover the correct interface number dynamically (using getifaddrs() or GetAdaptersAddresses() or similar); it's only hard-coded here for simplicity.
Modified program follows:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>

int main (int argc, char *argv[])
{
   int sd = socket(AF_INET6, SOCK_DGRAM, 0);
   if(sd < 0)
   {
      perror("Opening datagram socket error");
      exit(1);
   }
   else printf("Opening the datagram socket...OK.\n");

   // 4 is the interface ID (scope_id) of interface en0 on my Mac,
   // as printed by ifconfig; the appropriate interface index
   // value on your computer will likely be different  --jaf
   int my_network_devices_scope_id = 4;

   if(setsockopt(sd, IPPROTO_IPV6, IPV6_MULTICAST_IF, (char *)&my_network_devices_scope_id, sizeof(my_network_devices_scope_id)) < 0)
   {
       perror("Setting local interface error");
       printf ("%d\n", errno);
       exit(1);
   }
   else printf("Setting the local interface...OK\n");

   struct sockaddr_in6 multicastIP;
   multicastIP.sin6_family   = AF_INET6;
   multicastIP.sin6_scope_id = my_network_devices_scope_id;
   multicastIP.sin6_port     = htons(9999);  // destination port chosen at random
   inet_pton(AF_INET6, "ff12::bead:cede:deed:feed", &multicastIP.sin6_addr.s6_addr);  // a multicast address I chose at random

   while(1)
   {
       char buf[] = "hello";
       if (sendto(sd, buf, sizeof(buf), 0, (const struct sockaddr *) &multicastIP, sizeof(multicastIP)) == sizeof(buf))
       {
          printf("Sent a %i-byte multicast packet!\n", (int) sizeof(buf));
       }
       else perror("sendto");

       sleep(1);
   }

   return 0;
}


Q:

Retrieve folders and sub folders from document library by REST call

I need to get a list of folders and sub folders from document library. I feel that approaching this problem using REST call would be easier than the traditional CSOM query. Please suggest a relevant approach and solution.

A:

You could utilize GetItems method and specify the following query:
<View Scope="RecursiveAll">
     <Query>
         <Where>
            <Eq>
               <FieldRef Name="FSObjType" /><Value Type="Integer">1</Value>
            </Eq>
         </Where>
     </Query>
</View>

to return all folder items in a library.
Example
function getListItems(webUrl,listTitle, viewXml)
{
    var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getitems";
    var queryPayload = {
               'query' : {
                      '__metadata': { 'type': 'SP.CamlQuery' },
                      'ViewXml' : viewXml
               }
    };

    return $.ajax({
           url: url,
           method: "POST",
           contentType: "application/json;odata=verbose",
           data: JSON.stringify(queryPayload),
           headers: {
              "X-RequestDigest": $("#__REQUESTDIGEST").val(),
              "Accept": "application/json; odata=verbose"
           }
     });
}

function getAllFolderItems(webUrl,listTitle)
{
    var viewXml = '<View Scope="RecursiveAll"><Query><Where><Eq><FieldRef Name="FSObjType" /><Value Type="Integer">1</Value></Eq></Where></Query></View>';
    return getListItems(webUrl,listTitle,viewXml);
}

Usage
//print folder names from Documents library
getAllFolderItems(_spPageContextInfo.webAbsoluteUrl,'Documents')
.done(function(data)
{
     var items = data.d.results;
     for(var i = 0; i < items.length;i++) {
         console.log(items[i].Title);
     }
})
.fail(
function(error){
    console.log(JSON.stringify(error));
});

A:

Recently I answered a very similar question here. If you need all of the folders and subfolders (but no documents) recursively from a document library, that is what you should use (send it via POST to the server due to GetItems method call):
/_api/web/Lists/GetByTitle('Title of your doc. lib.')/GetItems(query=@v1)?$expand=Folder&$select=Title,Folder/ServerRelativeUrl&@v1={"ViewXml":"<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='FSObjType' /><Value Type='Integer'>1</Value></Eq></Where></Query></View>"}

Alternatively, you could use the following REST query as well (via HTTP GET):
/_api/web/Lists/GetByTitle('Title of your doc. lib.')/Items?$expand=Folder&$select=Title,Folder/ServerRelativeUrl

It will return all of the items (documents and folders) in you library, you should filter them on the client side based on the FileSystemObjectType property, as you can't use this one in the $filter expression in REST (see details here).
Last, but not least, you can use the SharePoint 2010 compatible REST Interface as shown in option 3:
/_vti_bin/listdata.svc/YourDocLib?$filter=ContentType eq 'Folder'

Note, that the syntax is language-specific in this case. The query above is OK for English, but for German it would be:
/_vti_bin/listdata.svc/YourDocLib?$filter=Inhaltstyp eq 'Ordner'


Q:

Pass multiple values to a single parameter in PL/SQL and insert them into a table

I want to pass a multiple values like '1,2,3,4,5,6,7,8,9,10,11,12' on as a single parameter and insert them into a table.
I have a scenario like saving a bill for particular customer, the customer might have purchased multiple items.

A:

You can pass the values comma separated.  This PL/SQL procedure breaks up a comma-separated string (passed as P_VALUE) and inserts each token into a table as a separate row, along with some other values.
PROCEDURE XXXXGL_INST_PARAMS (P_VALUE VARCHAR2) IS
    i          number;
    n          number;
    r          number;
    pos        number;
    L_NAT_ACCT varchar2(10);
    L_UID      number;
BEGIN
    L_UID := fnd_global.user_id;
    n := length(P_VALUE);
    i := 1;
    r := 1;

    WHILE (i < n) LOOP
        pos := (INSTR(P_VALUE,',',1,r)-i);
        IF pos < 0 THEN
            pos := n;
        END IF;
        SELECT substr(P_VALUE,i,pos) INTO L_NAT_ACCT FROM dual;

        INSERT INTO xxXXX.xxXXXgl_natural_accts_t
            (NATURAL_ACCT, CREATION_DATE, CREATED_BY, LAST_UPDATE_LOGIN,
             LAST_UPDATE_DATE, LAST_UPDATED_BY)
          VALUES(L_NAT_ACCT,SYSDATE,L_UID,L_UID,SYSDATE,L_UID);

        i := i + length(L_NAT_ACCT)+1;
        r := r+1;
    END LOOP;
END;

Note: I found this here.


Q:

Gunicorn and Django South incompatibility?

I tried installing and using gunicorn for my Django website, but I am running into this error:
$ python manage.py run_gunicorn
2012-12-19 01:46:50 [6877] [INFO] Starting gunicorn 0.16.1
2012-12-19 01:46:50 [6877] [INFO] Listening at: http://127.0.0.1:8000 (6877)
2012-12-19 01:46:50 [6877] [INFO] Using worker: sync
2012-12-19 01:46:50 [6878] [INFO] Booting worker with pid: 6878
2012-12-19 01:46:51 [6878] [ERROR] Exception in worker process:
Traceback (most recent call last):
  File "... project folder .../venv/lib/python2.7/site-packages/gunicorn/arbiter.py", line 469, in spawn_worker
    worker.init_process()
  File "... project folder .../venv/lib/python2.7/site-packages/gunicorn/workers/base.py", line 100, in init_process
    self.wsgi = self.app.wsgi()
  File "... project folder .../venv/lib/python2.7/site-packages/gunicorn/app/base.py", line 99, in wsgi
    self.callable = self.load()
  File "... project folder .../venv/lib/python2.7/site-packages/gunicorn/app/djangoapp.py", line 134, in load
    return mod.make_command_wsgi_application(self.admin_media_path)
  File "... project folder .../venv/lib/python2.7/site-packages/gunicorn/app/django_wsgi.py", line 116, in make_command_wsgi_application
    return AdminMediaHandler(make_wsgi_application(), admin_mediapath)
  File "... project folder .../venv/lib/python2.7/site-packages/gunicorn/app/django_wsgi.py", line 36, in make_wsgi_application
    if get_validation_errors(s):
  File "... project folder .../venv/lib/python2.7/site-packages/django/core/management/validation.py", line 35, in get_validation_errors
    for (app_name, error) in get_app_errors().items():
  File "... project folder .../venv/lib/python2.7/site-packages/django/db/models/loading.py", line 146, in get_app_errors
    self._populate()
  File "... project folder .../venv/lib/python2.7/site-packages/django/db/models/loading.py", line 61, in _populate
    self.load_app(app_name, True)
  File "... project folder .../venv/lib/python2.7/site-packages/django/db/models/loading.py", line 78, in load_app
    models = import_module('.models', app_name)
  File "... project folder .../venv/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module
    __import__(name)
  File "... project folder .../venv/lib/python2.7/site-packages/south/models.py", line 2, in <module>
    from south.db import DEFAULT_DB_ALIAS
  File "... project folder .../venv/lib/python2.7/site-packages/south/db/__init__.py", line 81, in <module>
    db = dbs[DEFAULT_DB_ALIAS]
KeyError: 'default'
Traceback (most recent call last):
  File "... project folder .../venv/lib/python2.7/site-packages/gunicorn/arbiter.py", line 469, in spawn_worker
    worker.init_process()
  File "... project folder .../venv/lib/python2.7/site-packages/gunicorn/workers/base.py", line 100, in init_process
    self.wsgi = self.app.wsgi()
  File "... project folder .../venv/lib/python2.7/site-packages/gunicorn/app/base.py", line 99, in wsgi
    self.callable = self.load()
  File "... project folder .../venv/lib/python2.7/site-packages/gunicorn/app/djangoapp.py", line 134, in load
    return mod.make_command_wsgi_application(self.admin_media_path)
  File "... project folder .../venv/lib/python2.7/site-packages/gunicorn/app/django_wsgi.py", line 116, in make_command_wsgi_application
    return AdminMediaHandler(make_wsgi_application(), admin_mediapath)
  File "... project folder .../venv/lib/python2.7/site-packages/gunicorn/app/django_wsgi.py", line 36, in make_wsgi_application
    if get_validation_errors(s):
  File "... project folder .../venv/lib/python2.7/site-packages/django/core/management/validation.py", line 35, in get_validation_errors
    for (app_name, error) in get_app_errors().items():
  File "... project folder .../venv/lib/python2.7/site-packages/django/db/models/loading.py", line 146, in get_app_errors
    self._populate()
  File "... project folder .../venv/lib/python2.7/site-packages/django/db/models/loading.py", line 61, in _populate
    self.load_app(app_name, True)
  File "... project folder .../venv/lib/python2.7/site-packages/django/db/models/loading.py", line 78, in load_app
    models = import_module('.models', app_name)
  File "... project folder .../venv/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module
    __import__(name)
  File "... project folder .../venv/lib/python2.7/site-packages/south/models.py", line 2, in <module>
    from south.db import DEFAULT_DB_ALIAS
  File "... project folder .../venv/lib/python2.7/site-packages/south/db/__init__.py", line 81, in <module>
    db = dbs[DEFAULT_DB_ALIAS]
KeyError: 'default'
2012-12-19 01:46:51 [6878] [INFO] Worker exiting (pid: 6878)
2012-12-19 01:46:51 [6877] [INFO] Shutting down: Master
2012-12-19 01:46:51 [6877] [INFO] Reason: Worker failed to boot.

I found this question which has a similar error, but my DATABASES dict inside settings.py seems correct:
DATABASES = {
    'default': {
        'ENGINE': 'postgresql_psycopg2',
        ...
    }
}

I've put gunicorn into my INSTALLED_APPS. runserver works just fine. south seems so work fine by itself as well.
I managed to get gunicorn working by commenting out south in my INSTALLED_APPS. I guess that can do for when I deploy to production. What is happening?
(For what it's worth, I'm using Django 1.3.2)

A:

Try to use the full path for database backend:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        ...
    }
}


Q:

xunit core in try catch block is not working right

[Duplicated]Assert in Try..Catch block is caught
When I using Xunit Core in NetCore1.1 in VS2017 as folllow:

     try
        {
            Assert.True(1<0," server is false");//vs2017 show green(test through)

        }
        catch (Exception e)
        {
            while (e != null)
            {
                _outputHelper.WriteLine(e.Message);
                e = e.InnerException;
            }
        }

        Assert.True(1 < 0, "current value is false");// vs2017 show red(test failed

The result is that the icon is green, not red when the first Assert.True it not right(failed).like that  as follow:

if add second  Assert.True it's red;
)
It is very odd, Is that right? I think that's a bug.

A:

This is not a bug.
All unit test frameworks, including xUnit.net, use exceptions for failing assertions. You have blindly caught and swallowed all exceptions; this would include the exception for the failed assertion.
It's also really not clear what you're trying to accomplish with this code. Maybe this was a simplification for the purposes of illustration...?


Q:

Spermatozoan or spermatozoal?

Spermatozoon is a single mature sperm cell. The plural is spermatozoa.
Which of the following is correct: "Spermatozoal motility" or "spermatozoan motility"? Or should it be something else?
Googling seems to find both "spermatozoal" and "spermatozoan".

A:

According to Pubmed:

spermatozoan motility yields 19 results
spermatozoic motility yields 0
spermatozoal motility yields 45
sperm motility yields 1399

Based on the wider usage, the breadth of journals it's used in, and the more recent use (several in press articles) "sperm motility" is the most popular.
None of the terms seem completely inappropriate, though the low use of spermatozoic (and only use in non-English journals in the 1950s), suggest it may best be avoided.
I think Pubmed is more informative than the dictionary in this case.

Pubmed searches were for the above terms in title of articles.
Edit: Added sperm motility as mentioned by @FumbleFingers, which is the clear winner.


Q:

Get UTF8.GetBytes from very large stringbuilder

I have a StringBuilder of length 1,539,121,968. When calling StringBuilder .ToString() on it fails with OutOfMemoryException. I tried creating a char array but was not allowed to create such big array.
I need to store it a byte array in UTF8 format. Is it possible?

A:

I'd suggest looking at the documentation for streams. As this might help.
Another way to approach it would be to split it up. As for your last comment stating that you wish to store it as a ByteArray with UTF8 you'd need a char[] as else you'd lose your encoding. I'd reccomend splitting it into many smaller strings (or char[]s) stored in separate objects that can easily be reconstructed. Something like this might suffice, create many StringSlices:
public class StringSlice()
{
     public Str {get;}
     public Index {get;}
     public StringSlice(string str, int index)
         {
              this.Str = str;
              this.Index = index;
         }

     public static List<string> ReconstructString(IEnumerable<StringSlice> parts)
         {
              //Sort input by index return list with new strings in order. Probably have to use a buffer on the disc so as not to breach 2GB obj limit.
         }
}

In essence what you would be doing here is similar to the way internet packets are split and reconstructed. I'm not entirely sure if I've answered your question but hopefully this comes some way to helping.


Q:

Why my strings can't be sorted like i want when i insert values from textview?

i have counter which count how many times i click a button.
public void onClick(View v) {

            counter++;
             text.setText("Score"+counter);

        }

then i insert to my DB this values
     text = (TextView) findViewById(R.id.textView1);
                final String Score = text.getText().toString();
                mySQLiteAdapter.openToWrite();

                mySQLiteAdapter.insert("sccore="Score);

                mySQLiteAdapter.close();

this is my insert function
public long insert(String content){
    ContentValues contentValues = new ContentValues();
    contentValues.put(KEY_CONTENT, content);
    return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);
}

So counter values which were inserted was-> Score = 2 ,Score = 1 ,Score = 111, Score = 3, Score = 21 <--(its counter values)
then i want to see this scores in another texview so:
 mySQLiteAdapter = new SQLiteAdapter(this);
    /*
     *  Open the same SQLite database
     *  and read all it's content.
     */
    mySQLiteAdapter = new SQLiteAdapter(this);
    mySQLiteAdapter.openToRead();
    String contentRead = mySQLiteAdapter.queueAll();
    listContent.setText(contentRead);
    mySQLiteAdapter.close();

my fucntion queueAll() looks like:
public String queueAll(){
    String[] columns = new String[]{KEY_CONTENT};
    Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
            null, null, null, null, KEY_CONTENT+" desc");
    String result = "";

    int index_CONTENT = cursor.getColumnIndex(KEY_CONTENT);
    for(cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()){
        result = result + cursor.getString(index_CONTENT) + "\n";
    }

    return result;
}

ok and in text view i saw this:
Score = 3  ,  Score=21 , Score=2 , Score=111, Score=1

but i want
score=111, score=21, score=3, score=2, score=1.

Why Order By DESC didnt sort this like i want in DESC? Why it thinks like this? Why My inserted counter values are not sorted DESC?
public static final String MYDATABASE_NAME = "MY_DATABASE";
public static final String MYDATABASE_TABLE = "MY_TABLE";
public static final int MYDATABASE_VERSION = 1;
public static final String KEY_CONTENT = "Content";

//create table MY_DATABASE (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE =
    "create table " + MYDATABASE_TABLE + " ("
    + KEY_CONTENT + " text not null);";

To be honest my column KEY_CONTENT should be NUMBER not STRING. How to change this?
When i change str to num will order by DESC work as i want ?

A:

You stored your numbers as text so you get the alphabetical sorting order.
You can convert your numbers to integer when you query:
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
        null, null, null, null, "CAST(" + KEY_CONTENT + " as integer) desc");


Q:

Unity Container: use ContainerControlledLifetimeManager by default for "Resolve" method group

How to fill TODO to make this test pass?
class MyClass { }

[Test]
public void Singleton_by_default_test()
{
    var parentContainer = GetUnityContainer();
    var container = parentContainer.GetChildContainer();

    // TODO: Add magic here (but do NOT explicitly register MyClass in container!)

    Assert.AreSame(container.Resolve<MyClass>(), container.Resolve<MyClass>());
}

Update:
There is a way that uses inheritance.
public class SingletonContainer : UnityContainer
{
    public override object Resolve(Type t, string name)
    {
        var obj = base.Resolve(t, name);
        RegisterInstance(t, name, obj, new ContainerControlledLifetimeManager());
        return obj;
    }
}

I am using container.GetChildContainer() to get container instance so this method does not suite me.

A:

I see where you are going with this.  Interesting problem.
I think you can do what you are doing with a Unity Behavior Extension.  Here's a great article on the design of Unity that describes the job of certain elements of Unity that a lot of people don't know about:
http://msdn.microsoft.com/en-us/library/dd140062.aspx
The Unity Container basically uses a "strategy chain" when handling a resolve request.  One of the strategies in the chain is the LifetimeStrategy.
The easiest thing to do would be to create a new strategy and insert it in the chain before the LifetimeStrategy so that when your strategy gets a chance to look at the type, it can register a ContainerControlledLifetimeManager for that type in the current container. It will get to the LifetimeStrategy and there will already be a ContainerControlledLifetimeManager registered for that type.
It might look like this:
public class MakeEverythingSingletonStrategy : BuilderStrategy
{
     public override void PreBuildUp(IBuilderContext context)
     {
          Type objectType = BuildKey.GetType(context.BuildKey);
          context.PersistentPolicies.Set<ILifetimePolicy>(
                  new SingletonLifetimePolicy(),
                  context.BuildKey);

     }
}

You should be able to apply this configuration to the sub container using the Configure<T> method, passing in a configuration class that adds this new extension.
I found a good sample of someone on Stackoverflow implementing a custom BuilderStrategy:
Custom object factory extension for Unity


Q:

Floating point inaccuracy examples

How do you explain floating point inaccuracy to fresh programmers and laymen who still think computers are infinitely wise and accurate?
Do you have a favourite example or anecdote which seems to get the idea across much better than an precise, but dry, explanation?
How is this taught in Computer Science classes?

A:

There are basically two major pitfalls people stumble in with floating-point numbers.

The problem of scale. Each FP number has an exponent which determines the overall “scale” of the number so you can represent either really small values or really larges ones, though the number of digits you can devote for that is limited. Adding two numbers of different scale will sometimes result in the smaller one being “eaten” since there is no way to fit it into the larger scale.
PS> $a = 1; $b = 0.0000000000000000000000001
PS> Write-Host a=$a b=$b
a=1 b=1E-25
PS> $a + $b
1

As an analogy for this case you could picture a large swimming pool and a teaspoon of water. Both are of very different sizes, but individually you can easily grasp how much they roughly are. Pouring the teaspoon into the swimming pool, however, will leave you still with roughly a swimming pool full of water.
(If the people learning this have trouble with exponential notation, one can also use the values 1 and 100000000000000000000 or so.)
Then there is the problem of binary vs. decimal representation. A number like 0.1 can't be represented exactly with a limited amount of binary digits. Some languages mask this, though:
PS> "{0:N50}" -f 0.1
0.10000000000000000000000000000000000000000000000000

But you can “amplify” the representation error by repeatedly adding the numbers together:
PS> $sum = 0; for ($i = 0; $i -lt 100; $i++) { $sum += 0.1 }; $sum
9,99999999999998

I can't think of a nice analogy to properly explain this, though. It's basically the same problem why you can represent 1/3 only approximately in decimal because to get the exact value you need to repeat the 3 indefinitely at the end of the decimal fraction.
Similarly, binary fractions are good for representing halves, quarters, eighths, etc. but things like a tenth will yield an infinitely repeating stream of binary digits.
Then there is another problem, though most people don't stumble into that, unless they're doing huge amounts of numerical stuff. But then, those already know about the problem. Since many floating-point numbers are merely approximations of the exact value this means that for a given approximation f of a real number r there can be infinitely many more real numbers r1, r2, ... which map to exactly the same approximation. Those numbers lie in a certain interval. Let's say that rmin is the minimum possible value of r that results in f and rmax the maximum possible value of r for which this holds, then you got an interval [rmin, rmax] where any number in that interval can be your actual number r.
Now, if you perform calculations on that number—adding, subtracting, multiplying, etc.—you lose precision. Every number is just an approximation, therefore you're actually performing calculations with intervals. The result is an interval too and the approximation error only ever gets larger, thereby widening the interval. You may get back a single number from that calculation. But that's merely one number from the interval of possible results, taking into account precision of your original operands and the precision loss due to the calculation.
That sort of thing is called Interval arithmetic and at least for me it was part of our math course at the university.

A:

Show them that the base-10 system suffers from exactly the same problem.
Try to represent 1/3 as a decimal representation in base 10. You won't be able to do it exactly.
So if you write "0.3333", you will have a reasonably exact representation for many use cases.
But if you move that back to a fraction, you will get "3333/10000", which is not the same as "1/3".
Other fractions, such as 1/2 can easily be represented by a finite decimal representation in base-10: "0.5"
Now base-2 and base-10 suffer from essentially the same problem: both have some numbers that they can't represent exactly.
While base-10 has no problem representing 1/10 as "0.1" in base-2 you'd need an infinite representation starting with "0.000110011..".

A:

How's this for an explantation to the layman.  One way computers represent numbers is by counting discrete units. These are digital computers.  For whole numbers, those without a fractional part, modern digital computers count powers of two: 1, 2, 4, 8. ,,,  Place value, binary digits, blah , blah, blah.  For fractions, digital computers count inverse powers of two: 1/2, 1/4, 1/8, ...  The problem is that many numbers can't be represented by a sum of a finite number of those inverse powers.  Using more place values (more bits) will increase the precision of the representation of those 'problem' numbers, but never get it exactly because it only has a limited number of bits.  Some numbers can't be represented with an infinite number of bits.
Snooze...
OK, you want to measure the volume of water in a container, and you only have 3 measuring cups: full cup, half cup, and quarter cup.  After counting the last full cup, let's say there is one third of a cup remaining.  Yet you can't measure that because it doesn't exactly fill any combination of available cups.  It doesn't fill the half cup, and the overflow from the quarter cup is too small to fill anything. So you have an error - the difference between 1/3 and 1/4.  This error is compounded when you combine it with errors from other measurements.


Q:

Excel change table Range for each month

I'm currently facing a problem in Excel. I'm trying to make a list, where I can track how often each employee is out of office (put in manually, for each day).
This is not a big issue, I managed to do that with this formula:
=SUMPRODUCT(COUNTIF($F$8:$AJ$8;$B$19:$B$21&""))

The Problem I'm facing is, that I have a fixed range 31(days). If a month only has 30 days/28 days, it will show 1(3) days of the next month. Because of that, percentage calculations are messed up.
Is there a way to change the range of the formula, if a month has less than 31 days?

Is there a way to change the formula, to ignore the days of the next month?

A:

I would use a formula like so
=SUM(OFFSET($B$1,MATCH(G8,$A$1:$A$19,0)-1,(EOMONTH(TODAY(),-1)-DATE(2017,1,1))+1,1,DAY(EOMONTH(TODAY(),0)))) based on your example
Something like this for the data


Q:

Cannot deserialize a JSON object

here's my JSON data
[
    {
        "market_id": "21",
        "coin": "DarkCoin",
        "code": "DRK",
        "exchange": "BTC",
        "last_price": "0.01777975",
        "yesterday_price": "0.01770278",
        "change": "+0.43",
        "24hhigh": "0.01800280",
        "24hlow": "0.01752015",
        "24hvol": "404.202",
        "top_bid": "0.01777975",
        "top_ask": "0.01790000"
    }
]

Here's my class
public class Model_MarketStats
{
    [JsonProperty(PropertyName="market_id")]
    public string market_id { get; set; }
    [JsonProperty(PropertyName = "code")]
    public string code { get; set; }
    [JsonProperty(PropertyName = "exchange")]
    public string exchange { get; set; }
    [JsonProperty(PropertyName = "last_price")]
    public string last_price { get; set; }
    [JsonProperty(PropertyName = "yesterday_price")]
    public string yesterday_price { get; set; }
    [JsonProperty(PropertyName = "change")]
    public string change { get; set; }
    [JsonProperty(PropertyName = "24hhigh")]
    public string highest { get; set; }
    [JsonProperty(PropertyName = "24hlow")]
    public string lowest { get; set; }
    [JsonProperty(PropertyName = "24hvol")]
    public string volume { get; set; }
    [JsonProperty(PropertyName = "top_bid")]
    public string top_bid { get; set; }
    [JsonProperty(PropertyName = "top_ask")]
    public string top_ask { get; set; }
}

The error said

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'MintpalAPI.Model_MarketStats_Root' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
  To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.

This is the way I desialize the JSON
Model_MarketStats = JsonConvert.DeserializeObject<Model_MarketStats>(json);

A:

You json is an array, use
var stats = JsonConvert.DeserializeObject<List<Model_MarketStats>>(json);


Q:

Is the pass-by-value-and-then-move construct a bad idiom?

Since we have move semantics in C++, nowadays it is usual to do
void set_a(A a) { _a = std::move(a); }

The reasoning is that if a is an rvalue, the copy will be elided and there will be just one move.
But what happens if a is an lvalue? It seems there will be a copy construction and then a move assignment (assuming A has a proper move assignment operator). Move assignments can be costly if the object has too many member variables.
On the other hand, if we do
void set_a(const A& a) { _a = a; }

There will be just one copy assignment. Can we say this way is preferred over the pass-by-value idiom if we will pass lvalues?

A:

Expensive-to-move types are rare in modern C++ usage. If you are concerned about the cost of the move, write both overloads:
void set_a(const A& a) { _a = a; }
void set_a(A&& a) { _a = std::move(a); }

or a perfect-forwarding setter:
template <typename T>
void set_a(T&& a) { _a = std::forward<T>(a); }

that will accept lvalues, rvalues, and anything else implicitly convertible to decltype(_a) without requiring extra copies or moves.
Despite requiring an extra move when setting from an lvalue, the idiom is not bad since (a) the vast majority of types provide constant-time moves and (b) copy-and-swap provides exception safety and near-optimal performance in a single line of code.

A:

But what happens if a is an lvalue? It seems there will be a copy
  construction and then a move assignment (assuming A has a proper move
  assignment operator). Move assignments can be costly if the object has
  too many member variables.

Problem well spotted. I wouldn't go as far as to say that the pass-by-value-and-then-move construct is a bad idiom but it definitely has its potential pitfalls.
If your type is expensive to move and / or moving it is essentially just a copy, then the pass-by-value approach is suboptimal. Examples of such types would include types with a fixed size array as a member: It may be relatively expensive to move and a move is just a copy. See also

Small String Optimization and Move Operations and
"Want speed? Measure." (by Howard Hinnant)

in this context.
The pass-by-value approach has the advantage that you only need to maintain one function but you pay for this with performance. It depends on your application whether this maintenance advantage outweighs the loss in performance.
The pass by lvalue and rvalue reference approach can lead to maintenance headaches quickly if you have multiple arguments. Consider this:
#include <vector>
using namespace std;

struct A { vector<int> v; };
struct B { vector<int> v; };

struct C {
  A a;
  B b;
  C(const A&  a, const B&  b) : a(a), b(b) { }
  C(const A&  a,       B&& b) : a(a), b(move(b)) { }
  C(      A&& a, const B&  b) : a(move(a)), b(b) { }
  C(      A&& a,       B&& b) : a(move(a)), b(move(b)) { }
};

If you have multiple arguments, you will have a permutation problem. In this very simple example, it is probably still not that bad to maintain these 4 constructors. However, already in this simple case, I would seriously consider using the pass-by-value approach with a single function
C(A a, B b) : a(move(a)), b(move(b)) { }
instead of the above 4 constructors.
So long story short, neither approach is without drawbacks. Make your decisions based on actual profiling information, instead of optimizing prematurely.

A:

For the general case where the value will be stored, the pass-by-value only is a good compromise-
For the case where you know that only lvalues will be passed (some tightly coupled code) it's unreasonable, unsmart.
For the case where one suspects a speed improvement by providing both, first THINK TWICE, and if that didn't help, MEASURE.
Where the value will not be stored I prefer the pass by reference, because that prevents umpteen needless copy operations.
Finally, if programming could be reduced to unthinking application of rules, we could leave it to robots. So IMHO it's not a good idea to focus so much on rules. Better to focus on what the advantages and costs are, for different situations. Costs include not only speed, but also e.g. code size and clarity. Rules can't generally handle such conflicts of interest.


Q:

Group Expression Relating to Cosets

I have a simple question about cosets that is evading me if anybody can provide a hand. I don't think the title informs the question much so if anybody can rephrase the title for me that would be appreciated.
Question
Is it true that for any subgroup $H$ of a finite group $G$, $\exists x \in G$ such that $G = \bigcup\limits_{i=0}^{|H|-1}x^iH$?

A:

If the subgroup $H$ happens to be normal (and assuming that the exponent $i$ should range from $0$ to $|G|/|H| - 1$ instead, which is the most number if we are just counting the number of elements), then what you are asking is equivalent to the quotient group $G/H$ being cyclic. And this is just not true in general.

A:

No, it is not true. Let $G$ be a non-trivial finite group and let $H=\{e_G\}$. Then your assertion means that, for some $x\in G$, $G=e_G\{e_G\}=\{e_G\}$.


Q:

Closing document without closing application in MS Word 2010

In pre-ribbon versions of Word you there was an 'X' that would show when you opened a document that would close it without closing the application.  I was placed right underneath the closing 'X' that closed the application.
In Microsoft Word 2010, I don't see that 'X', I only have the 'X' to close the application.
Is there some trick I don't know about to do a one-click close of the document?

A:

Click File > Close, right there under Open and Save. Does exactly what you want, it just takes an extra step than in previous versions. Leaves Word running with no document open.
If you want it to be one-click, add Close to the Quick Access Toolbar at the top. Click on the dropdown, then choose More Commands.

Under Choose Commands From, select File Tab, then select Close and click the Add >> button.

Now, just click on that close button, and the document will be closed but the Word window will remain open.

A:

You should be able to press CTRL-W on your keyboard to "close the child window" (your document).

A:

My solution was to assign a variable to the number of open documents. Close the active document without saving. Then test to see if the number of open documents had been greater than 1. If it was, the macro stopped, leaving other active documents open. If the number = 1 then Word closed.
Sub CloseWithoutSave()

  x = Documents.Count
  ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
  If x = 1 Then Application.Quit

End Sub


Q:

Distinguishing sign of zero : -float64(0) from float64(0) in Go

I want to serialize a floating point in such a way that sign info is not lost.  Specifically, I would like to distinguish IEEE-754 negative zero from regular zero.
The language spec says

The result of a floating-point division by zero is not specified beyond the IEEE-754 standard; whether a run-time panic occurs is implementation-specific.

which suggests that I cannot do
n == 0 && (float64(1) / n) < 0

and I tried math.Copysign and math.Signbit which says

func Signbit(x float64) bool

Signbit returns true if x is negative or negative zero.

but
n == 0 && math.Signbit(n)

doesn't seem to work for
n := -float64(0)

Any ideas?
EDIT:
I filed issue 2196 to track what I think is a confusing difference between
nz := -float64(0)

and
pz := float64(0)
nz := -pz

as suggested by peterSO.

A:

I couldn't get the go playground ( http://golang.org/doc/play/ ) to generate a -0 from literally typing it in source; I'd speculate the compiler converts it to 0.
However, I could generate a -0 like this:
fmt.Println(0);
fmt.Println(-0);
hmm := -1 / math.Inf(1);
fmt.Println(math.Signbit(hmm));
fmt.Println(hmm);

Prints:
0
0
true
-0

A:

package main

import (
    "fmt"
    "math"
)

func main() {
    pz := float64(0)
    nz := -pz
    fmt.Println(pz, math.Signbit(pz), nz, math.Signbit(nz))
    if n := nz; n == 0 && math.Signbit(n) {
        fmt.Println("n is negative zero:", n)
    }
}

Output:
0 false -0 true
n is negative zero: -0


Q:

Invalid JSON was returned from the route. Perhaps an exception was thrown?

I've been working on adding JWT authentication to my Lumen API. Please bare in mind I am new to Lumen, API design and TDD.  Before adding the authentication all of tests were passing. Honestly, everything seems to be working just fine except when I run phpunit.  What's difficult to understand is when I run the same test in postman I have no issues, however when I dump the response in phpunit i get NULL.  Perhaps a fresh set of eyes can help me out?
I've added the jwt.auth middleware to my restricted routes:
routes.php
// all other code omitted

$app->group([
  'prefix'     => $version . '/authors',
  'middleware' => 'jwt.auth',
  'namespace'  => 'App\Http\Controllers',
], function ($app) {

  $app->get('/{id:[\d]+}', ['as' => 'authors.show', 'uses' => 'AuthorsController@show']);

});

Part of my controller is as follows:
AuthorsController.php
class AuthorsController extends Controller
{

  // all other code omitted

  public function show($id)
  {
    return $this->item(Author::findOrFail($id), new AuthorTransformer());
  }

}

My model is as follows
Author.php
class Author extends Model
{
/**
 * The attributes that are mass assignable
 *
 * @var array
 */
  protected $fillable = ['name', 'biography', 'gender'];

  public function books()
  {
    return $this->hasMany(Book::class);
  }
}

And my Transformer is as follows:
AuthorTransformer.php
class AuthorTransformer extends TransformerAbstract
{

  protected $availableIncludes = [
    'books',
  ];

  public function includeBooks(Author $author)
  {
    return $this->collection($author->books, new BookTransformer());
  }

  /**
   * Transform an author model
   *
   * @param Author $author
   * @return array
   */
  public function transform(Author $author)
  {
    return [
      'id'        => $author->id,
      'name'      => $author->name,
      'gender'    => $author->gender,
      'biography' => $author->biography,
      'created'   => $author->created_at->toIso8601String(),
      'updated'   => $author->created_at->toIso8601String(),
    ];
  }
}

And my tests are as follows:
TestCase.php
class TestCase extends Laravel\Lumen\Testing\TestCase
{

// all other code omitted

/**
 * Convenience method for creating a user
 *
 * @return $user
 */
  protected function userFactory()
  {

    $user = factory(\App\User::class, 1)->create(['password' => app('hash')->make('supersecret')]);

    return $user;
  }

/**
 * Convenience method for getting jwt and authenticating
 *
 * @return $body
 */
  protected function jwtAuthTest($method, $url, $body = [])
  {
    $user = $this->userFactory();

    $token = JWTAuth::fromUser($user);
    JWTAuth::setToken($token);
    $headers = array(
      "Accept"        => "application/json",
      "Authorization" => "Bearer " . $token,
    );

    switch ($method) {
      case 'get':
        $this->get($url, $body, $headers);
        break;
      case 'post':
        $this->post($url, $body, $headers);
        break;
      case 'put':
        $this->put($url, $body, $headers);
        break;
      case 'patch':
        $this->patch($url, $body, $headers);
        break;
      case 'delete':
        $this->delete($url, $body, $headers);
        break;
    }

    $data = json_decode($this->response->getContent(), true);

    return $data;
  }

}

AuthorsControllerTest.php
class AuthorsControllerTest extends TestCase
{

  // all other code omitted

/** @test **/
  public function show_should_fail_on_an_invalid_author()
  {
    $body = $this->jwtAuthTest('get', '/v1/authors/1234');

    // this works fine...
    $this->seeStatusCode(Response::HTTP_NOT_FOUND);

    // NULL??
    var_dump($body);
  }
}

My response should be:
{
  "error": {
    "message": "Not Found",
    "status": 404
  }
}

However I am getting NULL
When I test the same route with a valid token in Postman I get, which is what I'm expected in my tests:
{
  "error": {
    "message": "Not Found",
    "status": 404
  }
}

Suddenly my route is returning null in phpunit tests.  I can't seem to figure out why?
My handler is as follows:
// all other code omitted
class Handler extends ExceptionHandler
{
  /**
   * A list of the exception types that should not be reported.
   *
   * @var array
   */
  protected $dontReport = [
    AuthorizationException::class,
    HttpException::class,
    ModelNotFoundException::class,
    ValidationException::class,
  ];

  /**
   * Report or log an exception.
   *
   * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
   *
   * @param  \Exception  $e
   * @return void
   */
  public function report(Exception $e)
  {
    parent::report($e);
  }

  /**
   * Render an exception into an HTTP response.
   *
   * @param  \Illuminate\Http\Request  $request
   * @param  \Exception  $e
   * @return \Illuminate\Http\Response
   */
  public function render($request, Exception $e)
  {
    if ($request->wantsJson()) {
      $response = [
        'message' => (string) $e->getMessage(),
        'status'  => 400,
      ];

      if ($e instanceof HttpException) {
        $response['message'] = Response::$statusTexts[$e->getStatusCode()];
        $response['status']  = $e->getStatusCode();
      } else if ($e instanceof ModelNotFoundException) {
        $response['message'] = Response::$statusTexts[Response::HTTP_NOT_FOUND];
        $response['status']  = Response::HTTP_NOT_FOUND;
      }

      if ($this->isDebugMode()) {
        $response['debug'] = [
          'exception' => get_class($e),
          'trace'     => $e->getTrace(),
        ];
      }

      return response()->json(['error' => $response], $response['status']);
    }

    return parent::render($request, $e);

  }

}

When my test fails I get:
There was 1 failure:

1) Tests\App\Http\Controllers\AuthorsControllerTest::show_should_fail_on_an_invalid_author
Invalid JSON was returned from the route. Perhaps an exception was thrown?

Please let me know if you need anything else and thank you in advance.
Source code: https://github.com/studio174/gscp

A:

The issue is in the TestCase.php there was a simple naming collision and invalid use of the get() method:
TestCase.php
/**
 * Convenience method for getting jwt and authenticating
 *
 * @return $body
 */
  protected function jwtAuthTest($method, $url, $body = [])
  {
    $user = $this->userFactory();

    $token = JWTAuth::fromUser($user);
    JWTAuth::setToken($token);
    $headers = array(
      "Accept"        => "application/json",
      "Authorization" => "Bearer " . $token,
    );

    switch ($method) {
      case 'get':
        // [FIX] removed $body from get request as this was overwriting my headers
        // and causing my handler to return plain text instead of JSON
        $this->get($url,  $headers);
        break;
      case 'post':
        $this->post($url, $body, $headers);
        break;
      case 'put':
        $this->put($url, $body, $headers);
        break;
      case 'patch':
        $this->patch($url, $body, $headers);
        break;
      case 'delete':
        $this->delete($url, $body, $headers);
        break;
    }

    // [FIX] changed $body= json_decode($this->response->getContent(), true);
    $data = json_decode($this->response->getContent(), true);

    return $data;
  }


Q:

Understanding memory consumption of a key in redis

I am running a local redis server. Had one bad key in redis which was occupying lot of memory. Before deleting that key "info memory" was showing 5.3GB as occupied memory.
That bad key occupied around 800MB of data. This is based on "debug object " output.
After deleting that key, the memory almost double that size got freed. The expectation was around 800MB only.
Any ideas as to what is behind this ?
Running on ubuntu.
127.0.0.1:6379[3]> info
# Server
redis_version:2.8.9

127.0.0.1:6379[3]> info memory
# Memory
used_memory:5746884728
used_memory_human:5.35G
used_memory_rss:6382206976
used_memory_peak:8865352096
used_memory_peak_human:8.26G
used_memory_lua:37888
mem_fragmentation_ratio:1.11
mem_allocator:jemalloc-3.2.0

127.0.0.1:6379[3]> debug object c43d3e42-7e63-47f3-bb63-b58a897c29a6
Value at:0x7f77a1db1d10 refcount:1 encoding:linkedlist
serializedlength:814237852 lru:994050 lru_seconds_idle:99559
(5.53s)

127.0.0.1:6379[3]> del c43d3e42-7e63-47f3-bb63-b58a897c29a6
(integer) 1
(1.78s)

127.0.0.1:6379[3]> info memory
# Memory
used_memory:4145366968
used_memory_human:3.86G
used_memory_rss:4375691264
used_memory_peak:8865352096
used_memory_peak_human:8.26G
used_memory_lua:37888
mem_fragmentation_ratio:1.06
mem_allocator:jemalloc-3.2.0

Thanks.

A:

DEBUG OBJECT shows you the serializedlength of the object. It's the size of the serialized data when saving the object on disk in RDB format. It's NOT the size of the object in memory.
When saving data on disk, Redis might compress the data. So normally, the serialized length is smaller than the size of the in-memory object.


Q:

jquery validate doesn't work with multiple forms

I have multiple forms in my web, you can show/hide them depeding on your query, but the jquery validate just work on the first one (Particular).
Here I have my forms: https://www.lokkura.es/contacto2.php clicking on the left panel you will change the form.
Form 1 (jquery validation works here):

            <form id="form" class="form" action="#" method="post">

                <input name="name" type="text" class="validate['required'] textbox1" placeholder="* Nombre : "
                onfocus="this.placeholder = ''" onBlur="this.placeholder = '* Nombre :'" />

                <input name="name" type="text" class="validate['required'] textbox1" placeholder=" Ciudad : "
                onfocus="this.placeholder = ''" onBlur="this.placeholder = '* Ciudad :'" />

                <input name="email" type="text" class="validate['required','email']  textbox1"
                placeholder="* Email : " onFocus="this.placeholder = ''" onBlur="this.placeholder = '* Email :'"/>

                <input name="phone" type="text" class="validate['required']  textbox1"
                placeholder="* Teléfono : " onFocus="this.placeholder = ''" onBlur="this.placeholder = '* Teléfono :'"/>

                <textarea name="message" class="validate['required'] messagebox1"
                placeholder="* Mensaje : " onFocus="this.placeholder = ''" onBlur="this.placeholder = '* Mensaje :'"></textarea>

                <input value="Enviar Mensaje"  name="submit" type="submit" class="submitBtn" />

            </form>

Form 2 (jquery validation does not work here):

                  <form  id="form"  class="form" action="#" method="post">

                <input name="name" type="text" class="validate['required'] textbox1" placeholder="* Nombre : "
                onfocus="this.placeholder = ''" onBlur="this.placeholder = '* Nombre :'" />

                <input name="name" type="text" class="validate['required'] textbox1" placeholder=" Ciudad : "
                onfocus="this.placeholder = ''" onBlur="this.placeholder = '* Ciudad :'" />

                <input name="email" type="text" class="validate['required','email']  textbox1"
                placeholder="* Email : " onFocus="this.placeholder = ''" onBlur="this.placeholder = '* Email :'"/>

                <input name="name" type="text" class="validate['required'] textbox1" placeholder=" Empresa : "
                onfocus="this.placeholder = ''" onBlur="this.placeholder = '* Empresa :'" />

                <input name="name" type="text" class="validate['required'] textbox1" placeholder=" Web de Empresa : "
                onfocus="this.placeholder = ''" onBlur="this.placeholder = '* Web de Empresa :'" />

                <input name="phone" type="text" class="validate['required']  textbox1"
                placeholder="* Teléfono : " onFocus="this.placeholder = ''" onBlur="this.placeholder = '* Teléfono :'"/>

                <textarea name="message" class="validate['required'] messagebox1"
                placeholder="* Mensaje : " onFocus="this.placeholder = ''" onBlur="this.placeholder = '* Mensaje :'"></textarea>

                <input value="Enviar Mensaje"  name="submit" type="submit" class="submitBtn" />

            </form>

Javascript Code:
jQuery(document).ready(function($){
"use strict";
  $('#form').validate(
    {
    rules: {
    name: {
    minlength: 2,
    required: true
    },
    phone: {
    required: true,
    },
    email: {
    required: true,
    email: true
    },
    message: {
    minlength: 2,
    required: true
    }
    },
    highlight: function(element) {
    $(element).closest('.control-group').removeClass('success').addClass('error');
    },
    success: function(element) {
    element
    .text('').addClass('valid')
    .closest('.control-group').removeClass('error').addClass('success');
    },
    submitHandler: function(form) {
                    // do other stuff for a valid form
                    $.post('contact_form.php', $("#form").serialize(), function(data) {
                         // action file is here
                    $('#post-message-contact').html(data);
                    });
                }
    });
    });

A:

You are attaching .validate() to the element with id="form"
$('#form').validate({...

However, you have two form elements with this same id.  You cannot use the same id more than once on a page.  Repeating the id is invalid HTML.  jQuery will only target the first instance.
Even if you used a class instead, the various jQuery Validate methods cannot be attached to selectors that target more than one element at a time.  So again, even if your target correctly selected a group of elements, only the first instance would be used.

1)  You need to fix the invalid HTML by using a unique id on each form.
<form id="form_1" ...

<form id="form_2" ...

2)  You need to construct a selector that targets all elements in this group.  You can use a "starts with" selector to grab every id that "starts with" form_.
$('[id^="form_"]')

3)  You need to enclose your .validate() within a jQuery .each() so that you can apply it to each instance and not just the first.
jQuery(document).ready(function($){

    $('[id^="form_"]').each(function() { // selects all forms with id starting with "form_"
        $(this).validate({ ....          // call 'validate()' method on each one

Alternatively, your .form class would work here too.
jQuery(document).ready(function($){

    $('.form').each(function() {  // selects all forms with class="form"
        $(this).validate({ ....   // call 'validate()' method on each one


Q:

Ajax / Javascript - Refresh one time only

How can i refresh this page one time only not repeating
    function timedRefresh(timeoutPeriod) {
  setTimeout("location.reload(false);",timeoutPeriod);
}

window.onload = timedRefresh(3000);

document.getElementById('myModal').style.display='block';

A:

The problem is that you reload the exact same page so with no way to persist the fact that you already ran that code it will just run it again.
The old-fashioned way of doing this was using cookies:
function timedRefreshIfNoCookie(timeoutPeriod, cookieName) {
    var cookies = document.cookie;
    if (cookies.indexOf(' '+cookieName+'=1;') < 0) {
        document.cookie = cookieName+'=1';
        setTimeout(function () {
            location.reload();
        }, timeoutPeriod);
    }
}
window.onload = function() {
    timedRefreshIfNoCookie(3000, 'refreshed');
}
document.getElementById('myModal').style.display='block';

You can probably use something a bit better like local storage or a cookie library to work with cookies more easily.


Q:

automatic array list swift

import UIKit
var imageArray = [UIImage(named: "f1"),UIImage(named: "f2"),UIImage(named: "f3"),UIImage(named: "f4")]
class Interest
{
    // MARK: - Public API
    var title = ""
    var featuredImage: UIImage
    var color: UIColor

    init(title: String, featuredImage: UIImage, color: UIColor)
    {
        self.title = title
        self.featuredImage = featuredImage
        self.color = color
    }

    // MARK: - Private
    // dummy data
    static func fetchInterests() -> [Interest]
    {
        return [
            Interest(title: "Travelling Around the World", featuredImage: UIImage(named: "f1")!, color: UIColor(red: 63/255.0, green: 71/255.0, blue: 80/255.0, alpha: 0.8)),
            Interest(title: "Cafe with Best Friends", featuredImage: UIImage(named: "f2")!, color: UIColor(red: 240/255.0, green: 133/255.0, blue: 91/255.0, alpha: 0.8)),
            Interest(title: "Study Personal Development Books and Courses", featuredImage: UIImage(named: "f3")!, color: UIColor(red: 105/255.0, green: 80/255.0, blue: 227/255.0, alpha: 0.8)),
            Interest(title: "Build Amazing iOS Apps", featuredImage: UIImage(named: "f4")!, color: UIColor(red: 102/255.0, green: 102/255.0, blue: 102/255.0, alpha: 0.8)),
        ]
    }
}

I want to use array after return statement but I can not , I want to make the example similar
return [
            Interest(title: "Travelling Around the World", featuredImage: UIImage(named: "imageArray[i]")!, color: UIColor(red: 63/255.0, green: 71/255.0, blue: 80/255.0, alpha: 0.8)),

        ]

Automatically add how many elements are in the array

A:

If you want to use the images you stored in the array imageArray inside your return statement you’d have to reference the array like this:
Interest(title: “Title”, featuredImage: imageArray[i], ....

Without the quotation marks. The way you do it now, swift will look for an Image file that’s literally called “imageArray[i]”, which of course doesn’t exist.
To generate Intersts from all images you’d have to iterate over the imageArray and generate your return array dynamically before returning it.
Hope this helps


Q:

Parse error: syntax error, unexpected T_VARIABLE in the for loop

I just have a simple for loop, however I keep getting this error and I cannot figure out what is wrong with the loop. I have researched the error and it is most likely a missing semi-colon or parentheses etc. Something simple...
for ($t=1; $t<=16; ++$t)
{
    $game$t = $_POST["game$t"];
}

A:

The problem is that you did not look up the manual page for the feature that you're trying to use. Something simple, indeed.
I think you're looking for ${game.$t} (not $game$t) in order to create a "family of variables" whose names all share a common prefix:
for ($t=1; $t<=16; ++$t) {
    ${game.$t} = $_POST["game$t"];
}

But I'd really suggest that you use an array instead:
$games = Array();
for ($t=1; $t<=16; ++$t) {
    $games[$t] = $_POST["game$t"];
}


Q:

Flutter how to get all the days of the week as string in the users locale

AS stated in the title: Is there an easy way to get all the days of the week as string(within a list ofcourse) in the users locale?

A:

My suggestion is:
static List<String> getDaysOfWeek([String locale]) {
  final now = DateTime.now();
  final firstDayOfWeek = now.subtract(Duration(days: now.weekday - 1));
  return List.generate(7, (index) => index)
      .map((value) => DateFormat(DateFormat.WEEKDAY, locale)
          .format(firstDayOfWeek.add(Duration(days: value))))
      .toList();
}

The idea is we define the date of the first day in the current week depending on current week day. Then just do loop 7 times starting from calculated date, add 1 day on each iteration and collect the result of DateFormat().format method with pattern DateFormat.WEEKDAY. To increase performance you can use lazy initialization. For example:
/// Returns a list of week days
static List<String> _daysOfWeek;
static List<String> get daysOfWeek {
  if (_daysOfWeek == null) {
    _daysOfWeek = getDaysOfWeek(); // Here you can specify your locale
  }
  return _daysOfWeek;
}


Q:

Moq - It.Is without having to specify all properties

I'm using Moq to test a method, and the method under test takes a json string as an argument, deserialises this into the expected class object, and calls a service with this deserialised class object.
I want to setup my service to expect an instance of the class object in question with the correct values, so that I can verify the step to deserialise the json string to class object works as expected.
Currently, I'm using the It.Is<MyClass>(...) method, however this means that I have to specify every property, and some of the expected objects contain a lot of properties.
public class MyClassTests
{
    private Mock<IMyService> _serviceMock = new Mock<IMyService>();

    public void UnitTest01()
    {
        // Arrange
        MyObject myObject = new MyObject
        {
            SomeProperty01 = "One",
            SomeProperty02 = 2,
            Timestamp = DateTime.Now
        };

        string input = Newtonsoft.Json.JsonConvert.SerializeObject(myObject);

        // *** how can I improve this so I dont have to specify every property? ***

        _serviceMock.Setup(x => x.DoSomething(It.Is<MyObject>(o =>
            o.SomeProperty01 == myObject.SomeProperty01
            && o.SomeProperty02 == myObject.SomeProperty02
            && o.Timestamp == myObject.Timestamp
            )));

        MyClass myClass = new MyClass(_serviceMock.Object);

        // Act
        myClass.DoWork(input);

        // Assert
        _serviceMock.Verify();
    }
}

// The class under test
public class MyClass
{
    private readonly IMyService _myService;

    public MyClass(IMyService myService)
    {
        _myService = myService;
    }

    // The method under test. I want to verify that deserialising works as expected,
    // and that the service is called with the expected argument.
    public void DoWork(string jsonString)
    {
        MyObject deserialised = Newtonsoft.Json.JsonConvert.DeserializeObject<MyObject>(jsonString);

        _myService.DoSomething(deserialised);
    }
}

public class MyService : IMyService
{
    public void DoSomething(MyObject myObject)
    {
        // For the sake of this test, it doesnt matter what this service method does
    }
}

public interface IMyService
{
    void DoSomething(MyObject myObject);
}

public class MyObject
{
    public string SomeProperty01 { get; set; }
    public int SomeProperty02 { get; set; }
    public DateTime Timestamp { get; set; }

    // Loads more properties...
}

Is it possible to do something similar to It.Is<MyObject>() where I dont have to specify each property? One solution might be to overrride the MyObject.Equals method, i.e. It.Is<MyObject>(o => o.Equal(myObject)). However, this is't ideal as it involves changing code for the sake of unit tests.

A:

Consider changing the approach. Capture the passed argument in a Callback from the mock and then assert that it is as expected using FluentAssertions.
public class MyClassTests {
    private Mock<IMyService> _serviceMock = new Mock<IMyService>();

    public void UnitTest01() {
        // Arrange
        MyObject expected = new MyObject {
            SomeProperty01 = "One",
            SomeProperty02 = 2,
            Timestamp = DateTime.Now
        };

        MyObject actual = null;

        //Setup the mock to capture the passed argument in a callback
        _serviceMock
            .Setup(x => x.DoSomething(It.IsAny<MyObject>())
            .Callback(MyObject arg => { actual = arg; });

        MyClass myClass = new MyClass(_serviceMock.Object);
        string input = Newtonsoft.Json.JsonConvert.SerializeObject(expected);

        // Act
        myClass.DoWork(input);

        // Assert using FluentAssertions
        actual.Should().BeEquivalentTo(expected);
    }
}

Now the test can be exercised without having to change the subject under test.


Q:

How to get value from A3 in Laravel Excel maatwebsite

I use Laravel Excel and I have data at ''A3'' cell. How to get it? I take this code is not working. It's show all data in that sheet.  Reference
 $sheet = $doc->getSheetByName('data');
 $sheet->getCell('A3');

A:

I'm using it too.You can check the array by dd, and get needed cell.
        public function loadExcel(Request $request)
        {
            $path = $request->file('file')->getRealPath();

            $records = \Excel::load($path, function ($reader) {
                  $reader->noHeading();
            })->get()[0]->toArray();

            dd($records);

          //When you find the index of needed cell just $needed_cell = $records['index'];
    }


Q:

dynamically change href value using php

i have this problem that i need to change the directory address of href in anchor, i'm hoping to use php to make it work.. for example if i'm inside the home link my href value would be "index.php" but if im inside the folder of products link home href value will be change to "../index.php" because the header is just included to every page.. and also if you could suggest any alternatives for it, i would be happy to hear it.. thanks!

Home

Products

Packages

Price List

A:

You should use absolute paths instead of relative ones. Relative paths will become difficult to manage down the road, and as you've discovered they have to change depending on which page you're viewing.
Instead of linking to ../index.php, just link to /index.php. This will work regardless of which page you're on.


Q:

To find the volume of the region that is bordered by 4 points in 3D space

To find the volume of the region that in the points $A(x_1,y_1,z_1),B(x_2,y_2,z_2),C(x_3,y_3,z_3),D(x_0,y_0,z_0)$.
Let's define a 4X4 matrix to determine plane equation  that are on $A,B,C$
$$\mathbf{M}=\begin{bmatrix}x & y & z& 1\\x_1 & y_1 & z_1& 1\\x_2 & y_2 & z_2& 1\\x_3 & y_3 & z_3& 1\end{bmatrix}$$
We know that plane equation can be found by $$det(\mathbf{M})=0$$ ,
Let's put $D(x_0,y_0,z_0)$ to plane equation and to get :
$$\mathbf{M_{3}}=\begin{bmatrix}x_0 & y_0 & z_0& 1\\x_1 & y_1 & z_1& 1\\x_2 & y_2 & z_2& 1\\x_3 & y_3 & z_3& 1\end{bmatrix}$$
We know if the point $D$ is on the plane (A,B,C) , $det(\mathbf{M_3})=0$. The point will satisfy the plane equation but if it is not on the plane we will have a value.
Is it true that volume $V$ of the region that is bordered by 4 points can written as
$V=\frac{1}{3} |det(\mathbf{M_3})|$ ?
I wrote it as intuition without proof. Can you help me to prove the lemma ? (or disprove)
And more generally ; Can the region value that is bordered by ($n+1$) points in the n-dimensional space be calculated by
$V_n=\frac{1}{n} |det(\mathbf{M_{n}})|$ ?
Please note that if $n=2$ ,
 The formula satisfies to find the area of triangle in 2D space
$$\mathbf{M_{2}}=\begin{bmatrix}x_0 & y_0 & 1\\x_1 & y_1 & 1\\x_2 & y_2 & 1\end{bmatrix}$$
$V_2=A=\frac{1}{2} |det(\mathbf{M_{2}})|$
Thanks for answers and comments
EDIT: I have found the paper in web while googling. You can see the related part in page 154 about N-dimensional volume calculation. As @Christian Blatter  pointed, the numarical factor must be $1\over n!$  not $1\over n$

A:

Given $n+1$ points ${\bf a}_k$ $(0\leq k\leq n)$ in ${\mathbb R}^n$ one considers their convex hull $S$ which is a (maybe degenerate) $n$-dimensional simplex. This simplex is spanned by the $n$ vectors ${\bf a}_k-{\bf a}_0$ $(1\leq k\leq n)$, and its volume is equal to the volume of the parallelotope $P$ spanned by these vectors, divided by $n!$ (see below). The volume of $P$ is, up to sign,  equal to  the determinant of the matrix having the coordinates of the spanning vectors ${\bf a}_k-{\bf a}_0$ in its columns. So
$${\rm vol}(S)={1\over n!}\>\biggl|\det\bigl[{\bf a}_1-{\bf a}_0,\ {\bf a}_2-{\bf a}_0,\ \ldots,\ {\bf a}_n-{\bf a}_0\bigr]\biggr|\ .\tag{1}$$
Consider now your matrices $M_2$ and $M_3$. If you subtract the first row from all the other rows you obtain  matrices $\hat M_2$ and $\hat M_3$ whose last column is zero, apart from the element in the upper right corner, which remains $1$. It's easy to see that the determinants of $\hat M_2$, $\hat M_3$, and therefore the determinants of $M_2$ and $M_3$, coincide, up to sign,  with the determinant appearing in $(1)$. But your conjectured numerical factor is wrong.
I cannot see how the equations of the  hyperplanes bounding $S$ should play a rôle here.
A proof of $(1)$ rests on induction and an application of Fubini's theorem. For arbitrary $n\geq1$ consider the special simplex  with vertices ${\bf 0}$ and $h{\bf e}_k$ $(1\leq k\leq n)$:
$$S_n(h):=\{(x_1,x_2,\ldots,x_n)\>|\>x_k\geq0 \ (1\leq k\leq n), \ x_1+x_2+\ldots+x_n\leq h\}\ .$$
It is geometrically obvious that ${\rm vol}_n\bigl(S_n(h)\bigr)=h^n\>{\rm vol}_n\bigl(S_n(1)\bigr)$.
We now proceed as follows:
$$\eqalign{{\rm vol}_{n+1}\bigl(S_{n+1}(1)\bigr)&=\int_{S_{n+1}(1)} 1\ {\rm d}(x_1,\ldots,x_n)\cr&=\int_0^1\left(\int_{S_n(1-x_{n+1})}1\ {\rm d}(x_1,\ldots,x_n)\right)\>dx_{n+1}\cr &=\int_0^1{\rm vol}_n\bigl(S_n(1-x_{n+1})\bigr)\>dx_{n+1}\cr
&={\rm vol}_n\bigl(S_n(1)\bigr)\int_0^1(1-x_{n+1})^n\>dx_{n+1}\cr
&={1\over n+1}{\rm vol}_n\bigl(S_n(1)\bigr)\ .\cr}$$


Q:

"The decimal field must be a number"

I'm trying to find a possible easy solution for this issue. All the solutions found in web are not working for me. I have in my model a price field which can be a decimal value like 30,5 using comma. But the validation returns me an error "The 'field' must be a number".
I'm using the default validation used in MVC that I suppose it is using jQuery. Is there any way to avoid this issue?
The model code is:
 [Range(0.0, Double.MaxValue, ErrorMessage = "Out of range")]
    [DataType(DataType.Currency)]
    public decimal Price { get; set; }

A:

I believe the error is coming from client-side validation, not server-side. If it actually got to the server, you should be fine having the culture specified. However, ASP.NET's unobtrusive validation actually use the jQuery Validation plugin, and as you can see here at the documentation page for the number validator, only a . as the decimal separator will validate. You may simply have to remove the number validation rule from the field.
$("#Price").rules("remove", "number");

UPDATE
This post may help you: http://blog.icanmakethiswork.io/2012/09/globalize-and-jquery-validate.html. It explains how to essentially monkey-patch jQuery Validation to actually pay attention to culture.


Q:

MS SQL If Selected is NULL Run another statement

I have two sql statements,
select * from UserTable where role='HOD'

select * from UserTable where role='Supervisor'

I want the results to be in a way such that if the first statement returns nothing, I want the second statement to run and if first statement returns something, second statement do not need to run. Is there a way to do it, be it in a stored procedure or a SQLQuery?

A:

Executing two queries is more expensive than executing a single one that returns both result sets. It would be cheaper to filter the results on the client.
Even if you return all results in a single query, you can differentiate the two cases. For example, HOD always comes before Supervisor. You could use a ranking function like ROW_NUMBER() to assign a value to each row, depending on whether it matches HOD or Supervisor:
with a as (
    select * ,row_number() over (partition by Role  order by Role) as rn
    from UserTable
    where Role in ('HOD','Supervisor')
)
select *
from a
where rn=1

Another option is to combine a query that returns HOD with a query that returns Supervisor if HOD doesn't exist:
select *
from UserTable
where Role ='HOD'
UNION ALL
select *
from UserTable
where Role ='Supervisor'
      AND NOT EXISTS (SELECT 1
                      from UserTable
                      where Role ='Supervisor')

The performance of both queries can be improved if Role is part of an index. The first query becomes equivalent to a simple index seek if the table has an index that covers all the returned fields. If the query returns only eg, ID, UserName, Role :
with a as (
    select * ,row_number() over (partition by Role  order by Role) as rn
    from UserTable
    where Role in ('HOD','Supervisor')
)
select ID,UserName, Role
from a
where rn=1

and the table has a covering index:
CREATE INDEX IX_UserTable_Roles ON UserTable (Role,ID,UserName)

The resulting execution plan is a single INDEX SEEK on the index


Q:

How to get a separate context in different SoapUI testcase instances running in parallel?

I have a SoapUI test case (name "create entity") with groovy script test step which uses some variables received in context, e.g. counter value, processes it and returns some other value, e.g. returnId
// these variables are effectively shared across different threads, I want to avoid it
def threadId = context.getProperty("threadId")
def counter = context.getProperty("counter").toInteger()
...
testRunner.testCase.setPropertyValue("returnId", returnId)

And this test case is called from another test case groovy script step, which creates several threads with numerous test case executions
...
def counter = new AtomicInteger()
...

// multiple threads
1.upto(2) {
  threads << new Thread({
    def tc = testRunner.testCase.testSuite.getTestCaseByName("create entity")
    def txInstanceContext = new com.eviware.soapui.support.types.StringToObjectMap()
    // thread specific parameter
    def threadId = ...
    txInstanceContext.put("threadId", threadId)

    // multiple executions loop
    1.upto(2) {
      def number = counter.getAndIncrement().toString()
      // execution specific variable
      txInstanceContext.put("counter", number)
      log.info "Started uploading " + number + " at " + new Date().getTime()
      def runner = tc.run( txInstanceContext, false )
      while(runner.status == Status.RUNNING) {
        this.sleep(50)
      }
      log.info "Status: " + runner.status + ", time taken for upload was: " + runner.timeTaken + " ms"
      ...
      assert runner.status != Status.FAILED : runner.reason
      def returnId = tc.getPropertyValue("returnId")
      log.info "Finished uploading " + number + " at " + new Date().getTime()
      log.info "Returned id: " + returnId
      ...
    }
  })
}

threads.each {
  it.start()
}
threads.each {
  it.join()
}

How to get an isolated scope for each execution, to avoid overriding/setting test case variables by other thread executions?

A:

I think you need to create a TC runner and then WsdlTestRunContext.
I ran into similar situation where I needed to create a TC runner. Here . I believe you can go one step further and create a context by using createContext(StringToObjectMap properties) method of this WsdlTestCaseRunner.


Q:

How to handle a global service for different views in angular?

Here is my scenario. I want to refresh my captcha if the form get error message. And I have multi views to use the captcha.
So I write a factory:
Services.factory 'Captcha', ['$rootScope', ($rootScope) ->
  service = {}
  service.new_captcha = () ->
    console.log 'render cap'
    $rootScope.captcha_src = "/captcha?action=captcha&i=#{+new Date}"
  service
]

And then another factory where handle the $http process will trigger the code below
$http
.error (data) ->
  service.signin_err_msg = data.error
  Captcha.new_captcha()
  $rootScope.$broadcast('new_captcha')

In the view controller, $scope value will listen to the broadcast and change the src value.
SignUpCtrl = App.controller 'SignUpCtrl', ($scope, UserService, $location, $rootScope) ->

  $scope.UserService = UserService

  $scope.$on 'new_captcha', (val) ->
    $scope.captcha_src = $rootScope.captcha_src

  $scope.captcha_src = $rootScope.captcha_src

This works. But I dont think this is a good way. I have to write the same code to listen the rootScope broadcast. Is there same method better?

A:

There is no need to use $rootScope or to broadcast any events.  This would also work:
Captcha Service
Services.factory('Captcha', [function() {
  var captchaSrc;
  return {
     get_captcha_src: function() {
       if (!captchaSrc) {
         this.refresh_captcha();
       }
       return captchaSrc;
     },
     refresh_captcha: function() {
       captchaSrc = "/captcha?action=captcha&i=" + new Date();
     }
  }
}]);

HTTP Handler
$http.error(function(data) {
  service.signin_err_msg = data.error;
  Captcha.refresh_captcha();
});

Controller
var SignUpCtrl = App.controller('SignUpCtrl', function($scope, $location, UserService, Captcha) {
  ...

  $scope.get_captcha_src = function() {
    return Captcha.get_captcha_src();
  }

  // or this: $scope.get_captcha_src = Captcha.get_captcha_src;

});


Q:

Error using \string

Consider
\documentclass{article}

\usepackage{lmodern}

\usepackage[T1]{fontenc}

\begin{document}

\texttt{\string\iftrue}

%% \texttt =\long macro:
%% #1->\ifmmode
%%       \nfss@text{\ttfamily#1}
%%     \else
%%       \hmode@bgroup\text@command{#1}\ttfamily\check@icl#1\check@icr\expandafter\egroup
%%     \fi

\end{document}

Processing this minimal example with pdflatex results in a rather nasty Incomplete \ifmmode error during the expansion of \texttt{\string\iftrue}. It seems to me that \string does not totally prevent TeX from taking account of \iftrue as a conditional. (The same is true for \detokenize, by the way.)
Can anybody explain what is precisely going on?

Addendum: Note that the error would disappear if \texttt stored its argument in an auxiliary macro before processing it.

A:

Consider:
\iffalse
\string\iftrue
\fi

On seeing the \iffalse TeX scans ahead matching tokens with definitions
\if (or the other primitive if tokens such as \ifx \iftrue etc) \else and \fi to get to a matching \fi when normal operation re-starts. In particular it does not execute any assignments or expand any tokens. So \string is simply skipped over but the inner \iftrue is seen so the \fi matches the \iftrue and things go wrong.
Depending what you want to do
\iffalse
 \textbackslash iftrue
\fi

or
\iffalse
\csname iftrue\endcsname
\fi

or
\iffalse
\expandafter\string\csname iftrue\endcsname
\fi

are all safe. (Or similarly and more usefully perhaps the same with \iftrue as the first token.)

A:

You need to bear in mind that TeX is a macro expansion language. Thus
\texttt{\string\iftrue}

expands the definition of \texttt with an argument containing two tokens, \string and \iftrue. That leads to
\ifmmode
  \nfss@text{\ttfamily\string\iftrue}
\else
  \hmode@bgroup
    \text@command{\string\iftrue}%
    \ttfamily
    \check@icl\string\iftrue\check@icr
  \expandafter\egroup
\fi

(formatting mine). TeX then scans the conditional, finds more tokens which start \if... statements than end them, and complains.
What you presumably want to do is pass the string \iftrue to \texttt:
\expandafter\texttt\expandafter{\string\iftrue}