text:
Q: Why i am getting buffer overflow in this code? typedef struct
{
    int top;
    char *arr;
}adjacent;

char *removeDuplicates(char * S)
{
    int count = 0;
    adjacent *ptr = malloc(sizeof(adjacent));
    ptr->top = 0;
    ptr->arr = malloc(sizeof(char) * strlen(S));

    ptr->arr[0] = S[0];
    for(int i = 1; i < strlen(S); i++)
    {
        if(ptr->arr[ptr->top] == S[i])
        {
            count--;
            ptr->top = (ptr->top) - 1;
        }
        else
        {
            count++;
            ptr->top = (ptr->top) + 1;
            ptr->arr[ptr->top] = S[i];
        }
    }
    ptr->arr[count + 1] = '\0';
    return ptr->arr;
}

The error i am receiving is on website leetcode.com.
The question was to remove all adjacent duplicates from a string.
Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.
We repeatedly make duplicate removals on S until we no longer can.
Return the final string after all such duplicate removals have been made.  It is guaranteed the answer is unique.
ERROR:
Runtime Error
=================================================================
==29==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60200000004f at pc 0x0000004018ae bp 0x7ffed3a16300 sp 0x7ffed3a162f8
READ of size 1 at 0x60200000004f thread T0
    #2 0x7f9d2765f2e0 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x202e0)
0x60200000004f is located 1 bytes to the left of 6-byte region [0x602000000050,0x602000000056)
allocated by thread T0 here:
    #0 0x7f9d28ae92b0 in malloc (/usr/local/lib64/libasan.so.5+0xe82b0)
    #3 0x7f9d2765f2e0 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x202e0)
Shadow bytes around the buggy address:
  0x0c047fff7fb0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0c047fff7fc0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0c047fff7fd0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0c047fff7fe0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0c047fff7ff0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x0c047fff8000: fa fa 07 fa fa fa 00 00 fa[fa]06 fa fa fa fa fa
  0x0c047fff8010: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c047fff8020: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c047fff8030: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c047fff8040: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c047fff8050: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07
  Heap left redzone:       fa
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb
==29==ABORTING

A: Besides the off-by-one allocation, the memory leak, and the unnecessary duplication of count and arr->top there is a more serious issue.
Suppose the second character is the same as the first. The index is reduced to -1. Then when you check the next character, it is no longer checking the previous character, but indexing out of range.
The whole technique is in error. Instead of playing with indices, just increment it.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *removeDuplicates(char * S)
{
    char *arr = malloc(strlen(S) + 1);      // fix the off-by-one
    if (arr == NULL) {
        exit(1);
    }

    int count = 0;
    int index = 0;
    while(S[index] != '\0') {
        int duplic = 0;
        while(S[index + duplic + 1] == S[index]) {
            duplic++;
        }
        if(duplic == 0) {
            arr[count++] = S[index];
        }
        index += duplic + 1;
    }
    arr[count] = '\0';
    return arr;
}

int main()
{
    char s[100] = "";
    while(strcmp(s, "q") != 0) {
        scanf(" %99[^\n]", s);
        char *result = removeDuplicates(s);
        printf("[%s]\n", result);
        free(result);
    }
}

Test run:

aaab
[b]
abbb
[a]
abba
[aa]
aabbaa
[]
q
[q]


text:
Q: Pattern match with Table for matrix dimension check In Mathematica, often an expression involving matrices will encounter dimension mismatch errors, like we are multiplying a 3x2 matrix to a 3x4 matrix. Below we define a new symbol Dim, which can be passed through your algorithm as a fake parameter to detect errors.
Dim /: Dot[Dim[{x_, y_}], z_] /;
   MatrixQ[z] :=
  (checkEq[y, Dimensions[z][[1]]];
   Dim[{x, Dimensions[z][[2]]}]);

This method can handle most matrix operations, but failed on Table, which seems quite special. In fact, I failed to pattern match with Table by writing:
Dim /: Times[Dim[{x_, y_}], Table[z_]] := Dim[x, y];(*incorrect, just for syntax*)
Dim /: Times[Table[z_], Dim[{x_, y_}]] := Dim[x, y];

The expected result should be:
Dim[{3, 2}] Table[Sin[i + j], {i, 3}, {j, 2}] == Dim[{3, 2}]

But now Dim is multiplied over every element of table and it returns:
{{Dim[{3, 2}] Sin[2], Dim[{3, 2}] Sin[3]}, {Dim[{3, 2}] Sin[3], Dim[{3, 2}] Sin[4]}, {Dim[{3, 2}] Sin[4], Dim[{3, 2}] Sin[5]}} == Dim[{3, 2}]

Full code:
Clear[Dim];
checkEq =
  Function[{x, y},
   If[x != y, Print[ToString[x] <> "!=" <> ToString[y]]; Abort[]]];
Dim /: Dimensions[Dim[x_]] := x;
Dim /: MatrixQ[Dim[_]] := True;
Dim /: Dot[Dim[{x_, y_}], z_] /;
   MatrixQ[z] :=
  (checkEq[y, Dimensions[z][[1]]];
   Dim[{x, Dimensions[z][[2]]}]);
Dim /: Dot[z_, Dim[{x_, y_}]] /;
   MatrixQ[z] :=
  (checkEq[Dimensions[z][[2]], x];
   Dim[{Dimensions[z][[1]], y}]);
Dim /: Times[z_, Dim[{x_, y_}]] /;
   MatrixQ[z] :=
  (checkEq[Dimensions[z], {x, y}]; Dim[{x, y}]);
Dim /: Times[Dim[{x_, y_}], z_] /;
   MatrixQ[z] :=
  (checkEq[Dimensions[z], {x, y}]; Dim[{x, y}]);
Dim /: Plus[z_, Dim[{x_, y_}]] /;
   MatrixQ[z] :=
  (checkEq[Dimensions[z], {x, y}]; Dim[{x, y}]);
(*Dim/:Dot[Dim[{x_,y_}],Dim[{z_,w_}]]:=(checkEq[y,z];Dim[{x,w}]);
Dim/:Times[Dim[{x_,y_}],Dim[{z_,w_}]]:=(checkEq[x,z];checkEq[y,w];Dim[{x,y}]);\
Dim/:Plus[Dim[{x_,y_}],Dim[{z_,w_}]]:=(checkEq[x,z];checkEq[y,w];Dim[{x,y}]);*)
Dim /: Times[x_, Dim[{y_, z_}]] /; NumberQ[x] := Dim[{y, z}];

(*Below are tests that should return true.*)
MatrixQ[Dim[{2, 3}]]
Dimensions@Dim[{1, 2}] == {1, 2}
Dim[{3, 2}].Dim[{2, 4}] == Dim[{3, 4}]
Dim[{3, 2}].RandomReal[1, {2, 4}] == Dim[{3, 4}]
RandomReal[1, {2, 4}].Dim[{4, 3}] == Dim[{2, 3}]
Dim[{3, 2}] Dim[{3, 2}] == Dim[{3, 2}]
2 Dim[{3, 2}] == Dim[{3, 2}]
Dim[{3, 2}] - Dim[{3, 2}] == Dim[{3, 2}]

(*Below are tests that should raise errors.*)
Dim[{3, 2}] - Dim[{2, 4}]
Dim[{3, 2}] Dim[{2, 4}]
Dim[{5, 3}].Dim[{2, 4}]

A: I believe you have an evaluation order problem.  I suspect that you are unaware of the order of evaluation regarding UpValues definitions.  Allow me to give a few illustrations.
I'll make a generic UpValue rule using UpSetDelayed:
_[___, up[1], ___] ^:= "one"

Arguments are evaluated before UpValues rules are triggered, unless the function has a Hold attribute such as HoldAll:
List[Print[1 + 1], up[1], Print[2 + 2]]

2
4
"one"

For this reason your Table is evaluated before your Dim rule is checked.  Perhaps the most direct way around this is to use Unevaluated for every instance of Table.  Using a simplified rule:
dim /: Times[dim[], _Table] := "Table found"

Times[dim[], Table[x[n], {n, 5}]] (* this doesn't match *)

{dim[] x[1], dim[] x[2], dim[] x[3], dim[] x[4], dim[] x[5]}

Times[dim[], Unevaluated @ Table[x[n], {n, 5}]] (* this does *)

"Table found"

Of course this isn't very convenient.
I must admit I don't understand how you are intending to use Dims and why you don't merely check the data with Dimensions.  If you explain that perhaps I can suggest a different implementation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Predicate Building with subquery using LinqKit I am trying to work out how to build a predicate with a subquery that references the parent query.
Example:
I have 2 classes (Foo and Bar, of course).
The ReferenceId of Bar refers to (in this particular instance) Foo's Id.
public class Foo
{
    public int Id { get; set; }

    public bool IsGood { get; set; }
}

public class Bar
{
    public int Id { get; set; }

    public int ReferenceId { get; set; }

    public bool IsSomething { get; set; }
}

I have a DB context.
public class MyContext : DbContext
{
    public DbSet<Foo> Foos { get; set; }
    public DbSet<Bars> Bars { get; set; }
}

I want to use a predicate builder (if possible) to create a function like this... which checks for the existence of a Bar with the Foo's Id.
I do not have the Bar as a navigation property so I need to access the context directly.
public static IQueryable<Foo> GetFooQuery(IQueryable<Foo> query, MyContext context)
{
    query = query.Where(f => f.IsGood)
                 .Where(f => context.Bars.Where(b => b.ReferenceId == f.Id)
                                         .Where(b => b.IsSomething)
                                         .Any());

    return query;
}

I found this, which (I think) is similar to what I want, but not the same.
Entity Framework Code First 4.3 / LINQKit predicate for related table
I wrote this
public static IQueryable<Foo> GetFooQuery(IQueryable<Foo> query, MyContext context)
{
    var barPredicateBuilder = PredicateBuilder.True<Bar>();
    barPredicateBuilder = barPredicateBuilder.And(b => b.IsSomething);

    var fooPredicateBuilder = PredicateBuilder.True<Foo>();
    fooPredicateBuilder = fooPredicateBuilder.And(f => f.IsGood);
    fooPredicateBuilder = fooPredicateBuilder.And(f => context.Bars
                                                              .Where(b => b.ReferenceId == f.Id) // A
                                                              .Where(barPredicateBuilder).AsExpandable() // B
                                                              .Any());

    query = query.Where(fooPredicateBuilder).AsExpandable();

    return query;
}

but I am getting the error: The parameter 'f' was not bound in the specified LINQ to Entities query expression.
If I remove either line A or B, it executes with error. With them both, it throws the exception.
Can anyone please offer some input on what I should be doing to achieve this?
Thanks

A: Seems I was almost there. I just needed to flip lines A and B.
public static IQueryable<Foo> GetFooQuery(IQueryable<Foo> query, MyContext context)
{
    var barPredicateBuilder = PredicateBuilder.True<Bar>();
    barPredicateBuilder = barPredicateBuilder.And(b => b.IsSomething);

    var fooPredicateBuilder = PredicateBuilder.True<Foo>();
    fooPredicateBuilder = fooPredicateBuilder.And(f => f.IsGood);
    fooPredicateBuilder = fooPredicateBuilder.And(f => context.Bars
                                                              .Where(barPredicateBuilder).AsExpandable() // B
                                                              .Where(b => b.ReferenceId == f.Id) // A
                                                              .Any());

    query = query.Where(fooPredicateBuilder).AsExpandable();

    return query;
}


text:
Q: Weird result from "@SuppressWarnings" Eclipse was warning me that a local variable randInt might not be initialized (it was). So I added the first line:
@SuppressWarnings("all")
return randInt;

The warning went away, but I'm getting two new errors on the first line:
Syntax error: insert "enum Identifier" to complete EnumHeaderName, and
Syntax error: insert "EnumBody" to complete BlockStatement
What on earth? It's surprisingly hard to find information about @SuppressWarnings. Is there a more precise way of getting rid of this specific warning than using "all"?
Minimal, complete, verifiable example:
public class SuppressTest {
    public int cut() {
        int randInt = 0;
        @SuppressWarnings("all")
        return randInt;
    }
}

A: You can't insert @SuppresWarnings on a return statement. In java 8 you can annotate only classes, methods/constructors, fields, parameters and (new in java 8) local variables.
So in your case java can't parse what you have written. Move the @SuppressWarnings at the method level.


text:
Q: PHP mutual exclusion (mutex) Read some texts about locking in PHP.
They all, mainly, direct to http://php.net/manual/en/function.flock.php .
This page talks about opening a file on the hard-disk!!
Is it really so? I mean, this makes locking really expensive - it means each time I want to lock I'll have to access the hard-disk )=
Can anymore comfort me with a delightful news?
Edit:
Due to some replies I've got here, I want to ask this;
My script will run only by one thread, or several? Because if it's by one then I obviously don't need a mutex. Is there a concise answer?
What exactly I'm trying to do
Asked by ircmaxell.
This is the story:
I have two ftp servers. I want to be able to show at my website how many online users are online.
So, I thought that these ftp servers will "POST" their stats to a certain PHP script page. Let's assume that the URL of this page is "http://mydomain.com/update.php".
On the website's main page ("http://mydomain.com/index.php") I will display the cumulative statistics (online users).
That's it.
My problem is that I'm not sure if, when one ftp server updates his stats while another does it too, the info will get mixed.
Like when multi-threading; Two threads increase some "int" variable at the same time. It will not happen as expected unless you sync between them.
So, will I have a problem? Yes, no, maybe?
Possible solution
Thinking hard about it all day long, I have an idea here and I want you to give your opinion.
As said these ftp servers will post their stats, once every 60sec.
I'm thinking about having this file "stats.php".
It will be included at the updating script that the ftp servers go to ("update.php") and at the "index.php" page where visitors see how many users are online.
Now, when an ftp server updates, the script at "update.php" will modify "stats.php" with the new cumulative statistics.
First it will read the stats included at "stats.php", then accumulate, and then rewrite that file.
If I'm not mistaken PHP will detect that the file ("stats.php") is changed and load the new one. Correct?

A: Well, most of PHP runs in a different process space (there are few threading implementations).  The easy one is flock.  It's guaranteed to work on all platforms.
However, if you compile in support, you can use a few other things such as the Semaphore extension.  (Compile PHP with --enable-sysvsem).  Then, you can do something like (note, sem_acquire() should block.  But if it can't for some reason, it will return false):
$sem = sem_get(1234, 1);
if (sem_acquire($sem)) {
    //successful lock, go ahead
    sem_release($sem);
} else {
    //Something went wrong...
}

The other options that you have, are MySQL user level locks GET_LOCK('name', 'timeout'), or creating your own using something like APC or XCache (Note, this wouldn't be a true lock, since race conditions could be created where someone else gets a lock between your check and acceptance of the lock).
Edit:  To answer your edited question:
It all depends on your server configuration.  PHP May be run multi-threaded (where each request is served by a different thread), or it may be run multi-process (where each request is served by a different process).  It all depends on your server configuration...
It's VERY rare that PHP will serve all requests serially, with only one process (and one thread) serving all requests.  If you're using CGI, then it's multi-process by default.  If you're using FastCGI, it's likely multi-process and multi-thread.  If you're using mod_php with Apache, then it depends on the worker type:

*

*mpm_worker will be both multi-process and multi-thread, with the number of processes dictated by the ServerLimit variable.

*prefork will be multi-process

*perchild will be multi-process as well

Edit:  To answer your second edited question:
It's quite easy.  Store it in a file:
function readStatus() {
    $f = fopen('/path/to/myfile', 'r');
    if (!$f) return false;
    if (flock($f, LOCK_SH)) {
        $ret = fread($f, 8192);
        flock($f, LOCK_UN);
        fclose($f);
        return $ret;
    }
    fclose($f);
    return false;
}

function updateStatus($new) {
    $f = fopen('/path/to/myfile', 'w');
    if (!$f) return false;
    if (flock($f, LOCK_EX)) {
        ftruncate($f, 0);
        fwrite($f, $new);
        flock($f, LOCK_UN);
        fclose($f);
        return true;
    }
    fclose($f);
    return false;
}

function incrementStatus() {
    $f = fopen('/path/to/myfile', 'rw');
    if (!$f) return false;
    if (flock($f, LOCK_EX)) {
        $current = fread($f, 8192);
        $current++;
        ftruncate($f, 0);
        fwrite($f, $current);
        flock($f, LOCK_UN);
        fclose($f);
        return true;
    }
    fclose($f);
    return false;
}

A: The question is: Where will you store the stats that the FTP servers are pushing with POST to your update.php file? If it's a local file, than ircmaxell in the second post has answered you. You can do this with a mutex as well - the semaphore functions. Another solution is to use MySQL MyISAM table to store the stats and use something like update info_table set value = value + 1. It should lock the table, and serialize your requests, and you will have no problems.

A: I recently created my own simple implementation of a mutex-like mechanism using the flock function of PHP. Of course the code below can be improved, but it is working for most use cases.
function mutex_lock($id, $wait=10)
{
  $resource = fopen(storage_path("app/".$id.".lck"),"w");

  $lock = false;
  for($i = 0; $i < $wait && !($lock = flock($resource,LOCK_EX|LOCK_NB)); $i++)
  {
    sleep(1);
  }

  if(!$lock)
  {
    trigger_error("Not able to create a lock in $wait seconds");
  }

  return $resource;
}

function mutex_unlock($id, $resource)
{
  $result = flock($resource,LOCK_UN);
  fclose($resource);

  @unlink(storage_path("app/".$id.".lck"));

  return $result;
}

A: Yes that's true, as PHP is run by Apache, and Apache can organize the threads of execution as it deems the best (see the various worker model). So if you want to access a resource one at a time, you either lock to a file (which is good if you are dealing with cron jobs for example), or you rely on database transaction mechanism, ACID features, and database resources locking, if you are dealing with data.

A: PHP doesn't support multithreading, every request (and therefore every PHP script) will be executed in only one thread (or even process, depending on the way you run PHP).


text:
Q: RGraph with missing data points I want to plot an area fill line chart with multiple series, using javascript & RGraph, for a period between two dates, but I do not have data points for every date; how do I do this with RGraph?
I cannot miss out dates in the data I pass to RGraph because although some of the series do not have that data, it might be that other series do (e.g. ABC has data for January and March, and XYZ has data for January and April).
I must have all dates for the year, which is represented with a horizontal axis showing just the month/period labels.
I have boiled this down to a simplified example below, and with a jsFiddle example on https://jsfiddle.net/Abeeee/25m1sc7d/1/
Both the code below and the JSFiddle show two charts controlled by the drawAll() function, which has a variable x in it. I want the second chart (cvs2) which uses x=null to not include plotting that null but simply draw the red line/area between 100 and 200, resulting a similar chart to the first one (cvs1).
<!DOCTYPE HTML>

<canvas id='cvs1' width='900' height='300' style='border:solid 1pt red'>
    [No canvas support]
</canvas>

<canvas id='cvs2' width='900' height='300' style='border:solid 1pt blue'>
    [No canvas support]
</canvas>

So, how do you tell RGraph to just draw the points with data and ignore those without whilst keeping all the date points?
Thanks
Abe

A: You can use null values in your data. The behaviour is slightly different for a single dataset vs multiple data sets though:
var data = [4,8,6,3,5,4,2,null,8,6,3,5,8,null,4,9,8];

A: Well it seems that RGraph doesn't do it, so I've resorted to ChartJS and on the whole it works - see https://jsfiddle.net/Abeeee/6xrk1m23/41/

  <canvas id="canvas" style='width:100%; height:300px'></canvas>

<button id='on'>
  Span Gaps=true
</button>

<button id='off'>
  Span Gaps=false
</button>

var config = {
       type: 'line',
       data: {
       labels: ['Jan\n2018', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
       datasets: [{
          label: 'Red',
          borderColor: '#FF0000',
          backgroundColor: '#FF0000',
             data: [
    10, 20, 30, 40, 50, 60, undefined, 80, 90, 100, 90, 80
             ],
           }, {
             label: 'Blue',
             borderColor: '#0000FF',
             backgroundColor: '#0000FF',
             data: [
               10, 20, undefined, 40, 50, 60, 70, 80, 92, undefined, 90, 80
             ],
           }]
        },
        options: {
           spanGaps: true,
           responsive: true,
           maintainAspectRatio: false,
           title: {
           display: true,
           text: 'Chart.js Line Chart - Stacked Area'
           },
           tooltips: {
           mode: 'index',
       },
       hover: {
         mode: 'index'
       },
       scales: {
          xAxes: [{
          scaleLabel: {
             display: true,
             labelString: 'Month'
          }
       }],
       yAxes: [{
           stacked: true,
           scaleLabel: {
              display: true,
              labelString: 'Value'
           }
       }]
     }
  }
};

var ctx1 = document.getElementById('canvas').getContext('2d');
var myChart = new Chart(ctx1, config);

$("#on").on("click", function() {
  myChart.options.spanGaps=true;
  myChart.update();
});

$("#off").on("click", function() {
  myChart.options.spanGaps=false;
  myChart.update();
});

Use the buttons to switch spanGaps on and off.
Note, I say on the whole, as it fixes my problem (of underlying data gaps), but it seems to fail to span if the dataset is sitting on top of another (a ChartJS bug perhaps?)


text:
Q: SyntaxError: Unexpected end of JSON input al tratar de filtrar con input y y checkboxes Gracias por vuestras repuestas.
Estoy tratando de filtrar una tabla de angular material, pero tengo un problema porque estoy tratando de filtrar con un input para que filtre por todos los contenidos y con cehckboxes por dispositivos online o provisionados. El filtrado con checkboxes funciona perfectamente, pero, al intentar filtrar con el input, me da este error: SyntaxError: Unexpected end of JSON input
Se muestra solo cuando se introduce algo en la entrada para filtrar la tabla. El filtrado con casillas de verificación no muestra ningún error.
El error completo es:

core.js:6014 ERROR SyntaxError: Unexpected token d in JSON at position 0
    at JSON.parse (<anonymous>)
    at MatTableDataSource.dataSource.filterPredicate (provisioned-list.component.ts:116)
    at table.js:568
    at Array.filter (<anonymous>)
    at MatTableDataSource._filterData (table.js:568)
    at MapSubscriber.project (table.js:543)
    at MapSubscriber._next (map.js:29)
    at MapSubscriber.next (Subscriber.js:49)
    at CombineLatestSubscriber.notifyNext (combineLatest.js:73)
    at InnerSubscriber._next (InnerSubscriber.js:11)

al clicar sobre table.js linea 568:
 _filterData(data) {
        // If there is a filter string, filter out data that does not contain it.
        // Each data object is converted to a string using the function defined by filterTermAccessor.
        // May be overridden for customization.
        this.filteredData =
   -->568         !this.filter ? data : data.filter(obj => this.filterPredicate(obj, this.filter));
        if (this.paginator) {
            this._updatePaginator(this.filteredData.length);
        }
        return this.filteredData;

¿como puedo solucionar esto?
html:

              <mat-form-field class="filterField">
                <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter"
                  [(ngModel)]='filterValue'>
              </mat-form-field>

              <mat-checkbox [(ngModel)]="onlineValue"
                (change)="applyFilterOn('isOnline',onlineValue ? true : false)">
                Online</mat-checkbox>

              <mat-checkbox [(ngModel)]="offlineValue"
                (change)="applyFilterOn('isOnline',offlineValue ? false : true)">
                Offline</mat-checkbox>

                <mat-checkbox [(ngModel)]="provisionedValue"
                (change)="applyFilterOn('isProvisioned',provisionedValue ? true : false)">
                Provisioned</mat-checkbox>

                <mat-checkbox [(ngModel)]="deprovisionedValue"
                (change)="applyFilterOn('isProvisioned',deprovisionedValue ? false : true)">
                Deprovisioned</mat-checkbox>

The problem seems to be in the JSON parse (line 116-->    const filterValues = JSON.parse(filter);)
my ts:
 ngOnInit(): void {
        this.dataSource.filterPredicate = ((data: DeviceModel, filter: string): boolean => {
            const filterValues = JSON.parse(filter);
            console.log(filterValues)

            return (this.onlineValue ? data.isOnline === filterValues.isOnline : true) &&
                (this.offlineValue ? data.isOnline === filterValues.isOnline : true) &&
                (this.provisionedValue ? data.isProvisioned === filterValues.isProvisioned : true) &&
                (this.deprovisionedValue ? data.isProvisioned === filterValues.isProvisioned : true);
        });

 applyFilterOn(column: string, filterValueOn: string): void {
         this.filterValues[column] = filterValueOn;
        this.dataSource.filter = JSON.stringify(this.filterValues);

    }

applyFilter(filterValue: string): void {
        filterValue = filterValue.trim(); // Remove whitespace
        filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
        this.dataSource.filter = filterValue;
    }

A: Al parecer estas tratando de parsear una cadena de texto común y corriente (En el caso que pones empieza con "d" y por ende, no es caracter válido). Necesitas arreglar esta linea:

 ngOnInit(): void {
        this.dataSource.filterPredicate = ((data: DeviceModel, filter: string): boolean => {
            const filterValues = JSON.parse(filter);
            console.log(filterValues)

El problema se debería solucionar omitiendo el JSON.parse.


text:
Q: Integration - separable equations I'm trying to integrate: dx/dt = bx(1-x) so I have the general solution for x(t)
I've separated it so I now have: 1/bx(1-x) = dt and that dx = du/1-2bx which leads to ln(1-2bx) = dx. However I'm not sure if I should change this into an exponent or should I leave it as it is?
Thanks :)

A: Your answer seems wrong. Instead, you should get by separating:
$$\ln\left ( \left | \frac{x}{1-x} \right | \right ) = bt+c; \quad \quad b, c\in \mathbb{R}, x\in \mathbb{R} \setminus \left \{ 0, 1 \right \}$$
Hint: use $\frac{1}{x(x+1)} = \frac{1}{x} + \frac{1}{1-x}$.
Finally, you can exponentiate in the end as $e^{x}$ is bijective on $x\in \mathbb{R}^{+} \setminus \left \{ 0 \right \}$, meaning:
$$e^{x} = a \Leftrightarrow x = \ln(a)$$ On the positive reals.


text:
Q: What is the index of field extension $\mathbb{C}/\mathbb{R}$? What is the index of field extension $\mathbb{C}/\mathbb{R}$?
I know that the answer is $2$, but if so, that means $\mathbb{C}/\mathbb{R}=\{\mathbb{R}, i+\mathbb{R}\}$, and how come $5i+\mathbb{R}=i+\mathbb{R}$?

A: The degree of the field extension is 2: $[\mathbb{C}:\mathbb{R}] = 2$ because that is the dimension of a basis of $\mathbb{C}$ over $\mathbb{R}$.
As additive groups, $\mathbb{R}$ is normal in $\mathbb{C}$, so we get that $\mathbb{C} / \mathbb{R}$ is a group. The cardinality of this group is uncountably infinite (we have an answer for this here), which you should attempt to prove along the lines you suggested in the body of your question.

A: Take the map $f : \Bbb C \longrightarrow \Bbb C$ defined by $a+bi \mapsto bi,\ a,b \in \Bbb R.$ Observe that the kernel of the map $f$ is isomorphic to $\Bbb R$ and the image is the imaginary axis. So by the first group isomorphism theorem we can conclude that as a group $\Bbb C/\Bbb R$ is isomorphic to the imaginary axis which is uncountably infinite.


text:
Q: Use a closure inside a thread I'm trying to use a closure in a thread but after 2 hours of trying I can't seem to find how. Here's the file discord_async.rs:
use discord::*;
use discord::model::Event;
use std::sync::Arc;
use shared_mutex::SharedMutex;
use std::thread;

pub struct DiscordAsync {
    client: Arc<SharedMutex<Discord>>
}

impl DiscordAsync {
    pub fn new(bot_token: &str) -> DiscordAsync {
        let client = Arc::new(SharedMutex::new(Discord::from_bot_token(bot_token).unwrap()));
        DiscordAsync {
            client: client
        }
    }

    pub fn start<F>(&self, mut event_handle: F) -> () where F: FnMut(Arc<Event>, Arc<SharedMutex<Discord>>) + Send + 'static {
        let (mut connection, _) = self.client.read().unwrap().connect().unwrap();
        let event_handle = Arc::new(SharedMutex::new(event_handle));

        loop {
            let event = Arc::new(connection.recv_event().unwrap());
            let event_handle = event_handle.read().unwrap();

            // Start a thread so we don't block shit
            thread::spawn(move || {

                // Match event to actions we want to handle
                event_handle(event.clone(), self.client);
            });
        }
    }
}

I use it like this in main.rs:
extern crate colored;
extern crate discord;
extern crate shared_mutex;

mod discord_async;

use std::thread;
use colored::*;
use discord::*;
use discord::model::{Event, Channel, ServerId};
use discord_async::DiscordAsync;

fn main() {
    // Server info
    let bot_token = "...";
    let server_id = ServerId(12345);

    let dis_async = DiscordAsync::new(bot_token);
    dis_async.start(|event, _| {
        println!("{:?}", event);
    });
}

Compiler message:
   Compiling bottest1 v0.1.0 (file:///home/kindlyfire/Documents/dev/rust/bottest1)
error[E0477]: the type `[closure@src/discord_async.rs:29:18: 33:5 event_handle:shared_mutex::SharedMutexReadGuard<'_, F>, event:std::sync::Arc<discord::model::Event>, self:&discord_async::DiscordAsync]` does not fulfill the required lifetime
  --> src/discord_async.rs:29:4
   |
29 |            thread::spawn(move || {
   |            ^^^^^^^^^^^^^
   |
   = note: type must outlive the static lifetime

And my Cargo.toml:
[package]
name = "bottest1"
version = "0.1.0"
authors = ["kindlyfire"]

[dependencies]
discord = "0.7.0"
colored = "1.4"
shared-mutex = "0.2"

I've looked at a lot of different ways to do this, including on SO, but I can't find any that work.

A: You lock the mutex and then try to move the locked object into the thread. That's the wrong way around. You need to clone the Arc and move that into the thread.
Edit: I haven't tested this, but something like this should work:
pub fn start<F>(&self, mut event_handle: F) -> ()
    where F: FnMut(Arc<Event>, Arc<SharedMutex<Discord>>) + Send + 'static
{
    let (mut connection, _) = self.client.read().unwrap().connect().unwrap();
    let event_handle = Arc::new(SharedMutex::new(event_handle));

    loop {
        let event = Arc::new(connection.recv_event().unwrap());
        let event_handle = event_handle.clone();
        let client = self.client.clone();

        // Start a thread so we don't block shit
        thread::spawn(move || {

            // Match event to actions we want to handle
            event_handle.read().unwrap()(event, client);
        });
    }
}

Note that we create clones of the Arcs outside the lambda, and then use them inside. Except for event, which we don't clone, because we're fine with moving the one pointer we have. This moves the clones into the lambda. You could probably get rid of the Arc around Event, though. You don't have any other pointers to it, don't need to keep it alive, and it has to be Send anyway (I think &T is only Sync if T is Send).
If this doesn't work, please update with the new compiler error.
As a side note on terminology, a "handle" is an object that refers to some resource. A function that deals with events is a "handler".


text:
Q: What is the effect of vibrations on an object's properties? What do vibrations do to an object's properties? By making an object vibrate at a high frequency (compared to its static state) would vibrations:

*

*Increase or reduce its moment of inertia?

*Increase toughness?

*Change Newton's equation $F=ma$ (increase the force or reduce it)?

*Decrease the impact of an applied force (absorbing it) or increase it?


text:
Q: The difference between $d\mu(\omega)$ and $\mu(d\omega)$ Let $(\Omega,\mathcal{A},\mu)$ be measure space and $f:\Omega\to \mathbb{R}$ be a integrable function.
What is the difference between the following two formulas :
$$
(1) \int_{\Omega} f(\omega)d\mu(\omega)
\qquad
(2) \int_{\Omega} f(\omega)\mu(d\omega)
$$
are the two formulas identical?


text:
Q: When do we need to call std::string::capacity()? As a user, I have std::string's size()/resize()/reserve() to know and manage the memory of all these strings.
But, when do I have to use capacity()? Is there any use case or necessity that I should call this function to do something to achieve something?
Thanks!

A: If you for some reason want to avoid to allocated memory. For example in a very performance critical section of a real time application.

A: capacity tells you the maximum numbers of chars that you current string can store without growing in size. So you'll use it if you don't want your string to grow in size and take up more memory.

A: It's a good question. I'm going to run a risk of a flame war by saying that the calling of capacity() in user code is a code smell.
The only reason to call it would be to avoid a memory allocation mid-operation. In which case, a cleaner and more fault-tolerant strategy would be to create one's own class (say limited_length_string). A possible implementation might allocate sufficient memory up front (either through it's own implementation or by encapsulating a std::string and calling reserve() on it.
If you see this call in code you're working on, then beware of landmines. If you write this call, it's a signal that your design is suspect.


text:
Q: How to display a number using Accelerometer value I'm quite new to android so forgive me if I am asking a dead simple question.
Basically What I want to do is Display a number. when the value of Y, event.value[1] is between 1 and 7.
I can display values of X Y Z position. but as soon as I add if statement to check my app stops working (See code below)
I really need someones help please.
Thanks you for your help.
public void onSensorChanged(SensorEvent event) {
    // TODO Auto-generated method stub

float x = event.values[0];
float y = event.values[1];
float z = event.values[2];

int YValueMin = 1;
int YValueMax = 7;

accelero.setText("X: "+event.values[0]+
        "\nY: "+event.values[1]+
        "\nZ: "+event.values[2]);

if (y >= YValueMin && y <= YValueMax ){

    RepCounter.setText("1");

    }
else {
    RepCounter.setText(" ");
}
}

A: What does the logcat say when it crashes?
It is highly likely that your RepCounter is null, you can check this using the debugger.
Edit: Please change your code to the following, it could be a solution. If not, I will need the full source code to make sure RepCounter isn't a class or uninitialised object.
public void onSensorChanged(SensorEvent event)
    {
        if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
        {
            float x = event.values[0];
            float y = event.values[1];
            float z = event.values[2];
            int YValueMin = 1;
            int YValueMax = 7;

            accelero.setText("X: " + event.values[0] + "\nY: " + event.values[1] + "\nZ: " + event.values[2]);
            if(y >= YValueMin && y <= YValueMax)
            {
                RepCounter.setText("1");
            }
            else
            {
                RepCounter.setText(" ");
            }
        }
    }


text:
Q: How to replace 0.00 values with null in OBIEE12c . my column datatype is number How to replace 0.00 values with null in OBIEE12c . my column datatype is number
i need to apply it in RPD or as a self servicing report . it is not require for dashboard and prebuild report

A: You can use a CASE statement in the column formula of the report, e.g.
case "MyTable"."MyColumn" when 0 then null else "MyTable"."MyColumn" end

A: 0 and NULL are totally different things in analytics and what you're trying to do is already conceptually wrong.
If you made 500 this month and -500 last month does NOT mean you did NULL when aggregating both months. You did 0. And that also why you can't use NULL with numerical data types because you can not aggregate NULL.
Please don't force the system to violate all rules of data processing just do pull some GUI stunts.
EDIT: "Show blank"? Well you're supposed to be doing analytics with corporate data and not MS Paint, but here goes: Set a conditional rule on the column where value = 0 and then set a custom CSS style of "display:none". Ridiculous but will do what you want.

A: The easiest option is to save as a system wide default for that column.
Set the formatting you want and then on column properties click the save as default and save as the system wide default for that column
Both options will work in the front end but the value will still be output if you export data
Conditional Formatting
Create an analysis with the column you want formatting in.
Add conditional formatting where this value = 0
Either set the font size to 0 or use an image and set to image only
Custom Number Format
Set the number format to be #


text:
Q: Algebraic dimension of the (algebraic) complement of the Banach space Y in a Banach space X Can we claim the dimension of the algebraic complement of a Banach space $Y$ in the Banach space $X$ never equals $\aleph_0?$ Here, $Y$ is a linear subspace of $X?$

A: If you have a closed subspace $Y$ of Banach space $X$ ($Y$ will be closed if and only if it is a Banach space in its own right), we can form the quotient space
$$X / Y = \{x + Y : x \in X\}.$$ We can equip this space with a norm that will make it a Banach space as well.
Suppose $Z$ is a (not necessarily closed) complement to $Y$ in $X$ (i.e. $X = Y \oplus Z$). We can naturally identify $x + Y$ with $z$, where $y \in Y$ and $z \in Z$ are the unique vectors where $x = y + z$. This map is well-defined, and forms an isomorphism between $X/Y$ and $Z$ as pure (un-normed) vector spaces.
So, if $Z$ has alebraic dimension $\aleph_0$, then so must the Banach space $X / Y$, which is impossible.


text:
Q: Entity-Framework-Core: Mapping 1 to 1 Relationships using Composite Keys I'm having difficult configuring a 1:1 mapping in EntityFrameworkCore using FluentAPI.  The navigational reference is always NULL.  The only obvious difference between my code and countless others I have examined is I am trying to map via composite keys.
I've played around using annotations instead of Fluent API but encounter the same issue described in my summary.
Class Definitions
[Table("SomeTable")]
public class Defect
{
    [Column("Record")]
    public int DefectId { get; set; }
    [Column("insp_id")]
    public int InspId { get; set; }
    [Column("defectnum")]
    public int Number { get; set; }

    public virtual Simulation Simulation { get; set; }
}

[Table("SomeSimulationTable")]
public class Simulation
{
    [Column("Record"), Key]
    public int SimTableId { get; set; }
    [Column("insp_id")]
    public int InspId { get; set; }
    [Column("DefectNumber")]
    public int Number { get; set; }

    [Column("SimulationName")]
    public string Name{ get; set; }
    [Column("SimulationAlgorithm")]
    public string Algorithm{ get; set; }

    public virtual Defect Defect { get; set; }
}

Fluent API (in OnModelCreating)
 modelBuilder.Entity<Defect>()
     .HasKey(h => new { h.InspId , h.Number });

 modelBuilder.Entity<Defect>()
     .HasOne<Simulation>(p => p.Simulation)
     .WithOne(i => i.Defect)
     .HasForeignKey<Simulation>(b => new { b.InspId , b.Number });

When the "Defect" class is populated through the dbContext all data is available; however, when I attempt to access the "Simulation" property of the "Defect" class I encounter the following error:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
I have also verified there is valid data in our database where the "Defect" should have a "Simulation".
Any help?  Throwing myself at the mercy of other coders....

A: Take a look at the Include method when loading from the database, it will be null unless you explicitly load:

*

*https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.entityframeworkqueryableextensions.include?view=efcore-2.1

*https://entityframeworkcore.com/querying-data-include-theninclude


text:
Q: How to prevent strings getting cut at the # sign? I'm creating a social network and I wanna include the #hashtag feature...problem is posts are cut at the #. For example, if I wrote, "Hello #StackOverflow community!", the resulting string would be "Hello ". Below are the code and a debug screenshot.
$("#btnPostStatus").click(function () {
    var post = $("#txtNewStatus").val();
    $.post('/Logic/postStory?text=' + post.toString() + '', null, function(result) {
        alert(result);
        location.reload();
    });
});

A: Encode them properly, via encodeURIComponent:
'/Logic/postStory?text=' + encodeURIComponent(post)

It's important to do that for any value you put in a URL query string. (In fact, keys should be done too, but encodeURIComponent("text") is "text" so you can get away with not doing it for that particular key, and any other that's just made up of letters and digits.)
Also note that both the .toString() on post and the + '' are unnecessary.

Note that you're including the text parameter in the URL (e.g., like a GET parameter), not as POST data. If that's really what you mean to do, that's fine, but if you meant to include it in the POST data, you need to provide it as the second argument: $.post('/Logic/postStory', {text: post}, ...). (And if you pass it that way, as an object, jQuery will handle doing the URI-encoding for you.)

A: This happens because the # sign in a URL is interpreted as a so called named anchor. Try encoding the URL like this:
$.post('/Logic/postStory?text=' +  encodeURIComponent(post.toString()), ...

BTW, the + '' is not necessary in your case.

A: # should be replaced with %23
Please check HTML URL Encoding Reference for more details.
You can encode request using encodeURIComponent or simply by replacing # with %23 in your code.
I would suggest to encode whole URL.


text:
Q: How to Split string into an array using C#? When Domain Model property Name gets data from the database it's a string "David,James", but I have created another View Model to convert that string into an array ["David","James"]. I have used my ViewModel in the read method now, now the ViewModel should read the Name property as ["David","James"]. I am not sure how to make it happen.
I would appreciate if anybody has any suggestion on how to make it happen.
Domain Model:
public class FullName
{
    public Int32 Id { get; set; }
    public String Name { get; set; }
    public String Address {get; set;}
}

View Model:
public class NameViewModel
{
    public Int32 Id { get; set; }
    public List<string> Name { get; set; }
    public String Address { get; set;}
}

Read Method:
public ActionResult Name_Read([DataSourceRequest]DataSourceRequest request)
{
    try
    {
        DataSourceResult result = Identity.ToDataSourceResult(request, NameViewModel => new
        {
            Id = NameViewModel.Id,
            Name = NameViewModel.Name ,
            Address = NameViewModel.Address,
        });

        return Json(result);
    }

A: I think you're looking for something like this:
    DataSourceResult result = Identity.ToDataSourceResult(request, dataModel => new NameViewModel
    {
        Id = dataModel.Id,
        Name = dataModel.Name.Split(","),
        Address = dataModel.Address,
    });

A: // typical delimiter characters
char[] delimiterChars = { ' ' };

// verify the name exists
if (!String.IsNullOrEmpty(name))
{
    // Get the list of strings
    string[] strings = name.Split(delimiterChars);

    if (strings != null)
    {
        if (strings.Length == 1)
        {
           firstName = strings[0];
        }
        else if (strings.Length == 2)
        {
           firstName = strings[0];
           lastName = strings[1];
        }
        else if (strings.Length == 3)
        {
           firstName = strings[0];
           middleName = strings[1];
           lastName = strings[2];
        }
    }
}

I am not at Visual Studio, but I think that is right.

A:
When Domain Model property Name gets data from the database it's a string "David,James"

That is a terrible mistake in database Design. The ideal solution would be to fix the Backend Database to actually have two fields for those distinct values.
Failing that, the next step would be to try and split on the DB side. Many modern DBMS support Views, wich can have columns computed from actuall rows. That way you could avoid issues, like different code splitting the same input differently. And you could even henceforth treat it like it was always two Columns.
If you really want or need to it in code and given this exact input format, String.Split() can deal with this. Of coruse you can get fancier, and use stuff like Regular Expressions instead. But for this example, Split seems perfectly suiteable for the case.


text:
Q: In C/C++, does left or right shift by ZERO actually generate an instruction? I am not very familiar with assembly language or disassembly binary codes, could someone tell me, if "x <<= 0;" or "x >>= 0;" will actually generate instructions?

A: If x is an integer type, x >>= 0 and x <<= 0 should not generate any code.  Yet there are specific circumstances where the compiler could and indeed should generate code:

*

*If you turn optimizations off (clang -O0 or gcc -O0), the compiler may generate code and in the case of clang, will.  But it is not required to.

*If x is a volatile qualified type, the compiler is required to generate code to read its value and write back the value read.  The actual shifting will do nothing to the value, so the code generated may be identical to that generated for x = x;.

A: It depends really on the compiler and which optimizations are on. Nevertheless, GCC seems to consider them as no op even if optimization is -O0.
Live Demo
While CLANG with -O0 takes them under consideration and generates instructions.
Live Demo
Both compilers for -O1 and above optimize away these instructions.


text:
Q: Re-ordering nodes in an xml via jquery ui drag and drop I hope someone can help me here...
I am currently working on a small piece of code that will allow me to re-order nodes in an xml file via a jquery ui sortable interface.
Take the following xml file:
<Root>
   <Page1>
     <content>
       This is content 1
     </content>
   </Page1>
   <Page2>
     <content>
       This is content 2
     </content>
   </Page2>
   <Page3>
     <content>
       This is content 3
     </content>
   </Page3>
</Root>

I have been able to use php to to build a drag and drop interface based on the number of nodes in the xml file. What I am trying to achieve is a way of saving the new order of the xml files when the data is passed from the sortable interface.  From the jquery ui, I can get the ids required and I am able to pass that onto php.  My main issue is how to manipulate the xml file to get the following result:
<Root>
   <Page1>
     <content>
       This is content 3
     </content>
   </Page1>
   <Page2>
     <content>
       This is content 1
     </content>
   </Page2>
   <Page3>
     <content>
       This is content 2
     </content>
   </Page3>
</Root>

Hope this is making sense and I hope someone has an idea of how I can achieve this.  Is it possible to do this with DOMDocument as I believe SimpleXML is not powerful enough to handle such a task.
My day would be made if a solution can be attained.
Thanks.


text:
Q: Multiply two columns in a pandas MultiIndex dataframe I have never used multiIndex pandas dataframes, and the Python API for CalcBench, a financial program I use, returned one when I typed the following code:
dataItems = ["ROE", "StockholdersEquity", "SharesOutstandingEndOfPeriod", "EndOfPeriodStockPrice"]
data = cb.normalized_data(tickers, dataItems, start_year=2021, end_year=2021, period_type='annual')

If I try to explore my dataframe by typing data.info(), I get:
<class 'pandas.core.frame.DataFrame'>
PeriodIndex: 1 entries, 2021 to 2021
Freq: A-DEC
Columns: 1800 entries, ('EndOfPeriodStockPrice', 'A') to ('StockholdersEquity', 'ZTS')
dtypes: float64(1800)

Typing data.columns() gives me:
MultiIndex([('EndOfPeriodStockPrice',    'A'),
            ('EndOfPeriodStockPrice',  'AAL'),
            ('EndOfPeriodStockPrice',  'AAP'),
            ('EndOfPeriodStockPrice', 'AAPL'),
            ('EndOfPeriodStockPrice', 'ABBV'),
            ('EndOfPeriodStockPrice',  'ABC'),
            ('EndOfPeriodStockPrice',  'ABT'),
            ('EndOfPeriodStockPrice',  'ACN'),
            ('EndOfPeriodStockPrice', 'ADBE'),
            ('EndOfPeriodStockPrice',  'ADI'),
            ...
            (   'StockholdersEquity', 'WYNN'),
            (   'StockholdersEquity',  'XEL'),
            (   'StockholdersEquity',  'XOM'),
            (   'StockholdersEquity', 'XRAY'),
            (   'StockholdersEquity',  'XYL'),
            (   'StockholdersEquity',  'YUM'),
            (   'StockholdersEquity',  'ZBH'),
            (   'StockholdersEquity', 'ZBRA'),
            (   'StockholdersEquity', 'ZION'),
            (   'StockholdersEquity',  'ZTS')],
           names=['metric', 'ticker'], length=1800)

I would like to create a new metric MarketCapAtEndOfPeriod in this dataframe for each firm in the year 2021 by multiplying the corresponding entries for EndofPeriodStockPrice and SharesOutstandingEndOfPeriod.
My efforts to do so have gone nowhere, and searching StackOverflow has not helped me solve my problem. Loosely speaking, I'm looking to write something like:
data["MarketCapAtEndOfPeriod"] = data["EndofPeriodStockPrice"] * data["SharesOutstandingEndOfPeriod"]

A: market_cap = data.EndOfPeriodStockPrice * data.SharesOutstandingEndOfPeriod
market_cap_df = pd.concat(
    {"MarketCap": market_cap},
    names=["metric"],
    axis=1,
)

data = data.join(market_cap_df)

A:
multiplying the corresponding entries for EndofPeriodStockPrice and SharesOutstandingEndOfPeriod

Use DataFrame.xs to access MultiIndex cross-sections by specifying the label and an optional axis/level.

*

*In your case, the target labels are in the first level (default), so you can leave out level=0 and just specify axis=1 for columns.

*To assign the output as new columns, reconstruct the MultiIndex with MultiIndex.from_product before rejoining with the original dataframe.

key1 = 'EndofPeriodStockPrice'
key2 = 'SharesOutstandingEndOfPeriod'
new = 'MarketCapAtEndOfPeriod'

prod = data.xs(key1, axis=1) * data.xs(key2, axis=1)

prod.columns = pd.MultiIndex.from_product([[new], [key1, key2]])
# MultiIndex([('MarketCapAtEndOfPeriod', 'EndofPeriodStockPrice'),
#             ('MarketCapAtEndOfPeriod', 'SharesOutstandingEndOfPeriod')])

df = df.join(prod)

If hypothetically you wanted to divide corresponding AAPL and ABC entries, those are in the second column level, so specify both axis=1 and level=1:
data.xs('AAPL', axis=1, level=1) / data.xs('ABC', axis=1, level=1)


text:
Q: Webpack file-loader serving images but not audio (mp3) I'm writing a TypeScript application using Webpack and file-loader for serving images and audio. I can't get the webpack config to work with audio files.
Im getting GET http://localhost:8080/media/d.mp3 404 (Not Found)
The images work fine on the dev server and also build fine with the webpack setup below.
Folder structure:
|-public
|---audio
|---images
|-src
|---audio
|---images

Same result if I combine all extensions into one string and use a single folder.
My webpack.config.js:
const path = require('path');

module.exports = {
    entry: "./src/index.ts",
    output: {
        path: path.resolve(__dirname, 'public/scripts'),
        filename: 'bundle.js'
    },
    devtool: "source-map",
    module: {
        rules: [{
                test: /\.tsx?$/,
                loader: "awesome-typescript-loader"
            },
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            },
            {
                test: /\.(scss|sass|css)$/,
                exclude: /node_modules/,
                use: ['style-loader', 'css-loader', 'sass-loader']
            },
            {
                test: /\.(png|jpe?g|gif)$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: '[name].[ext]',
                            outputPath: '../images/',
                            publicPath: 'images/',
                            useRelativePaths: true
                        }
                    }
                ]
            },
            {
                test: /\.(mp3|wav)$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: '[name].[ext]',
                            outputPath: '../audio/',
                            publicPath: 'audio/',
                            useRelativePaths: true
                        }
                    }
                ]
            },
        ]
    },
    resolve: {
        extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
    },
    devServer: {
        contentBase: path.resolve(__dirname, 'public'),
        publicPath: '/scripts/'
    },
    node: {
        fs: "empty"
    }
};


text:
Q: Magical record Saving big amount of data to DB I am using magical record to save big amount of data to my database. I want to save it in the background but it freezes the UI. I'm saving it using
[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
    } completion:^(BOOL success, NSError *error) {
    }];

So it should not block the UI. But I've found that it uses main thread for some reasons to merge changes or something like that. I would be really grateful if someone could suggest a solution of how to make this more efficient.
Code that I'm using:
- (void)saveRidesForUser:(User *)user fromResponseData:(id)responseData
{

    if (![[[responseData valueForKey:@"rides"] class] isSubclassOfClass:[NSArray class]]) {
        return;
    }
    NSArray *rides = [responseData valueForKey:@"rides"];

    if (!rides)
        return;

    NSMutableArray *photoCacheArray = [[NSMutableArray alloc] init];

    [MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {

        User *rideUser = [user MR_inContext:localContext];

        for (NSDictionary *rideDictionary in rides) {

                Ride *ride = [Ride MR_createEntityInContext:localContext];
                ride.title = ([rideDictionary objectForKey:@"title"]) ? [rideDictionary valueForKey:@"title"] : @"";

                NSNumber *rideTimeStamp =[rideDictionary objectForKey:@"start_date"];
                if (rideTimeStamp)
                    ride.startDate = [NSDate dateWithTimeIntervalSince1970:[rideTimeStamp doubleValue]];

                NSNumber *rideEndTimeStamp =[rideDictionary objectForKey:@"end_date"];
                if (rideEndTimeStamp)
                    ride.endDate = [NSDate dateWithTimeIntervalSince1970:[rideEndTimeStamp doubleValue]];

                ride.serverID = [NSNumber numberWithInt:[[rideDictionary objectForKey:@"id"] intValue]];
                ride.isPopular = [NSNumber numberWithBool:NO];

                if ([rideDictionary objectForKey:@"intervals"]) {
                    NSArray *intervals = [rideDictionary objectForKey:@"intervals"];

                    for (NSDictionary *intervalDictionary in intervals) {

                        RideInterval *interval = [RideInterval MR_createEntityInContext:localContext];

                        interval.startDate = [NSDate dateWithTimeIntervalSince1970:[[intervalDictionary objectForKey:@"start_date"] integerValue]];
                        interval.endDate = [NSDate dateWithTimeIntervalSince1970:[[intervalDictionary objectForKey:@"end_date"] integerValue]];

                        interval.ride = ride;

                        if ([intervalDictionary objectForKey:@"points"] && ![[[intervalDictionary objectForKey:@"points"] class] isSubclassOfClass:[NSString class]]) {
                            NSArray *points = [intervalDictionary objectForKey:@"points"];

                            for (NSDictionary *pointDict in points) {

                                NSDictionary *pointDictionary = [pointDict dictionaryByReplacingNullsWithStrings];

                                RidePoint *point = [RidePoint MR_createEntityInContext:localContext];
                                point.timestamp = [NSDate dateWithTimeIntervalSince1970:[[pointDictionary objectForKey:@"timestamp"] integerValue]];

                                point.latitude = [NSNumber numberWithDouble:[[pointDictionary objectForKey:@"latitude"] doubleValue]];
                                point.longitude = [NSNumber numberWithDouble:[[pointDictionary objectForKey:@"longitude"] doubleValue]];
                                point.distanceFromPrevious = [NSNumber numberWithDouble:[[pointDictionary objectForKey:@"distance_from_previous"] doubleValue]];
                                point.interval = interval;
                            }
                        }
                    }
                }

                if ([rideDictionary valueForKey:@"photos"] && [[[rideDictionary valueForKey:@"photos"] class] isSubclassOfClass:[NSArray class]]) {
                    NSArray *photos = [rideDictionary objectForKey:@"photos"];

                    for (NSDictionary *photoDict in photos) {

                        NSDictionary *photoDictionary = [photoDict dictionaryByReplacingNullsWithStrings];
                        RidePhoto *photo = [RidePhoto MR_createEntityInContext:localContext];

                        photo.caption = [photoDictionary valueForKey:@"caption"];

                        NSNumber *timeStamp =[photoDictionary objectForKey:@"timestamp"];
                        if (timeStamp)
                            photo.timestamp = [NSDate dateWithTimeIntervalSince1970:[timeStamp doubleValue]];

                        photo.locationLatitude = [NSNumber numberWithDouble:[[photoDictionary objectForKey:@"location_latitude"] doubleValue]];
                        photo.locationLongitude = [NSNumber numberWithDouble:[[photoDictionary objectForKey:@"location_longitude"] doubleValue]];
                        photo.serverPath = [photoDictionary objectForKey:@"url"];
                        photo.imagePath = [NSString getUUID];
                        photo.ride = ride;

                        [photoCacheArray addObject:photo];
                    }
                }

                ride.user = rideUser;
            }

    } completion:^(BOOL success, NSError *error) {

        [[NSNotificationCenter defaultCenter] postNotificationName:kLTRideServise_RoutesDownloadedNotification object:nil userInfo:nil];

    }];

}

Thanks in advance for any help!

A: Are you using MR_defaultContext for your all other main-thread tasks?
I'm using saveWithBlock: method for background saving, MR_defaultContext for main-thread operations and it works fine. As far as I know, MagicalRecord is merging localContext with defaultContext at the end of saving operation.
Example code:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.0 * NSEC_PER_SEC),
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
        // your loop here in background thread
    } completion:^(BOOL success, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // completion on main thread
        });
    }];
});

A: [[NSNotificationCenter defaultCenter] postNotificationName:kLTRideServise_RoutesDownloadedNotification object:nil userInfo:nil];
==> Check what processing you are doing on completion. This notification is called on main thread, may be you are doing a lot of processing which is keeping main thread busy, resulting in freezing of UI.
Also check if you have registered for NSManagedObjectContextDidSaveNotification from any context, and see if you are doing any processing there.

A: I'm using

[[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreWithCompletion:aCallback];

to save context into Database.
It's documented like this

/// \brief      Asynchronously save changes in the current context all the way back to the persistent store
/// \param       completion  Completion block that is called after the save has completed. The block is passed a success state as a `BOOL` and an `NSError` instance if an error occurs. Always called on the main queue.
/// \discussion Executes asynchronous saves on the current context, and any ancestors, until the changes have been persisted to the assigned persistent store. The completion block will always be called on the main queue.

And this works fine for me, without any freezing.


text:
Q: Why don't different URLs work at the same time? I have a php function that runs the code below.
    echo SystemService::getCurrentTime();

    sleep(10);

    echo '------------2----' . SystemService::getCurrentTime();

    die;

And this function is triggered via a url. The problem is that even if I open 4 same links from an incognito tab, they all have a delayed start time.
For example, I entered the links 4 times at the same time. The first started immediately, the second 20 seconds later, the third 30 seconds later, and the fourth 30 seconds later.
If the links are working lagging, then why does the second and third start with a delay and the last link starts at the same time as the third link?
Sample outputs are as follows.
1st link: 2022-08-17 16:27:07------------2----2022-08-17 16:27:17
2nd link: 2022-08-17 16:27:17------------2----2022-08-17 16:27:27
3rd link: 2022-08-17 16:27:27------------2----2022-08-17 16:27:37
4th link: 2022-08-17 16:27:28------------2----2022-08-17 16:27:38

They all have to start at the same time. How can I fix this?


text:
Q: Drop down in UFT I am trying to select values from a drop down in my application. Drop down is getting identified as WebEdit in UFT.
Here is the line of code:
Browser().page().WebEdit("html tag:=INPUT","name:=WebEdit").Set "Add Document"

Add Document is a value in dropdown. Apart from "Add document" value, there are more values in drop down. please suggest how can i select those values one by one.
Thanks.

A: it should be WebList Object in Web application if it's a Dropdown.
I guess it's a Text Box Only in which if you click, multiple suggestion come like MakeMyTrip .
if it's the case you can use two approach.
1) Browser().page().WebEdit("html tag:=INPUT","name:=WebEdit").Set "SomeValue"
or
2) Browser().page().WebEdit("html tag:=INPUT","name:=WebEdit").Set "Someval"
  ' Then There will be Multiple Sujjestions, Which are nothing but WebElement.
  ' just click that WebElement

A: You can use descriptive programming to select values.
That way UFT won't select it as textbox implicitly.
Let me know if you are still facing issues.

A: From my experience, I guess the drop down you mentioned should be a dynamic one, Meaning a drop down will appear when you type words in that WebEdit column.
If so, my suggestion is that you can write a function to locate object's location (i.e. x,y property), and simulate mouse click the object. Now the object has been activated and you can type words. Use SendKey method to type some keywords you want to select, and use SendKey to press Enter to select it.
It's an ugly solution but sometimes it helps...


text:
Q: Derivative of rotation matrix in a form skew-symmetric matrix I am working on an application of CV, in which a way to calculate the derivative of rotation matrix is involved.
$$R$$ is the rotation matrix and $$R \in SO(3)$$
Also, $R$ is changing with $t$ giving $R(t)$.
$R(t)R(t)^\mathrm{T} = I$ is known. We calculate the derivative of $R(t)R(t)^\mathrm{T} $ which gives us a skew symmetric matrix $\dot{R}(t)R(t)^\mathrm{T} = -R(t)\dot{R}{}^\mathrm{T}(t) =: \phi(t)$, where
$$\phi (t) = \left[ \begin{matrix}
0 & -\phi_3  & \phi_2 \\
\phi_3 & 0 & -\phi_1\\
-\phi_2 & \phi_1 & 0
\end{matrix}
\right].
$$
The derivative of $R(t)$ is then given by
$$
\dot{R}(t) = \phi (t)  R(t).$$
To derive the Lie algebra, later, it gives the 1st order expansion of $R(t)$
$$ R(t) \approx R(t_0) + \dot{R}(t_0)\ (t-t_0) = I + t\ \phi (t_0) ,$$
where $t_0 = 0$ and $R(t_0) = I$.
By given an assumption that $\phi (t_0) = \phi_0$ around $t_0$, it gets
$$
\dot{R}(t) = \phi (t_0) R(t) = \phi_0 R(t).$$
This is the one I cannot get, i.e. the last equation is my question.
Any suggestion would be appreciated.

A: $\phi$ can be thought of as the tangent vector $\text{d}/\text{d}t$ of $R(t)$. For any $R(t)$, we can use the exponential map to obtain
$$R(t_0 + t) = R(t_0) + t\frac{\text{d}}{\text{d}t} R(t_0) + \frac{1}{2!}\left(t \frac{\text{d}}{\text{d}t}\right)^2 R(t_0) + \frac{1}{3!}\left(t \frac{\text{d}}{\text{d}t}\right)^3 R(t_0) + \ldots \\ = \sum^\infty_{n = 0} \frac{1}{n!} \left(t \frac{\text{d}}{\text{d}t}\right)^n = e^{t \phi } R |_{t_0}$$
By definition $R(t_0 = 0) = I$, we have
$$R(t) = e^{t\phi}$$
and we can differentiate the matrix exponential to obtain
$$\dot{R}(t) = \phi e^{t\phi} = \phi_0 R(t)$$

A: Use your $t_0 = 0$  so $R(0) = I$,
$$\dot{R}(t)R(t)^\mathrm{T}   =: \phi(t)= \phi(0)+ O(t)\leadsto \\
\dot{R}(t)= (\phi_0+ O(t) ) R(t)= (\phi_0+ O(t) )( I+ O(t))= \phi_0+ O(t)  .
$$
The order t terms vanish at 0, so $\dot{R}(0)=\phi_0$, antisymmetric, alright.


text:
Q: Windows 7/8 Screen overlay VC++ I am working on an application that would display things(graphics, texts, etc) like an OSD in Windows. The problem is that I am a newbie in windows programming and I couldn't find any proper solution.
What I've tried:
1: I tried to create a layered window with the WS_EX_LAYERED flag:

CreateWindowEx(WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_TOPMOST |
  WS_EX_TOOLWINDOW, szWindowClass, NULL, WS_POPUP | WS_VISIBLE |
  WS_SYSMENU, 0, 0, 0, 0, hWndDesktop, NULL, hInstance, NULL);

The problem is with this approach is that everything works fine, I can draw any images or texts on the screen until I am not in fullscreen in other application. For example playing videos.
After searching a lot I have found an other solution for my problem:
2: Direct3D
I found a code example and a good tutorial at msdn: http://msdn.microsoft.com/en-us/library/windows/desktop/dd797814(v=vs.85).aspx, but there is a problem(as always). It seems to me it uses a hardware overlay which is not supported in every graphics card. For example: ATI Radeon HD 6XXXX. But it is exactly what I need.
Does anyone know a proper solution that doesn't need hardware support? Or did I do something wrongly?

A: I solved the problem. I hope it will be helpful for someone:
So the only problem was that i didnt bring the window to the foreground after I had drawn on it. You can do it by calling the SetWindowPos. Altough this solution isnt working on Windows 8 metro surface.

A: Did you try with SetWindowsRgn?


text:
Q: Change a single byte in a file Using batch files, is it possible to modify a single byte of a file?
I am looking to make the following change:
Address 0x829: 1B -> 1A in file a\b\c.class
as you can see it is an edit of a compiled java class file, if that helps, but I don't want to use Java.

A: With pure batch it's extremly hard to handle binary data and if the data contains NULL then it will fail completly.
But you could use vbscript, that can handle it and is installed from WinXP to Win7

A: if you have debug1, that can be scripted
the e command edits memory
here is a tutorial: http://www.armory.com/~rstevew/Public/Tutor/Debug/debug-manual.html
1 debug is only available on 32 bit systems. It's available in XP, but I left 32 bit behind after that...


text:
Q: Can Azure Data factory publish data to Rest API We need the ADF to publish the data to a 3rd Party application exposing its REST API, can it be done via ADF or need we have a custom .Net code to do the data posting.
From the documentation it seems it can only retrieve the data https://learn.microsoft.com/en-us/azure/data-factory/connector-rest

A: You can publish data to a REST API from within ADF by using a web activity (recommended) or using a custom activity (using .NET code).
If you want to publish the output of an activity, you can chain the web activity to the activity you want to send the result of. You can then in your web activity reference the output of the previous activity using a dynamic expression similar to this :
@string(activity('CopyFromBlobToBlob').output)

Hope this helps.

A: This table shows which connectors are supported as source and sink. None of the web-based connectors is currently supported as sink. So no, you cannot do this with the built-in copy activity.
https://learn.microsoft.com/en-us/azure/data-factory/copy-activity-overview#supported-data-stores-and-formats


text:
Q: what situation could cause exist some digit number append main class name(e.g. FooApp(1)) in eclipse? I used spring boot to create some project , and run SomeApplication class in eclipse.  In Console tab exist this kind of message, e.g.

See above there is (1) appended Application class name. I'm curious why have (1).
When I run another spring boot project, it only have Application class name,

So what situation could cause exist some digit number append main class name in eclipse?

A: That is the name of the 'Run Configuration' for the application - see the 'Run > Run Configurations' dialog.
The configuration has been duplicated for some reason, in this case Eclipse adds '(1)' to the configuration name.


text:
Q: How to identify and re-establish the PostgreSQL connection based on the PostgreSQL server status? A PostgreSQL connection will be established once the project started running.
The same connection is used by multiple threads for database operations (insertion,selection etc.).
The connection will be gone once the server is down.
Then how to identify it and re-establish the connection as soon as the server is up?


text:
Q: Show that $x^{\frac1x}<1.5$ for $x \in \mathbb R$ Well, I've proven that :
$$x^{\frac1x}<1.5$$ for $x \in \mathbb R^+$, or more specifically I've shown that the maximum value of the expression is $1.44...$ for $x = e$. But I used calculus (finding the derivative, then finding the critical point and proving it is a local max).
But I'm looking for another method that does not require calculus (induction if possible, that's why I added $x \in \mathbb N$). The induction step seems pretty hard: I have no way to simplify $(x+1)^{\frac1{x+1}}$. Any help would be appreciated. (AM-GM inequality seems a good idea, though I am not able to proceed further..., or more specifically, it's not working for smaller values of x.)

A: For $x\in\{1,2,3\}$ it's obvious.
For $x\in\mathbb N$ and $x\geq3$ it's enough to prove that $$x^{\frac{1}{x}}>(x+1)^{\frac{1}{x+1}}$$ or
$$x^{x+1}>(x+1)^x,$$  for which we can use induction. See here: Prove by induction that $(k + 2)^{k + 1} \leq (k+1)^{k +2}$


text:
Q: How to Navigate A Grid Let's say I have the following grid:

I can't seem to figure out how to navigate it using a for loop starting in the bottom left hand corner. The order of cells should be
0,5 => 0,4 => 1,5 => 1,4 => 0,3 => 2,5, => 1,3 => 2,4 => 2,3...

Another way to visualize it:
(1) 0,5 =>
(2) 0,4 => (1,5) (1,4)
(3) 0,3 => (2,5) (1,3) (2,4) (2,3)
(4) 0,2 => (3,5) (1,2) (3,4) (2,2) (3,3) (3,2)

So Here is the Pattern that I see:

*

*To start each loop take the previous loops value (x,y) and make it (x, y-1)

*So then the pattern emerges that goes like: (+1, y) (x,-1) (+1, y) (x, -1) and so you could pull the old values and alternate increasing x with decreasing y.

Is a for loop the wrong tool for this job?
Is there a clever algorithm that will do so I don't have to pull the previous value and can just calculate them? Am I barking up the wrong tree here and should I approach it differently (correctly?)?
EDIT:
Here is an attempt at drawing the Path. Not sure if this makes more sense:

The idea is start in the bottom left corner on the first cell. Go up one cell, and then alternate as they form a right angle. Once the complete right angle is formed, go up one cell and alternate to form a new right angle.

A: Possible solution, edited for non square grid:
for(startY = maxY, startY >= 0; startY++)
{
    x1 = 0;
    y1 = startY;
    x2 = 5 - startY;
    y2 = 5;

    while(!(x1 == x2 && y1 == y2))
    {
        if(x1 <= maxX)
            //Point 1 is x1, y1

        if(y2 >= 0)
            //Point 2 is x2, y2

        x1++;
        y2--;
    }

    if(x1 <= maxX)
        //Final point is x1, y1
}

So you calculate two points on each iteration of the while loop and the last diagonal point for each iteration through the for loop after the rest of the points for that section of the path.


text:
Q: Focus on custom element when user clicks and create an overlay behind it I have a custom element which takes input whenever user clicks on it I want to focus on it and create an overlay on other elements and when the user clicks outside the div I want to remove the overlay.
I am trying to do it using iron-overlay-behavior but not able to achieve the expected behavior.
<custom-element
    with-backdrop
    scroll-action="lock"
    clicked="{{isClicked}}"
></decision-view>

All the examples shown are mostly for paper-dialog but how can I use iron-overlay-behavior for a custom element of my own?

A: The iron-overlay-behavior seems to be meant more for modal dialogs, what you are trying to accomplish is something different (for instance, modal dialogs are only shown one at a time, and require user input before going back to normal application/website behavior). So I think a natural thing for that behavior would be to disable anything else to focus!
When you say:

create an overlay on other elements

what does that mean? Just paint white over them like they were not visible?

A: I had a similar issue last week. See Showing a gray backdrop with a mixin
.
For a demo, see this pen from Makha:
<dom-module id="parent-component">
  <template>

Try me.

    <paper-button on-tap="_doTap">Push</paper-button>

  </template>

</dom-module>

<parent-component></parent-component>

<dom-module id="my-child">
  <template>

I'm a child.

    <paper-button on-tap="_doTap">Close</paper-button>
  </template>

</dom-module>


text:
Q: integral of product of monotonic non-decreasing function I need this thing for my work, I think it is true but not sure, didn't manage to prove it.
$f, g, f', g': \mathbb{R} \to \mathbb{R}^+$ are  all monotonic non-decreasing functions, continuous almost everywhere. We know that 1>$\int_{-\infty}^\infty f(x) dx > \int_{-\infty}^\infty f'(x) dx$ and $1>\int_{-\infty}^\infty g(x) dx > \int_{-\infty}^\infty g'(x) dx$. Prove that $\int_{-\infty}^\infty f(x)g(x) dx > \int_{-\infty}^\infty f'(x)g'(x) dx$.
Thanks!

A: I'll try a standard trick
and see if it helps.
Spoiler:
Didn't work.
Oh, well.
Maybe it will help someone else,
so I'll submit it.
$\begin{array}\\
\int_{-\infty}^\infty (f(x)g(x)- f'(x)g'(x)) dx
&=\int_{-\infty}^\infty (f(x)g(x)-f'(x)g(x)+f'(x)g(x)- f'(x)g'(x)) dx\\
&=\int_{-\infty}^\infty (f(x)g(x)-f'(x)g(x))dx+\int_{-\infty}^\infty(f'(x)g(x) -f'(x)g'(x)) dx\\
&=\int_{-\infty}^\infty (f(x)-f'(x))g(x)dx+\int_{-\infty}^\infty f'(x)(g(x)-g'(x)) dx\\
\end{array}
$


text:
Q: Attempt to call loadedData when saving models in ember I keep getting this error in my app but have no idea what is causing it.
It happens whenever I commit my data store:
Attempted to handle event loadedData on  while in state rootState.loaded.updated.inFlight. Called with undefined
Anyone?
Here is the code that causes it:
var ts_setting;

ts_setting = Cluey.Setting.find(Cluey.SettingsKeyIDs.API_TIMESTAMP);

if (ts_setting.get('value') != null) {
  console.log("Found Timestamp");
} else {
  console.log("Creating Initial Timestamp...");
  ts_setting.set("id", Cluey.SettingsKeyIDs.API_TIMESTAMP);
  ts_setting.set("value", 0);
  Cluey.store.commit();
}

Edit
I have boiled it down to the following code (written in coffeescript) that is causing the error. The thing is, that the first time I run the code, when the object first does not exist in the data store, it runs fine. The error then happens when I run the code on a data store that already contains a record with the specified id. This might help you decipher what is happening.
ts_setting = Cluey.Setting.find(Cluey.SettingsKeyIDs.API_TIMESTAMP)
ts_setting.get('value')
ts_setting.set("id", Cluey.SettingsKeyIDs.API_TIMESTAMP)
ts_setting.set("value", 0)
Cluey.store.commit()

Edit 2
I am having a similar problem creating a record:
ts_setting = Cluey.Setting.createRecord
    id: Cluey.SettingsKeyIDs.API_TIMESTAMP,
    value: 0

Cluey.store.commit()

The above code gives me this error:
Uncaught Error: Attempted to handle event `loadedData` on <Cluey.Setting:ember327:1> while in state rootState.loaded.created.inFlight. Called with undefined

Edit 3
So it turns out I was calling @timestamp = ts_setting.get('value') just after committing the store which I suppose was causing the issue, as I was trying to fetch some data from an object that had not yet been saved.

A: Loading data is asynchronous. Cluey.Setting.find returns you a promise that will be resolved/updated once the XHR request succeeds.
So you get your promise when calling Cluey.Setting.find, modify it (ts_setting.set("value", 0)) then at some point in time, you get the result from your server (the response from find).
At that moment, ember data raises an error because it can't update a record that is being modified.
What you want to do is to wait for your record to get completely loaded before modifying and saving it.
ts_setting = Cluey.Setting.find(Cluey.SettingsKeyIDs.API_TIMESTAMP);
ts_setting.one('didLoad', function() {
  ts_setting.set("value", 0);
  Cluey.store.commit();
});


text:
Q: Counting coin tosses Here's a question I got as a homework assignment:

A coin is tossed $k$ times. At some point the result was $T$, and then
  later on it was $H$. What are the number of possible permutations?

So, this is what I came up with:
$$\sum_{i=1}^{k-1}(i-1)(k-i-1)$$
$i$ represents the point where before it there was at least one $T$, and after it there was at least one $H$. $i$ can be in $k-1$ different index points, and then once we determine $i$ the are $i-1$ unknown elements to the left of it, and $k-i-1$ unknown elements to the right of it.
Am I right? Thanks!

A: You're thinking in a productive direction, but your counting is way off. First, you have to be a bit more careful in picking $i$; you should specify that it's the number of the first T. The $i-1$ tosses before the first T must all be H, so there's only one way that they can turn out. The $k-i$ tosses after the first T are another story: they can be anything except all T's. There are $2^{k-i}$ possible strings of $k-i$ heads or tails, and only one of them is ruled out, so there are $2^{k-i}-1$ possibilities for the $k-i$ tosses after the first T. That is, there are $2^{k-i}-1$ sequences of $k$ coin tosses that have their first T's on the $i$-th toss and have at least one H after that. The correct answer is therefore $$\sum_{i=1}^{k-1}\left(2^{k-i}-1\right)\;.$$
This can be simplified if you substitute $j=k-i$: then $j$ runs between $1$ (when $i=k-1$) and $k-1$ (when $i=1$), so
$$\sum_{i=1}^{k-1}\left(2^{k-i}-1\right)=\sum_{j=1}^{k-1}\left(2^j-1\right)=\sum_{j=1}^{k-1}2^j-\sum_{j=1}^{k-1}1=\sum_{j=1}^{k-1}2^j-(k-1)\;.$$
To finish simplifying the result, just use the formula for the sum of a finite geometric series.
By the way, there is a completely different way of analyzing the problem that leads to the final result a bit faster. There are $2^k$ possible outcomes when you toss a coin $k$ times. Which of them do not have the property that there is at least one T and at least one H after the first T? Obviously a string of $k$ heads, but there are others. In fact, these 'bad' strings are precisely the strings that consisting of $i$ heads followed by $k-i$ tails for $i=0,\dots,k$; how many bad strings are there, then, to be subtracted from $2^k$?


text:
Q: Why couldn't Nebula see Adam Warlock? This is a question about the original comic story of Infinity war. It's a question about events near the end, so I'll put the rest in spoiler tags.

 At the end, Nebula has the infinity gauntlet, and Dr. Strange teleports himself, Silver Surfer, Adam Warlock, and Thanos to face her. However, despite having the Godlike powers of the gauntlet, being able see the future and know the second they arrive, she is unable to sense Adam Warlock.  This allows him to enter the soul stone and eventually wrest the gauntlet away from her.

My question is, why?

 What kept Nebula from being able to see Adam Warlock even though she had the limitless power of the gauntlet?

A: A couple of facts first, from The Infinity Gauntlet #6.

*

*Thanos said to Nebula "You haven't the vision necessary to properly exploit the infinity gems!"

*Strange and Surfer stated "He stands outside the realms of chaos and order."

It's kinda like not knowing ultraviolet light exists.  Children don't know it exists so they don't look for it.  Nebula is that child.
She doesn't know that Warlock exists outside these 2 realms so she doesn't look for him when he arrives. Warlock also doesn't let his presence be known.  Strange, Surfer and Thanos know that Adam is there because they know this "secret" and use their powers to perceive Warlock. Of course, this isn't explained in the comic, you have to infer it yourself.
If Nebula had prior knowledge that such beings existed, she could have easily "wished" the gauntlet to let her see any such beings.
Nebula also doesn't sense Warlock because she misunderstands the capabilities of the Infinity Guantlet.  At most, she thinks its like a wish granting magic lamp/weapon of unlimted power.  If she was less ignorant, she could have stopped time and played with the guantlet and see what it's capabilities were.
But she just wasn't that smart/intelligent/knowledgeable.


text:
Q: How to get average of values in array between two given indexes in Swift I'm trying to get the average of the values between two indexes in an array. The solution I first came to reduces the array to the required range, before taking the sum of values divided by the number of values. A simplified version looks like this:
let array = [0, 2, 4, 6, 8, 10, 12]
// The aim is to take the average of the values between array[n] and array[.count - 1].

I attempted with the following code:
 func avgOf(x: Int) throws -> String {

let avgforx = solveList.count - x

// Error handling to check if x in average of x does not overstep bounds
        guard avgforx > 0 else {
            throw FuncError.avgNotPossible
        }

solveList.removeSubrange(ClosedRange(uncheckedBounds: (lower: 0, upper: avgforx - 1)))
        let avgx = (solveList.reduce(0, +)) / Double(x)

// Rounding
        let roundedAvgOfX = (avgx * 1000).rounded() / 1000
        print(roundedAvgOfX)
        return "\(roundedAvgOfX)"
    }

where avgforx is used to represent the lower bound :
array[(.count - 1) - x])

The guard statement makes sure that if the index is out of range, the error is handled properly.
solveList.removeSubrange was my initial solution, as it removes the values outside of the needed index range (and subsequently delivers the needed result), but this has proved to be problematic as the values not taken in the average should remain.
The line in removeSubrange basically takes a needed index field (e.g. array[5] to array[10]), removes all the values from array[0] to array[4], and then takes the sum of the resulting array divided by the number of elements.
Instead, the values in array[0] to array[4] should remain.
I would appreciate any help.
(Swift 4, Xcode 10)

A: Apart from the fact that the original array is modified, the error in your code is that it divides the sum of the remaining elements by the count of the removed elements (x) instead of dividing by the count of remaining elements.
A better approach might be to define a function which computes the average of a collection of integers:
func average<C: Collection>(of c: C) -> Double where C.Element == Int {
    precondition(!c.isEmpty, "Cannot compute average of empty collection")
    return Double(c.reduce(0, +))/Double(c.count)
}

Now you can use that with slices, without modifying the original array:
let array = [0, 2, 4, 6, 8, 10, 12]
let avg1 = average(of: array[3...])  // Average from index 3 to the end
let avg2 = average(of: array[2...4]) // Average from index 2 to 4
let avg3 = average(of: array[..<5])  // Average of first 5 elements


text:
Q: How to handle additional cases in subclass constructor? I have a java class.
Class ClassA {
    ClassA(int type)
    {
        switch(type)
        {
            case 1: handleType1(); break;
            case 2: handleType2(); break;
            default: throw new IllegalArgumentException(); break;
        }
    }

    private void handleType1(){}
    private void handleType2(){}
}

Now I have to add support for type 3 and type 4. But I can not modify code of ClassA.
So I thought I would write ClassB which extends ClassA and add support for type3 and type 4 as below.
Class ClassB extends ClassA{
    ClassB(int type)
    {
        case 3: handleType3(); break;
        case 4: handleType4(); break;
        default:
        {
            try{
                /* To support type 1 and type 2. */
                super(type);
            } catch(IllegalArgumentException e) {
              /* Handle exception. */
            }
        } break;
    }

    private void handleType3(){}
    private void handleType4(){}
}

I thought this would work. But I got "Call to super() must be first statement in constructor body" error in ClassB's construcor.
I read this post and I understand why super() has to be the first statement in the constructor.
I can address my use-case by writing complete code of ClassA in ClassB and adding support for type 3 and 4. But I want to know if there are any better solutions to this problem.

A:
Now I have to add support for type 3 and type 4. But I can not modify code of ClassA.

Then ClassB cannot reasonably subclass ClassA. A subclass must call a parent class constructor. (The unreasonable way it might subclass it would be to lie to the ClassA constructor by passing in a different type.)
Ideally, ClassA and ClassB would both implement an interface, and the rest of the application would be coded to use that interface rather than ClassA or ClassB specifically.

A: Parent class must be correctly initialized (via explicitly or implicitly calling parent class constructor) during initializing a child class, but in your case parent class can't be initialized with types 3 and 4 (and without types too).

A: You have a serious design flaw.
switches in general are a strong sign that you should make use of interfaces and polymorphism.
The code you currently have in the constructor of A should be in a factory class, and there should be an implementation of an interface declaring common methods for each handleTypeX


text:
Q: C++ error, Undefined reference class Why does codeblocks give this error "Undefined reference to class::classfunction()"
It happens when a class is created in a separated file.All of these files are in the same folder
This is the main .cpp file
#include<iostream>
#include "Class2.h"

using namespace std;

main()
{
    Class2 classObject;
    cout<<"I'm class2"<<endl;

}

class header file
#ifndef CLASS2_H
#define CLASS2_H

class Class2
{
    public:
        Class2();
        ~Class2();
    protected:
    private:
};

#endif // CLASS2_H

class cpp file
#include "Class2.h"
#include<iostream>

using namespace std;

Class2::Class2()
{
    cout<<"Hello, I'm Constructor"<<endl;
}

Class2::~Class2()
{
    cout<<"Yo!! I'm Destructor"<<endl;
}

error is "undefined reference to Class2::Class2()"

A: You need to link both main.o and class.o into your executable. The exact command depends on your compiler and OS. For g++ the command would look something like
g++ -o main main.cpp class.cpp


text:
Q: How to get value of  tag and preserve all the white spaces? I am using a
 tag to preserve white spaces and new lines. I am using contenteditable="true" inside the
 tag so that the user can edit the data.
I want to store the user edited data in a variable in JavaScript while preserving the users input but I am not quite sure how to do it. Any help or suggestion will be appreciated.Thanks!
XSL

<xsl:value-of select="$txn_desc"/>

A: Use .innerHTML if you want to get the markup inside the tag and use .textContent if you only need the text.
const pre = document.querySelector("pre");//get the tag
const text = pre.textContent;
const html = pre.innerHTML;

To prevent HTML being inserted into the contenteditable element, you can add an event listener for keydown and insert "\n" instead when the enter key is pressed.
pre.addEventListener("keydown", function(e){
    if(e.keyCode===13){
     document.execCommand('insertHTML', false, '\n');
     e.preventDefault();
  }
});

Demo:

const pre = document.querySelector('pre');
document.querySelector('button').addEventListener("click", function(e){
    alert(pre.textContent);
});
pre.addEventListener("keydown", function(e){
    if(e.keyCode===13){
     document.execCommand('insertHTML', false, '\n');
     e.preventDefault();
  }
});

Text inside

that is multi
line!
!

  !

<button>
Get text
</button>


text:
Q: How to prevent mysql injection in Php before it is submitted to the database
Possible Duplicate:
Best way to stop SQL Injection in PHP

Recently, I got my database wiped through a hacker inserting a DROP table command through a signup form.
This annoyed me and got me thinking:
How can I prevent mysql injection in php, before the information is sent to the database, e.g is there a way to detect that the user is trying to inject bad code into the database that can wipe it, and if so, detect it and display an error?
Also, is there a way to detect the mysql injection after it has been added, so when I am displaying the query, if it is the delete injection code, don't display it.
Thanks again, I apologise for any waffle.

A: Use either PDO or Mysqli with the binding syntax.  This alone will prevent most injection attacks.
Example:
    $stmt = $db->prepare(
                'UPDATE users ' .
                'SET userEmail=:email, userSalt=:salt, userPass=:pass ' .
                'WHERE userId=:userId LIMIT 1' );
    $stmt->bindParam( ':email',  $this->_email,    \PDO::PARAM_STR );
    $stmt->bindParam( ':salt',   $this->_salt,     \PDO::PARAM_STR );
    $stmt->bindParam( ':pass',   $this->_password, \PDO::PARAM_STR );
    $stmt->bindParam( ':userId', $this->_id,       \PDO::PARAM_INT );
    $stmt->execute();

In the above example, trying to escape the :email binding to insert a DROP TABLE won't work.
You still need to be careful with user-provided data.  For instance, if the user provides a $docId for a get document query, make sure they're authorized for the document being requested.  (And not just guessing a $docId belonging to some other user).

A: If you do not want to use PDO or mysqli I would suggest using transactions and only commiting to the database when you are sure that everything is correct.

A: Use PDO or mysqli's bind parameters functionality:
http://php.net/manual/en/mysqli-stmt.bind-param.php
http://www.php.net/manual/en/pdostatement.bindparam.php
The PDO syntax is easier to use, but either will work:
$pdo = new PDO($stuff);

$stmt = $pdo->prepare('SELECT * FROM foo WHERE bar = :baz');
$stmt->bindParam(':baz', $baz);
$stmt->execute();

A: <?php

function hashPassword($str)
{
        return hash("sha512", $str . "salt");
        //Change so it fits your database configuration.
}

$username = mysql_real_escape_string($_POST['username']);
$password = hashPassword($_POST['password']);

?>

This should do it.

A:
is there a way to detect that the user is trying to inject bad code?

It is useless and wrong approach.
You have to format your data properly, not hunt for some odd codes.
Besides that, I have a feeling that your problem cannot be solved with prepared statements.
If so, you will find the solution in my answer in the question linked in the comments.


text:
Q: input con calendario rango de fechas Hola tengo un input con calendario , necesito que permita seleccionar desde hoy a 6 dias atras , la ultima semana seria, hice este codigo pero no me muestra la parte de seleccionar solo ese rango de fechas, aca subo todo el codigo , para mas detalles, lo estoy haciendo con datepicker yo ese codigo lo tengo metido en un archivo .blade.php
desde ya gracias
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Datepicker - Select a Date Range</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

From
<input type="text" id="from" name="from">
to
<input type="text" id="to" name="to">

A: Podrías implementar esta librería daterangepicker e implementar algo más o menos parecido a esto:
$(function() {
  $('input[name="birthday"]').daterangepicker({
    singleDatePicker: true,
    showDropdowns: true,
    minYear: 2000,
    maxDate: "2020/10/10",
    maxYear: parseInt(moment().format('YYYY'),10)
  }, function(start, end, label) {
    var years = moment().diff(start, 'years');
    alert("You are " + years + " years old!");
  });
});

Al configurar el objeto puedes en la propiedad maxDate calcular la fecha actual y restarle los días, y pasarselo para que solo deje seleccionar en ese rango. En la página se ve más clara la explicación.


text:
Q: Two questions: Math mode and tree diagrams for probability in LaTeX I am trying to print a worksheet for the math class I'm teaching and I was wondering if anyone can specifically help me out in two areas.
a) How do I get the output BAL1L2 without the slant?
     $BAL_{1}L_{2}$

b) And is there is an easier code out there to create tree diagrams for probability?

A: You can use \(\mathrm{BAL_{1}L_{2}\) to remove the slant.
The best tree-diagram program out there is pgf-tkiz, but you could also hack out something with dirtree.
More on probability trees with pgf at this link: Example: Probability tree
Some dirtree stuff here: (Semi-)automatic directory-tree in LaTeX

A: A recommended tree with PSTricks.
\documentclass[preview,border=12pt]{standalone}
\usepackage{pst-tree}

\psset{treemode=R,edge=\ncline}

\def\ABCD{%
    \psTree{\Tcircle{A}}
        \psTree{\Tcircle{B}}
            \pstree[edge={\ncline[linecolor=red]}]{\Tcircle{C}}{\Tcircle{D}}\taput{\tiny an example}
            \pstree{\Tcircle{D}}{\Tcircle{C}}
        \endpsTree
        \psTree{\Tcircle{C}}
            \pstree{\Tcircle{B}}{\Tcircle{D}}
            \pstree{\Tcircle{D}}{\Tcircle{B}}
        \endpsTree
        \psTree{\Tcircle{D}}
            \pstree{\Tcircle{B}}{\Tcircle{C}}
            \pstree{\Tcircle{C}}{\Tcircle{B}}
        \endpsTree
    \endpsTree
}

\def\BACD{%
    \psTree{\Tcircle{B}}
        \psTree{\Tcircle{A}}
            \pstree{\Tcircle{C}}{\Tcircle{D}}
            \pstree{\Tcircle{D}}{\Tcircle{C}}
        \endpsTree
        \psTree{\Tcircle{C}}
            \pstree{\Tcircle{A}}{\Tcircle{D}}
            \pstree{\Tcircle{D}}{\Tcircle{A}}
        \endpsTree
        \psTree{\Tcircle{D}}
            \pstree{\Tcircle{A}}{\Tcircle{C}}
            \pstree{\Tcircle{C}}{\Tcircle{A}}
        \endpsTree
    \endpsTree
}

\def\CABD{%
    \psTree{\Tcircle{C}}
        \psTree{\Tcircle{A}}
            \pstree{\Tcircle{B}}{\Tcircle{D}}
            \pstree{\Tcircle{D}}{\Tcircle{B}}
        \endpsTree
        \psTree{\Tcircle{B}}
            \pstree{\Tcircle{A}}{\Tcircle{D}}
            \pstree{\Tcircle{D}}{\Tcircle{A}}
        \endpsTree
        \psTree{\Tcircle{D}}
            \pstree{\Tcircle{A}}{\Tcircle{B}}
            \pstree{\Tcircle{B}}{\Tcircle{A}}
        \endpsTree
    \endpsTree
}

\def\DABC{%
    \psTree{\Tcircle{D}}
        \psTree{\Tcircle{A}}
            \pstree{\Tcircle{B}}{\Tcircle{C}}
            \pstree{\Tcircle{C}}{\Tcircle{B}}
        \endpsTree
        \psTree{\Tcircle{B}}
            \pstree{\Tcircle{A}}{\Tcircle{C}}
            \pstree{\Tcircle{C}}{\Tcircle{A}}
        \endpsTree
        \psTree{\Tcircle{C}}
            \pstree{\Tcircle{A}}{\Tcircle{B}}
            \pstree{\Tcircle{B}}{\Tcircle{A}}
        \endpsTree
    \endpsTree
}

\begin{document}
\psTree[thislevelsep=0]{\Tn}
    \ABCD
    \BACD
    \CABD
    \DABC
\endpsTree
\end{document}


text:
Q: Using ini_set("memory_limit", "-1") and still out of memory I'm processing an old database php array to a new database. The data .php files are in total around 220 MB large.
I've inserted these lines in the script so that it should run fine:
ini_set("memory_limit", "-1");
set_time_limit(0);

This is how I include the products:
// The exports made by PHPMYADMIN, exported as PHP-Array
require_once 'export/tx_ttproductsv2_products.php';
require_once 'export/tx_ttproductsv2_keyword.php';
require_once 'export/tx_ttproductsv2_keywords_in_products.php';
require_once 'export/tx_ttproductsv2_typebook.php';
require_once 'export/tx_ttproductsv2_typegospel7.php';
require_once 'export/tx_ttproductsv2_typemedia.php';

When the script is trying to require them I get this error:

PHP Fatal error:  Out of memory (allocated 880541696) (tried to allocate 469762048 bytes) in ......

I've got an local EasyPHP installation running on x64 Win 7 SP1. I've got 6 GB memory, Intel i5.
How can I get PHP to run the whole script without the memory error?

A: Memory limitation comes from the OS, not from PHP itself.
Your script allocated 800MB and is trying to allocate further 500MB
Try to run the script on 64bit OS with 64 bit PHP.