How to detect where my app collapsed in linux

Question: HI, i am recently in a project in linux written in C.
This app has several processes and they share a block of shared memory...When the app run for about several hrs, a process collapsed without any footprints so it's very diffficult to know what the problem was or where i can start to review the codes....
well, it could be memory overflown or pointer malused...but i dunno exactly...
Do you have any tools or any methods to detect the problems...
It will very appreciated if it get resolved. thanx for your advice...
Answer: Before you start the program, enable core dumps:
ulimit -c unlimited

(and make sure the working directory of the process is writeable by the process)
After the process crashes, it should leave behind a core file, which you can then examine with gdb:
gdb /some/bin/executable core

Alternatively, you can run the process under gdb when you start it - gdb will wake up when the process crashes.
Answer: You could also run gdb in gdb-many-windows if you are running emacs. which give you better debugging options that lets you examine things like the stack, etc. This is much like Visual Studio IDE.
Here is a useful link
http://emacs-fu.blogspot.com/2009/02/fancy-debugging-with-gdb.html

Answer: Valgrind is where you need to go next. Chances are that you have a memory misuse problem which is benign -- until it isn't. Run the programs under valgrind and see what it says.
Answer: I agree with bmargulies -- Valgrind is absolutely the best tool out there to automatically detect incorrect memory usage. Almost all Linux distributions should have it, so just emerge valgrind or apt-get install valgrind or whatever your distro uses.
However, Valgrind is hardly the least cryptic thing in existence, and it usually only helps you tell where the program eventually ended up accessing memory incorrectly -- if you stored an incorrect array index in a variable and then accessed it later, then you will still have to figure that out. Especially when paired with a powerful debugger like GDB, however (the backtrace or bt command is your friend), Valgrind is an incredibly useful tool.
Just remember to compile with the -g flag (if you are using GCC, at least), or Valgrind and GDB will not be able to tell you where in the source the memory abuse occurred.


Mostrar telas diferentes dinamicamente usando UITableView

Question: Bom galera, vou explicar o que preciso fazer.
 Preciso criar uma tabela, onde cada linha tocada, terá que mostrar uma tela (Na verdade, um esqueleto padrão) e preencher essa nova tela com os dados referentes a ela.
E que seja de forma dinâmica, pois a tabela será uma lista de itens que serão adicionados e removidos.
Por exemplo: o app Relógio do iPhone, a função de Despertador. Quando você toca  em uma linha para editar um alarme, a tela que abrirá para edição é a mesma, porém os dados são referentes aquela linha que você escolheu.
Será uma grande ajuda! Obrigado.
Answer: Você pode fazer isso por dois meios.
O primeiro basta você definir uma propriedade na próxima UIViewController do tipo de objecto que você quer mostrar as informações. Feito isso, você instancia a UIViewController que você deseja mostrar as informações.
Por exemplo:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle:nil];
DetalhesEAlteracoesViewController *detalhesViewController = [storyboard instantiateViewControllerWithIdentifier:@"Detalhes"];
[detalhesViewController setObjeto: objetoASerDescrito];
[self.navigationController pushViewController:detalhesViewController animated:YES];
}

O segundo você pode usar outro meio, que é através dos métodos delegate de navegação. Basta usar a função performSegueWithIdentifier: e também definir uma propriedade na UIViewController que deseja apresentar as informações.
Exemplo:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[self performSegueWithIdentifier: @"Detalhes" sender: self];
}

No método delegate de navegação você instancia a UIViewController se defini o objeto:
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

if ([[segue identifier] isEqualToString: @"Detalhes"]) {
    DetalhesEAlteracoesViewController *detalhesViewController = [segue destinationViewController];
    [detalhesViewController setObjeto: objetoASerDescrito];
    [self.navigationController pushViewController: detalhesViewController animated:YES];
}
}

Comment: Vou tentar e retorno com o resultado! Obrigado!!
Comment: Bom seu código me ajudou! Mas fiz a navegação usando static cell. Então a célula se comporta feito um button pelo storyboard e é possível utilizar a navegação por push ou model transiction. Mas obrigado!!!
Answer: Você pode fazer:
-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
  NSArray segues = @[ @"SegueLinha1", @"SegueLinha2", @"SegueLinha3" ];
  [self performSegueWithIdentifier:segues[indexPath.row] sender:self];
}

Comment: Você pode inicializar a variável `segue` fora do método para evitar processamento redundante
Comment: Acho que você quis dizer indexPath.row :)
Comment: Sim, isso mesmo. Obrigado Otávio


Online audio stream using ruby on rails

Question: I'm trying to write small website that can stream audio online(radio station) and got few questions:
1. Do i have to index all my music files into database, or i can randomily pick file from file system and play it.
2. When should i use ajax to load new song(right after last finished, or few seconds before to get responce from server with link to file?)
3. Is it worth to use ajax, or better make list, that will play its full time and then start over?
Answer: I think you are asking the wrong Questions.

You need to think about how you will play the Audio in the browser (what player will you be using?).
You don't need Ruby on Rails to deliver the Files to the client. They can be requested directly from the Web server (Apache or Nginx)
Rails is only required for rendering the Website alongside the Player that will then play the Audio. Depending on what player you are using you can either control it through javascript to request the next song from the server or simply write a static playlist to the client that then gets played.
Comment: Most of all i'll use some simple js player + html5 audio api.
But i'm not sure if i understood you correctly about requesting files using Web server, can you explain more details, or point me where i can read about this.
I found some info on how to make radio streaming using php, and there are alot of code that doesnt response for views. Also i'd like to show current song name using ruby tag gem, that can read id3 tags from files
Comment: Well .. Ruby on Rails is a web framework that is focused on rendering HTML to the Client. Web servers main purpose (like Apache or NginX) is to serve Files from the Server's file-system to the Clients. So if you just put the mp3 file in the Rails application's public folder it is accessible from a client without you having to do anything..
Comment: Well i think i wont do that, because ill be in need of huge space on hosting. Is it possible to use some cloud based system like dropbox or g-drive\skydrive to host audio files and then use them using RoR?
Comment: How you store the data is totally up to you. You could even go ahead and use SoundCloud to host the Data and only embed their Audio Player in your Web-Site.. Rails is only serving the Website that acts as a Directory to access the Audio sources. Where you store it is dependent on you... But webhosting for large volumes of audio files is not cheap.. Free services only take you so far..
Answer: Regarding the streaming I aggree with @Tigraine
Now,
Single song play:
1 if you want to play an individual song then in your ajax call to action return a key value pair in json response which contains the audio URL of requested song.

For Playlist:
2. You should return an array which contains the audio URL in the same arrangement as they were added into playlist.
Then in your java script declare variable
var current_song
var total_song
In js audio player we commonly have methods which detects when the song completes and then on song complete you can increment the song counter as
current_song+=0
when the counter reaches to end reset it to one:
Sample code is:
Here I am using Jplayer you can use any other player which one of the best and fully customizable player.
<code> var current_song = 0;
    var total_songs;
    var song_id_array;

        $.ajax({
            url:"<%=url_for :controller => 'cont_x',:action => 'song_in_playlist'%>",
            data:'playlist_id=' + encodeURIComponent(playlist_id),
            cache:false,
            success:function (data) {
                song_id_array = data.array; //data.array variable contain's the audio URL's array of songs inside selected playlist which is returned by the action //
                total_songs = song_id_array.length;
            }
        })
        current_song = 0;
        play_right_song(current_song);
    }

    function play_right_song(current_song) {
        $("#jquery_jplayer_1").jPlayer("destroy");
        var audio_url_inside = song_id_array[current_song];
        $('#jquery_jplayer_1').jPlayer({
            ready:function (event) {
                $(this).jPlayer("setMedia", {
                    mp3:audio_url_inside
                }).jPlayer("play");
            },
            ended:function () { // The $.jPlayer.event.ended event
                current_song += 1;
                if (current_song >= total_songs) {
                    current_song = 0;
                }
                play_right_song(current_song);
            },
            swfPath:"<%= asset_path('Jplayer.swf')%>",
            supplied:"mp3"
        });
    }
</code>
and if you want to handle next and previous song in playlist just ask for the code. I will update the answer.
Comment: Thanks for answer. But i understood that i need streaming server to broadcast music like on radio.

Online audio stream using ruby on rails


Conversor de C# para JavaScript: ((objeto)sender).atributo

Question: Estou desenvolvendo um conversor de C# para JavaScript e estou em um entrave, quando o código tiver uma linha de código assim:
<code>((CONTROLE)sender).Atributo
Exemplo:((ImageButton)sender).ImageUrl
</code>
Qual o código correspondente em JavaScript?
Comment: JavaScript puro ou você usa um Framework para converter?
Comment: JavaScript puro.
Answer: Veja, em C#, você está dizendo:
((ImageButton)sender).ImageUrl
-Pegue o objeto "sender" e faça um Cast pro tipo 'ImageButton';
-Com o objeto resultante (que é uma instancia de 'ImageButton'), pegue a propriedade ImageUrl (que faz parte do tipo ImageButton);
Pois bem, javascript é uma linguagem fracamente tipada. Esse cast é desnecessário. Se o objeto for do tipo ImageButton, a propriedade ImageUrl estará lá, sem você precisar do cast. Bastará:
sender.ImageUrl.
Caso precise atestar o cast, use typeof para verificar a classe da instancia.


Is it possible to have a facebook tab application without a tab?

Question: A client wants to have a facebook page tab app, but they don't want the tab to be visible to the public. They're OK with the general public accessing the app if they obtain a link to it somehow, but don't want to advertise the app with a page tab icon at the top of their facebook page.
If I "Remove from favorites" on the page tab icon, the app itself becomes inaccessible. If I put the app in sandbox mode, only admins/testers can access it. All I really want to do is hide the icon itself but the leave the app up and running. Is this possible?
Answer: No, it's not possible to have a page tab app which doesn't appear as a tab.
You/They should probably use a canvas app ('App on Facebook' in the settings, accessed via apps.facebook.com) for this purpose.
This also has the advantage of giving them more screen real estate to work with, and it can be kept 'anonymous' by just linking directly to it and not promoting it any other way


Dynamic memory allocation trouble

Question: The program stops running after memory is allocated to "namn". Why?
The goal is to enter two SEPARATE strings and concatenate them, then print.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char namn, fornamn[25], efternamn[25];
    scanf("%s", fornamn);
    scanf("%s", efternamn);

    namn = malloc((strlen(fornamn)+strlen(efternamn)+1)*sizeof(char));
    strcpy(namn, fornamn);
    strcat(namn, efternamn);
    printf("%s", namn);

    return 0;
}

Comment: `char namn` => `char *namn`. The warnings of your compiler should probably have helped you.
Comment: The way you prevent this from happening is the **enable compiler warnings** and do not accept code until it compiles -- without warning. For gcc add `-Wall -Wextra -pedantic` to your compile string. For clang, add `-Weverything`, for VS (`cl.exe`) add `/W3` (or `/W4` for truly everything)
Comment: Also, `sizeof(char)` is *defined* to be one.
Comment: Wow... Should've noticed that. Thank you.
Answer: Since namn is of type char, the return value of malloc is truncated to the size of a char, which is insufficient to store a valid pointer value.
Fix is:
char *namn;

Your compiler probably issues a lot of warnings when compiling. It's always interesting to read them. Example with gcc (without options: default warning setting):
L:\>gcc test.c
test.c: In function 'main':
test.c:11:6: warning: assignment makes integer from pointer without a cast [-Wint-conversion]
 namn = malloc((strlen(fornamn)+strlen(efternamn)+1)*sizeof(char));
      ^

Aside, you can limit user input and avoid buffer overflow with:
scanf("%24s", fornamn);
scanf("%24s", efternamn);

And sizeof(char) is always 1. So no need to specify it when allocating string memory.
Answer: The variable namn is a simple char. Malloc returns a pointer to the memory. Hence, you need a char pointer (char *namn).

Dynamic memory allocation trouble


How to implement route guards in Blazor?

Question: I am currently trying out Blazor and has successfully created a JWT Auth login. Im in the part where im trying to create guards but the doc provided by Microsoft doesnt really explain much. Is there any way someone could guide me in the right direction for securing my routes if the user is not logged in? thank you.
Answer: The concept of route guards in Blazor does not currently exist. The route system in Blazor is rather poor, but I guess this is going to change in the near future.
As a temporary solution I suggest you store the JWT token in the local storage, and read it for validation whenever the user attempts to access secured parts of your application. You may create a service that you can call  to check for access permission during the Init or OnParametersSet component's life-cycle methods.
Of course you can implement your own custom router ;)
Hope this helps...


SQL Query for pull value in between index range

Question: I have one table in which i require Service Type field from 2nd table.
KmReading   ServiceType
40203
30143
30143
30143

In table 2 i have index range for KMReading like
StartKM EndKM   ServiceType
0   2000    Service1
2001    7000    Service2
7001    12000   Service3
12001   17000   Service4
17001   22000   Service5
22001   27000   Service6
27001   32000   Service7
32001   37000   Service8
37001   42000   Service9

so if any value comes in between StartKM and EndKM in table1 then it can pull value of ServiceType from table2 to table1
Comment: Why is this tagged MySql but has MS Access in the title? Please clarify your tags.
Answer: Try this,it maybe works for MS Access.
UPDATE T1
SET T1.ServiceType = T2.ServiceType
FROM table1 T1
 JOIN table2 T2
   ON T1.KmReading BETWEEN T2.StartKM AND T2.EndKM

Answer: Edit: For MySQL this should do it:
UPDATE table1 AS t1, table2 AS t2
SET t1.ServiceType = t2.ServiceType
WHERE t1.KmReading >= t2.StartKm AND t1.KmReading <= t2.EndKm


Filter one or more matched strings to reduce data set

Question: I am trying to filter a set of data based on strings that are stored in localStorage. The number of strings could be 0 - 4. (If the string exists then I split it at the comma).
Currently my function loops through the data, and reduces the set but only according to the first string.
I need some way to loop over the data x times and store the filtered data into a new array using push (I presume). I guess it's passing the first string selector and reducing the set.
I have a jsfiddle here: https://jsfiddle.net/lharby/fxv94185/1
For simplicity I am simply storing the strings into a variable (rather than using jsfiddle local storage). var chQualityFilters = "ok,ko" this can be changed in the fiddle to an empty string, or one or more of the four selectors 'ok', 'ko', 'spark', 'oos'.
Full code is here:
var url = 'https://api.myjson.com/bins/14xw8x';
var dataWrapper = $('.data-wrapper');
var endSpan = '';
var spanWide = '';
var chQualityFilters = "ok,ko"; // this can be 1 or more of 'ok', 'ko', 'spark', 'oos'

returnQualityData = function(){
  $.ajax({
    type:'GET',
    url:url,
    dataType:'json',
    success:function(data){
      if (chQualityFilters !== null && chQualityFilters !== 'none') {
        getSetFilters();
      }
      var filteredData = data.filter(function(d){
        for(var i=0; i<chQualityFilters.length; i++){ // how to loop over the chQualityFilters array a second time.
          return (d.Status.toLowerCase() == chQualityFilters[i]);
        }
      });
      console.log(filteredData);
      dataWrapper.empty();
      dataWrapper.prepend('
'
                          +'Date' + spanWide
                          +'Database name' + spanWide
                          +'Table name'+ endSpan
                          +'Lake
volume'+ endSpan
                          +'Source
volume'+ endSpan
                          +'Difference'+ endSpan
                          +'Null %'+ endSpan
                          +'Std. index'+ endSpan
                          +'Hazard
index'+ endSpan
                          +'Source data available'+ endSpan
                          +'Status'
                          +'
');
      for(var i in filteredData){
        var statusLowerCase = filteredData[i]["Status"].toLowerCase();
        var year = filteredData[i]["Data Date"].slice(0,4);
        var month = filteredData[i]["Data Date"].slice(4,6);
        var day = filteredData[i]["Data Date"].slice(6,8);
        var date = day+ "/" +month+ "/" +year;
        dataWrapper.append('
'
                           +date+ spanWide
                           +filteredData[i]["Database Name"]+ spanWide
                           +filteredData[i]["Table Name"]+ endSpan
                           +filteredData[i]["Lake Volume"]+ endSpan
                           +filteredData[i]["Source Volume"]+ endSpan
                           +filteredData[i].Difference+ endSpan
                           +filteredData[i]["Null Percent"]+ endSpan
                           +filteredData[i]["Standardisation Index"]+ endSpan
                           +filteredData[i]["Hazard Index"]+ endSpan
                           +filteredData[i]["Source Data Available"]+ '' +statusLowerCase
                           + ''
                           + '
'
                           + '
Source database name ' +filteredData[i]["Source Database Name"] + '
'
                           + '
Ingestion frequency ' +filteredData[i]["Ingestion Frequency"]+ '
'
                           + '
Unload type ' +filteredData[i]["Unload Type"]+ '
'
                           + '
Number of columns ' +filteredData[i]["Number Of Columns"]+ '
'
                           + '
'
                           + '
');
      }
    },
    error:function(status){
    },
    complete:function(){
    }
  });
  return false;
}();

getSetFilters = function() {
  var qualityFilterInput = $('[name="filterStatus"]');
  if (chQualityFilters !== null && chQualityFilters !== 'none') {
    chQualityFilters = chQualityFilters.split(',');
  }

  if(chQualityFilters){
    for(var i=0; i<chQualityFilters.length; i++){
      $('[data-filter="status"] [value=' +chQualityFilters[i]+ ']').prop('checked',true);
    }
  }
}

Sample of data:
[
   {
      "Database Name":"bu",
      "Table Name":"pro_fis",
      "Status":"OOS",
      "Ingestion Frequency":"Daily - Mon-Sun",
      "Unload Type":"Full",
      "Source Database Name":"n/a",
      "Data Date":"20170426",
      "Number Of Columns":"31",
      "Lake Volume":"384931",
      "Source Volume":"0",
      "Difference":"384931",
      "Difference Percent":"100",
      "Null Percent":"0",
      "Standardisation Index":"79.7425",
      "Hazard Index":"0.000002",
      "Source Data Available":"No"
   },
   {
      "Database Name":"ca",
      "Table Name":"prepart_",
      "Status":"Spark",
      "Ingestion Frequency":"Daily - Mon-Sun",
      "Unload Type":"Full",
      "Source Database Name":"bp1",
      "Data Date":"20171021",
      "Number Of Columns":"43",
      "Lake Volume":"0",
      "Source Volume":"1699573",
      "Difference":"1699573",
      "Difference Percent":"0",
      "Null Percent":"0",
      "Standardisation Index":"0",
      "Hazard Index":"0",
      "Source Data Available":"Yes"
   },
   {
      "Database Name":"ca",
      "Table Name":"pte_co",
      "Status":"Spark",
      "Ingestion Frequency":"Daily - Mon-Sun",
      "Unload Type":"Full",
      "Source Database Name":"sv09",
      "Data Date":"20171021",
      "Number Of Columns":"13",
      "Lake Volume":"0",
      "Source Volume":"2848018",
      "Difference":"2848018",
      "Difference Percent":"0",
      "Null Percent":"0",
      "Standardisation Index":"0",
      "Hazard Index":"0",
      "Source Data Available":"Yes"
   }
]

Full dataset is here (as used in the fiddle): https://api.myjson.com/bins/14xw8x
Comment: Not getting what the question is.
Comment: If the variable `chQualityFilters == 'ok'`, loop through the data and remove any records that do not match `status = ok`. If `chQualityFilters = 'ok,oos'`, split the string at the comma, we now need to loop through the data twice. First filter by `Status == ok`, then loop again and add `Status == 'oos'` to the filtered data. Does that make sense? return Status == 'ok' && Status == 'oos'.
Answer: I think you need to change:
for(var i=0; i<chQualityFilters.length; i++){
   return (d.Status.toLowerCase() == chQualityFilters[i]);
}

to something like:
return chQualityFilters.includes(d.Status.toLowerCase())

Comment: Yes, I had just implemented your code in the fiddle @charlietfl and it worked, so I was going to award you the points. But this solution seems very similar.
Comment: @lharby your code would have worked if you had simply converted string to array


MongoDB Mongoose aggregate query deeply nested array remove empty results and populate references

Question: This question is a follow up to a previous question for which I have accepted an answer already. I have an aggregate query that returns the results of a deeply nested array of subdocuments based on a date range. The query returns the correct results within the specified date range, however it also returns an empty array for the results that do not match the query.
Technologies: MongoDB 3.6, Mongoose 5.5, NodeJS 12
Question 1:
Is there any way to remove the results that don't match the query?
Question 2:
Is there any way to 'populate' the Person db reference in the results? For example to get the Person Display Name I usually use 'populate' such as find().populate({ path: 'Person', select: 'DisplayName'})
Records schema
let RecordsSchema = new Schema({
  RecordID: {
    type: Number,
    index: true
  },
  RecordType: {
    type: String
  },
  Status: {
    type: String
  },
  // ItemReport array of subdocuments
  ItemReport: [ItemReportSchema],
}, {
  collection: 'records',
  selectPopulatedPaths: false
});

let ItemReportSchema = new Schema({
  // ObjectId reference
  ReportBy: {
    type: Schema.Types.ObjectId,
    ref: 'people'
  },
  ReportDate: {
    type: Date,
    required: true
  },
  WorkDoneBy: [{
    Person: {
      type: Schema.Types.ObjectId,
      ref: 'people'
    },
    CompletedHours: {
      type: Number,
      required: true
    },
    DateCompleted: {
      type: Date
    }
  }],
});

Query
Works but also returns empty results and also need to populate the Display Name property of the Person db reference
db.records.aggregate([
    {
        "$project": {
            "ItemReport": {
                $map: {
                    input: "$ItemReport",
                    as: "ir",
                    in: {
                        WorkDoneBy: {
                            $filter: {
                                input: "$$ir.WorkDoneBy",
                                as: "value",
                                cond: {
                                    "$and": [
                                        { "$ne": [ "$$value.DateCompleted", null ] },
                                        { "$gt": [ "$$value.DateCompleted", new Date("2017-01-01T12:00:00.000Z") ] },
                                        { "$lt": [ "$$value.DateCompleted", new Date("2018-12-31T12:00:00.000Z") ] }
                                    ]
                                }
                            }
                        }
                    }
                }
            }
        }
    }
])

Actual Results
{
    "_id": "5dcb6406e63830b7aa5427ca",
    "ItemReport": [
        {
            "WorkDoneBy": [
                {
                    "_id": "5dcb6406e63830b7aa53d8ea",
                    "PersonID": 111,
                    "ReportID": 8855,
                    "CompletedHours": 3,
                    "DateCompleted": "2017-01-20T05:00:00.000Z",
                    "Person": "5dcb6409e63830b7aa54fdba"
                }
            ]
        }
    ]
},
{
    "_id": "5dcb6406e63830b7aa5427f1",
    "ItemReport": [
        {
            "WorkDoneBy": [
                {
                    "_id": "5dcb6406e63830b7aa53dcdc",
                    "PersonID": 4,
                    "ReportID": 9673,
                    "CompletedHours": 17,
                    "DateCompleted": "2017-05-18T04:00:00.000Z",
                    "Person": "5dcb6409e63830b7aa54fd69"
                },
                {
                    "_id": "5dcb6406e63830b7aa53dcdd",
                    "PersonID": 320,
                    "ReportID": 9673,
                    "CompletedHours": 3,
                    "DateCompleted": "2017-05-18T04:00:00.000Z",
                    "Person": "5dcb6409e63830b7aa54fe88"
                }
            ]
        }
    ]
},
{
    "_id": "5dcb6406e63830b7aa5427f2",
    "ItemReport": [
        {
            "WorkDoneBy": []
        }
    ]
},
{
    "_id": "5dcb6406e63830b7aa5427f3",
    "ItemReport": [
        {
            "WorkDoneBy": []
        }
    ]
},
{
    "_id": "5dcb6406e63830b7aa5427f4",
    "ItemReport": [
        {
            "WorkDoneBy": []
        }
    ]
},
{
    "_id": "5dcb6406e63830b7aa5427f5",
    "ItemReport": [
        {
            "WorkDoneBy": []
        }
    ]
},

Desired results
Note the results with an empty "WorkDoneBy" array are removed (question 1), and the "Person" display name is populated (question 2).
{
    "_id": "5dcb6406e63830b7aa5427f1",
    "ItemReport": [
        {
            "WorkDoneBy": [
                {
                    "_id": "5dcb6406e63830b7aa53dcdc",
                    "CompletedHours": 17,
                    "DateCompleted": "2017-05-18T04:00:00.000Z",
                    "Person": {
                      _id: "5dcb6409e63830b7aa54fe88",
                      DisplayName: "Joe Jones"
                    }
                },
                {
                    "_id": "5dcb6406e63830b7aa53dcdd",
                    "CompletedHours": 3,
                    "DateCompleted": "2017-05-18T04:00:00.000Z",
                    "Person": {
                      _id: "5dcb6409e63830b7aa54fe88",
                      DisplayName: "Alice Smith"
                    }
                }
            ]
        }
    ]
},

Answer: First question is relatively easy to answer and there are multiple ways to do that. I would prefer using $anyElementTrue along with $map as those operators are pretty self-explanatory.
{
    "$match": {
        $expr: { $anyElementTrue: { $map: { input: "$ItemReport", in: { $gt: [ { $size: "$$this.WorkDoneBy" }, 0 ] } } } }
    }
}

MongoPlayground
Second part is a bit more complicated but still possible. Instead of populate you need to run $lookup to bring the data from other collection. The problem is that your Person values are deeply nested so you need to prepare a list of id values before using $reduce and $setUnion. Once you get the data you need to merge your nested objects with people entities using $map and $mergeObjects.
{
    $addFields: {
        people: {
            $reduce: {
                input: "$ItemReport",
                initialValue: [],
                in: { $setUnion: [ "$$value", "$$this.WorkDoneBy.Person" ] }
            }
        }
    }
},
{
    $lookup: {
        from: "people",
        localField: "peopleIds",
        foreignField: "_id",
        as: "people"
    }
},
{
    $project: {
        _id: 1,
        ItemReport: {
            $map: {
                input: "$ItemReport",
                as: "ir",
                in: {
                    WorkDoneBy: {
                        $map: {
                            input: "$$ir.WorkDoneBy",
                            as: "wdb",
                            in: {
                                $mergeObjects: [
                                    "$$wdb",
                                    {
                                        Person: { $arrayElemAt: [{ $filter: { input: "$people", cond: { $eq: [ "$$this._id", "$$wdb.Person" ] } } } , 0] }
                                    }
                                ]
                            }
                        }
                    }
                }
            }
        }
    }
}

Complete Solution
Comment: @pengz you should include them on `$map` level. Line ~ 9 and then ~ 93 like `RecordID: "$$ir.RecordID",`(line numbers from my Playground)
Comment: Oh I think I got it! I just had to add RecordID: 1, RecordType: 1, etc to both project statements. Seriously thank you SOOO much this is not the first time you've helped me tremendously. :) e.g. `"$project": {
      "RecordID": 1,
      "RecordType": 1,
      "ItemReport": {
        $map: {..`
Comment: Excellent thank you SO much. The only issue I am having is that I am also trying to return some other fields on the record, for example RecordID, RecordType, and Status. I tried adding those fields to the last $project statement at the bottom but it doesn't seem to return those fields. `$project: {
          RecordID: 1,
          RecordType: 1,
          Status: 1,
          ItemReport: {
            $map: { ...`
Comment: Hm, `$$ir.RecordID` isn't working I think perhaps because RecordID, RecordType, etc. properties are not on the Item Report level, they are on the 'top' level above.


Processing - How do I show a quadrant of the screen in a larger frame?

Question: I want I have a splitscreen video that is split into 4 quadrants. I want to use Processing to take a clicked quadrant, and show the view in a larger, frame or window that is centered. Below I already have a click function and a called mousePressed(). You can also find code that helps you identify which quadrant you are dealing with. Each quadrant is noted just in case.
import peasy.*;
import peasy.org.apache.commons.math.*;
import peasy.org.apache.commons.math.geometry.*;
import processing.video.*;
import ddf.minim.*;
import processing.video.*;
String Path = "/Users/Gameheads/Desktop/Video1/POV Sports Prototype.mp4";

PeasyCam cam;
Movie myMovie;
Minim minim;
int boxSize = 75;
boolean overBox = false;
boolean locked = false;
float bx;
float by;
int boxNumber;
//AudioPlayer floor;

// Three variables for the background color.
float r = 0;
float b = 0;
float g = 0;
float a = 0;
// transparency rgba(100, 0, 0, 0)
void setup() {
    background(r, g, b, a);
    frameRate(30);
    size(1280, 720);
    // minim = new Minim(this);
    //floor = minim.loadFile("Floor.mp3", 512);
    myMovie = new Movie(this, Path);
    // colorMode(HSB);
    myMovie.play();
}

//Each Rectangle size should be 320x180
//XY (00)
//(X,Y,width, height)
void draw() {

    image(myMovie, 0, 0, width, height); // draws video

    // Draw the box
    rect (0, 0, 55, 55); //Top Left, add 320 x 180 end
    rect(640, 0, 55, 55); //Top Right, add 320 x 180 end
    rect(0, 360, 55, 55); //Bottom Left
    rect(640, 360, 55, 55); //Bottom right

    // background(r,g,b);
    stroke(255);
    line(width/2,0,width/2,height);
    line(0,height/2,width,height/2);

    // Test if the cursor is over first gray square
    if (mouseX > bx-boxSize && mouseX < bx+boxSize &&
        mouseY > by-boxSize && mouseY < by+boxSize) {
        overBox = true;
        if(!locked) {
            stroke(255, 0, 255);
            fill(153);
        }
    }
    //Bottom Right Quadrant
    else if (mouseY > height/2 && mouseX >= 640) {
        overBox = true;
        if(!locked) {
            stroke(255, 0, 255);
            fill(153);
        }
    }
    //Bottom Left Quadrant
    else if  (mouseY > height/2 && mouseX < 640)
    {
        stroke(255, 255, 125);
        fill(153);
    }
    // top right Quadrant
    else if (mouseY < height/2 && mouseX >= 640) {
        overBox = true;
        if(!locked) {
            stroke(0, 0, 255);
            fill(153);
        }
    }
    //Top Left Quadrant
    else if  (mouseY < height/2 && mouseX < 640)
    {
        overBox = true;
        if(locked){
            stroke(255, 0, 0);
            fill(153);
        }
    }
}

// Called every time a new frame is available to read
void movieEvent(Movie m) {
    m.read();
}

void mousePressed() {
    if(overBox) {
        locked = true;
        fill (255, 255, 255);
    }
}
void mouseReleased() {
    locked = false;
}

Answer: Stack Overflow isn't really designed for general "how do I do this" type questions. It's for specific "I tried X, expected Y, but got Z instead" type questions. But I'll try to help in a general sense:
You need to split your problem up into smaller pieces and then take on those pieces one at a time. It's good that you started by writing a program that identifies which quadrant. But now I'd recommend creating a separate program that just shows a new window whenever you click anywhere in the first window. Don't worry about the video, just get that working by itself. Hint: Do a search for the PApplet.runSketch() function.
Separately from that, create a simple program that just draws a quadrant of an image (not a video) to the screen. You might use the createGraphics() function to help with this. Use an image, that way you don't have to worry about a whole video, plus it's easier for us to help you if you get stuck.
Get those things working perfectly by themselves before you start thinking about combining them. Then if you get stuck on a specific step, you can post a MCVE of just that step. Good luck.
Comment: Thank you very much! I will post the MCVE if/when I have another issue.


Which values of Lambert W function are rational?

Question: I mean the branch of Lambert-W function when it is single-valued (The $W_0$ function):  Defined on $x\geq \dfrac{1}{e}$ and by the relation $w = W(x) \iff x = we^{w}$.
I know that $0$ is one of the rational values, since $W(0)=0$, because $0e^{0} = 0$. I wonder what are the others?
I see here (https://cs.uwaterloo.ca/research/tr/1993/03/W.pdf) that I can write $W_0(x) = \displaystyle\sum_{n=1}^{\infty} \frac{(-n)^{n-1}}{n!} x^n$, then it is analytic around $0$, and the range is $[-1,\infty)$, so by the Intermediate Value Theorem there must be infinite values where $W(x)$ is rational, but I have no idea how to analyse that.
Any help would be appreciated.
Answer: In addition to $W(-e^{-1}) = -1$ and $W(0)=0$, there are infinitely many: if $p$ and $q$ are integers, then $x = (\frac pq) \exp(\frac pq) \implies W(x) = \frac pq$.  This follows from the definition of $W(x)$, which is $$W(x) \cdot e^{W(x)} = x.$$  Substituting $x = (\frac pq) \exp(\frac pq)$, $$W(x) e^{W(x)} = \left(\frac pq\right) \exp\left(\frac pq\right). \tag{1}$$  Comparing both sides of $(1)$, clearly $$W(x)=\frac pq.$$


How to set default form fields value from controller

Question: How to setup default form fields value from a form created in a controller?
I tryed to set the $form_state param but it does not work.
...
$form_state = new FormState();
$form_state->set('myfield_1', 'car');
$form_state->set('myfield_2', 'bus');
$form = $this->formBuilder->buildForm('Drupal\mymodule\Form\MyForm', $form_state);
return $form;

Answer: Add the default values to getForm():
return $this->formBuilder()->getForm('Drupal\mymodule\Form\MyForm', $default1, $default2);

And set the default values in the form class:
class MyForm extends FormBase {

  public function buildForm(array $form, FormStateInterface $form_state, $default1 = NULL, $default2 = NULL) {

    $form['field1'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Field 1'),
      '#default_value' => $default1,
    ];

    // ...

  }
}

Answer: The working example for add node form:
       <?php

        namespace Drupal\mymodule\Controller;

        use Drupal\Core\Controller\ControllerBase;

        class addController extends ControllerBase {

           public function build() {

             $entity = $this->entityTypeManager()->getStorage('node')->create(array(
               'type' => 'SomeContentType',
             ));

             $entity->set('field_link_to_item', 5);

             $form = $this->entityFormBuilder()->getForm($entity);

             return $form;
           }

        }


The number of equivalence classes of finite symmetric difference relation

Question: Let $\Sigma$ be an infinite set.
Let $A,B \subseteq \Sigma$ be of finite symmetric difference iff they have a finite difference, more formally:

$A \sim B$ iff $|A \Delta B| \in \mathbb{N}$

How many equivalence classes does $\sim$ have?
Comment: What you're calling *difference* is generally called *symmetric difference*.
Comment: @Brian, thanks, I added "symmetric".
Answer: Let $A \subseteq \Sigma$ be an arbitrary set. Then the size of $[A]$ (the equivalence class of $A$) is equal to the number of finite subsets of $\Sigma$. The number of finite subsets of $\Sigma$ is of the same cardinality as $\Sigma$ since $\Sigma$ is an infinite set. Therefore we have $|[A]| = |\Sigma|$ for all $A$.
Let $I$ be the set of equivalence classes. We have $P(\Sigma) = \bigcup_{[A]\in I} [A]$ and distinct equivalence classes are disjoint. Therefore we have $2^{|\Sigma|} = |P(\Sigma)| = |\bigcup_{[A]\in I} [A]| = |I| |\Sigma|$. Thus by cardinal arithmetic we have $|I| = 2^{|\Sigma|}$.
Comment: $f(S) = A \Delta S$. Then $f(S) \Delta A = S$. So $f$ is a bijective, mapping any finite subset $S$ to a $B$ in equivalence class of A.
Comment: Looks fine to me.
Comment: Why is $[A]$ equal to the number of finite subsets of $\Sigma$?


How do I interpret/find the coefficient for an aliased factor?

Question: I've made a binomial model using the glm function in R as:
<code>model <- glm(formula = ym ~ year + class, family = "binomial")
</code>
Where year is an integer and class is a factor with 4 levels (class = A, B, C, D). Which gave coefficients:
<code>              Estimate Std. Error z value Pr(>|z|)
(Intercept)  -12.0538   33.24887  -0.753   0.4512
year          0.19302    0.01712   0.746   0.4558
classB        0.19528    0.17428   1.293   0.1961
classC        0.23886    0.15071   0.722   0.4701
classD        0.35708    0.13439   1.913   0.0557 .
</code>
Ignoring the significance of variables, I'm trying to interpret the coefficients from the model before I go on to improve it. I believe the effect of each is logit(p) = intercept + classAx + classBx + classCx + classDx, where x = 1 only for the class the individual belongs to.
First, what is the coefficient for classA (which has been removed) here? is it -(0.19528+0.23886_0.35708), the negative sum of the other coefficients of class?
Second, while I understand year can be interpreted as an increase of year by one unit corresponds to an increase in logit(p) of 0.19302, for the classes would it simply be membership to class C increases logit(p) by 0.23886?
Comment: See also https://stats.stackexchange.com/questions/515719/categorical-variable-more-than-two-levels/515804#515804
Answer: The coefficient for class A is 0. So if you want to get the logit value for an individual in class A for year X, the formula would read
$$
\widehat{\text{logit}}(p(A,X))= -12.0538+0+0.19302\cdot \text{year}.
$$

for the classes would it simply be membership to class C increases logit(p) by 0.23886?

Yes, compared to class A.


I want view FBX file in ubuntu using opengl

Question: can i open the FBX file using opengl?
I want just view FBX file.
I did ViewScene project that fbx sdk sample. but i can't compile project...
so, How do view FBX file using opengl in ubuntu 14.04?
Answer: OpenGL has nothing relates to FBX. FBX is a format of file to store 3D scenes. OpenGL is a rendering API. You can read FBX file (with FBX SDK for example) create a scene (by your own) and then render it using OpenGL API.


Optimise and speed up very slow Linq / SQL code

Question: I have the following C# method which I use to pre-load a data table of stock.  Although it works very well, now I have many rows in the table, it can be very very slow to load.
Please can someone recommend a better and much faster way to do this?  (Ideally to remove the "foreach" code as this is the slow bit!).
public static DataTable GetProducts()
{
    DataTable table = new DataTable();

    using (DataClassesDataContext data = new DataClassesDataContext(cDbConnection.GetConnectionString()))
    {
        var query = (from p in data.Products
                     where p.Deleted == false
                     join s in data.ProductStocks on p.ProductID equals s.ProductID
                     group s by p into g
                     select new { g });

        table.Columns.Add("Barcode", typeof(string));
        table.Columns.Add("Stock Code", typeof(string));
        table.Columns.Add("Description", typeof(string));
        table.Columns.Add("Price", typeof(string));
        table.Columns.Add("Tax", typeof(string));
        table.Columns.Add("Stock", typeof(string));
        table.Columns.Add("Service Item", typeof(bool));
        table.Columns.Add("Deduct Stock", typeof(bool));

        if (query != null)
        {
            foreach (var item in query)
            {
                try
                {
                    decimal? Tax = 0;
                    if (item.g.Key.ProductTax != null)
                    {
                        Tax = Common.Utilities.IsValueValidDecimal(item.g.Key.ProductTax.TaxRate, 0);   // Tax
                    }
                    else
                    {
                        Tax = 0;
                    }

                    bool DeductStock = !Convert.ToBoolean(item.g.Key.ServiceItem);

                    string[] row = new string[]
                    {
                        item.g.Key.EANCode.ToString(),       // Barcode
                        item.g.Key.OurStockCode.ToString(),  // Product Code
                        item.g.Key.Description.ToString(),   // desc
                        GetGUIDisplayPrice(item.g.Key.RetailPrice, item.g.Key.RetailPriceExVAT),  // cost
                        Tax.ToString(),                         // Tax
                        item.g.Sum(s => s.QtyOnHand).ToString(), // Stock
                        item.g.Key.ServiceItem.ToString(),   // Service Item (non-stock)
                        DeductStock.ToString()                  // if not a service item, the its a stocked item so deduct!
                    };

                    table.Rows.Add(row);
                }
                catch (Exception ex)
                {
                }
            }
        }//ENDIF NULL
    }//END USING

    return table;
}

Comment: Please put more effort into formatting your code before you post - look at the question you're about to post, and ask whether it's formatted how you'd want to see it if you were going to answer.
Comment: What does your profiling show? Is it slow on the db on in this code?
Comment: what is the code of Common.Utilities.IsValueValidDecimal ?
Comment: var query = (query).toList().. This will load all the data to the query variable, Which i think should improve the performance when you do the iterations.
Comment: is this linq to sql or entity framework?
Comment: Thank you for your replies, I am basically trying to see if I can replace the Foreach with Linq so that I can perform all the calculations on the server instead of for each row from the table.

I have limited sql / linq knowledge and this basically written from advice I have got form this in previous questions and trial and error!
Comment: Jon Skeet - How do you suggest I format the code? I think my code is perfectly formatted for this question!  Your suggestions would be greatful?
Comment: Fredou - this function checks for a valid int (i.e. not null),  the code is linq to sql.
Comment: Richard - This is something I do not know and something I have never done before?  (time for google!)
Comment: @ViswasMenon: var query = (query).toList() doesn't speed up anything. It might slowdown the process, because you want to stream the results instead of fetching it complete.
@Belliez: why do you use a nullable decimal? Tax.ToString() will fail on null. Also `select new { g }` should be replaced with `select g`. Try to move the `item.g.Sum(s => s.QtyOnHand).ToString()` into the query, so it is calculated serverside.
Answer: from p in data.Products
                 where p.Deleted == false
                 join s in data.ProductStocks on p.ProductID equals s.ProductID
                 group s by p into g
                 select new { g }

What is the schema of the Products and ProductStocks tables? What indexes do you have? start by reading How to analyse SQL Server performance.
Some things stand out immediate:

you are fetching all the data from the server on the client. Don't. Process on the back end.
using a Deleted bit field is a recipe for (performance) disaster. You can add it a clustered index leftmost key, with dubious results at best. Partitioning by can help, but not much. There is no silver bullet. Try to eliminate this requirement. Delete the deleted rows.

There is not much room to optimize. Stop fetching all the data.
Comment: Thank you, I gathered this would be the response. I will look into processing on the server instead of the client.
Answer: In the end, this function was turned into a stored procedure and the stored procedure returned the table that was created on the server, not the client. This was almost instant and massive performance improvement!


Android View Model binding in kotlin

Question: i am facing a strange issue. I am binding a viewModel to my layout by factory design patter. When ever i build that there is difference between inferred and expected view model.
My View Model Class
class SleepTrackerViewModel(
        val database: SleepDatabaseDao,
        application: Application) : AndroidViewModel(application) {
    private var viewModelJob = Job()
    private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)
    var alarmList = database.getAllAlarms()

    override fun onCleared() {
        super.onCleared()
        viewModelJob.cancel()
    }

    fun onStartTracking() {
        uiScope.launch {
            val newNight = AlarmModel()
            insert(newNight)
        }
    }

    private suspend fun insert(night: AlarmModel) {
        withContext(Dispatchers.IO) {
            database.insert(night)
        }
    }
}

So when every i try to assign the view model in fragment, it shows error that expected and inferred view model are different
My XML file
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>

        <variable
            name="viewModel"
            type="com.example.android.trackmysleepquality.Fragments.SleepTrackerViewModel" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.recyclerview.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            app:listData="@{viewModel.alarmList}" />

    </LinearLayout>
</layout>

My Factory Class
class SleepTrackerViewModelFactory(
        private val dataSource: SleepDatabaseDao,
        private val application: Application) : ViewModelProvider.Factory {
    @Suppress("unchecked_cast")
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(SleepTrackerViewModel::class.java)) {
            return SleepTrackerViewModel(dataSource, application) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}

Comment: How you are instantiating SleepTrackerViewmodel in fragment?. Provide that code.
Comment: nope, in factory
i have added the factory code, kindly chk
Comment: Can you provide your fragment code as well.
Comment: fragment code is already there
Comment: I need to look into your SleepTrackerFragment class. Add that
Answer: Remove ViewModel from your XML file and try this one.
class AddMovieFragment : Fragment() {

  private lateinit var viewModel: AddMovieViewModel

  companion object {
    const val SEARCH_QUERY = "SEARCH_QUERY"
  }

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    viewModel = ViewModelProviders.of(this).get(AddMovieViewModel::class.java)
  }

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
    return inflater.inflate(R.layout.fragment_add_movie, container, false)
  }

Android View Model binding in kotlin


Example of $\alpha$-norm.

Question: We say that $\mathcal N$ is a $\alpha$-norm if $\mathcal N(xà=0\iff x=0$, $\mathcal N$ is sub-linear and $\mathcal N(\lambda x)=\lambda ^\alpha \mathcal N(x)$. Do you have an example of such a norm ? I was wondering for example of $\mathcal N(x)=x^2$ being a $2$-norm, but it doesn't look sub-additive since I can't do better that $$\mathcal N(x+y)=|x+y|^2=2(|x|^2+|y|^2)=2(\mathcal N(x)+\mathcal N(y)). $$
Answer: Note that an $\alpha$-norm does not exist for $\alpha>1$ as we find
$$2\mathcal{N}(x)<2^{\alpha}\mathcal{N}(x)=\mathcal{N}(2x)\leq2\mathcal{N}(x)$$
which is a contradiction.
Would you consider $\mathcal{N}:\mathbb{R}\rightarrow\mathbb{R}_{\geq0}$ given by
$$\mathcal{N}(r)=\sqrt{|r|}$$
to be an example of an $\alpha$-norm?
Clearly we have $\mathcal{N}(x)=0$ if and only if $x=0$, we find for all $a,b\in\mathbb{R}$ that
$$\sqrt{|a+b|}\leq\sqrt{|a|+|b|}\leq\sqrt{|a|}+\sqrt{|b|}$$
and for all $\lambda,x\in\mathbb{R}$ we have $\mathcal{N}(\lambda x)=|\lambda|^{\frac{1}{2}}\mathcal{N}(x)$.

Example of $\alpha$-norm.


ValueError: min() arg is an empty sequence

Question: I'm current coding a highway traffic model. On the deciding the distance between the front car, I'm stuck at min(). It somehow an empty sequence.

Traceback (most recent call last):
[93, 72, 55]
File "C:/Users/Try Arie/PycharmProjects/traffic_model/traffic.py", line 44, in
55
[]
d = min(dlist)
ValueError: min() arg is an empty sequence

I checked the value of distance list. It should be inside and using min(), I will assign the lowest value to d. But it doesn't
class car:

    def __init__(self, no, x, v):
        self.no = no
        self.x = x
        self.v = v

for i in range(N):
    cars.append(car(i+1, randint(0, 100), 0))

for i in range(N):

    dlist = []

    for j in range(N):
        if cars[j].x > cars[i].x:
            dlist.append(cars[j].x)

    print(dlist)

    d = min(dlist)

    print(d)

I want value d 55, so then I can use it for my next code
Comment: If anyone wondering the x (position) of each car, here: 53, 93, 1, 38, 47, 24, 34, 72, 55, 20
Comment: somehow `if cars[j].x > cars[i].x:` this condition is not met and the dlist remains empty which cause the error
Comment: what does `print(dlist)` show?
Comment: print(dlist) print all value in the list. It's [93, 72, 55].
Answer: dlist will by empty for the i for which cars[i].x has the biggest value. For this i the test cars[j].x > cars[i].x will never be true, hence you will never append anything to dlist.
As you can see in your output that exactly this happens: In the first iteration over i you find all cars with x larger than 53: [93, 72, 55] and you also print 55. In the next iteration you find all cars with x larger than 93. There is no such car, hence you get an empty dllist [] and then min raises an exception.
You will either have to treat the special case of empty explicitly or use >= instead of > in your test.
And btw, wouldn't it be faster/easier to just sort the cars by x? Then at position k in the sorted list you have the minimum car among all the cars that have an x larger than or equal to cars[k].x.


Redirecting a registration link in logintoboggan

Question: I've got a register link and a log in link that is augmented by logintoboggan. All I want to do is redirect the register link from the user account form page to a new page I've just made. It seems very simple, but I can't find where the I can change the link. Any help would be amazing, thanks.
Comment: may be try Login Redirect Module: http://drupal.org/project/login_redirect
Comment: you also can have a look to rules module
Answer: Use a hook_menu_alter to alter the user/register path and add your own page callback to it.
Comment: Thanks, karthik. I really just needed to find where the URL was, which was in the template folder, duh.
Answer: You can also try the Redirect module. Here is a quote about it (from the module's project page):

Work in progress for a Drupal 7 integration and collaboration between redirection-type modules:

Path redirect
Global redirect

Current features:

Common API for loading, saving, and deleting redirects.
Case-insensitive redirect matching with a hook to allow other modules to narrow-down the candidate redirects.
Redirect counter and last used timestamp, with automatic cleanup of inactive redirects.
Integration with Drupal's page cache to optimize redirects and performance.
Complete individual redirect access API.
Views API integration.
Answer: Also you can do it in your  template.php of active theme or custom module
<code> function YOURthemename_preprocess_page(&$vars) {
      // this will give you a good idea of the page content and variables
      if(arg(0)=='user' && arg(1)=='register'){
              drupal_goto('newregisterpath');
      }
        if((arg(0)=='user' && arg(1)=='login') || if(arg(0)=='user' && arg(1)=='')){
         drupal_goto('newloginpath');
       }
    }
</code>
And further you have modules like Path_redirect etc already mentioned in the previous comments.
Hope it willhelp you!


How to do 2 queries in the same sql statement?

Question: I have a DB in which I save all the daily visits to a lot of websites, the fields of the day table are name, nvisit and date
I want to make a comparison between the visits of the day before yesterday and those of yesterday, so the result to show should be 3 rows. name, the day before yesterday and yesterday
I have tried with this query but it shows me everything in 2 rows.
SELECT *
FROM (
    SELECT name as nombre, nvisit as anteayer
    from day
    WHERE date < CURDATE() -1 and date > CURDATE() -2
    UNION ALL
    SELECT name as nombre, nvisit as ayer
    from day
    where date < CURDATE() and date > CURDATE() -1
    GROUP by name
    )
    day

What can I do to solve this problem?
When executing the sentence the result is:
|name         |beforeyesterday|
|.............|...............|
|example1.com |2154           |
|example1.com |3215           |
|example2.com |1524           |
|example2.com |2546           |

What I need:
|name         |beforeyesterday|yesterday|
|.............|...............|.........|
|example1.com |2154           |3215     |
|example2.com |1524           |2546     |

Comment: Please provide sample data and desired results.
Answer: I would want a separate row for each name with the columns for the counts on the various days:
select name,
       sum(case when date < curdate() and date > curdate - interval 1 day
                then nvisit
           end) as yesterday,
       sum(case when date < curdate() - interval 1 day and date > curdate - interval 2 day
                then nvisit
           end) as day_before
from day
group by name;

Comment: Thank you very much, it worked for me in the end with this code:
```
select name,
  sum(case when date < CURDATE() -1 and date > CURDATE() -2
         then nvisit
        end) as yesterday,
        sum(case when date < CURDATE() and date > CURDATE() -1
            then nvisit
        end) as day_before
from day
group by name
```
Comment: @yuso88 . . . I would advise you to use interval arithmetic.  You can see the difference here:  https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=28d7e3ca3865ab99f7611306bfcfc34f.


A host invites n couples to a party, She wants

Question: A host invites $n$ couples to a party, She wants to ask a subset of the $2n$ guests to give a speech, but she does not want to ask both members of any couple to give speeches. In how many ways can she proceed?
Comment: What are your thoughts on the problem?
Answer: For each couple, there are three possibilities from which to choose:  husband speaks, wife speaks, or neither speaks.  The host thus has $3^n$ possible ways to choose a subset of speakers.  (Note:  this includes the empty set.)
Comment: (Not really a mathematical comment, but couples don't always consist of husband and wife.)
Answer:
Choose a certain number of couple.
Then choose which member of each couple will speak.

This give
$$
{n\choose k} {2\choose 1}^k
$$
if you have a fixed number of speaker in mind. If not, then you can sum
$$
\sum_{k=0}^n {n\choose k} {2\choose 1}^k= \sum_{k=0}^n {n\choose k} 2^k= 3^n
$$
where the last equality is from the binomial theorem. This agrees with @Barry's answer, provided you accept the empty set of speaker.
Comment: So is sum from k=0 to n of (2^k)*(n choose k) a correct way of thinking about it? We choose a group of size k, which can be done in n choose k ways, and then each of those people either speak or don't? It also equals 3^n but I am wondering if this is a way to think about it.
Comment: both my way and Barry's way are good way of thinking. His has the advantage of being really simple, while mine has the advantage of giving a quick solution if you are asked to choose, say, 7 persons to speak.  Note that we first fix a number $k$, and choose $k$ couples from $n$. We then need to choose exactly $1$ person per couple among THOSE $k$ couples. To get the general result, we then sum on $k$. This uses what is often called the principle of multiplication and the principle of addition in combinatorics.


Calculating a real integral with residues

Question: I'm attempting to compute $$\int_{-\infty}^0 \frac{x^{1/3}}{x^5-1}dx.$$
My attempt is to use the standard keyhole contour along the negative real axis (which we also take to be the branch cut for $z^{1/3}$), but I'm already having trouble simply computing the residue sum $$\sum_{k=1}^5\operatorname{Res}\left(\frac{z^{1/3}}{z^5-1}, e^{2\pi ik/5}\right) = \sum_{k=1}^5 \lim_{z\to e^{2\pi ik/5}}\frac{z^{1/3}(z-e^{2\pi ik/5})}{z^5-1}.$$
Given that this question appeared on a timed qualifying exam, I'm sure that there's a quick or clever solution to this problem that I'm not seeing. Any help would be greatly appreciated.
Edit: Another idea I had was to substitute $x \mapsto x^3$ which gives $$3\int_{-\infty}^0 \frac{x^3}{x^{15}-1}dx.$$
This relieves us of the branch cut issue at the cost of introducing many more singularities, so I'm not sure if it's actually helpful.
Answer:
...but I'm already having trouble simply computing the residue...

Hint. One may observe that, for any differentiable function $f$ near $a$, we have
$$
\lim_{z \to a} \frac{f(z)-f(a)}{z-a}=f'(a)
$$ giving here
$$
\lim_{z\to e^{2\pi ik/5}}\frac{z-e^{2\pi ik/5}}{z^5-1}=\lim_{z \to z_k} \frac{z-z_k}{z^5-z_k^5}=\frac{1}{5z_k^4}
$$ hoping this helps to obtain the given sum.
Answer: A classmate of mine pointed out that after making the substitution $x\mapsto -x$, the integral becomes $$ \int_0^\infty \frac{x^{1/3}}{x^5+1}\ dx, $$ which we can calculate by integrating the corresponding complex function $$ f(z) = \frac{z^{1/3}}{z^5+1}$$ (taking the principal branch of $z^{1/3}$) over the (counter-clockwise) contour $$ \Gamma_R = \gamma_R \cup C_R \cup \gamma'_R,$$ where $\gamma_R$ is the horizontal line from $0$ to $R$, $\gamma'_R$ is the line connecting $Re^{2\pi i/5}$ to $0$, and $C_R$ is the circular arc of radius $R$ connecting $R$ to $Re^{2\pi i/5}$. For $R>1$, the only singularity contained inside $\Gamma_R$ is at $e^{\pi i/5}$, so we have
$$
2\pi i\operatorname{Res}(f(z),e^{\pi i/5}) = \lim_{R\to \infty} \int_{\Gamma_R} f = \int_0^\infty \frac{x^{1/3}}{x^5+1}\ dx - \int_0^\infty \frac{(xe^{2\pi i/5})^{1/3}}{(xe^{2\pi i/5})^5 +1}e^{2\pi i/5}\ dx.
$$
Thus,
$$
\int_0^\infty \frac{x^{1/3}}{x^5+1} = \frac{2\pi i\operatorname{Res}(f(z),e^{\pi i/5})}{1-(e^{2\pi i/5})^{4/3}}.
$$
By Olivier's helpful answer, we can easily calculate this residue: $$\operatorname{Res}(f(z),e^{\pi i/5}) = \lim_{z\to e^{\pi i/5}}z^{1/3}\frac{z-e^{\pi i/5}}{z^5 - (e^{\pi i/5})^5} =\frac{(e^{\pi i/5})^{1/3}}{5(e^{\pi i/5})^4} = \frac{1}{5}e^{-11\pi i/5}.$$ The final answer can surely by simplified, but we have $$\int_0^\infty \frac{x^{1/3}}{x^5+1} = \frac{2\pi i e^{-11\pi i/5}}{5(1-e^{8\pi i/15})} \approx 0.845486.$$


MVC 6 Best way to send parameters to view

Question: I would like to know what is the best way to send a parameter to a view.
This is my first time with MVC.
I have a menu and I would like to change the item menu class depending which item menu is selected.
For example I have a menu with Home, Products, About.

                    Home

                    Products

                    About

If I select Products I want to add the class 'selected' to it, and remove the class selected to the item menu was selected before an so on.
I know how to do it in jquery, is very simple, but the thing is when I click one of the items menu the selected class continue in the home item menu, that is because I initialize the selected on the Home item menu.
I need some kind of parameter to pass to the view and depending on that value add the class selected to the item menu selected.
I know should be very simple, any help will be appreciate it!
Thanks.
Answer: In the controller you can use return View(model), where model is some variable or object. In the cshtml file you can then declare @Model int for instance, when passing an integer and access it like a normal variable as model. For instance: @if (model == 1){ your code here }.
EDIT: you can also add parameters to the ViewBag (google it, there are lots of examples) but I would use the model since it is strongly typed.
Comment: But do you think is necessary a model for just a parameter, If I would like to return more than one model to my view, could I do that? For example if I want to send a list to the view and also a variable as you wrote me....
Comment: As far as I know, you can only pass one model, but you can create a type that incorporates your model with other vars and pass that as a model instead. Otherwise you have to use the Viewbag (and for a simple parameter this might even be better than creating complex types)
Comment: No problem, glad I could help
Comment: If you want to use two or more models in the same view, you could see this link:  http://stackoverflow.com/questions/30925122/mvc-multiple-models-in-one-view.
Comment: Which is exactly what I already described; combining all models and parameters into a single model.
Answer: ASP.NET MVC Send Multiple Data to View
My opinion
ViewBag, ViewData,TempData is basic solution method exm: (alert, message, script vb. other run client-side code and single data) but write a long code line this dirty and complexible. But using ViewModel property is best solve so your code is not complexible and full compatible Object Oriented Programming architecture.
Understanding ViewModel
Comment: ViewModel is not the best solve if it forces you to create more complex types. For simple parameters Viewbags are way more readable.
Comment: Please you try read to my message and think. I know how to use field for Viewbag,ViewData,TempData vb. object.  I'm recommended solution is ViewModel so Clean and availability. But The simple problem of course using the ViewModel,ViewBag, Tempdata.


Any ideas how to improve the cajón sound?

Question: I bought a cajón kit that I had to assemble myself:
https://meinlpercussion.com/products/Product/show/622/619/
I'm not very advanced in the subject, but the sound isn't as good as what I heard from other cajóns (I believe we followed the instructions well while mounting it). It might also just be the quality of the product.
Do you have any tricks to improve the sound of the cajón?
Comment: Does it sound different to other ones you've played, or only other ones you've heard other people play? The first could be a 'hardware' issue, the 2nd could simply be technique.
Comment: different from what i've played. unlike on these others, it's like i need to tap very strongly in order to get a sound from the snare. so i tried a few different thing like unscrewing a bit the playing surface, putting the snare closer , then farther, but that didn't improve
Answer: I build Cahons from scratch as a hobby..
You don't say what is wrong with the sound from your Cahon, but here are some tips;

On the model you have, there are two screws - top left, and top right of the cahon. Remove those (there are enough left). That will loosen the corners of the tapa, and you'll get a sharper snap when you hit the cahon in that position.
Make sure that the snare is positioned correctly so that it lightly touches the tapa. The snare is one of the important aspects to making a good Cahon sound good.
A slightly more advanced tip is to add jingles to the front of the tapa (see image - but I usually put mine a little lower). They don't have to be different sizes, so using parts from a cheap tamborine will work. This will give a more snare-like tone, but tightening the wingnuts (from any hardware store) will give you some control.

Comment: i'll try tips #1  and 2 and let you know if there are improvements
Answer: I purchased this exact same cajon kit.  The instructions are really easy considering there are only a few pieces.  Unless you put the front face on the bottom and left a whole side off, I am sure that you assembled it correctly.  One thing that I did during construction was to counter-sink the screws holding the front face on.  This was more for comfort as I did not like my hand slapping the screw heads.
As with many instruments, it takes some time to "get to know" your instrument.
That being said, if you look at the prices of what this same cajon costs already assembled from Meinl, you will see that it is not a top-of-the-line cajon.  More expensive cajons may have adjustable snares, better woods or a different shape that may affect the acoustics.
For me, it has taken a bit of time, but I really like the sound I can get from my cajon.  It just took me a while to figure out how hard (or soft) and where around the front face to hit to get the sounds I look for.


Minitab and output

Question: When you conduct a 1 sample t-test why does minitab only give an upper bound or a lower bound for a confidence interval? So if $H_0: \mu = \mu_0$ and we test $H_a: \mu < \mu_0$ or $H_a: \mu > \mu_0$ why is only an upper bound or lower bound of a confidence interval returned respectively? Whereas testing $H_a: \mu \neq \mu_0$ returns both a lower and upper bound.
Comment: Do you mean "or $H_a : \mu\geq\mu_0$"?
Comment: @Scortchi: yes i do
Answer: It depends on the options you supply for the alternative hypothesis: "less than", "not equal", or "greater than" $\mu_0$.  If you're doing a one-sided test, Minitab assumes you're interested in a one-sided confidence interval. And it makes sense to assume that if you're interested only in testing whether the population mean's higher than a certain value, you'd also be interested in saying that values of the mean lower than a certain bound are implausible.

Minitab and output


dell sc1435 CPU upgrade

Question: I have the sc1435 server and it worked well with 2 2374 Opterons (bios 2.2.5). I also tried with 8389 (2.9GHZ) and it works with no problem. Recently came to my hand Operon 8393 (3.1GHZ) so tried to upgrade to this processor but it was unsuccessfu, however it worked fine on one processor. Than i tried to put back my two old 2374s but it didint want to boot with them and similar works fine on one processor.  During boot fans initially slow down than go on max speed. Any idea what it can be ?? Is it possible that 8393 damaged the MB so it work only on one processor now ??
Krzysztof
Comment: after some research I think the temperature sensor collapsed in my server. It still doesn't work on two processors, on one processor works with both fans in full. HW monitor don't show airflow temperature which is shown in my another sc1435. Is it possible to repair it ??
Answer: I can confirm now that Opetron 8393 (3.1GHZ) damages main board of  dell sc1435 so don't try it !!! Stick to processors approved by dell.

dell sc1435 CPU upgrade


Custom plugin for checkmarx

Question: We are writing a large application using IBM Integration Bus and using ESQL as major language for transformation. We are investigating CheckMarx for static code analysis and scanner. But CheckMarx does not support ESQL out of the box.
Is it possible to write a custom plugin for CheckMarx, to make to able to scan and analyse ESQL code as well? I can't find any online resource for the same.
Answer: When using Checkmarx, it is quite easy to create your own custom queries and fine tune the scans for the supported languages.
Since esql files are not yet supported by Checkmarx, it means esql is not parsed. It is not possible to write a custom plugin.
You can contact Checkmarx Support and ask if scanning esql is planned in the future.
Comment: Thank you @yaloner. But it does not answer my question. Is it possible to write a custom plugin for CheckMarx?
Comment: No, it is not possible. Added it to my answer.
Comment: Thank you. Selected as answer now. :)
Comment: Have you had any traction on this issue over the past 2 years.  I also am curious about Informix support.
Comment: @ojblass No. I have left that company altogether and I do not have any idea about how they are doing it. The latest I knew is that no tool was being used for static code analysis when I left the company.
Answer: The selected answer is not entirely true.  Informix ESQLC files are first parsed and intermediate C files are created.  This means that Checkmarx's support for the C programming language could be used to accommodate the files provided you use the -keep option when generating the intermediate files.  The same is true for 4GL files that Informix uses.  The major problem here is that it would be difficult to map the original source line to the generated C code's line.  The results would be hard to consume.
Comment: This question is related to the IBM Integration Bus which has Extended SQL see tag [[tag:extended-sql]], it is not related embedding SQL statements in a host language such as C, see tag [[tag:embedded-sql]], which your answer seems to be referencing.

Custom plugin for checkmarx


AWS Elastic Beanstalk (.ebextension) config - Support .config file in IntelliJ

Question: I've tried to look for IntelliJ/PhpStorm/WebStorm plugins to support *.config files. It looked like a mess.

I found AWS Elastic Beanstalk Integration but doesn't seem to work
Answer: Ok, after a few research, looks like a good solution.
<code>> File -> Settings (Ctrl + Alt + S)

> Editor -> File Types
</code>
EbExtension Files follow yaml syntax/format
<code>> Recognized File Types -> choose YAML

> Registered Patterns -> Click (+) plus icon on its right side

> add *.config

> click Ok -> Apply

> Wait to finish indexing
</code>


What happens when 'return' is called from within a 'using' block?

Question: If I have a method with a using block like this...
<code>    public IEnumerable<Person> GetPersons()
    {
        using (var context = new linqAssignmentsDataContext())
        {
            return context.Persons.Where(p => p.LastName.Contans("dahl"));
        }
    }
</code>
...that returns the value from within the using block, does the IDisposable object still get disposed?
Comment: Check out your generated code with ILDASM or Reflector.
Comment: See also http://stackoverflow.com/questions/662773/returning-in-the-middle-of-a-using-block and http://stackoverflow.com/questions/1223865/best-practice-regarding-returning-from-using-blocks
Answer: Yes it does.  The disposing of the object occurs in a finally block which executes even in the face of a return call.  It essentially expands out to the following code
<code>var context = new linqAssignmentsDataContext();
try {
  return context.Persons.Where(p => p.LastName.Contans("dahl"));
} finally {
  if ( context != null ) {
    context.Dispose();
  }
}
</code>
Answer: From the MSDN documentation:

The using statement ensures that Dispose  is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose  in a finally block; in fact, this is how the using statement is translated by the compiler.

So the object is always disposed. Unless you plug out the power cable.
Comment: "So the object is always disposed. Unless you plug out the power cable." - In which case, the object is disposed as the electrons disperse ;-)
Comment: Reminds me to this TheDailyWTF article (the first one): http://thedailywtf.com/Articles/My-Tales.aspx
Comment: Calling Environment.FailFast will also not call Dispose in addition to pulling the power cable.
Comment: Robert Davis: In .NET, a stack overflow shuts downs the process as well without executing finally blocks.
Comment: Yes, it was just an example. And by the time I wrote that answer, I thought about the TheDailyWTF article, too... ;)


Views listing of nodes and node title as exposed filter

Question: When I started this view I thought it would be simple… But it's not.
I've an "Office" content type and a view (block) where are listed my "Office" nodes as teaser.
First of all it could be great if the result should be sorted with AJAX, but it's only an option.
I would like an exposed dropdown list filter with all the nodes title of my "Office" content type. But it seems I could only expose an input search field.
I already looked at BEF and several posts here but I didn't find a clear solution.
Comment: I think that you will go to make this programmatically, because I never had seen this.
Comment: In the field settings, there's a check box at the very bottom with something like "views exposed" that lets you use the field as an exposed filter. I'm not sure though as I think the question is a little unclear.
Answer: Finally found a solution with Views Selective Filters. :)
By added a "Regions" field in my content type I've been able to get only the regions with results exposed as a filter in my views.


Inequalities for the tail of the normal distribution (Halfin-Whitt paper)

Question: I am reading the famous paper by Halfin and Whitt, [1]. I'd like to prove remark (1) on page 575. The authors state
\begin{align}
\frac{\beta \alpha}{(1-\alpha)} = \frac{\phi(\beta)}{\Phi(\beta)} \Rightarrow \alpha = \frac{\phi(\beta)}{\beta \Phi(\beta) + \phi(\beta)},
\end{align}
where $\phi(x)$ is the standard normal pdf and $\Phi(x)$ the standard normal cdf. The authors want to have bounds on $\alpha$, stating
\begin{align}
1 - \Phi(\beta) \le  \alpha \le \frac{1-\Phi(\beta)}{1-\beta^{-2}\Phi(\beta)}, \quad \beta \ge 1. \qquad \qquad (1)
\end{align}
The authors state that they use (1.8) on page 175 of Feller [2]. This equation reads
\begin{align}
(x^{-1} - x^{-3})\phi(x) < 1 - \Phi(x) < x^{-1} \phi(x), \quad x > 0.
\end{align}
By manipulating this equation I obtain
\begin{align}
\frac{\phi(\beta)}{\beta^{-2}\phi(\beta) + \beta} < \alpha < \beta^{-1} \phi(\beta), \quad \beta > 0. \qquad \quad \quad (2)
\end{align}
Both bounds $(1)$ and $(2)$ are indeed valid for their respective domains. Clearly, the difference for these bounds has to do with the fact that $\beta \ge 1$ in the first, and $\beta > 0$ in the second.
I do not know how to obtain $(1)$, does anyone else have an idea?
[1] S. Halfin, and W. Whitt, Heavy-traffic limits for queues with many exponential servers. PDF
[2] W. Feller, An introduction to probability theory and its applications, Vol. I, Ed. 3.
Answer: For every $x\gt0$, define $\varphi_-(x)$ and $\varphi_+(x)$ by
$$
1 - \Phi(x)=(x^{-1} - x^{-3})\varphi_+(x),\qquad 1 - \Phi(x) = x^{-1} \varphi_-(x).
$$
For every $x\gt1$, $\varphi_-(x)\gt0$ and $\varphi_+(x)\gt0$, and Feller's (1.8) implies that $\varphi_-(x)\lt\varphi(x)\lt\varphi_+(x)$ (but if $0\lt x\lt1$ the factor $x^{-1}-x^{-3}$ reverts the inequality sign related to $\varphi_+(x)$). The definition of $\alpha$ and the fact that, for every $\beta\gt0$, the function
$$u\mapsto\frac{u}{\beta\Phi(\beta)+u}
$$
is nondecreasing on $u\gt0$ (while if $\beta\lt0$, the function is not defined on the whole interval $u\gt0$),
 yield
$$
\frac{\varphi_-(\beta)}{\beta\Phi(\beta)+\varphi_-(\beta)}\lt\alpha\lt\frac{\varphi_+(\beta)}{\beta\Phi(\beta)+\varphi_+(\beta)}.
$$
The LHS and the RHS of this inequality coincide with the LHS and the RHS in (1).
Comment: Thank you for your answer. Just one question. How does it follow from Feller (1.8) that $\varphi_-(x) < \varphi(x) < \varphi_+(x)$?


Cannot Create an instance of the abstract class on interface 'HttpRequest'

Question: Estou recebendo o seguinte erro:

Cannot Create an instance of the abstract class on interface 'HttpRequest'

Nessa parte do meu código:
class FakeContext
{
    public static HttpContext FakeHttpContext()
    {
        var httpRequest = new HttpRequest("", "http://stackoverflow/", "");
        var stringWriter = new StringWriter();
        var httpResponse = new HttpResponse(stringWriter);
        var httpContext = new HttpContext(httpRequest, httpResponse);

        var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
                                                new HttpStaticObjectsCollection(), 10, true,
                                                HttpCookieMode.AutoDetect,
                                                SessionStateMode.InProc, false);

        httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
                                    BindingFlags.NonPublic | BindingFlags.Instance,
                                    null, CallingConventions.Standard,
                                    new[] { typeof(HttpSessionStateContainer) },
                                    null)
                            .Invoke(new object[] { sessionContainer });

        return httpContext;
    }
}

oque estou fazendo errado ?
Answer: Você está confundindo System.Web.HttpRequest do .Net Framework com o Microsoft.AspNetCore.Http.HttpRequest do .Net Core.
O segundo é uma classe abstrata e como o erro informa, você não pode instancia-la. Você pode usar Injeção de Dependência para utiliza-lo com o IHttpContextAccessor.
Mas pro seu caso, pra fazer um request, veja o exemplo da própria Microsoft. Acredito que você seguiu algum exemplo do .Net Framework mas em um projeto que utiliza o .Net Core.
Abaixo um exemplo simplificado:
public class HomeController : Controller
{
    private readonly IHttpClientFactory _clientFactory;

    public HomeController(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }

    public async Task<HttpResponseMessage> FakeHttpContext()
    {
        var request = new HttpRequestMessage(HttpMethod.Get, "http://stackoverflow/");
        var client = _clientFactory.CreateClient();
        var response = await client.SendAsync(request);

        //Restante do seu código...

        return response;
    }
}


longest increasing subsequence with at most k deletion

Question: Given a number array of length n and a number k, what is the longest non-decreasing contiguous subarray if we allow at most k deletions in our original array?
example:
n, k = 5, 2
array = 5 2 1 3 4
answer = 2 3 4
with deleting 1 from index 2.
Answer: Suppose the initial array is named $R$.
The problem can be solved by storing $k+1$ lists $L_i, 0\leq i \leq k$. Element $L_i[t]$ denotes the length of the longest non-decreasing subarray ending with (and using) element $t$ of $R$, with at most $i$ deletions. These lists can be filled in a dynamic-programming fashion. $L_i[0]=1$, for all $i$. Suppose all lists $L_i$ are filled up to index $t$. Then we can determine $L_i[t+1]$ for all $i$ by simple reasoning.
For example: if $R[t+1]<R[t]$ then $L_0[t+1]=1$ because we cannot append element $t+1$ to the subarray ending at element $t$. Otherwise, $L_0[t+1]=L_0[t]+1$.
For $L_1[t+1]$ we need to take the maximum of two possibilities: either we skip element $R[t]$ and end up with a subarray of length $L_0[t-1]+1$ (if $R[t-1]\leq R[t+1]$), or we allow an earlier skip and use $L_1[t]+1$ (if $R[t]\leq R[t+1]$).
Filling in $L_i[t+1]$ for $i>1$ is completely analogous, and requires to take the maximum over the lengths reached by the $i+1$ possible skips. The longest subarray with at most $k$ skips is then equal to the maximal value found in the list $L_k$.
Answer: You can use DP to solve this problem.

subproblem: $dp(i)$ = length of non-decreasing subsequence ending at index i
recurrence: $dp(j) = max_{i < j, A[i] <= A[j]} ${dp(i)}$ + 1$ where . This is because the subsequence ending at index j is going to be extended by some subsequence ending at a previous index of i. E.g. 1,2,3,...i,..j. So we maximum over all position ending before j s.t. $A[i] <= A[j]$. After we find it, we add 1 additional element, which is jth element.
To find the solution, we have to take $max_{0 <= j <= n}$ ${dp(j)}$ and the sum of 'decreasing' element should less than k. This is because j can be anywhere in the array and we also need to consider k.
The time complexity is $O(n^{2})$ because we have to solve n subproblem and each of them takes O(n) time.
Comment: Try to improve your answer by using https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Comment: It is unclear what step 3 in this algorithm means. Furthermore, this version could only work if the OP intended that the 'offset' of the subarray is counted as deletions.


Lumen: update records via json body

Question: I have a Laravel Lumen API. I'm seeing an issue with the update functionality.
In my controller, the code for updating an item is:
public function update(Request $request, $id)
    {

        $this->validate($request, [
            'name' => 'required',
            'description' => 'required',
            'completed' => 'required',
         ]);

        $todo = Todo::find($id);
        $todo->name = $request->name;
        $todo->description = $request->description;
        $todo->completed = $request->completed;
        $todo->save();
        return response()->json(['status' => 'success']);
    }

I can update the todo item using:
http://lumen-todo.app/api/51?name=test&description=test&completed=1

however was hoping I could send the parameters in a json body, like this
PUT http://lumen-todo.app/api
{
  "id": 1
  "name": "Test",
  "description": "Test",
  "completed": 1,
}

For adding items, it works via a json body, so don't understand why it does not work for updates. For info, the 'add item' controller code is here:
public function store(Request $request)
{

    $this->validate($request, [
        'name' => 'required',
        'description' => 'required',
        'completed' => 'required'
     ]);

    $todo = new Todo();
    $todo->name = $request->name;
    $todo->description = $request->description;
    $todo->completed = $request->completed;
    $todo->save();
    return response()->json(['status' => 'success']);

}

Answer: If you want to get the json data from request payload, validate and store it, use
public function store(Request $request)
{
    $data = $request->json()->all();

    $this->validate($data, [
        'name' => 'required',
        'description' => 'required',
        'completed' => 'required'
     ]);

    $resource = $this->model->find($id);

    $resource->fill($request);
    $resource->save();

    return response()->json(['status' => 'success']);
}

Answer: Instead of doing this:
$todo = new Todo();
$todo->name = $request->name;
$todo->description = $request->description;
$todo->completed = $request->completed;
$todo->save();

Do, this:
use App\Todo;

protected $model;

public function __construct(Todo $model) {
    $this->model = $model;
}

$resource = $this->model->find($id);
$resource->fill($request);
$resource->save();

Also, you can do json_decode() function to change your json params to array and use that to validate and save data.

Lumen: update records via json body


What is the proper name of this optimal-policy area chart, and how can I make one?

Question: When preparing a summary document for policy-makers, it's fairly common to include a graphic that represents how the optimal policy solution varies with two variables. It may be the result of a formal or informal optimisation analysis. Below is an example of such a graphic. The graphic partitions the chart area into contiguous areas, with each area indicating that combinations of (x,y) within that area all share an optimal policy solution.
What's the proper name for such data visualisation? And is there an easy way in Matlab (or even Excel) to generate such graphics relatively automatically from data, without having to just draw every component manually as a custom shape (because if I was going to do that, I'd just use Illustrator)?
For now, please ignore the "CALM" / "SEGREGATE" labels and arrows - I'm interested in the partitioning of the chart into separate areas, and the distinct shading and labelling of each area. I'm not assuming this graph was generated from data: it's just to illustrate the chart style, nothing more. I want to generate a similar style of graph from data. As with the graph below, some of the boundaries may be non-linear.
Comment: I doubt there's gonna be any good answers to the question. The problem is that the you're assuming this graph was generated "from data". The data in this case are speeds and vehicle flow rates. The categories that are placed over them cannot be mapped by analytical function. I'd guess the edges were created fairly arbitrarily, based on expert judgement. Hard to know without the original context. You COULD create a mapping, but it'd just be a massive block of "IF" statements, combined with linear functions, which would be just as arbitrary. For the name, no idea, would be interested to find out
Comment: thanks for the comment. I've tried to clarify these issues in an edit to the last paragraph of my question,
Answer: As naught already mentioned, I find it unlikely a specific name for the type of chart is currently in use, although just identifying it by its common components with other charts (a line chart and an area chart superimposed) I would think would be sufficient.
Essentially when working with any statistical program that can produce statistical graphics, the graphical elements of the chart (lines and area) can be added to a plot in a programatic fashion, as well as rendering the cartesian coordinate system. The other meta data elements though (labels for lines and area fills, the background Calm and Segregate Arrows), are unlikely to be implemented in a programatic fashion. This is because they aren't data in the sense that their coordinates, orientation or any other aesthetic in plot directly depict data, hence their placement within the chart is arbitrary.
In my experience typical meta data that can be automatically added to plots are axis labels and labels for graphical elements (and labels for the axis that define the cartesian coordinate system obviously). Placement of labels to avoid overplotting of graphical elements is very difficult though, and so I would bet the labels in the above chart were placed by hand in a vector graphics editing program (like illustrator). You could do it programatically, but it would only work for the one particular chart you taylor it to.
The supplemental labels for the Y axis guide is unique, and so such a guide is unlikely already implemented in any statistical program (although in theory that would be much easier to implement than placement of the labels for elements within the plot).
IMO there isn't much point to adding a name to a particular type of chart once you understand the grammer of the components that make up the chart (which you do given your question). Knowing the grammar there could be very many different types of charts, and so what is the point in giving a line + area chart a special name.
It would be possible to make such a graph in excel (I don't know about Matlab), as well as various other statistical programs. Although it would be difficult to whip up a turn-key script to produce such a polished graphic as the one posted in your question (compared to the amount of time to add such elements post-hoc in a vector editing environment).
Comment: Also, in any decent vector graphics package (I recommend inkscape) you can align line segments to a grid, which would make the graph just as accurate as anything painstakingly created in any maths/stats package or spreadsheet editor (at least for the linear segments)


Show development and test site with same domain on browser

Question: I have a situation where domain.com (is the live server - A record points to this server). We have another domain.com (which is the test server - users manually set hosts file).
Users would like to access the live and test sites simultaneously on the the browser. What is the best way to do this? Users use their PCs/Macs to view the site.
I know that if you set the Hosts file setting on the PC then you can decide which IP to use that works but then switching hosts file each time is pretty hard to do.
Answer: Did you see this: https://addons.mozilla.org/en-US/firefox/tag/HostsFile
It's a Firefox addon that allows you to switch between different hosts file (and also do the DNS cache cleanup).
What we do on my job is to have subdomains for every environment like dev.domain.com or staging.domain.com.
Answer: If you use firefox get this addon: https://addons.mozilla.org/en-US/firefox/tag/HostsFile
If not your best bet is using Fiddler which act as a web proxy and thus can use his own hosts file ("Tools" Menu, "HOSTS File"), there's even a function to proxy for multiple remote clients.
NB: Fiddler is an excellent tool, it supports addons and many of them ar very useful and easy to use: http://www.fiddler2.com/Fiddler2/extensions.asp


When do you end a pedal sustain on a row change?

Question: I am learning the proper way to notate a pedal sustain in music notation, but am not sure about how to mark a transition from one line of music to another.  In this hypothetical only example ...

... the song continues the pedal sustains from measures 4 to 5, and 9 to 10.  Which is the proper notation for the pedal sustain line: use a square bar at the end of measure 4 and pick things up again at measure 5, or carry over the sustain pedal line as in measure 9 to 10?  Visually, choice 1 seems neater, but ...
Comment: @ToddWilcox I wonder if it has to do with visual clutter. "Ped" followed by "*" is cleaner than a line extending across an entire section of a piece.
Comment: Side note: I was surprised and dismayed to read in *Behind Bars*, which is a highly respected book on notation, that the "Ped. *" notation is preferred over the lines. Not to say you shouldn't use the lines if you like them better.
Comment: @ToddWilcox I'm all for it, but do they indicate why? The lines do seem more precise.
Comment: @Aaron - by the time phrase marks etc. have been added, it starts to look too busy. Most good players shouldn't need more than a guide anyway. Unless it's some really 'clever' stuff.
Comment: @Aaron Yes if you think about it the lines have to be continued and aligned and connected to retain meaning but Ped * is just two symbols that can be more easily arranged at the engraving stage. I agree with Tim also that pedaling such as indicated in this question is better denoted by being explicit in the first few measures and then marking *simile* or something like that. "Continue pedaling each measure" would be another way. Or even just "pedal every downbeat" at the start of the score with no explicit marks. Even "with pedal" or "sostenuto" would be enough.
Comment: Maybe I should just add an answer quoting Elaine Gould on pedal marks
Comment: @ToddWilcox I think it's deserving of its own Q&A. A quick looks through questions tagged with both [tag:keyboard-pedals] and [tag:notation] doesn't turn up a good existing question.
Answer: They are played differently. With m4-5 there will be a clear audible gap and with m9-10 not. So I'd definitely go with m9-10.
Answer: The 9>10 seems more accurate, but any player who knows what he's doing will pedal properly anyhow, holding until the first note in the next bar and changing while that is held down. But pedalling those particular notes..?
Answer: In order to continue the pedal across the end of the line, leave a flat pedal line.1

To release the pedal at the end of the line, use a vertical release line.2

1 Stephen Heller, "The Avalanche", op. 45, no. 2, mm. 29-30b. Published in "Celebration Series: Piano Etudes, Level 4", 2015 edition, RCM Publishing, page 13.
2 Ibid., mm. 30-32a, page 12.
Comment: @Dekkadeci In this piece, there are a first and second ending; they share measure numbers and are differentiated by "a" (first ending) and "b" (second ending). It's the first time I've ever seen that.
Comment: Unless "a" and "b" are part of a notation system I am not familiar with, how does Measure 30 appear one page before Measure 29 of the same piece?
Answer: Do you even need to use any pedal here? The left hand part moves by step and is pretty low, so pedaling through any two consecutive notes would sound really muddy. And even if you pedal each note separately it could sound too heavy, plus there would probably not be enough time to allow the reverb to fade away, and then it would clash with the next note.
Comment: I think (hope) the dots were sort of random!


Transparent proxy between two applications

Question: I've got a following setup:
Application A - makes HTTP requests to some API, running on http://localhost:8090.
Application B - intercepts HTTP request from A, a proxy running on http://localhost:8080.
Is it possible to force HTTP traffic from one application to another app running on the same host?
I've been trying something like that:
<code>iptables -t nat -A OUTPUT -p tcp --dport 80 -j REDIRECT --to-port 8080
</code>
But it seems it works only if the destination of HTTP request is some external API, it is not working if API resource server is deployed also on localhost (I suspect this is due to --dport 80). I don't know much about iptables, but something like that is even possible? If so, how can I accomplish this?
Answer: The iptables rule can work, but you have to activate routing on the machine for this to work on locally delivered packets. Also beware that on newer machines "localhost" often resolves to IPv6 loopback (::1), so then you would need the corresponding ip6tables rules. An initial connection failure on IPv6 can be masked and come back to haunt you later by an automatic fallback to IPv4 in your testing client (for example this is what curl does, if you do not specify -6 on the commandline)
If packets come from outside, you need to set the same rule in the PREROUTING chain.
<code># Activate forwarding
# Note: These forward settings are not reboot persistent
# Note: Putting your machine in router mode resets a lot of IP stack parameters
sysctl -w net.ipv6.conf.all.forwarding=1
sysctl -w net.ipv4.ip_forward=1
</code>
Comment: Thanks @Gerrit for your comment. Yes, I know about active routing. I enabled it before trying to create iptables. The thing is that I have no idea how to force traffic from 8080 to 8090. The only thing I have achieved is 80 -> 8090, I think is due to the fact that port 80 is designed for HTTP traffic. But when I create iptables 8080->8090 my proxy doesn't anything at all, just like the traffic wasn't there.
Comment: iptables certainly does not treat any port number in a special way. A HTTP server may act differently depending on how it received the traffic, because a client can for example include the original portnumber in the HOST header. Do your rules get hit? Use `iptables -t nat -nvL` to look at packet counts.