text:
Q: Conditionally aborting in a Bash alias I have an alias:
alias local='if [ -z "${FUNCNAME[0]}" ]; then builtin local; fi; declare'

Which I want to use to redirect local commands into my modified declare function, which then can declare the variables, and only use the builtin local to get error messages if outside an function.
The alias has an output of (using set -x):
+ '[' -z '' ']'
+ builtin local
-bash: local: can only be used in a function
+ declare

Right now it executes the declare anyways and I would like it to exit if the check fails. I can't use a function for this.
So far I've tried return, break and exit (exit not here for obvious reasons):
alias 'local=if [ -z "${FUNCNAME[0]}" ]; then builtin local; return 1; break; fi; declare'

+ '[' -z '' ']'
+ builtin local
-bash: local: can only be used in a function
+ return 1
-bash: return: can only `return' from a function or sourced script
+ break
-bash: break: only meaningful in a `for', `while', or `until' loop
+ declare

Example:
# When outside an function
local some_var=val
+ '[' -z '' ']'
+ builtin local
-bash: local: can only be used in a function
# That's it

# When inside an function func
local some_var=val
+ '[' -z func ']'
+ declare some_var=val
# Uses my modified declare function

A: Not sure why you need such an alias.  In any case, don't use an alias for this.  Use a function instead:
local() {
  if [ -z "${FUNCNAME[0]}" ]; then
    builtin local "$@"
  else
    declare -g "$@" # -g (for global) is necessary - otherwise variable set by declare would be local to the function
  fi
}

A: As builtin local is only used to get the error message, this will work:
alias local='builtin local 2>&1 >/dev/null; [ -n "${FUNCNAME[0]}" ] && declare'

It will always print only the error, if not inside a function, but won't print out all the local variables if inside one:
$> func () { local var2=foo; local var=bar; echo $var; }
$> func
+ func
+ builtin local
+ '[' -n func ']'
+ declare var2=foo
+ builtin local
+ '[' -n func ']'
+ declare var=bar
+ echo bar
bar

This way local gets replaced by declare, which then I can modify with a wrapper.


text:
Q: Find files in order in sorted folders I have directories listed as
01  02   03_rev  04_N  .....  154  155

I want find to look for a file in (numerical order of folders) sorted folders as listed above, How can I modify below find command?
for f in $(find . -name 'log_*.log'); do
    ....
done

Thanks

A: You don't need find, you can just use shell globbing, you would get the files sorted by natural numeric order:
for f in [0-9]*; do echo "$f"; ## Do stuffs; done

Example:
$ for f in [0-9]*; do echo "$f"; done
01
02
03_rev
04_N
154
155

Answer based on comment:
If you want to search for a file in these directories, recursively and then read the file if found, do:
Rather than looping over each directory separately, you should go to their parent directory and let find traverse on these directories only (use globbing), and search for the file:
find /parent/[0-9]* -type f -name 'file.txt'

To read the content of the file(s):
find /parent/[0-9]* -type f -name 'file.txt' -exec cat {} +

Assuming the parent directory of these directories is /parent, and the file you are searching for is file.txt.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to handle the mysql error in nodejs?if the result is an empty array? i have a nodejs code given below. The sql query works perfect when i gave a valid data, if the input is not available in sql it will return a null result (result []).How do i render this to another page if the result is an empty array?
app.post('/verify',urlencodedParser,async function(req,res){///////////// verify form
    var reg1 = req.body.regno;
    console.log("reg");
    console.log(reg1);

    sql ="select * from json where id="+db.escape(reg1);
    db.query(sql,async(err,resulter)=>{
        if (err) throw err;

        console.log("my result:",resulter);

        console.log(resulter[0].name);
    jname = resulter[0].name;
    var contents = JSON.parse(fs.readFileSync(path1 + "/public/issued_json/"+jname, 'utf8'));
    console.log(contents);
    console.log(JSON.stringify(contents.employee[0]));


text:
Q: How to obtain the width of a QTableWidgetItem object? I have a program with a few different widgets, one of which is a table. I wish to obtain the width of the headers of my table, to use for making more widgets to ensure that they are the same Width.
(Width of the headers (QTableWidgetItem) varies depending on my program input, so I wish to be able to set the width of other widgets based on whatever the width is of the QTableWidgetItems for each execution)
I have looked a fair bit of documentation myself, but It seems as though there is no easy/obvious method such as .width() to obtain it?
I have tried using the methods from a similar question, such as:
width = mainWindow.frameGeometry().width()
height = mainWindow.frameGeometry().height()

but unfortunately I just get the error that the method isn't available for the QTableWidgetItem object

A: The solution is width() or height() in
self.YourTableNameHere.horizontalHeader().geometry().height()


text:
Q: Axis Range and Domain issue on bar graph using D3 I am implementing a bar graph in which the as per the moment of the slider the vertical values of rows would change. I'm getting issue in adding a particular range on the Y-axis domain and decreasing the thickness of both the Y and X Axis. for Y-axis I want the data to be added via the array "ydata" but only first two value gets reflected in this case. The value should be "0-9", "20-29", "40-49", "60-69", "80-89" and "100+" My code is feature on this link:
https://digitalxlabs.com/d3-charts/retirement-transition-graph.php
Username: DXLdemo
Password: View@098#
Also, here is my code below:
<!DOCTYPE html>

    <link data-require="jqueryui@1.10.0" data-semver="1.10.0" rel="stylesheet" href="jquery-ui-1.10.0.custom.min.css" />

2000
2010
2020
2030
2040
2050

A: See this link working plnkr - i have minimized the rangePoints to [300,0]. Then the ticks will be arranged in the middle. Hope it helps.
 var y = d3.scale.ordinal().domain(ydata.map(function(d) {
        return d.val;
      })).rangePoints([300, 0]);


text:
Q: How to schedule Mandrill mail in Laravel 4? The Mandrill documentation says that the send_at parameter should be set in the mail Api call for scheduling mail.
Mail::send('template', array('name'=>$GLOBALS['name']), function($message)
{
    $message->to($GLOBALS['email'], $GLOBALS['name'])->subject('Subject');
});

In the above code where should I set the parameter: send_at
Thanks in advance :)

A: Use the X-MC-SendAt header.
Mail::send('template', array('name'=>$GLOBALS['name']), function($message)
{
    $message->to($GLOBALS['email'], $GLOBALS['name'])->subject('Subject');

    $headers = $message->getHeaders();
    $headers->addTextHeader('X-MC-SendAt', '2014-09-01 01:00:00');
});

Note that I haven't tested this - you might need to use a different method than addTextHeader - refer to the swiftmailer documentation.
Refer to the documentation (Using SMTP Headers to customize your messages for more details and note that the documentation does indicate that this only works for paid accounts.

A: Found a package for laravel that does the same thing
Maybe useful for other people:
http://packalyst.com/packages/package/abishekrsrikaanth/mailto#send-mandrill-time


text:
Q: SIGABRT When Mallocing Space for Element in Pointer Array I'm attempting to have an array of strings in c where each string has the correct amount of chars allocated for it, however, I am receiving the following error:
sort: malloc.c:2394: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.

Program received signal SIGABRT, Aborted.
0x00007ffff7a42428 in __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:54

I ran the program in GDB and the error occurs on the second line entry ex if the input is: "this\nis\n"
 the program fails when processing "is." The line causing the error is
words[j]=(char *)malloc((i+1)*sizeof(char));

Here words[j] is a pointer pointer array at location 1. 'i' is the number of chars in the input string (in this case the input was "is" so i is 2).
I also ran the program through Valgrind which quits on the first word with the following error message:
==15272== Invalid write of size 8
==15272==    at 0x4C326CB: memcpy@@GLIBC_2.14 (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==15272==    by 0x400A16: main (sort.c:59)
==15272==  Address 0x52064c0 is 0 bytes inside a block of size 5 alloc'd
==15272==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==15272==    by 0x4009AD: main (sort.c:54)
==15272==

The line of code associated with 54 is again:
words[j]=(char *)malloc((i+1)*sizeof(char));

The line associated with 59 is:
memcpy(words[j],buffer,sizeof(buffer)+1);

Where buffer is an array of size 1024 containing the user input string: "is\0"
As requested, here is more of the code:
 char **words=malloc(1024*sizeof(*words));
 if(!words){
     perror("The word array could not be allocated in memory.");
     exit(7);
 }
 int word_count=0;
 char buffer[1024];
 c= ' ';
 for(int j=0;j<1024;j++){
     memset(buffer,0,sizeof(buffer));
     for(int i=0;i<1024;i++){
         c=getchar();
         if(c==EOF || c== '\n'){
             //printf("c is %c buffer is %s\n",c,buffer);
             buffer[i]='\0';
             word_count++;
             words[j]=(char *)malloc((i+1)*sizeof(char));
             if(!words[j]){
             perror("The word could not be allocated in memory.");
             exit(7);
             }
             memcpy(words[j],buffer,sizeof(buffer)+1);
             words[j][sizeof(buffer)+1]='\0';
             break;
         }
         buffer[i]=c;
     }
     if(c==EOF){
         break;
     }
     else continue;
 }
 }

A:
The line associated with 59 is:
memcpy(words[j],buffer,sizeof(buffer)+1);

Where buffer is an array of size 1024 containing the user input string: "is\0"

This is the bug.  sizeof(buffer)+1 is 1025; you are copying 1025 chars, regardless of the length of the input string.  You only allocated space for i+1 chars, so i+1 chars is how much you should copy.


text:
Q: Use DataStudio to specify the date range for a custom query in BigQuery, where the date range influences operators in the query I currently have a DataStudio dashboard connected to a BigQuery custom query.
That BQ query has a hardcoded date range and the status of one of the columns (New_or_Relicensed) can change dynamically for a row, based on the dates specified in the range. I would like to be able to alter that range from DataStudio.
I have tried:

*

*simply connecting the DS dashboard to the custom query in BQ and then introducing a date range filter, but as you can imagine - that does not work because it's operating on an already hard-coded date range.

*reviewing similar answers, but their problem doesn't appear to be quite the same E.g. BigQuery Data Studio Custom Query
Here is the query I have in BQ:
SELECT t0.New_Or_Relicensed, t0.Title_Category FROM (WITH
  report_range AS
  (
    SELECT
      TIMESTAMP '2019-06-24 00:00:00' AS start_date,
      TIMESTAMP '2019-06-30 00:00:00' AS end_date
  )
SELECT
  schedules.schedule_entry_id AS Schedule_Entry_ID,
  schedules.schedule_entry_starts_at AS Put_Up,
  schedules.schedule_entry_ends_at AS Take_Down,
  schedule_entries_metadata.contract AS Schedule_Entry_Contract,
  schedules.platform_id AS Platform_ID,
  platforms.platform_name AS Platform_Name,
  titles_metadata.title_id AS Title_ID,
  titles_metadata.name AS Title_Name,
  titles_metadata.category AS Title_Category,
  IF (other_schedules.schedule_entry_id IS NULL, "new", "relicensed") AS New_Or_Relicensed
FROM
  report_range, client.schedule_entries AS schedules
JOIN client.schedule_entries_metadata
  ON schedule_entries_metadata.schedule_entry_id = schedules.schedule_entry_id
JOIN
  client.platforms
  ON schedules.platform_id = platforms.platform_id
JOIN
  client.titles_metadata
  ON schedules.title_id = titles_metadata.title_id
LEFT OUTER JOIN
  client.schedule_entries AS other_schedules
  ON schedules.platform_id = other_schedules.platform_id
  AND other_schedules.schedule_entry_ends_at < report_range.start_date
  AND schedules.title_id = other_schedules.title_id
WHERE
  ((schedules.schedule_entry_starts_at >= report_range.start_date AND
   schedules.schedule_entry_starts_at <= report_range.end_date) OR
  (schedules.schedule_entry_ends_at >= report_range.start_date AND
   schedules.schedule_entry_ends_at <= report_range.end_date))
) AS t0 LIMIT 100;

Essentially - I would like to be able to set the start_date and end_date from google data studio, and have those dates incorporated into the report_range that then influences the operations in the rest of the query (that assign a schedule entry as new or relicensed).

A: Have you looked at using the Custom Query interface of the BigQuery connector in Data Studio to define start_date and end_date as parameters as part of a filter.
Your query would need a little re-work...
The following example custom query uses the @DS_START_DATE and @DS_END_DATE parameters as part of a filter on the creation date column of a table. The records produced by the query will be limited to the date range selected by the report user, reducing the number of records returned and resulting in a faster query:

Resources:
Introducing BigQuery parameters in Data Studio
https://www.blog.google/products/marketingplatform/analytics/introducing-bigquery-parameters-data-studio/
Running parameterized queries
https://cloud.google.com/bigquery/docs/parameterized-queries

A: I had a similar issue where I wanted to incorporate a 30 day look back before the start (@ds_start_date). In this case I was using Google Analytics UA session data and using table suffix in my where clause. I was able to calculate a date RELATIVE to the built in data studio "string" dates by using the following:
...
WHERE
        _table_suffix BETWEEN
        CAST(FORMAT_DATE('%Y%m%d', DATE_SUB (PARSE_DATE('%Y%m%d',@DS_START_DATE), INTERVAL 30 DAY)) AS STRING)
        AND
        CAST(FORMAT_DATE('%Y%m%d', DATE_SUB (PARSE_DATE('%Y%m%d',@DS_END_DATE), INTERVAL 0 DAY)) AS STRING)


text:
Q: Multiple Default Buttons in a User Control I have a user control that is comprised of 3 textboxes, 3 buttons and a gridview.  I can set the defaultbutton property of the form, but that would only affect one button.
Each textbox/button combo should have a behavior that when the textbox has focus, pressing Enter should fire its associated button.
To further complicate the issue, this is being used inside a Master Page implementation.
Is there any way to do this?  As far as I can tell, .NET will only allow one default button - it doesn't provide to explicitly associate textboxes and buttons.
I welcome your insights.

A: Here one way:
<form id="form1" runat="server">

    <asp:Panel ID="Panel1" DefaultButton="Button1" runat="server">
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

        <asp:Button ID="Button1" runat="server" Text="Button" />
    </asp:Panel>
    <asp:Panel ID="Panel2" DefaultButton="Button2" runat="server">
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

        <asp:Button ID="Button2" runat="server" Text="Button" />
    </asp:Panel>
    <asp:Panel ID="Panel3" DefaultButton="Button3" runat="server">
        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>

        <asp:Button ID="Button3" runat="server" Text="Button" />
    </asp:Panel>

</form>

A: Try creating a separate User Control for each TextBox/Button set.  That way each Textbox will fire it's associated Button.

A: You can disable the default button and handle the textbox's onKeyPress event.

A: Here is a sweet solution by usage of an Attached Property:
http://neilmosafi.blogspot.com/2007/04/default-buttons-in-wpf-and-multiple.html
Just create a class with the attached property code of the article and add it to controls, which encapsulate each TextBox and Button pair.
Example: <StackPanel ... local:AccessKeyScoper.IsAccessKeyScope="True"> <TextBox ... /> <Button ... /> </StackPanel>
Note:
If you add the file with the Dependency Property to a subdirectory, you need to use an other namespace definition instead of local:.


text:
Q: estimation of a yearly prediction interval for monthly data I have a monthly time series and my objective is to provide my client with the next 12 point forecasts along with a yearly forecast. To obtain the yearly forecast, I simply summed up the 12 points forecasts. And, to associate this yearly forecast with a prediction interval, I came up with the following solution which does not make an assumption of the distribution of the residuals:

*

*Predict the 12 point forecasts using a model (ex. ARIMA or Prophet).

*Check that the residuals are uncorrelated. If it is the case then:

*

*To each of the 12 point forecasts yhat_i, add an epsilon e_i drawn from the train residuals (yhat'_i = yhat_i + e_i) .

*Sum the noisy yhat_i to obtain a noisy yearly forecast.

*Repeat steps 2 and 3 a large number of times (ex. 1000).

*Select the quantiles (alpha/2, 1-alpha/2) which constitute the yearly prediction interval with alpha being the risk level.

Let me know what you think

A: That won't work for all models.
Here's an example where it won't work. Suppose the data comes from a random walk without drift:
$$Y_t = Y_{t-1} + \varepsilon_t$$
The $h$-ahead point forecasts are:
$$\mathbb{E}(Y_{t+h} | Y_1,...,Y_t) = Y_t$$
You want to simulate the yearly sum $\sum_{h=1}^{12} Y_{t+h}$ conditional on $Y_t$, which you can write as:
$$\sum_{h=1}^{12} Y_{t+h} = (Y_t + \varepsilon_{t+1}) + \ldots + (Y_t + \varepsilon_{t+1} + \ldots \varepsilon_{t+12}) = 12Y_t + \sum_{h=1}^{12} (13-h)\varepsilon_{t+h}$$
The residuals are just the $\varepsilon_t$, which in your suggestion you would resample. Let $\left(\tilde{\varepsilon}^{(1)},\ldots,\tilde{\varepsilon}^{(12)}\right)$ be such a sample. You would suggest to simulate from the yearly sum like this:
$$(Y_t + \tilde{\varepsilon}^{(1)}) + \ldots + (Y_t + \tilde{\varepsilon}^{(12)}) = 12Y_t + \sum_{h=1}^{12} \tilde{\varepsilon}^{(h)}$$
This is not the same distribution. Here's an illustration:
# Generate some data
set.seed(123)
x <- cumsum(rnorm(300))

residuals <- diff(x)

nsim <- 5000
h <- 12

# Sample of residuals
eps <- matrix(sample(residuals, nsim * h, replace = TRUE), nrow = nsim, ncol = h)

# Sample the correct paths, passing the shocks through the dynamics
sims_correct <- matrix(NA_real_, nsim, h)
for(i in 1:h) {
  if (i == 1) {
    sims_correct[,i] <- x[length(x)] + eps[,i]
  } else {
    sims_correct[,i] <- sims_correct[,i-1] + eps[,i]
  }
}

# Sample paths incorrectly, adding the shock on top of the point forecast
sims_wrong <- matrix(NA_real_, nsim, h)
for (i in 1:h) {
  sims_wrong[,i] <- x[length(x)] + eps[,i]
}

# Add up the simulated months
yearly_sim_correct <- rowSums(sims_correct)
yearly_sim_wrong <- rowSums(sims_wrong)

# Compare density
plot(density(yearly_sim_correct), main = "Yearly predicted density", ylim =     c(0,0.15))
lines(density(yearly_sim_wrong),col='red')
legend("topleft", legend = c("Correct", "Wrong"), col = 1:2, lty=1)

The issue is that you're just adding noise "on top" of the point forecast, but in many time series models, shocks are defined in a way that they are fed forward through the dynamics. That's how autocorrelation is constructed from independent shocks. In the random walk process, each new shock has a permanent effect on the future level and appears in the distribution of each value from then on. You need to do the same with resampled residuals so that you obtain the correct joint pathwise distribution and hence the correct summed yearly distribution.
So, this won't work for most ARIMA models. There are models where your idea will work as-is, namely models that have a deterministic trend function $f$ and iid noise, like this:
$$Y_t = f(t) + \varepsilon_t$$


text:
Q: Get current country from trip information I have a simple table (TRIP), which stores trip information like the following
trip_id traveler    country_from    country_to  departure_date  arrival_date
1        Test1       Germany         Italy       2016-01-01     2016-01-02
1        Test1       Italy           France      2016-04-01     2016-04-02
1        Test1       France          Italy       2016-08-28     2016-08-28
1        Test1       Italy           Germany     2016-08-30     2016-10-31
2        Test2       France          USA         2016-01-28     2016-02-28
2        Test2       USA             France      2016-08-30     2016-10-31

Actually this means that
Test1 travels: Germany -> Italy -> France -> Italy -> Germany
Test2 travels: from France -> USA -> France

departure_date and arrival_date defines when traveler will leave country_from, and when he will be in country_to... actually it is time spend in flight
(I agree, this table is awful, and have lots of normalizing issues but I cant manage it, we have what we have)
I need to write a query, which will return traveler name, and the Country, in which traveler will be located (or if many countries the first country) for a given time period...
For example for time period 2016-03-01 - 2016-04-02 query should return
Test1 Italy
Test2 USA

Please advice optimal way to get that result, I have tried to join table itself with few variations, but always come to corner cases which are not covered

A: You need the beginning and end of the trip for each country in one row.  In SQL Server 2012+ you can use lead() for this purpose.  The rest of the query is just handling overlapping timeperiods:
select t.*
from (select t.country_to as country, t.arrival_date,
             lead(t.departure_date) over (partition by t.traveler order by arrival_date) as departure_date
      from trips t
      where t.traveler = @traveler
     ) t
where @date1 <= t.departure_date and
      @date2 >= t.arrival_date;

EDIT:
You can do the same thing in earlier versions using outer apply:
select t.*
from (select t.country_to as country, t.arrival_date,
             t2.departure_date
      from trips t outer apply
           (select top 1 t2.*
            from trips t2
            where t2.traveler = t.traveler and
                  t2.arrival_date > t.arrival_date
            order by t2.arrival_date
           ) t2
      where t.traveler = @traveler
     ) t
where @date1 <= t.departure_date and
      @date2 >= t.arrival_date;


text:
Q: How do I write NOT Operation for the Risc-V (Assembly Language)? How do I write NOT Operation for the Risc-V (Assembly Language)? If there's no NOT instruction, how do you achieve the same thing?

A: Like MIPS and some other architectures, RISC V does not provide dedicated instructions for many things, including two-operand unary operations, as these operations can be had using their three-operand format, usually with x0 as the third operand, but sometimes constant 1 or -1 as the third operand.
For convenience, the assembler will accept what are called pseudo instructions for these unary operations (and others).  Here's a list of the common RISC V pseudo instructions and their replacements.
To do more complex or unlisted things, use math & logic, and as many instructions as needed.
li rd, immediate     | Myriad sequences               | Load immediate
mv rd, rs            | addi rd, rs, 0                 | Copy register
not rd, rs           | xori rd, rs, -1                | One's complement
neg rd, rs           | sub rd, x0, rs                 | Two's complement
negw rd, rs          | subw rd, x0, rs                | Two's complement word
sext.w rd, rs        | addiw rd, rs, 0                | Sign extend word
seqz rd, rs          | sltiu rd, rs, 1                | Set if = zero
snez rd, rs          | sltu rd, x0, rs                | Set if ̸= zero
sltz rd, rs          | slt rd, rs, x0                 | Set if < zero
sgtz rd, rs          | slt rd, x0, rs                 | Set if > zero
beqz rs, offset      | beq rs, x0, offset             | Branch if = zero
bnez rs, offset      | bne rs, x0, offset             | Branch if ̸= zero
blez rs, offset      | bge x0, rs, offset             | Branch if ≤ zero
bgez rs, offset      | bge rs, x0, offset             | Branch if ≥ zero
bltz rs, offset      | blt rs, x0, offset             | Branch if < zero
bgtz rs, offset      | blt x0, rs, offset             | Branch if > zero
bgt rs, rt, offset   | blt rt, rs, offset             | Branch if >
ble rs, rt, offset   | bge rt, rs, offset             | Branch if ≤
bgtu rs, rt, offset  | bltu rt, rs, offset            | Branch if >, unsigned
bleu rs, rt, offset  | bgeu rt, rs, offset            | Branch if ≤, unsigned
j offset             | jal x0, offset                 | Jump
jal offset           | jal x1, offset                 | Jump and link
jr rs                | jalr x0, 0(rs)                 | Jump register
jalr rs              | jalr x1, 0(rs)                 | Jump and link register
ret                  | jalr x0, 0(x1)                 | Return from subroutine
call aa              | auipc x1, aa[31 : 12] + aa[11] | Call far-away subroutine
                     | jalr x1, aa[11:0](x1)          | (two instructions)
tail aa              | auipc x6, aa[31 : 12] + aa[11] | Tail call far-away subroutine
                     | jalr x0, aa[11:0](x6)          | (also two instructions)

As an aside, there's an educational processor called the LC-3.  It has only three arithmetic/logical operations: ADD, AND, NOT.  Yet students are expected to write code that does multiplication, division, modulus, XOR, OR, etc..!!  Multiplication & division/modulus are done with a loop; XOR and OR are done using logic sequences — we know all the boolean operation can be had using only NAND gates, so having (only) AND & NOT is primitive but sufficient.
My favorite sequence for XOR on that processor comes from this formula:
(A AND NOT B) + (NOT A AND B)

Where here the + is literally ADD, which works as a substitute for OR because the two operands will never both be 1 at the same time, so carry from one bit position to another will not occur, and under those circumstances, ADD and OR are equivalent.


text:
Q: JScrollPane won't scroll whole div? -- JScrollPane won't move dynamically with div on window resize I am using JScrollPane on a div in order to scroll through it. The div contains a self wrote javascript code that fetches the last couple of posts from my tumblr feed. However, even though the scrollpane is showing fine, for some reason it doesn't scroll completely through the div. This means that when I scroll to the end of the jscroll, there is still more content below the viewable area of the div that is not showing up. I was wondering if anyone could help me figure this out..
Here's the link to the page that I am I working with:
http://prisingh.com/#recent
This is in the head part of the document:
<link type="text/css" href="css/jquery.jscrollpane.css" rel="stylesheet" media="all" />

This is in the body part:

Here are the javascript codes that are being used:
http://www.prisingh.com/js/
EDIT: now that I have a fix for the original div load problem I was wondering how I would go about having the Jscrollpane move dynamically with the div on window resize. Everytime I resize the window, the JScrollpane remains at the same place it was in when the website was originally loaded. I have tried the code that was given with the plugin:
$(function()
{
$('.scroll-pane').each(
    function()
    {
        $(this).jScrollPane(
            {
                showArrows: $(this).is('.arrow')
            }
        );
        var api = $(this).data('jsp');
        var throttleTimeout;
        $(window).bind(
            'resize',
            function()
            {
                if (!throttleTimeout) {
                    throttleTimeout = setTimeout(
                        function()
                        {
                            api.reinitialise();
                            throttleTimeout = null;
                        },
                        50
                    );
                }
            }
        );
    }
)

});

This has not solved the problem, the scroll bar keeps the div at the same width it was at on the original loading of the website.
For a demonstration just visit prisingh.com/#recent and try resizing the window once the page is loaded.

A: Try this
$(document).ready(function() {
  var $images = $(".tumblr img")
    , imageCount = $images.length
    , counter = 0;
    $images.one("load",function(){
         counter++;
         if (counter == imageCount) {
             $('.scroll-pane').jScrollPane();
         }
    }).each(function () {
        if (this.complete) {
            $(this).trigger("load");
        }
    });
});


text:
Q: NGRX Effects breaks app on error, how to handle errors? I am using NGRX effects in my app.
When it fails it seems to break the stream.
@Effect()
createUser$: Observable<Action> = _action$.ofType(fromUser.CREATE_NEW_USER_ACTION)
  .pipe(
    mergeMap((action: fromUser.CreateNewUserAction) =>
      this._tokenService.post('users', action.payload)
        .pipe(
          map(response => {
            this._router.navigate(
              ["dashboard", "users", "view"],
              { queryParams: { id: response.json().message.id } });
            return new fromUser.CreateNewUserCompleteAction(response.json().message);
          },
            catchError(error =>
              of(new fromUser.CreateNewUserFailedAction(error.json().message))
            )
          )
        )
    )
  );

The error action is never triggered, I tried logging.

A: What is your tokenService returning?  It might be handling any errors from the API call internally.  CatchError should work as long as your API call is not burying the error event.  If that is the case you may need to throw the error from that service using Observable.throw().
I typically format my effects more like this for readability.
@Effect() updateUser$: Observable<Action>;

constructor(action$: Actions, tokenService: TokenService) {
this.updateUser$ = action$.ofType(fromUser.UPDATE_USER_ACTION)
.pipe(
    mergeMap((action: fromUser.UpdateUserAction) =>
        tokenService.patch(`users/${this.user.id}`, action.payload)
           .pipe(
              map(response => {
                 this._router.navigate(
                    ["dashboard", "users", "view"],
                    { queryParams: { id: response.json().message.id } });
                 return new fromUser.UpdateUserCompleteAction(response.json().message);
              },
              catchError(error =>
                 of(new fromUser.UpdateUserFailedAction(error.json().message))
              )
           )
        )
    )
);
}

This code looks like it should work.  Take a look at your TokenService.

A: Looks like your parentheses are not correctly placed inside the 2nd pipe function. The map and the catchError should be in parallel inside the pipe. In your code, the catchError function is inside map.
@Effect()
createUser$: Observable<Action> = _action$.ofType(fromUser.CREATE_NEW_USER_ACTION)
  .pipe(
    mergeMap((action: fromUser.CreateNewUserAction) =>
      this._tokenService.post('users', action.payload)
        .pipe(
          map(response => {
            this._router.navigate(
              ["dashboard", "users", "view"],
              { queryParams: { id: response.json().message.id } });
            return new fromUser.CreateNewUserCompleteAction(response.json().message);
          }),
          catchError(error =>
            of(new fromUser.CreateNewUserFailedAction(error.json().message))
          )
        )
    )
  );

BTW, this is a good practice placing the catchError with the http request rather than put in in the outer pipe stream which would potentially stop the action$ observable and no future actions will be received by the NGRX Framework.


text:
Q: document.write sometimes works, sometimes doesn't What am I doing wrong here? The last bit (kkk or mmm) doesn't work. How should I modify my code?
    <!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8" />

        <input type="text" id="userInput"></input>
        <button onclick="test()">Submit</button>

I've read similar questions but I'm still not sure what to do so I would really appreciate your help!
edit: The string ". Your public code: " is displayed.

A: I think the problem is here:
document.getElementById("Beg").innerHTML = document.write(". Your public code: ");

document.write does not return a value. You should use istead
document.getElementById("Beg").innerHTML = ". Your public code: ";

Hope that helps.


text:
Q: pod spec lint command fails due to project-Swift.h I am building an objective C framework with some swift files in it, and I want to create a pod. When I am using command pod spec link I get an error that says

*

*ERROR | [iOS] xcodebuild: Returned an unsuccessful exit code.

and I noticed that the is is a NOTE logged that says
fatal error: 'project/project-Swift.h' file not found
Xcoce builds normally the project but as I understand the xcodebuild command that runs through pod spec lint can not find the auto generated header.
Any thoughts? Do the other warnings of the code make xcodebuild to fail compilation and so the auto generated header is not getting created?


text:
Q: How to find recurring word groups in text with C#? I'm getting recurring word counts in StringBuilder(sb) with this code which i've found on internet and according to writer it's really consistent like Word's word counter.
StringBuilder wordBuffer = new StringBuilder();
        int wordCount = 0;
        // 1. Build the list of words used. Consider ''' (apostrophe) and '-' (hyphen) a word continuation character.
        Dictionary<string, int> wordList = new Dictionary<string, int>();
        foreach (char c in sb.ToString())
        {

            if (char.IsLetter(c) || c == '\'' || c == '-')
            {
                wordBuffer.Append(char.ToLower(c));
            }
            else
            {
                if (wordBuffer.Length > 3)
                {
                    int count = 0;
                    string word = wordBuffer.ToString();
                    wordList.TryGetValue(word, out count);
                    wordList[word] = ++count;

                    wordBuffer.Clear();
                    wordCount++;
                }
            }
        }

This is my sample text:

The green algae (singular: green alga) are a large, informal grouping of algae consisting of the Chlorophyte and Charophyte algae, which are now placed in separate Divisions.
  The land plants or Embryophytes (higher plants) are thought to have emerged from the Charophytes.[1] As the embryophytes are not algae, and are therefore excluded, green algae are a paraphyletic group. However, the clade that includes both green algae and embryophytes is monophyletic and is referred to as the clade Viridiplantae and as the kingdom Plantae. The green algae include unicellular and colonial flagellates, most with two flagella per cell, as well as various colonial, coccoid and filamentous forms, and macroscopic, multicellular seaweeds. In the Charales, the closest relatives of higher plants, full cellular differentiation of tissues occurs. There are about 8,000 species of green algae.[2] Many species live most of their lives as single cells, while other species form coenobia (colonies), long filaments, or highly differentiated macroscopic seaweeds.
  A few other organisms rely on green algae to conduct photosynthesis for them. The chloroplasts in euglenids and chlorarachniophytes were acquired from ingested green algae,[1] and in the latter retain a nucleomorph (vestigial nucleus). Green algae are also found symbiotically in the ciliate Paramecium, and in Hydra viridissima and in flatworms. Some species of green algae, particularly of genera Trebouxia of the class Trebouxiophyceae and Trentepohlia (class Ulvophyceae), can be found in symbiotic associations with fungi to form lichens. In general the fungal species that partner in lichens cannot live on their own, while the algal species is often found living in nature without the fungus. Trentepohlia is a filamentous green alga that can live independently on humid soil, rocks or tree bark or form the photosymbiont in lichens of the family Graphidaceae.

With my sample text, I'm getting green and algae words in the first lines as expected.
Problem is, I don't need only single words, I need word groups too. With this example text, I want green algae words too, together with green and algae words.
And my optional problem is: I need to do it with high performance, because texts can be very long. As i researched it's not high performance to use RegEx with this case, but I'm not sure about if there is a second way to make it possible.
Thanks in advance.
UPDATE If you got what I'm asking about, you don't need to read these lines.
As I see too many comments about my "group" definiton is not clear, I think I need to state my point with more detail and I wished write these lines on comments section but it's a little narrow area for this update. Firstly, I know StackOverflow is not a coding service. I'm trying to find the most used word groups in an article and trying to decide what's article about, we can call it tag generator too. For this purpose I tried to find most used words and it was okay at the beginning. Then i realized it's not a good way to decide about topic because I can't assume the article is about only first or second word. In my example I can't say this article is only about green or algae because they mean something together here, not alone. If i try this with an article about a three named celebrity like "Helena Bonham Carter" (if I assume it's written full name along article, not only surname), I want to take these words together not one by one. I'm trying to achieve more clever algorithm which is guessing the topic in most accurate way and with one shot. I don't want to limit the word count because article may be about "United Nations Industrial Development Organization" (again I assume it's now written like "UNIDO" in article). And I can achieve this by trying to get every word group starting from any index to the end of text with any length. Okay it's not a good way really, especially with long texts but it's not impossible right? But i was looking for a better way to do this and I just asked about a better algorithm idea and best tool to use, I can write the code by myself. I hope I stated my goal clear finally.

A: The way to achieve this is to take the initial text, and split it by whitespace into a string array using string.split(' ');
Next, you need to iterate over every string in the array.
This is easy for single words, but more complex for groups.
For this reason, you need to define a group size. You must control the number of places in the array the pointer advances for each iteration.
Once you are able to iterate the array, you need to grab the group of words (however long you have chosen it to be), and store it somewhere.
Your dictionary in the example is a good approach.
If the dictionary contains the word group, you increment its value by one.
If it doesn't contain the group, just add it with a default value of 1.
 if (wordList.ContainsKey(theKey)) {
   wordList[theKey]++;
 } else {
   wordList.Add(theKey, 1);
 }

You do rightly mention that your research showed that regex is not high performance. For this task, regex is completely the wrong tool - you're not looking for patterns, you're examining groups.
For that, you have to go through the text from start to finish, checking values.
Any task that involves iterating through text and running a repeating function on it should never use regex.
EDIT: My initial assumption of the performance of Regex was not correct - in C#, it seems to be a great deal faster than in Java, yet I would still maintain that a pure regex approach is not as quick as using regex to tokenise the text then use either a loop or linq expression to find the groups.
Stating

@galakt As I mentioned above, let's say 3. Does it matter?

The idea of a word group is entirely abstract. Yes, it's a group of words, but the whole block of text is a group of words.
Rules have to be applied to govern how you act on that group of words.
Below is a sample method which will return a dictionary of all the word groups based on a size passed via the method call.
It does not strip any non-alphanumeric chars from the text, but it is fast, even with larger group sizes.
To call it, use Dictionary<String, int> SingleWordGroups = GetWordGroupInstances(1);
    private Dictionary<String, int> GetWordGroupInstances(int GroupSize) {

        Dictionary<String, int> WordGroupInstances = new Dictionary<string, int>();

        //Grab the string to work from...
        String[] sourceText = GetSourceText().Split(' ');
        int pointer = 0;
        StringBuilder groupBuilder = new StringBuilder();
        while (pointer < sourceText.Length - GroupSize) {
            groupBuilder.Clear();
            int offset = pointer + GroupSize;
            for (int i = pointer; i < offset; i++) {
                //prepend a space to allow separation between words in groups.
                //We can make a substring from this later starting from char 1
                //to lose the initial whitespace from the string.
                groupBuilder.Append(" ").Append(sourceText[i]);
            }

            String key = groupBuilder.ToString().Substring(1);
            if (!WordGroupInstances.ContainsKey(key)) {
                WordGroupInstances.Add(key, 1);
            } else {
                WordGroupInstances[key]++;
            }

            /**
             * Setting the pointer to increase by group size grabs a group, moves on
             * to the end of the group, and grabs the next.
             *
             */
            pointer += GroupSize;

            /**
             * Setting the point to increment by 1 grabs a group, advances by 1 word, then
             * grabs the next, so from the phrase - "Hello world, I'm some text", the groups of size 2 would be
             * "Hello world,", "world, I'm", "I'm some" etc...
             */
            //pointer++;
        }

        return WordGroupInstances;

    }

The method below is modified to produce all the group output in turn, so
The
The Green
Green Algae
The Green Algae
etc...
It's worth noting that the entire text must be converted to either lower or upper case so that words are not case dependent.
I've refined this a little to improve the performance (and remove the need for the break instruction).
   private Dictionary<String, int> GetAllGroups() {
        Dictionary<string, int> WordGroupInstances = new Dictionary<string, int>();
        StringBuilder groupBuilder = new StringBuilder();
        String[] sourceText = GetSourceText().Split(' ');

        for (int i = 0; i < sourceText.Length; i++) {
            groupBuilder.Clear();
            for (int j = i; j < sourceText.Length; j++) {
                groupBuilder.Append(" ").Append(sourceText[j]);
                String key = groupBuilder.ToString().Substring(1);
                if (!WordGroupInstances.ContainsKey(key)) {
                    WordGroupInstances.Add(key, 1);
                } else {
                    WordGroupInstances[key]++;
                }
            }
        }
        return WordGroupInstances;
    }

After performance testing with the corpus of text (288 words), it will create the 41773 word groups in 0.171886 seconds.

A: Here is a streaming approach that recursively builds up groups of size N (3 in this example) from an enumerable of words.  It doesn't matter how you tokenize your input into words (I've used a simple regex in this example).
//tokenize input (enumerable of string)
var words = Regex.Matches(input, @"\w+").Cast<Match>().Select(m => m.Value);

//get word groups (enumerable of string[])
var groups = GetWordGroups(words, 3);

//do what you want with your groups; suppose you want to count them
var counts = new Dictionary<string, int>(StringComparer.CurrentCultureIgnoreCase);
foreach (var group in groups.Select(g => string.Join(" ", g)))
{
    int count;
    counts.TryGetValue(group, out count);
    counts[group] = ++count;
}

IEnumerable<string[]> GetWordGroups(IEnumerable<string> words, int size)
{
    if (size <= 0) throw new ArgumentOutOfRangeException();
    if (size == 1)
    {
        foreach (var word in words)
        {
            yield return new string[] { word };
        }

        yield break;
    }

    var prev = new string[0];

    foreach (var next in GetWordGroups(words, size - 1))
    {
        yield return next;

        //stream of groups includes all groups up to size - 1, but we only combine groups of size - 1
        if (next.Length == size - 1)
        {
            if (prev.Length == size - 1)
            {
                var group = new string[size];
                Array.Copy(prev, 0, group, 0, prev.Length);
                group[group.Length - 1] = next[next.Length - 1];
                yield return group;
            }

            prev = next;
        }
    }
}

One advantage with a streaming approach such as this is you minimize the number of strings that must be held in memory at any time (this reduces memory use for large bodies of text). Depending on how you receive your input, another optimization may be to use a TextReader to produce an enumeration of tokens as you read the input.
An example of the intermediate grouping output follows (each item is actually array of tokens, joined with a white space for output here):
The
green
The green
algae
green algae
The green algae
singular
algae singular
green algae singular
green
singular green
algae singular green
alga
green alga
singular green alga

A: I think that this works fairly well.
var text = @"The green algae (singular: green alga) are ..."; // include all your text

var remove = "().,:[]0123456789".Select(x => x.ToString()).ToArray();

var words =
    Regex
        .Matches(text, @"(\S+)")
        .Cast<Match>()
        .SelectMany(x => x.Captures.Cast<Capture>())
        .Select(x => remove.Aggregate(x.Value, (t, r) => t.Replace(r, "")))
        .Select(x => x.Trim().ToLowerInvariant())
        .Where(x => !String.IsNullOrWhiteSpace(x))
        .ToArray();

var groups =
    from n1 in Enumerable.Range(0, words.Length)
    from n2 in Enumerable.Range(1, words.Length - n1)
    select String.Join(" ", words.Skip(n1).Take(n2));

var frequencies =
    groups
        .GroupBy(x => x)
        .Select(x => new { wordgroup = x.Key, count = x.Count() })
        .OrderByDescending(x => x.count)
        .ThenBy(x => x.wordgroup.Count(y => y == ' '))
        .ThenBy(x => x.wordgroup)
        .ToArray();

This gives me the frequency of every single word grouping of contiguous sequences of words including up to a single word group of all the words.
The number of words is 288. The total number of word groups is 288 x (288 + 1) / 2 = 41,616. The final number of word groups (after grouping duplicate word groups and removing empty/whitespace strings) is 41,449.
Here are the first 100 of these 41,449:

20 x "the", 13 x "and", 12 x "algae", 12 x "in", 11 x "green", 10 x "of", 9 x "green algae", 8 x "are", 6 x "as", 6 x "species", 5 x "a", 4 x "is", 4 x "or", 4 x "to", 3 x "embryophytes", 3 x "form", 3 x "found", 3 x "lichens", 3 x "live", 3 x "on", 3 x "plants", 3 x "that", 3 x "algae and", 3 x "and in", 3 x "as the", 3 x "in the", 3 x "of the", 2 x "alga", 2 x "can", 2 x "clade", 2 x "class", 2 x "colonial", 2 x "filamentous", 2 x "from", 2 x "higher", 2 x "macroscopic", 2 x "most", 2 x "other", 2 x "seaweeds", 2 x "their", 2 x "trentepohlia", 2 x "while", 2 x "with", 2 x "algae are", 2 x "are a", 2 x "green alga", 2 x "higher plants", 2 x "in lichens", 2 x "of green", 2 x "species of", 2 x "the clade", 2 x "the green", 2 x "green algae and", 2 x "green algae are", 2 x "of green algae", 2 x "species of green", 2 x "the green algae", 2 x "species of green algae", 1 x "about", 1 x "acquired", 1 x "algal", 1 x "also", 1 x "associations", 1 x "bark", 1 x "be", 1 x "both", 1 x "cannot", 1 x "cell", 1 x "cells", 1 x "cellular", 1 x "charales", 1 x "charophyte", 1 x "charophytes", 1 x "chlorarachniophytes", 1 x "chlorophyte", 1 x "chloroplasts", 1 x "ciliate", 1 x "closest", 1 x "coccoid", 1 x "coenobia", 1 x "colonies", 1 x "conduct", 1 x "consisting", 1 x "differentiated", 1 x "differentiation", 1 x "divisions", 1 x "emerged", 1 x "euglenids", 1 x "excluded", 1 x "family", 1 x "few", 1 x "filaments", 1 x "flagella", 1 x "flagellates", 1 x "flatworms", 1 x "for", 1 x "forms", 1 x "full", 1 x "fungal", 1 x "fungi"


text:
Q: YouTube video in an iframe in Webview continues to play after navigation I had to embed a YouTube video in one of my windows 8 xaml apps. I added an iframe in a webView like this.
Now my problem is that when I navigate away from the page the YouTube video continues to play. Since the page in which the WebView is not present in the current view after navigation, I am not able to access the iframe as well. Is there a way to stop the video somehow once I navigate away from the page?
Thanks and Regards,
Ramya

A: Do you want to pause the video (and cache the page) so they can come back to where they were?
If not, then a less than elegant (but effective) option:

    protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
    {
        base.OnNavigatingFrom(e);
        wv.NavigateToString("");
    }

If you want to pause the video, I believe you should be able to accomplish that goal by including some JavaScript in the YouTube IFrame API in combination with OnNavigatingFrom and a call to InvokeScript.


text:
Q: Screen Recording on Mac is free using QuickTime 10. Is the free solution on Windows using CamStudio? On the Mac, we can now record a full screen or part of the screen if you have QuickTime 10 on Snow Leopard or QuickTime 10.1 on Lion.  It is free and it records sound as well.   The video is smooth and in high quality.
What if it is on PC.  Is the standard solution that is free on the PC CamStudio?  Is there any reliable alternatives?  I was a little bit worried because CamStudio's website looks like it might be pushing it a little hard, so I am worried about any possibility of adware or malware in it.


text:
Q: IOS after post request get error with additional symbol "\" I want to make a post request to my server. But when I get the response the server says that I sent wrong data. My code where i make the request is :
let urlAddress = Constants.API_DOMEN + Constants.SOC_LOGIN_ENDING
let request = NSMutableURLRequest(URL : NSURL(string: urlAddress)!)
let session = NSURLSession.sharedSession()

request.HTTPMethod = "POST"

let params = [Constants.NAME : name,
              Constants.EMAIL: email,
              Constants.PROVIDER: provider,
              Constants.UID: userId,
              Constants.PHONE_NUMBER: phoneNumber,
              Constants.AVATAR: photoURL,
              Constants.TYPE: "3",
              Constants.KEY: getMD5Hash(userId, provider: provider)]
            as Dictionary<String, String>

request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

let task = session.dataTaskWithRequest(request){ data, response, error in
....

But when i get the response
...
let task = session.dataTaskWithRequest(request){ data, response, error in
            guard data != nil else {
                print("no data found: \(error)")
                return
            }

            let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
.....

I see :
 dataString NSString?   "{\"head\": {\"errcode\": 400}, \"postdata\":
    {\"oe\": [\"57AE2750\\\",\\\"phone\\\":\\\"\\\",
    \\\"name\\\":\\\"\\u0418\\u043b\\u044c\\u044f \\u041c\\u044f\\u0441\\u043e\\u0435\\u0434\\u043e\\u0432\\\",
    \\\"provider\\\":\\\"facebook\\\",
    \\\"uid\\\":\\\"236653050055667\\\",
    \\\"type\\\":\\\"3\\\",
    \\\"key\\\":\\\"b182111b0cf5d2b0e652675eac544490\\\"}\"], \"{\\\"email\\\":\\\"\\\",\\\"avatar\\\":
\\\"https:\\\\/\\\\/scontent.xx.fbcdn.net\\\\/hprofile-xfa1\\\\/v\\\\/t1.0-1\\\\/s200x200\\\\/10354686_10150004552801856_220367501106153455_n.jpg?oh\": [\"e809266ec7a9e37c304ff6ec183b735b\"]},
 \"error\": {\"name\": 401, \"type\": 401,
 \"uid\": 401, \"key\": 401, \"provider\": 401}}"

1) In field name I get wrong symbols.I suppose that something wrong with encoding here.
2) IOS is adding symbol "\" to every quote. But I can't understand why.
Grateful for any help!

A: I found the solution. The right way to make a post request is shown below. I have added the complete function:
class func socialSignIn(name : String!, email: String!, provider: String!, userId: String!, photoURL: String!, phoneNumber: String!){
        var globalSuccess:Bool = false
        let urlAddress = Constants.API_DOMEN + Constants.SOC_LOGIN_ENDING
        let request = NSMutableURLRequest(URL : NSURL(string: urlAddress)!)
        let session = NSURLSession.sharedSession()

        request.HTTPMethod = "POST"

        var postString = Constants.NAME + "=" + name + "&";
        postString = postString + Constants.EMAIL + "=" + email + "&";
        postString = postString + Constants.PROVIDER + "=" + provider + "&";
        postString = postString + Constants.UID + "=" + userId + "&";
        postString = postString + Constants.PHONE_NUMBER + "=" + phoneNumber + "&";
        postString = postString + Constants.AVATAR + "=" + photoURL + "&";
        postString = postString + Constants.TYPE + "=" + "3" + "&";
        postString = postString + Constants.KEY + "=" + getMD5Hash(userId, provider: provider);

        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        let task = session.dataTaskWithRequest(request){ data, response, error in
            guard data != nil else {
                print("no data found: \(error)")
                return
            }

            //get user cookies
            let sessionId = getSessionId(response!)
            PreferencesHelper.setAuthToken(sessionId)

            do {
                if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary{
                    let success = json.objectForKey("head")?.objectForKey("errcode") as? Int
                    if success == Constants.SUCCESS {
                        globalSuccess = true
                    }
                    print("Success: \(success)")
                }else{
                    let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)    // No error thrown, but not NSDictionary
                    print("Error could not parse JSON: \(jsonStr)")
                }
            } catch let parseError{
                print(parseError)                                                          // Log the error thrown by `JSONObjectWithData`
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("Error could not parse JSON: '\(jsonStr)'")
            }

            NSNotificationCenter.defaultCenter().postNotificationName(ViewController.notificationResult, object: nil, userInfo:[Constants.SUCCESS:globalSuccess ])
        }

        task.resume()
}

The function that gets the session id looks like:
class func getSessionId(response: NSObject)->String{
        if let httpResponse = response as? NSHTTPURLResponse{
            if let headers = httpResponse.allHeaderFields as? [String:String], url = httpResponse.URL{
                let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(headers, forURL: url)
                for cookie in cookies{
                    var cookieProperties = [String: AnyObject]()
                    cookieProperties[NSHTTPCookieName] = cookie.name
                    if (cookie.name == "sessionid"){
                        return cookie.value
                    }
                }
            }
        }

        return ""
    }


text:
Q: Magento 2 configurable product variation dropdown attribute/s want to select automatically, if it has single option? We have configurable product have some drop down attribute variations. here would like to choose by default when the attribute has single option in the product view page.
Can you please give me some suggestions?

I found template file in the vendor:-

vendor/magento/module-configurable-product/view/frontend/templates/product/view/type/options/configurable.phtml

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

?>

<?php
/** @var $block \Magento\ConfigurableProduct\Block\Product\View\Type\Configurable*/
$_product    = $block->getProduct();
$_attributes = $block->decorateArray($block->getAllowAttributes());
?>
<?php if ($_product->isSaleable() && count($_attributes)):?>
    <?php foreach ($_attributes as $_attribute): ?>

            <label class="label" for="attribute<?= /* @escapeNotVerified */ $_attribute->getAttributeId() ?>">
                <?= $block->escapeHtml($_attribute->getProductAttribute()->getStoreLabel()) ?>

                <select name="super_attribute[<?= /* @escapeNotVerified */ $_attribute->getAttributeId() ?>]"
                        data-selector="super_attribute[<?= /* @escapeNotVerified */ $_attribute->getAttributeId() ?>]"
                        data-validate="{required:true}"
                        id="attribute<?= /* @escapeNotVerified */ $_attribute->getAttributeId() ?>"
                        class="super-attribute-select">
                    <option value=""><?= /* @escapeNotVerified */ __('Choose an Option1...') ?></option>
                </select>

    <?php endforeach; ?>

<?php endif;?>

pub/static/frontend/Magento/luma/en_US/Magento_ConfigurableProduct/js/configurable.js

_fillSelect: function (element) {
            var attributeId = element.id.replace(/[a-z]*/, ''),
                options = this._getAttributeOptions(attributeId),
                prevConfig,
                index = 1,
                allowedProducts,
                i,
                j;

            this._clearSelect(element);
            element.options[0] = new Option('', '');
            element.options[0].innerHTML = this.options.spConfig.chooseText;
            prevConfig = false;

            if (element.prevSetting) {
                prevConfig = element.prevSetting.options[element.prevSetting.selectedIndex];
            }

            if (options) {
                for (i = 0; i < options.length; i++) {
                    allowedProducts = [];

                    /* eslint-disable max-depth */
                    if (prevConfig) {
                        for (j = 0; j < options[i].products.length; j++) {
                            // prevConfig.config can be undefined
                            if (prevConfig.config &&
                                prevConfig.config.allowedProducts &&
                                prevConfig.config.allowedProducts.indexOf(options[i].products[j]) > -1) {
                                allowedProducts.push(options[i].products[j]);
                            }
                        }
                    } else {
                        allowedProducts = options[i].products.slice(0);
                    }

                    if (allowedProducts.length > 0) {
                        options[i].allowedProducts = allowedProducts;
                        element.options[index] = new Option(this._getOptionLabel(options[i]), options[i].id);

                        if (typeof options[i].price !== 'undefined') {
                            element.options[index].setAttribute('price', options[i].prices);
                        }

                        element.options[index].config = options[i];
                        index++;
                    }

                    /* eslint-enable max-depth */
                }

            }
        },

A: You can use custom jquery to select first option automatically, when there is a single option, like below in phtml file :

A: *

*Copy and pasted configurable.js from vendor/magento/module-configurable-product/view/frontend/web/js/configurable.js to my custom theme app/design/frontend/Vendor/Theme_Name/Magento_ConfigurableProduct/web/js/configurable.js

*There is a method _fillSelect: function around 356 line number as per the requirement modified as below.
  /*** Populates an option's selectable choices.
     * @private
     * @param {*} element - Element associated with a configurable option.
     */
    _fillSelect: function (element) {
        var attributeId = element.id.replace(/[a-z]*/, ''),
            options = this._getAttributeOptions(attributeId),
            prevConfig,
            index = 1,
            allowedProducts,
            i,
            j;

        this._clearSelect(element);
        element.options[0] = new Option('', '');
        element.options[0].innerHTML = this.options.spConfig.chooseText;
        prevConfig = false;

        if (element.prevSetting) {
            prevConfig = element.prevSetting.options[element.prevSetting.selectedIndex];
        }

        if (options) {
         var customIndex = 0; //define custom variable here
            for (i = 0; i < options.length; i++) {
                allowedProducts = [];

                /* eslint-disable max-depth */
                if (prevConfig) {
                    for (j = 0; j < options[i].products.length; j++) {
                        // prevConfig.config can be undefined
                        if (prevConfig.config &&
                            prevConfig.config.allowedProducts &&
                            prevConfig.config.allowedProducts.indexOf(options[i].products[j]) > -1) {
                            allowedProducts.push(options[i].products[j]);
                        }
                    }
                } else {
                    allowedProducts = options[i].products.slice(0);
                }

                if (allowedProducts.length > 0) {
                    options[i].allowedProducts = allowedProducts;
                    element.options[index] = new Option(this._getOptionLabel(options[i]), options[i].id);

                    if (typeof options[i].price !== 'undefined') {
                        element.options[index].setAttribute('price', options[i].prices);
                    }
                    element.options[index].config = options[i];
                    index++;
                    customIndex++;  //incremented
                }
                /* eslint-enable max-depth */
            }
             //add custom code here for preselect if single option avilable
             if(customIndex == 1){
                 setTimeout(function(){
                  $('#attribute'+attributeId).val($('#attribute'+attributeId+' option:nth-child(2)').val()).trigger('change');
                  $("#attribute"+attributeId).prop("disabled", false);
                 },200);
            }
        }
    },

*Executed deploy commands and cleared flush cache


text:
Q: LLVM IR main function returning void I'm testing a main function that simply returns void and am get core dump errors (signal 65 or 73) when running the bitcode with lli:
define void @main() {
entry:
  ret void
}

Is it a limitation of lli or just plain illegal in LLVM?
I'm well aware that in C++ the declaration of a main function with a return type of void is incorrect. In fact I've tried this with Clang (it's just a warning to do so) and get almost the same code (not exactly the same because of the #0 attributes, but close enough that I believe the differences are not causing this problem):
; Function Attrs: nounwind
define void @main() #0 {
entry:
  ret void
}

A: It doesn't crash for me, so the culprit must be something else:
$ echo "define void @main() {entry: ret void}" | lli -
$

In any case, lli supports void main methods, as you can see in ExecutionEngine::runFunctionAsMain().


text:
Q: Can I run a DLL in a separate thread? I have a program I'm writing in vb.net that has ballooned into the most complicated thing I've ever written.  Because of some complex math and image rendering that's happening constantly I've been delving into multithreading for the first time to improve overall performance.  Things have honestly been running really smoothly, but we've just added more functionality that's causing me some trouble.
The new functionality comes from a pair of DLLs that are each processing a video stream from a USB camera and looking for moving objects.  When I start my program I initiate the DLLs and they start viewing the cameras and processing the videos.  I then periodically ping them to see if they have detected anything.  This is how I start and stop them:
Declare Function StartLeftCameraDetection Lib "DetectorLibLeft.dll" Alias "StartCameraDetection" () As Integer
Declare Function StopLeftCameraDetection Lib "DetectorLibLeft.dll" Alias "StopCameraDetection" () As Integer

When I need to check if they've found any objects I use several functions like this:
Declare Function LeftDetectedObjectLeft Lib "DetectorLibLeft.dll" Alias "DetectedObjectLeft" () As Integer

All of that works really well.  The problem is, I've started to notice some significant lag in my UI and I'm thinking it may be coming from the DLLs.  Forgive my ignorance on this, but as I said I'm new to using multiple threads (and incorporating DLLs too if I'm honest).  It seems to me that when I start a DLL it running it's background tasks on my main thread and just waiting for me to ping it for information.  Is that the case?  If so, is it possible to have the DLL running on a sperate thread so it doesn't affect my UI?
I've tried a few different things but I can't seem to address the lag.  I moved the code that pings the DLL and processes whatever information it gets into a sperate thread, but that hasn't made any difference.  I also tried calling StartLeftCameraDetection from a separate thread but that didn't seem to help either.  Again, I'm guessing that's because the real culprit is the DLL itself running these constant background tasks on my main thread no what thread I actually call it's functions from.
Thanks in advance for any help you might be able to offer!

A: There's a lot to grok when it comes to threading, but I'll try to write a concise summary that hits the high points with enough details to cover what you need to know.
Multi-threaded synchronization is hard, so you should try to avoid it as much as possible.  That doesn't mean avoiding multi-threading at all, it just means avoiding doing much more than sending a self-contained task off to a thread to run to completion and getting the results back when it's done.
Recognizing that multi-threaded synchronization is hard, it's even worse when it involves UI elements.  So in .NET, the design is that any access to UI elements will only occur through one thread, typically referred to as the UI thread.  If you are not explicitly writing multi-threaded code, then all of your code runs on the UI thread.  And, while your code is running, the UI is blocked.
This also extends to external routines that you run through Declare Function.  It's not really accurate to say that they are doing anything with "background tasks on the main thread", if they are doing anything with "background tasks" they are almost certainly implementing their own threading.  More likely, they aren't doing any task breakdown at all, and all of their work is being done on whichever thread you use to call them---the UI thread if you're not doing anything else.
If the work being done in these routines is CPU-bound, then it would definitely make sense to push it off onto a worker thread.  Based on your comments on what you already tried:

I moved the code that pings the DLL and processes whatever information it gets into a sperate thread, but that hasn't made any difference. I also tried calling StartLeftCameraDetection from a separate thread but that didn't seem to help either.

I think the most likely problem is that you're blocking in the UI thread waiting for a result from the background thread.
The best way to avoid this depends on exactly what the routines are doing and how they produce results.  If they do some sort of extended process and return everything in function results, then I would suggest that using Await would work well.  This will basically return control to the UI until the operation finishes, then resume whatever the rest of the calling routine was going to do.
Note that if you do this, the user will have full interaction with the UI, and you should react accordingly.  You might need to disable some (or all) operations until it's done.
There are a lot of resources on Async and Await.  I'd particularly recommend reading Stephen Cleary's blog articles to get a better understanding of how they work and potential pitfalls that you might encounter.


text:
Q: Split data between 2 dates in SQL I have 2 date columns called Start_date and End_date in my table. I need to first find out how many weeks are in between those 2 dates and split the data.
--For e.g. if data is as given below,
ID  Start_date  End_date   No_Of_Weeks
1   25-Apr-11   8-May-11     2
2   23-Apr-11   27-May-11    6

--I need the result like this:
ID  Start_date       End_date

1       25-Apr-2011     01-May-2011
1       02-May-2011     08-May-2011

2       23-Apr-2011     24-Apr-2011
2       25-Apr-2011     01-Apr-2011
2       02-May-2011     08-May-2011
2       09-May-2011     15-May-2011
2       16-May-2011     22-May-2011
2       23-May-2011     27-May-2011

Please help me out with the query. My week start date is Monday.

A: As per the last understanding, this will work :
with demo_cte as
(select id,
 start_date,
 dateadd(day,6,DATEADD(wk, DATEDIFF(wk,0,start_date), 0)) end_date,
 end_date last_end_date,
 no_of_weeks no_of_weeks from demo

 union all

 select id,dateadd(day,1,end_date),
   dateadd(day,7,end_date),

 last_end_date
 ,no_of_weeks-1 from demo_cte

 where no_of_weeks-1>0)

 select id, start_date,
case
when end_date<=last_end_date then end_date
else
last_end_date
end
end_date
from demo_cte order by id,no_of_weeks desc

SQL Fiddle
And if number of weeks is not available use this :
with demo_cte as
(select id,
 start_date,
 dateadd(day,6,DATEADD(wk, DATEDIFF(wk,0,start_date), 0)) end_date,
 end_date last_end_date
 --,no_of_weeks no_of_weeks
 from demo

 union all

 select id,dateadd(day,1,end_date),
   dateadd(day,7,end_date),

 last_end_date
 --,no_of_weeks-1
 from demo_cte

 where --no_of_weeks-1>0
 dateadd(day,7,end_date)<=last_end_date
)

 select id, start_date,
case
when end_date<=last_end_date then end_date
else
last_end_date
end
end_date
from demo_cte order by id,start_date
--,no_of_weeks desc

A: You can use a Calendar table defining then weeks and join it to your data.
I've created a sql fiddle for the following:
CREATE TABLE Calendar_Weeks (
  week_start_date date,
  week_end_date date )

CREATE TABLE Sample_Data (
  id int,
  start_date date,
  end_date date )

INSERT Calendar_Weeks (week_start_date, week_end_date) VALUES ('2011-04-18','2011-04-24')
INSERT Calendar_Weeks (week_start_date, week_end_date) VALUES ('2011-04-25','2011-05-01')
INSERT Calendar_Weeks (week_start_date, week_end_date) VALUES ('2011-05-02','2011-05-08')
INSERT Calendar_Weeks (week_start_date, week_end_date) VALUES ('2011-05-09','2011-05-15')
INSERT Calendar_Weeks (week_start_date, week_end_date) VALUES ('2011-05-16','2011-05-22')
INSERT Calendar_Weeks (week_start_date, week_end_date) VALUES ('2011-05-23','2011-05-29')

INSERT Sample_Data (id, start_date, end_date) VALUES (1, '2011-04-25','2011-05-08')
INSERT Sample_Data (id, start_date, end_date) VALUES (2, '2011-04-23','2011-05-27')

SELECT id, week_start_date, week_end_date
FROM Sample_Data CROSS JOIN Calendar_Weeks
WHERE week_start_date BETWEEN start_date AND end_date
UNION
SELECT id, week_start_date, week_end_date
FROM Sample_Data CROSS JOIN Calendar_Weeks
WHERE week_end_date BETWEEN start_date AND end_date

I have to admit the UNION of the queries feels a bit of a hack to include rows at the start or end of the set, so you might prefer to use Ravi Singh's solution.
You can also use INNER JOIN if you like:
SELECT id, week_start_date, week_end_date
FROM Sample_Data INNER JOIN Calendar_Weeks
ON week_start_date BETWEEN start_date AND end_date
UNION
SELECT id, week_start_date, week_end_date
FROM Sample_Data INNER JOIN Calendar_Weeks
ON week_end_date BETWEEN start_date AND end_date

A: setting ambient test
    declare @dt table (ID int,Start_date datetime,
                       End_date datetime,No_Of_Weeks int)

    insert into @dt (ID,Start_date,End_date,No_Of_Weeks)
    select 1,   '25-Apr-11',   '8-May-11',     2
    union all
    select 2,  '23-Apr-11' ,  '27-MAy-11' ,   6;

try this...
    with cte as (select d.ID
                       ,d.Start_date
                       ,(select MIN([end]) from (values(d.End_date),(DATEADD(day,-1,DATEADD(week,DATEDIFF(week,0,d.Start_date)+1,0))))V([end])) as End_date
                       ,d.End_date as end_of_period
                 from @dt d
                 union all select d.ID
                      ,DATEADD(day,1,d.End_date) as Start_date
                       , case when d.end_of_period < DATEADD(week,1,d.End_date) then d.end_of_period else DATEADD(week,1,d.End_date) end as End_date
                       ,d.end_of_period as end_of_period
                 from cte d
                 where end_of_period <> End_date
                )
    select ID
          ,cast(Start_date as DATE) Start_date
          ,cast(End_date as date) End_date
    from cte
    order by cte.ID,cte.Start_date
    option(maxrecursion 0)

the resultset achieved...
    ID  Start_date  End_date
    1   2011-04-25  2011-05-01
    1   2011-05-02  2011-05-08
    2   2011-04-23  2011-04-24
    2   2011-04-30  2011-05-01
    2   2011-05-07  2011-05-08
    2   2011-05-14  2011-05-15
    2   2011-05-21  2011-05-22
    2   2011-05-28  2011-05-27

A: try this query, hope it will work
If your week starts on Sunday, use below
set datefirst 7

declare @FromDate datetime = '20130110'
declare @ToDate datetime = '20130206'

select datepart(week, @ToDate) - datepart(week, @FromDate) + 1

If your week starts on Monday, use below
set datefirst 1

declare @FromDate datetime = '20100201'
declare @ToDate datetime = '20100228'

select datepart(week, @ToDate) - datepart(week, @FromDate) + 1

note: both query will yield to diffrent results, since their starting dates differ.

A: You should look at using the DATEDIFF function.
I'm not sure what you're asking for in the second part of your question, but once you've got the difference between the dates, you may want to have a look at using CASE on the result of your DATEDIFF.

A: Here's a solution that uses the datepart function to account for the fact that your weeks start on Mondays:
with demo_normalized as
(
 select id,
  start_date,
  (datepart(dw,start_date) + 5) % 7 as test,
  dateadd(d,
       0 - ((datepart(dw,start_date) + 5) % 7),
       start_date
  ) as start_date_firstofweek,
  dateadd(d,
       6 - ((datepart(dw,start_date) + 5) % 7),
       start_date
  ) as start_date_lastofweek,
  end_date,
  dateadd(d,
       0 - ((datepart(dw,end_date) + 5) % 7),
       end_date
  ) as end_date_firstofweek,
  dateadd(d,
       6 - ((datepart(dw,end_date) + 5) % 7),
       end_date
  ) as end_date_lastofweek,
  datediff(week,
      dateadd(d,
          0 - ((datepart(dw,start_date) + 5) % 7),
          start_date
      ),
      dateadd(d,
          6 - ((datepart(dw,end_date) + 5) % 7),
          end_date
      )
  ) as no_of_weeks
 from demo
),
demo_cte as
(
  select
    id,
    dateadd(day,7,start_date_firstofweek) as start_date,
    dateadd(day,7,start_date_lastofweek) as end_date,
    end_date_firstofweek,
    no_of_weeks
  from demo_normalized
  where no_of_weeks >= 3
  UNION ALL select
    id,
    dateadd(day,7,start_date) as start_date,
    dateadd(day,7,end_date) as end_date,
    end_date_firstofweek,
    no_of_weeks
  from demo_cte
  where
    (dateadd(day,8,start_date) < end_date_firstofweek)
),
demo_union as
(
  select id, start_date, end_date, no_of_weeks from demo_normalized where no_of_weeks = 1
  union all
  select id, start_date, start_date_lastofweek as end_date, no_of_weeks
  from demo_normalized where no_of_weeks >= 2
  union all
  select id, start_date, end_date, no_of_weeks from demo_cte
  union all
  select id, end_date_firstofweek as start_date, end_date, no_of_weeks
  from demo_normalized where no_of_weeks >= 2
)
select
  d0.id,
 d0.no_of_weeks,
 convert(varchar, d0.start_date, 106) as start_date,
 convert(varchar, d0.end_date, 106) as end_date
from demo_union d0
order by d0.id, d0.start_date

EDIT (added CTE for the weeks in between):
Here is the link to sqlfiddle.
Note: This solution requires no additional DDL - no additional entities have to be created and maintained. In short, it doesn't reinvent the Calendar.
All the calendar logic is contained in the query.

A: You should use a date tally table similar to the type that Jeff Moden suggests in The "Numbers" or "Tally" Table: What it is and how it replaces a loop (required login).

A Tally table is nothing more than a table with a single column of very well indexed sequential numbers starting at 0 or 1 (mine start at 1) and going up to some number. The largest number in the Tally table should not be just some arbitrary choice. It should be based on what you think you'll use it for. I split VARCHAR(8000)'s with mine, so it has to be at least 8000 numbers. Since I occasionally need to generate 30 years of dates, I keep most of my production Tally tables at 11,000 or more which is more than 365.25 days times 30 years.

I started with Tony's SQL Fiddler but implemented a DateInformation table to be a little more generic.  This could be something that you could reuse.
--Build Test Data, For production set the date
--range large enough to handle all cases.
CREATE TABLE DateInformation (
    [Date] date,
    WeekDayNumber int,
)

--From Tony
CREATE TABLE Sample_Data (
id int,
start_date date,
end_date date )

DECLARE @CurrentDate Date = '2010-12-27'

While @CurrentDate < '2014-12-31'
BEGIN
    INSERT DateInformation VALUES (@CurrentDate,DatePart(dw,@CurrentDate))
    SET @CurrentDate = DATEADD(DAY,1,@CurrentDate)
END

--From Tony
INSERT Sample_Data VALUES (1, '2011-04-25','2011-05-08')
INSERT Sample_Data VALUES (2, '2011-04-23','2011-05-27')

Here's the solution using CTE to join the sample data to the DateInformation table.
--Solution using CTE
with Week (WeekStart,WeekEnd) as
(
  select d.Date
        ,dateadd(day,6,d.date) as WeekEnd
  from DateInformation d
  where d.WeekDayNumber = 2
)

select
  s.ID
  ,case when s.Start_date > w.WeekStart then s.Start_Date
    else w.WeekStart end as Start_Date
  ,case when s.End_Date < w.WeekEnd then s.End_Date
    else w.WeekEnd end as End_Date
from Sample_Data s
join Week w on w.WeekStart > dateadd(day,-6,s.start_date)
            and w.WeekEnd <= dateadd(day,6,s.end_date);

See solution in SQL Fiddle

A: set datefirst 1
GO

with cte as (
    select ID, Start_date, End_date, Start_date as Week_Start_Date, (case when datepart(weekday, Start_date) = 7 then Start_Date else cast(null as datetime) end) as Week_End_Date, datepart(weekday, Start_date) as start_weekday, cast(0 as int) as week_id
    from (
        values (1, cast('25-Apr-2011' as datetime), cast('8-May-2011' as datetime)),
                (2, cast('23-Apr-2011' as datetime), cast('27-May-2011' as datetime))
    ) t(ID, Start_date, End_date)

    union all

    select ID, Start_date, End_date, dateadd(day, 1, Week_Start_date) as Week_Start_Date, (case when start_weekday + 1 = 7 then dateadd(day, 1, Week_Start_date) else null end) as Week_End_date, (case when start_weekday = 7 then 1 else start_weekday + 1 end) as start_weekday, (case when start_weekday = 7 then week_id + 1 else week_id end) as week_id
    from cte
    where Week_Start_Date != End_date
)
select ID, min(Week_Start_Date), isnull(max(Week_End_Date), max(End_Date))
from cte
group by ID, Week_id
order by ID, 2
option (maxrecursion 0)

If you wanted to get the number of weeks, you could change the select after the cte to be:
select ID, Start_date, End_date, count(distinct week_id) as Number_Of_Weeks
from cte
group by ID, Start_date, End_date
option (maxrecursion 0)

Obviously to change the data used, the anchor (first part) of the cte where values() is being used would be changed.
This uses Monday as the first day of the week. To us a different day, change the set datefirst statement at the top - -- http://msdn.microsoft.com/en-gb/library/ms181598.aspx

A: Enjoy!
WITH D AS (
SELECT id
     , start_date
     , end_date
     , start_date AS WEEK_START
     , start_date + 7 - DATEPART(weekday,start_date) + 1
       AS week_end
 FROM DATA
), W AS (
SELECT id
     , start_date
     , end_date
     , WEEK_START
     , WEEK_END
 FROM D
UNION ALL
SELECT id
     , start_date
     , end_date
     , WEEK_END + 1 AS WEEK_START
     , WEEK_END + 7 AS WEEK_END
 FROM W
WHERE WEEK_END < END_DATE
)
SELECT ID
     , WEEK_START AS START_DATE
     , WEEK_END AS END_DATE
 FROM W
 ORDER BY 1, 2;


text:
Q: Is it possible to understand when a WPF window or page controlls loading is complete? I am working on a WPF Browser Application. I want to know how I can understand when the loading of a page is finished and the components are shown to start loading the heavy background services. Otherwise I just see a white page for some seconds untill all the services are loaded... Any recommendations to solve this problem?
Here is the thing I have tried:
    public Page1()
    {
        InitializeComponent();
    }

    private void Page_Loaded_1(object sender, RoutedEventArgs e)
    {

        // Just some heavy process in the begining
        int j = 1;
        for (int i = 0; i < 10000000; i++)
        {
            for (int k = 0; k < 1000; k++)
                j=j * 2;
        }
        MessageBox.Show("ready");
    }

However, the page components don't get loaded in the page untill the processes in page_loaded is finished. Without having the heavy process in the page_loaded, every thing loads very quickly, so there is not any problem in UI.
UPDATE: The thing I understood from loaded event for page or window is that it gets triggered when the page or window gets loaded, and loading of the components and the controlls on the page even the style of it will occure after that... and I don't seem to find any event that shows the loading of the controlls is completed...
UPDATE2: A better solution for my problem is to use BackgroundWorker or the Dispatcher to run the heavy process on background. As discussed in this post.

A: The Window class offers the Loaded event:

Occurs when the element is laid out, rendered, and ready for interaction.

Hook up a handler and execute your code there:
<Window ... Loaded="Window_Loaded"/>

A: You need to implement threading in your application for this. if you write any code in page load method. Your page will not rendered until the load method is completely executed. so you can use Background Worker and run the processes in background

A: As per my comment on your question and as per Tudor's answer, you need to use the Loaded event on your Page.
<Page ... Loaded="Page_Loaded_1"/>

Now it seems from your different comments that your Kinect initialisation is done as part of your Page UI rendering. Or that some other time-consuming task is being processed.
I have strictly no clue how Kinect works but I suspect in your code its initialization is called from one of the controls you added on the Page from Visual Studio Designer.
For example something like that:
<ContentControl DataContext="{Binding MyKinnectStuff}"/>

It may be more subtile. For example using a databinding on a property which getter calls a method initialising your Kinect thing. Double check it's not the case.
From the code sample you added in your edit, be sure that everything related to Kinect (initialisation, databinding, etc) is located in the method Page_Loaded_1 and that nothing is done directly from within the UI. Also ensure that you don't have any other time-consuming task performed in the UI. Finally, once again, ensure in your XAML you have <Page Loaded="Page_Loaded_1"/> and not <Page Loaded="Something_Else"/>.
You should edit again your question and show us what your XAML looks like.


text:
Q: "Gradle files have changed since last project sync." message does not go away after changing date I modified my PC's date(current date - 2) for some reason and after that I'm facing issues with the Gradle syncing process. No matters how many times I sync it the message

Gradle files have changed since last project sync. A project sync
  maybe necessary for IDE to work properly

pops up again and again. I have tried to apply other stack overflow solutions, i.e

correcting my time,date and timezone, cleaning and rebuilding the
  project and even deleting the files mentioned in .gitignore file
  (which is present in the project root directory) the files I was able to found
  and then building again, but to no avail. Maybe I'm missing something while following the solutions.

I'd really thankful if someone can help me in this matter.
This is how I have adjusted my time and date.
This is my top level build.gradle file
buildscript {

repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.1'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
    classpath 'com.google.gms:google-services:3.1.0'
  }
}

allprojects {
repositories {
    google()
    jcenter()
  }
}

task clean(type: Delete) {
delete rootProject.buildDir
}

And this is my app level build.gradle file:
apply plugin: 'com.android.application'

android {
compileSdkVersion 26
defaultConfig {
    applicationId "com.biji.riderapp"
    minSdkVersion 15
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
    }
 }
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.google.firebase:firebase-database:11.0.4'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.1'
  implementation 'com.android.support:recyclerview-v7:26.1.0'
}

apply plugin: 'com.google.gms.google-services'


text:
Q: NAudio 1.7 MediaFoundationEncoder I have a problem with MediaFoundationEncoder
I need to record from input device file in AAC format, I write the following code:
    private Timer timer;
    private static IWaveIn _waveIn;
    private static IWaveProvider _provider;
    public void StartRecorder()
    {
        _waveIn = new WaveInEvent
            {
                WaveFormat = new WaveFormat(8000, 1)

            };
        _provider = new WaveInProvider(_waveIn);

        _waveIn.DataAvailable += OnDataAvailable;
        _waveIn.StartRecording();

        //for testing purpose write only first 5 seconds.
        timer = new Timer(5000);
        timer.Elapsed += (sender, args) => Stop();
        timer.Start();

    }

    private void Stop()
    {
        timer.Stop();
        _waveIn.StopRecording();
        _waveIn.Dispose();
        _waveIn = null;
        var outputFilename = String.Format("D:\\{0:yyy-mm-dd HH-mm-ss}.aac", DateTime.Now);
        MediaFoundationEncoder.EncodeToAac(_provider, outputFilename);
        _provider = null;
    }

Also I tried to use MediaFoundationEncoder.EncodeToWma - BUT the file size continued to grow even after stopping the recording and disposed _waveIn. Timeline in file is corrrect, something writes to file trash bytes.
P.S. Im using the lastet build of NAudio (1.7).

A: The file size growing indefinitely issue is likely because your input provider never returns 0 from its Read method. I'd recommend you write all your audio to a memory stream and then use that with a RawSourceWaveProvider to form the input to your encoder. (remember to set the MemoryStream position to 0 before encoding)


text:
Q: How to push golang binary files to nexus repository from jenkinsfile? I have a problem when using golang, and nexus as the repository. it's different from maven which can download and push automatically to nexus, while golang can't automatically push when the module has been downloaded and the project binary has been built.
is there a way to push binary files into the in nexus golang repository?


text:
Q: Regarding the definition of totally bounded spaces The definition of totally bounded subset $A$ of a metric space according to most online sources was that for any given $e>0$ there exists a finite number of spheres of radius $e$ with centers in the metric space such that their union contains $A$. However my professor insisted that the centers of the spheres must belong to the $A$. I request anyone to shed some light on this matter.( by a sphere I mean the usual open balls)

A: I think your professor is right in the sense that you don't want whether $A$ is totally bounded to depend on the space $A$ is in, so his is a better way of phrasing the definition.  However, the definitions are equivalent.  Obviously, if $A$ is totally bounded in your professor's definition, it is totally bounded in the web's definition.  On the other hand, if it is totally bounded in the web's definition, consider any $\epsilon>0$.  $A$ is covered by a finite number of $\epsilon/2$ balls in the ambient space.  You can discard any of those balls that don't meet $A$.  From each of the remaining ones, select a point in the ball that is also in $A$.  Then that finite set of points is a set of centers in $A$ of $\epsilon$ balls that cover $A$ (since an $\epsilon$ ball centered at $x$ contains any $\epsilon/2$ ball that contains $x$).

A: Engelking ,General Topology, p266 defines it as "a metric space $(X,\rho)$ is uniformly bounded iff for every $\varepsilon >0$ there is a finite $A \subseteq X$  that is $\varepsilon$-dense". The latter means that for every $x \in X$ there exists some $a \in A$ such that $\rho(x,a) < \varepsilon$. (This essentially states that $\{B(a, \varepsilon): a \in A\}$ covers $X$).
So it's defined as a property of a metric space, and when we have a subset $A$ of a metric space, we restrict the metric on $X$ to $A$ and consider that set with the restricted metric as a metric space in its own right. If we then see what $A$ is totally bounded" means, we exactly get the "finite cover of balls with centres in $A$" definition. As Monsour noted, this is equivalent to the one with any open balls around any point of a larger space, but the generally used definiion (as Engelking uses it) is more "intrinsic", as there is no separate notion of a totoaly bounded subset of $X$, just of a totally bounded metric space.


text:
Q: Running all files in directory, what is go run ./cmd/*.go? I am currently looking at this project (Mattermost) that has a certain line in the makefile that I'm confused about:
$(GO) run $(GOFLAGS) $(GO_LINKER_FLAGS) ./cmd/platform/*.go --disableconfigwatch &

What is the meaning of ./cmd/platform/*.go? What specific files are executed? The program executes correctly when I type it in the terminal.
I am trying to enter the command line arguments in an IDE but I need a specific entry file.....

A:
Wikipedia
glob (programming)

In computer programming, in particular in a Unix-like environment,
    glob patterns specify sets of filenames with wildcard characters. For
    example, the Unix command mv *.txt textfiles/ moves (mv) all files
    with names ending in .txt from the current directory to the directory
    textfiles. Here, * is a wildcard standing for "any string of
    characters" and *.txt is a glob pattern. The other common wildcard is
    the question mark (?), which stands for one character.

Clearly, ./cmd/platform/*.go, starting in the current directory, looks in the cmd/platform directory for files matching the wildcard *.go.
The ls ./cmd/platform/*.go command will list the files on Linux.
So, the go run ./cmd/platform/*.go command compiles and runs these Go (*.go) source files. See Command go documentation: Compile and run Go program.