There exists a subsequence that converges to f pointwise a.e .

Question: Let $f,f_k,\,k\in\mathbb{N}$, be measurable functions on a measurable set $E\subset\mathbb{R}$.
If  $$\lim_{k \to \infty}\int_{E} \frac{|f_k(x)-f(x)|}{1+|f_k(x)-f(x)|}\, dx=0,$$
show that there exists a subsequence that converges to f pointwise a.e .
I have a idea that "Since $f_k$ converges to $f$ in measure, it has a subsequence that converges to $f$ pointwise a.e."
But I dont know how to prove that $f_k$ converges to f in measure?
Answer: Noting that the function $f(x)=\frac{x}{1+x}$ is increasing for $x>-1$, therefor for $|f_k(x)-f(x)|\ge\sigma$, one has
$$ \frac{|f_k(x)-f(x)|}{1+|f_k(x)-f(x)|}\ge\frac{\sigma}{1+\sigma}. $$
Let $E_k(\sigma)=\{x\in E: |f_k(x)-f(x)|\ge \sigma\}$.
$$ \int_{E}\frac{|f_k(x)-f(x)|}{1+|f_k(x)-f(x)|}dx\ge\int_{E_k(\sigma)}\frac{|f_k(x)-f(x)|}{1+|f_k(x)-f(x)|}dx\ge \frac{\sigma}{1+\sigma}|E_k(\sigma)|.$$
Letting $k\to\infty$, one has $|E_k(\sigma)|\to 0$, for $\forall \sigma>0$. Thus $f_k(x)$ converges to $f(x)$ in measure.
Comment: Thanks very much for your very clear answer.
Answer: As is well known, if $g_k \to g$ in $L^p, p\ge 1,$ then there is a subsequence $g_k$ that converges pointwise a.e.to $g.$ Your hypothesis implies $g_k(x)=|f_k(x)-f(x)|/(1+|f_k(x)-f(x)|) \to 0$ in $L^1(E).$ Thus there is a subsequence $g_{k_j} \to 0$ pointwise a.e. Now if $y_n$ is a sequence in $[0,\infty),$ then $y_n/(1+y_n) \to 0$ iff $y_n \to 0.$ Thus $f_{k_j} \to 0$ pointwise a.e.


How to log the visits on asp.net-core identity based application

Question: I am using Entity Framework core & ASP.NET core Identity and I want to log who visited the cars/details page. log table only have three columns (visitid, username, visittime).
Answer:
I am using Entity Framework Core & ASP.NET Core Identity and I want to log who visited the cars/details page. log table only have three columns (visitid, username, visittime).

I suppose you have created a LogModel which contains the three columns (visitid, username, visittime), and you have generated the related table in the database. If the log table not created, you can refer the following code to create a model, then add migration and update database to generate the table.
public class LogModel
{
    public int VisitId { get; set; }
    public string VisitName { get; set; }
    public DateTime VisitTime { get; set; }
}

Then, in the controller details action method, you can create a new LogModel, when a user visits this action method, it will insert the new LogModel instance into the database. Code like this:
public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    private readonly MvcMovieContext context;
    public HomeController(ILogger<HomeController> logger, MvcMovieContext movieContext)
    {
        _logger = logger;
        context = movieContext;
    }

    public IActionResult Details()
    {
        //create a new log record.
        var newlog = new LogModel()
        {
            VisitId = 101, //set the value, or set this column as auto increase (Identity).
            VisitName = User.Identity.Name,  //get the current user name through the User.
            VisitTime = DateTime.Now
        };

        context.Logs.Add(newlog); //insert into the database
        context.SaveChanges();  //save change.

        return RedirectToAction("Index");
    }

Edit:
To log current user information into the database using Action Filter method, you could get the current user information and get the request action method name in the Action Filter, and then, insert records into database.
Code as below:
   public class TestActionFilter:IActionFilter
    {
        private readonly ApplicationDbContext _dbcontext;

        public TestActionFilter(ApplicationDbContext context)
        {
            _dbcontext = context;
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            //get current user name
            var currentuser = context.HttpContext.User.Identity.Name;
            //get the request action method,
            var actionname = context.HttpContext.Request.RouteValues["action"];
            //based on the action method to insert record into database.
            //use _dbcontext to insert data.
            // Do something before the action executes.
            Console.WriteLine("TestActionExecuting:  " + context.HttpContext.Request.Path);
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            // Do something after the action executes.
            Console.WriteLine("TestActionExecuted:  " + context.HttpContext.Request.Path);
        }
    }

Then, register the action filter in the ConfigureServices method in the Startup.cs file
        services.AddControllersWithViews(options=> {
            options.Filters.Add(typeof(TestActionFilter));
        });

More detail information about ActionFilter, see: Filters in ASP.NET Core
Comment: thank you very much Zhi Lv. And what about Action Filters? I don't have to add this code block to all controllers in solution. do you have any sample project which is generated on aspnetcore with action filter?
Comment: @togy,  we can also use the Action Filters method to do that, in the OnActionExecuting method, we could get the current user information and the request action method, then insert the record into the database, please check my reply.
Comment: Thank you very much for detailed answer Zhi Lv. It works fine


Firebase Realtime Database Security Rules - How to get into second node

Question: I am struggling with the security rules on the firebase realtime database. My database structure is as following:

On the first level you have Chats. On the second level there are the Chat partners (a concatenated string with user IDs of chat partners). On the third level you have the messages. And on the last level there are the variables datetime, userid and message.
My question is, how can I get into the second child node, e.g. check if the auth.uid is within the concataneted string. My idea was to give the users read access, if the userid is within the chatpartners string, to ensure that only the chatpartners can read their messages. Or is this a thinking error?
I have tryid a lot of things, however no success:
"Chats":{
   ".read": "root.child('Chats').val().contains('auth.uid')"
 }

#Update
{
 "rules": {
   "Chats": {
     "$chatid": {
      ".read": "$chatid.contains(auth.uid)",
      ".write": "auth != null"
      }
   },
   "Suchencards": {
      ".read": "true",
            ".write": "auth != null"
   },
   "UserData": {
     "$uid": {
      ".read": "$uid === auth.uid",
            ".write": "$uid === auth.uid"
     }
   }
 }
}

I am using the playground on firebase console to check if I get true or false, however in that case I get false.
#Update 2
Screen1
Screen2
Comment: If you're using the rules playground to test this, please show a screenshot of the playground with all relevant values visible.
Comment: Added the screenshots.
Answer: You can only access data in your rules if you know the exact path to that data, so you won't be able to access all chats from a rule on /Chats. Trying to do so typically means that you're trying to define your rules on the wrong level.
For example, if you want to allow a user to read a specific child of Chats, you'll need to define rules on that level:
"Chats":{
  "$chatid": {
    ".read": "$chatid.contains(auth.uid)"
  }
}

While the above will work for accessing a specific room, you will not be able to use this to query for all chat rooms that a user has access to (as Firebase queries don't support a "contains" operation). Have a look at the userChatrooms node in my answer here for a better model for tracking the chat rooms for a user: Best way to manage Chat channels in Firebase
Comment: Thanks Frank!
Tried that code chunk you have provided with the wildcard solution $chatid.contains(). I put auth.uid into contains as well as the whole concataneted string. Both gives me a false, not a true, althoug the concataneted string is in the database.
Comment: Can you update your question to show the updated rules, and the minimal code that reproduces the problem (as rules don't do anything on their own)?
Comment: Okay just edited/updated my post.
Comment: You're trying to read `/Chats/chatid` in those screenshots, which means that `$chatid` is `"chatid"` and doesn't contain the UID you used. To make it work, read a path that includes the UID.
Comment: Thanks Frank. It works fine, when reading the correct path, however something goes wrong when trying that on the device. Will check it.


Sorting an Array by Age

Question: My function is sorting a Array by age, but its not working for some reason?
Other code so you know what im calling, array name etc.
var employeeA = new Array();
var employee = new Object();
var employeeList = [];
var employeeListA = [];
var name;
var age;
var position;
var type = 3;
var canvas;
var ctx;

function setupCanvas() {
    //alert("1");
    canvas = document.getElementById("employeeRecords");
    if (canvas.getContext) {
        ctx = canvas.getContext('2d');
        ctx.fillStyle = "lightblue";
        ctx.rect(0, 0, 500, 500);
        ctx.fill();
    }

Heres the Sort Age code:
function sortAge() {
    type = 1;
    employeeList.forEach(function(empl) {
        name = empl.name;
        age = empl.age;
        position = empl.position;
        employeeA = new Array(age, name, position);
        employeeListA.push(employeeA);
    });
    var y = employeeListA.length;
    if (y > 1) {
        employeeListA.sort();
    }
}

this code is being called for the sorting buttons
function arrayButtons() {
    employeeListA = [];
    if (type === 0) {
        sortName();
    } else {

        if (type === 1) {
            sortAge();
        } else {
            employeeList.forEach(function(empl) {
                name = empl.name;
                age = empl.age;
                position = empl.position;
                employeeA = new Array(name, age, position);
                employeeListA.push(employeeA);

            });

Thanks for the help! Appreciate it
:D
Comment: The `.sort()` method can be passed a callback function, and that would allow you to compare parts of the array elements directly.
Comment: You can provide a sorting function to `.sort()`. Try `employeeList.sort(function( a, b ){ return a.age - b.age; });` So no need to create new arrays just to be able to use `.sort()` directly.
Comment: Possible duplicate of [Sort array of objects by string property value in JavaScript](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value-in-javascript)
Answer: Using sort() method is very easy way to get expected result in a single line of code.
more info
const myTeam = [
  {
    name: "Virat",
    age: 40
  },
    {
    name: "Rohit",
    age: 30
  },
    {
    name: "Bhuvi",
    age: 20
  },
    {
    name: "Raina",
    age: 33
  }
]

const sortedByAge = myTeam.sort((firstEl,secondEl)=> secondEl.age - secondEl.age);

  console.log(sortedByAge);

Comment: Please relate your answer to the existing.
Answer: This is what you're looking for:
Sort array of objects by string property value in JavaScript
TLDR:
You can use the method .sort of an array which can take as a first argument a comparator function. This function takes 2 arguments which will be each object in the for loop.

var employees = [
  {
    age: 28
  },
  {
    age: 18
  },
  {
    age: 35
  }
];
employees.sort(
    function(a, b) {
       return a.age - b.age
    }
);
console.log(employees)

Hope this helps you.
Comment: I can't figure out why this works in the code snippet and Chrome console, but not in IE console. I would expect this to not work all the time, since `.sort()` expects a number and you return true or false, which is converted to 0 or 1. But if I paste this code into IE console, the array stays in the same order.
Comment: Yeah you're right, in fact, sort expects  `-1, 0 or 1` but true (1) and false (0) are enough to sort a list. Haven't tried in IE tbh, I'm only using chrome. But isn't that implicit conversion equivalent in every explorer?
Comment: In W3Schools doesn't even mention about the 3 possible values, but yes in mozilla's docs [Array.prototype.sort()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description)
Comment: I think IE might not do the conversion automatically and hence, not do the sort, since true is not a number. Hence I always use + and - in sorting functions. Sidenote: it does not have to be -1 0 or 1, any number will suffice according to the spec.
Comment: It should be `a.age - b.age` and not `a.age > b.age`
Comment: You are both right. I've already edited the answer. Thank you.

Sorting an Array by Age


c# api methods created dynamically

Question: Just as the title states, is it possible to create an api dynamically? I did some research and couldn't find any way of doing this. I have a method that pulls the columns in a table. I want to create all the CRUD operations from that pull of information. Those operations would then be able to be called through an API. Let me know if I am unclear or I need to post anything else.
Comment: Do you want to do it completely dynamically? By this I mean that it is generated at runtime. Or that you do code generation first and generate static code that is compiled after. By api you mean WebApi or just a library?
Comment: I mean a webapi,I would think it would be the former and generate at run time in case the information in the db changes. If i need to do the code generation first then I would do that, Please let me know if I need to clarify more please. I appreciate your time.
Comment: Code generation first I think is easier than generating all at runtime. Just another clarification Do you want to generate all the controllers with all the methods from the database or you need just the model to dynamically change and reflect the model in the database. By this I mean that you have a static controller for each table and if you add or remove a column the api will automatically also add or remove it to the output.
Comment: Probably to generate all the controllers with all the methods from the database. I do not believe I will be able to generate the static controller ahead of time.
Answer: Here is one possible solution to do it using T4 templates to generate code. T4 templates are available out of the box by Visual Studio. For more details check the documentation about generating code with T4 Text templates.
For the sample I have created an include file Common.t4 that has the functions to retrieve model information. If you already have a library that does that you can import the assembly directly in the template and don't need also a common code file. I return only static data in the functions for simplicity you have then to implement it by calling your method that gets you the data.
Sample common file:
<#@ import namespace="System" #>
<#+
public string[] GetEntities()
{
    // TODO: implement logic to get entitities
    return new string[] { "Entity01", "Entity02", "Entity03" };
}
public class FieldDefinition
{
    public string Name { get; set;}
    public Type Type { get; set; }
}
public FieldDefinition[] GetEntityFields(string entityName)
{
    // TODO: Implement retrieval of Entity fields
    return new FieldDefinition[]
    {
        new FieldDefinition() { Name = "Id", Type = typeof(int) },
        new FieldDefinition() { Name = "Name", Type = typeof(string) }
    };
}
#>

Once you have this common function you can create one T4 template file for the models and one for the controllers.
Here is a sample models template:
<#@ template hostspecific="false" language="C#" #>
<#@ output extension=".cs" #>
<#@ include file="Common.t4" #>

using System;
using System.Collections.Generic;
using System.Linq;

namespace WebApplication3.Models
{
<#
foreach (string entity in GetEntities())
{
#>
    public class <#=entity#>Model
    {
<#
    foreach (FieldDefinition fieldDefinition in GetEntityFields(entity))
    {
#>
        public <#= fieldDefinition.Type.FullName#> <#= fieldDefinition.Name#> { get; set; }
<#
    }
#>
    }

<#
}
#>
}

And finally the Controllers template:
<#@ template hostspecific="false" language="C#" #>
<#@ output extension=".cs" #>
<#@ include file="Common.t4" #>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebApplication3.Models;

namespace WebApplication3.Controllers
{
<#
foreach (string entity in GetEntities())
{
#>
    [Produces("application/json")]
    [Route("api/<#=entity#>")]
    public class <#=entity#>Controller : Controller
    {
        // GET: api/<#=entity#>
        [HttpGet]
        public IEnumerable<<#=entity#>Model> Get()
        {
            return new <#=entity#>Model[] { new <#=entity#>Model(), new <#=entity#>Model() };
        }

        // GET: api/<#=entity#>/5
        [HttpGet("{id}", Name = "Get")]
        public <#=entity#>Model Get(int id)
        {
            return new <#=entity#>Model();
        }

        // POST: api/<#=entity#>
        [HttpPost]
        public void Post([FromBody]<#=entity#>Model value)
        {
        }

        // PUT: api/<#=entity#>/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]<#=entity#>Model value)
        {
        }

        // DELETE: api/<#=entity#>/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }

<#
}
#>
}

There are also many other commercial and free code generation tools available. Check this link: Comparison of code generation tools. This offers also alternatives to T4 if you don't like it or you are missing some feature.
In the end I also mention the technologies you can use for fully dynamic code generation in the runtime. For such a scenario you can use Roslyn compiler, CodeDOM or Reflection.Emit.

c# api methods created dynamically


Learning for entry level exam for music school

Question: On Sunday I am going to take a entry level exam in music theory. They didn't give me any sample exam or references to where can I learn this stuff. All I have is a list of what will be in the exam (Translated from Hebrew):
Written Theory exam:

Scales - building and identifying the major and minor (natural,harmonic,melodic) scales.
 Modes -  building and identifying the different modes: Dorian, Phrygian, Lydian, Mixolydian, Locrian
 Intervals -  building and identifying intervals on every note.
 Triads and their inversions - building and identifying Triads and their inversions (Major, Minor, Augmented, Diminished)
 Seventh chords and their inversions - building and identifying the following seventh chords and their inversions:Major seventh, Minor seventh, Dominant seventh, Diminished seventh, Half-diminished seventh, Minor major seventh, Augmented major seventh
 Transposition
 Continuing a given melody
 Knowledge rhythmic values
 To harmonize a given soprano and bass using standard degrees and chords
 To analyze a given musical piece excerpt (for example, a Bach chorale)

Sections 1-5 and 8 I know how to learn to, 6 I think I do, but I have no clue how to learn for sections 7,9 and 10. Where can I learn this things?
Comment: Just curious: what is the typical age or prior background of candidates?
Comment: I just returned form the exam. typical age: 19-23
Answer: 7, 9, and 10 are simply applications of all the other skills.
7. To continue a given melody, notice what mode the melody is based in and what general sorts of intervals and rhythmic values it's been using thus far (and what chords it has been implying). Then write something that fits in that general style. (Your ear will be better at this than your brain!)
9. To harmonize a given soprano and bass, use your knowledge of triads and seventh chords to determine a reasonable chord pattern that fits the soprano and bass ("reasonable" meaning "implies functional harmony"). Then fill in the missing notes (most likely, with some attention to voice leading).
10. To analyze a given musical piece, use your knowledge of triads and seventh chords to label each chord in the piece. I doubt an entry-level exam would expect any more than that.
Comment: Yes. What he said.
Comment: You can train for 7. (=1. here) with your own instrument first or by singing. If you have listened to a lot of music in different styles you have intuitively acquired a certain sense of their styles and device. a) Play a record of music featuring your instrument, stop it somewhere and try to go on by yourself for a few bars. Try to write down what you did. b) recall a musical theme you like, try to do a simple variation or imitation of it that could be play after it.
Comment: @ogerard. I think you forgot to put a link in the word "here":)
Comment: @idober: you are right, I should have written (=1. in this answer).
Answer: You should really consider obtaining the services of an experiences theory teacher. This things take a long while to master.
7 - 10 seems like your general theory questions you would need to know to gain access to a college music program.
7) Also sometimes called the completion of a melody.
You are a given a two bar excerpt and asked to write a melody in response to what they give. Usually depending on the standard either 8 or 16 bars. You may also be asked to modulate either to the dominant or the relative key. You also have to give meaningful articulation for whatever instrument you have to write the melody.
You need to master the following at the very least know how to do.

Know your chord progressions
Know your cadences and where your cadence points may be.
Know how to modulate successfully so that the modulation is clear.
Be sure of how the rhythmical sequence works.

9 seems like a general four voice harmony exercise. Here you are given either the soprano or bass voice and are asked to harmonise the given voice for four voices.
You first go about discerning the key.
Then you decide what chords you are in (Be wary of non chordal notes)
You then write a melody in the opposing outside voice.
When you have done this you complete the middle voices.
THINKS TO TAKE NOTE OF:

You may NOT have consecutive octaves or fifths know what this means and how to avoid them.
A chords notes cannot be more than an octave between notes in the difference voices the only exception being the notes of the bass and tenor voice.
You need to be able to use the passing 6/4 progressions and the 6/4 cadence progressions
You need to know the proper doubling of the notes.
The melody you write should have a nice line and it always good to aim to get an octave between the lowest note in the melody and the highest.

Usually even if all the notes are correct if you melody line is boring or stagnant you will not get a good mark. This is not just an exercise in testing your knowledge they want you to make good music.
10 seems like a genera analysis type of question.
Here you general music knowledge is tested. You may be asked a variety of questions that may include but not be limited to.
Questions of eras.
Analysis of the score.
Chords and inversions.
Intervals.
Music terms.
Knowledge about transposing instruments and concert pitch.
Scales and Modes.


Improvisation Technique and Theory Over Modal Sus or slash chords

Question: i would like to understand how to improvise over a Modal Sus chord progression.
As an example you can look at the video down here at 3"00. There Begins a Improvisation by a Keyboarder and later a guitarist over a chord change with Sus or slash chords.
I think the Progression is Gmaj/A , Ebmaj/F , Cmaj/D , Cmaj/D
What would be the right way of thinking about this Progression?
What scales or Arpeggios should be used for Improvisation?
Comment: This was put on hold because it is basically asking "What do they do in this video?", and that kind of analysis of a particular song is considered too specific. If you rephrase it to be more about the general concept you are looking for, and take you-tube out of the title, rather than "How does this guy play this progression," I'd vote to reopen. I think you are trying to get at a general concept, but you are also asking about what and how it is done here. It's a mixed message.
Comment: Change the title and use Lukather's song as an example. I hope this gets reopened because content-wise it's probably one of the more interesting questions here. By the way, the first chord is Gmaj7/A, listen to the bass, it's definitely an A.
Comment: In the progression you mentioned, there are no sus chords
Comment: @Shevliaskovic: There are. C/D is just another way of writing a D9sus4 chord.
Answer: When improvising over a progression like this, you need to change scales when the chords change. Since all chords are of the same type, you can use the same scale (with a different root, obviously) over each chord. The appropriate chord scale is mixolydian, but especially in Lukather's solo I can also hear dorian over the first chord Gmaj7/A.
Pentatonic scales sound especially good over such a progression. You could try E minor pentatonic over G/A, G minor pentatonic over Eb/F, and A minor pentatonic over C/D. So, just as an idea, you could play a melody in E minor pentatonic, shift it up by a minor third (G min. pent.), then shift it up another whole tone to A minor pentatonic. This will get you safely over the progression. Minor 7 Arpeggios will also work well. E.g., try Bm7 over G/A, Cm7 over Eb/F, and Am7 (or Em7) over C/D.
You see there are many possibilities that you can play around with. Note that the same type of chord is used in the progression of Herbie Hancock's tune Maiden Voyage. Also listen to the solos on that song and learn from them. I've written a blog post about improvising over suspended chords, using Maiden Voyage as an example. Also check out Toto's version of it called Butterfly with Steve Lukather's solo on it.


Drupal 7 Ajax GET - Error 400 (Hook_menu)

Question: I am trying to send an array back to Drupal to save in a database table. I'm getting an error 400 though when inspecting in the console and the url seems correct:

GET http://localhost/audiophreak/callback/%?[1,2,3,4,5,6,45,46,47] 400
  (Bad Request)

Here is my hook_menu:
/**
* Implementation of hook_menu().
*/
function my_db_module_menu() {
  $items['callback/%?'] = array(
    'title' => 'My callback',
    'description' => 'Desc',
    'page callback' => 'mymodule_getinfo',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
    'page arguments' => array(1),
  );
  return $items;
}

Here is my callback:
/**
 * My callback
 */
function mymodule_getinfo($data) {

echo drupal_json_decode($data);

  // //Parse the data and input it into the database
  // $result = db_insert('my_db')
  // ->fields(array(
    // 'nid' => $data->node,
    // 'uid' => $data->user,
    // 'progress' => $data->progress,
  // ))
  // ->execute();
}

And here is my AJAX
//Data
    var post = plnzVideoTracker.progress

    //Begin Ajax
    $.ajax({
          url: '/audiophreak/callback/%',
          contentType: "application/json; charset=utf-8",
          type: 'GET',
          dataType: 'json',
          data: JSON.stringify(post),
          success: function(data) {
            if(data == "success")
            {
            $('.status').attr("innerHTML","Name submitted successfully!");
            }
            else
            {
              $('.status').attr("innerHTML","Name submit failed!");
            }
            },
            beforeSend: function() {
              $(document).ready(function () {
              $('.status').attr("innerHTML","Loading....");
            });
            },
            'error': function(data) {
              $(document).ready(function () {
              $('.status').attr("innerHTML","ERROR OCCURRED!");
            });
          }
     });

plnzVideoTracker.progress is an array inside of an object literal if that has anything to do with it?
Answer: The % symbol is type of placeholder in hook_menu item. You can read more about it here: https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_menu/7#sec_path_wildcards.
For you example I suggest to use the following:
function my_db_module_menu() {
  $items['callback'] = array(
    'title' => 'My callback',
    'description' => 'Desc',
    'page callback' => 'mymodule_getinfo',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
  );

  return $items;
}

Simple path  - callback.
And use the following AJAX:
$.ajax({
  url: '/callback',
  type: 'POST',
  dataType: 'json',
  data: {data: post},
  ...

By this way, you can access the data in your webhook more simply:
/**
 * My callback
 */
function mymodule_getinfo() {
  $data = !empty($_POST['data']) ? $_POST['data'] : array();

  // do what you want...
}

Comment: Hmm now getting the error: POST http://localhost/callback 404 (Not Found). Url seems to be deprecating the base path
Comment: Did you cleared the cache before try to access it?
Comment: Yes, i'll double check everything again though. uno momento.
Comment: kala4ek, I seem to have solved it partially thanks to you. I set the callback in the ajax request to a relative path: $.ajax({
          url: '/audiophreak/callback',
          type: 'POST',
          dataType: 'json',
          data: {data: post},
          success: function(response){
                    alert(response);
                    //echo what the server sent back...
                }
         }); and used if(isset($_POST['data']) && !empty($_POST['data'])) {
        // echo json_encode(array("blablabla"=>$variable));
        echo json_encode($_POST['data']);
    }
Comment: This now alerts the array I am sending. Thank you!


How to create a new property in MSBuild and reference it in WIX

Question: We need to create a property to indicate our software version. Then we want to use it inside our WIX project, i.e., reference it in wxs file. We don't want to define it in wxs file because we want the MSBuild to rename output file based on this version number too. A definition of constants in PropertyGroup is not a proper place for us and here is the reason:
The properties defined in the PropertyGroup is Configuration/Platform specific. Whenever we modify this preprocessor in Visual Studio IDE from project properties window, normally we only modify the value for a specific Configuration/Platform combination. (I know it is possible to modify it for All Config/Platform in IDE, but it is actually done by making copies to all combinations. And it is still possible we ruin the synchronization by modifying a value for only one combination. For example, by default when we open the build tab of project properties window, it will show the active Config/Platform). On the other hand, even though we can define a PropertyGroup without any condition, whenever we modify it in the IDE, we are normally only modifying it for the specific combination, not all of them. Since we are purely building our SW in VS IDE, it will be hard to maintain and prone to problem.
I tried to use CreateProperty task of MSBuild inside BeforeBuild target, but it seems in the following execution the value will not be effective at all. For example, if I overwrite an existing property in BeforeBuild, and when I reference it in WIX, it will still use the old value. And if I create a totally new property, WIX is complaining undefined preprocessor.
Is there a proper way to do that: create a MSBuild property and use it inside WIX?
Comment: What do you mean by overwriting an existing property? Can you show the msbuild?
Answer: You don't need to use BeforeBuild. This definitely works on wixproj.
my.properties
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
  <PropertyGroup>
    <DefineConstants>$(DefineConstants);foo=bar</DefineConstants>
  </PropertyGroup>
</Project>

updated wixproj
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

<Import Project="my.properties" />
</Project>

Wix
<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
    <Product Id="*" Name="SetupProject1$(var.foo)" Language="1033" Version="188.8.131.52" Manufacturer="$(var.foo)" UpgradeCode="863d8da1-422b-4b28-aa68-56e3190770d7">

Comment: thanks, I am almost there. Now my only problem is how to use this constant inside wixproj file? Because the target is to use it for MSBuild to rename the output, so how can I reference foo inside .wixproj? I tried $(foo), which would work if I directly define a property, but it doesnä't work with DefineConstants
Comment: Set the $(OutputName) property. But you need to do it earlier than at the end of the project. Move the Import element right after the configuration-specific property groups.     $(OutputName)-somethingelse
Comment: I am sorry but this doesn't seem to work. It just simply complains preprecessor foo is not defined. But I have done it in another way: I use a MSBuild task to automatically read the version number from one xml file which we maintain and write this value to WIX file directly. That way we only need to define the version one place(in the xml file) and keep using our current WIX file.
Comment: It works for me. I'm using Wix 3.6, the equivalent for other versions might be slightly different but the underlying concepts are the same. It's not great to update the file, it might mess up up to date checks and interfere with source control, but if that works for you that's great. If you're using a different version of Wix you may want to look at the name of the MSBuild property that holds the constants.
Comment: I was also using Wix3.6, although I tried with 3.7, neither worked. And the really weird thing is at first I thought it worked, but only to find out it was because the preprecessor got secretly created and hence it was available. By "secretly" I mean I couldn't find the definition in .wixproj file, nor any source file visible in VS. I swear I searched all the files but couldn't find it. I am not an expert of MSBuild, so I don't know where else it could get the value. And what makes it worse is everything time I deleted the definition from IDE, it got created again next time I loaded the window
Comment: I suggest you try bumping up the msbuild verbosity and check what parameters are used for Candle and Light. There is a wix targets file somewhere under program files (check the import statement in your wixproj and look for that file). You should be able to track the properties and items used as parameters and update accordingly. But I still don't understand what didn't work for you; could you elaborate/provide samples of your updates to the wixproj file?
Comment: That solution certainly works. The only catch is that the my.properties could not have properties from other projects, like a  property sheet.
Answer: Please check preprocessor variables here. I'm not sure actually if you can reference project properties other than standard, but looks like it is possible.
Comment: Thanks for your reply. But what is possible? Basically my question is whether it is possible to create a preprocessor in MSBuild, and use this value in WIX. Because it seems that the manipulation I did in BeforeBuild target of MSBuild won't take effect for the further execution of WIX. If I change the value of one pre-defined preprocessor, in the execution of WIX it is still the old value. If I create a new one, it won't be available at all for WIX. And use DefineConstants in PropertyGroup is also not what I want.
Comment: If you have old value, please check the project build order (right-click on solution file > Build order). Maybe your installer isn't dependent on the project you are referencing and installer is building before it. If so, you can add custom dependency in Project Depenencies view
Comment: This is the installer project, i.e., I can't use the new value I set at wixproj file for my wxs file.


how to create the pagination for customized portfolio template

Question: I will create the portfolio gallery page using custom content types with thumbnail and bigimage  image fields. then i am using the following code for rendering content types
<?php
$content_type = 'websiteportfolio';
$query = new EntityFieldQuery();

$entities = $query->entityCondition('entity_type', 'node')
->entityCondition('bundle', $content_type)
->propertyCondition('status', 1)
->pager(9)
->execute();
$nodes = entity_load('node', array_keys($entities['node']));?>

<?php
  $i = 1;
  foreach($nodes as $val=>$key1)

  {

 ?>

<a href=<?='sites/default/files/'. $key1->field_bigimage['und']['0']['filename']; ?> rel="lightbox[portfolio]"  title="<?= 'Portfolio'.$i ?>"><img src=<?='sites/default/files/websiteportfolio/'. $key1->field_images['und']['0']['filename']; ?> alt="<?= 'Portfolio'.$i ?>" />

 <?php
$i++;
}

 ?>

finally i got the 9  thumbnail images in my page and also light box functionality working well.My issue Only show first 9 images I need pagination for showing the remaining images how  can fix this issue..
Answer: First things first, that code shouldn't be in the template file; it should be in a preprocess function. The reasons for this have been documented at great length both on this site and the internet in general so I won't go into them here.
You might also find the l() function interesting, as well as theme_image()...API replacements for the custom HTML you're building up.
Other than that, the only thing you're missing is the code to actually render the pager; that would entail adding this to your preprocess function, after the query has been run:
$vars['pager'] = theme('pager');

And in the template file simply outputting it wherever you'd like it:
<?php echo $pager; ?>


How did Glenn Gould know, in 1955, the proper ornamentation for Bach's "Goldberg Variations"?

Question: This question has its origin in Why does the Open Goldberg score have a G rather than A in bar 9 of variation 25?. See that Q&A for background information.

At what time, and on what basis, was ornamentation corrected in the Goldberg Variations, Variation 25?
In the first edition of the Goldberg Variations, the first measure does not contain an ornamental D5 preceding the Bb5.

However, in Glenn Gould's 1955 recording, he includes the ornament.

The ornament does appear in the handexemplar, but that was not discovered until 1974.

How did Gould, in 1955, know about this ornament?

According to the editions available on IMSLP, the ornament was included as early as Czerny's ca. 1850 edition. But at what point was it first introduced, and on what basis?

Wanda Landowska, in 1933, made the first Goldberg recording. She does not include the ornament.
Comment: Yeah, since the ornament appears in print by 1850 seems to me the inquiry is less about Gould and more about the paper trail (or not-paper trail?). A reception/performance history of the Goldberg Variations through the lens of a single ornament. The game is afoot!
Comment: Perhaps the important question is, What missing links fill in the gap between the lost _handexemplar_ and the 1850 Czerny? Is it simply a performance tradition that got transmitted? (I'm not sure of the reception history of the Goldberg Variations, but I suspect there's a bit of a gap...)
Comment: @AndyBonner Yes, that's the essence of the question. Perhaps I should state it more directly?
Comment: @AndyBonner Okay...cogitating. I put the focus on Gould thinking that would call more attention to the question. I'll revise...
Comment: There are still fascinating (separate) questions about Gould. I'm no expert, by my perception is he was little troubled with or limited by scholarship. Regardless of what happened to the ornament between 1741 and 1850, how did it come into his performance? Was he actually working from the Czerny (or a derived edition)? Does the ornament appear in recordings by earlier pianists?
Answer: Apart from being in other readings as you noted, this is a typically baroque portamento ornamentation that lyrical solos (like those executed by singers) would quite often be expected to include by default.  With an ornament immediately before and a long target note after a jump upwards, this is quite the location for this ornament.
Here the lead voice is clearly in the lyrical ballpark, so giving it this ornament is sort of a natural execution choice in baroque practice.  Whether Gould made this choice independently of other readings or in acknowledgment of them is likely impossible to discern at this point of time.


Custom Binding consuming a weblogic webservice ws-security 1.2

Question: I'm trying to consume a WebLogic webservice with ws-security 1.2.
In the WSDL, the security section is the following:
<wsp:UsingPolicy wssutil:Required="true"/>
<wsp1_2:Policy wssutil:Id="Wssp1.2-2007-SignBody.xml">
<ns1:SignedParts xmlns:ns1="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702">
<ns1:Body/>
</ns1:SignedParts>
</wsp1_2:Policy>
<wsp1_2:Policy wssutil:Id="Wssp1.2-2007-Wss1.0-X509-Basic256.xml">
<ns2:AsymmetricBinding xmlns:ns2="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702">
<wsp1_2:Policy>
<ns2:InitiatorToken>
<wsp1_2:Policy>
<ns2:X509Token ns2:IncludeToken="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/AlwaysToRecipient">
<wsp1_2:Policy>
<ns2:WssX509V3Token10/>
</wsp1_2:Policy>
</ns2:X509Token>
</wsp1_2:Policy>
</ns2:InitiatorToken>
<ns2:RecipientToken>
<wsp1_2:Policy>
<ns2:X509Token ns2:IncludeToken="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/Never">
<wsp1_2:Policy>
<ns2:WssX509V3Token10/>
</wsp1_2:Policy>
</ns2:X509Token>
</wsp1_2:Policy>
</ns2:RecipientToken>
<ns2:AlgorithmSuite>
<wsp1_2:Policy>
<ns2:Basic256/>
</wsp1_2:Policy>
</ns2:AlgorithmSuite>
<ns2:Layout>
<wsp1_2:Policy>
<ns2:Lax/>
</wsp1_2:Policy>
</ns2:Layout>
<ns2:IncludeTimestamp/>
<ns2:ProtectTokens/>
<ns2:OnlySignEntireHeadersAndBody/>
</wsp1_2:Policy>
</ns2:AsymmetricBinding>
<ns3:Wss10 xmlns:ns3="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702">
<wsp1_2:Policy>
<ns3:MustSupportRefKeyIdentifier/>
<ns3:MustSupportRefIssuerSerial/>
</wsp1_2:Policy>
</ns3:Wss10>
</wsp1_2:Policy>
<wsp:Policy wssutil:Id="Wssp1.2-2007-Wsp1.5-EncryptBody.xml">
<ns4:EncryptedParts xmlns:ns4="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702">
<ns4:Body/>
</ns4:EncryptedParts>
</wsp:Policy>

After a lot of search because I'm new in wcf I ended up into the following configuration:
<system.serviceModel>
<client>
    <endpoint name="wssMutualCert_Client"
     address="https://..."
     binding="customBinding"
     bindingConfiguration="custom1"
     contract="MyWebService.WebServicesMainMethod"
     behaviorConfiguration="MutualCertBehavior">
    </endpoint>
</client>
<bindings>
    <customBinding>
        <binding name="custom1" closeTimeout="00:01:00"
  openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00">

            <textMessageEncoding messageVersion="Soap11" writeEncoding="UTF-8" />
            <security defaultAlgorithmSuite="Basic256"
                      authenticationMode="MutualCertificateDuplex"
                      includeTimestamp="True"
                      messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10"
                      securityHeaderLayout="LaxTimestampLast" messageProtectionOrder="SignBeforeEncrypt">
                <localClientSettings maxClockSkew="00:07:00" />
                <localServiceSettings maxClockSkew="00:07:00" />
                <secureConversationBootstrap>
                    <localClientSettings maxClockSkew="00:07:00" />
                    <localServiceSettings maxClockSkew="00:07:00" />
                </secureConversationBootstrap>
            </security>
            <context protectionLevel="EncryptAndSign"/>
            <httpsTransport requireClientCertificate="true" maxBufferPoolSize="20000000" maxBufferSize="20000000" maxReceivedMessageSize="20000000"/>
        </binding>

    </customBinding>
    <ws2007HttpBinding>
        <binding name="wssMutualCertBinding">
            <security mode="TransportWithMessageCredential">
                <message clientCredentialType="Certificate"/>
                <transport clientCredentialType="Certificate"/>
            </security>
        </binding>
    </ws2007HttpBinding>
</bindings>
<behaviors>
    <endpointBehaviors>
        <behavior name="MutualCertBehavior">
            <clientCredentials>
                <serviceCertificate>
                    <defaultCertificate
                      findValue="XXXXX"
                      storeLocation="LocalMachine"
                      storeName="TrustedPeople" x509FindType="FindByThumbprint"/>
                </serviceCertificate>
                <clientCertificate
                    findValue="YYYYY"
                    storeLocation="LocalMachine"
                    storeName="TrustedPeople" x509FindType="FindByThumbprint"/>
            </clientCredentials>
        </behavior>
    </endpointBehaviors>
</behaviors>
<system.serviceModel>

My test appl looks like following:
static void Main(string[] args)
{
    MyWebService.WebServicesMainMethodClient client = new WebServicesMainMethodClient("wssMutualCert_Client");
    MyWebService.webRequest request = new webRequest();
    ServicePointManager.ServerCertificateValidationCallback = RemoteCertificateValidationCallback;

    try
    {
        webResponse response = client.retrieve(request);
    }
    catch (Exception e)
    {
        throw e;
    }
}
public static bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
    return true;
}

And what ever change I try in my configuration I receive the following:
An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail.

Server stack trace:
   at     System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply      (Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request      (Message message, TimeSpan timeout)
   at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message,     TimeSpan timeout)
    at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway,      ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway,      ProxyOperationRuntime operation, Object[] ins, Object[] outs)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService    (IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at Client.MyWebService.WebServicesMainMethod.retrieve(retrieve request)

I have been trying to find something helpfull almost 2 days now. I've searhed time sychonization issues, certs issues.
ANY IDEA OR RECOMMENDATION WOULD BE VERY HELPFULL.
Thank you all in advance.
Comment: please publish a sample working soap (ask one from the vendor)
Comment: If you have a similar problem, may be worth looking at this SO question If you are using WCF then this SO question may help you http://stackoverflow.com/questions/24635950/remove-timestamp-element-from-ws-security-headers-created-by-wcf
Answer: The error means that SOAP request WCF sends is not compatible with the weblogic security configurations. Usually there are issues with timestamp WCF sends and password as a text, but often non-.Net services want Digest Mode. There is no easy solution. Read this and this. I did downgrade to WSE 3.0 to be able to send requests to Java based service. There is easier to achieve this.
Comment: Thanks but I think WSE 3.0 does not support ws-security 1.2


Find matrix of change of basis from $(e_1, ... e_n)$ to $(e_n, e_{n-1} ... e_1)$, and $(e_1, e_2)$ to $(e_1 + e_2, e_1 - e_2)$

Question: a) Find the matrix of the change of basis from $K^n$, if the old basis is the standard basis $(e_1, ... e_n)$ and the new basis is $(e_n, e_{n-1} ... e_1)$
b) Find the matrix that describes the change from the old basis $(e_1, e_2)$ of $K^2$ to the new basis $(e_1 + e_2, e_1 - e_2)$

a) $(e_1, ... e_n)\cdot \begin{bmatrix}
    0 & 0 & \cdots & 0 & 1 \\
    \vdots & \vdots & \ddots & 1 & 0 \\
    \vdots & \vdots & 1 & \ddots & \vdots \\
    0 & 1 & 0 & \vdots & \vdots \\
    1 & 0 & 0 & 0 & 0
\end{bmatrix} = (e_n, e_{n-1} ... e_1)$
b)$(e_1, e_2)\cdot \begin{bmatrix}
    1 & 1 \\
    1 & -1
\end{bmatrix} = (e_1 + e_2, e_1 - e_2)$
Is this correct ? I'm quite new to the subject so your feedback would be really helpful
Thanks for your suppport !
Comment: @GloriousErin Thank you for the edit, I just notice now that I wrote $(e_n, e_{n-1}... e_n)$ instead of $(e_n, e_{n-1} ... e_1)$
Answer: If you have Basis $B = (b_1,b_2,..,b_n),$ and  Basis $C = (c_1,c_2,...,c_n)$ of some vector space and want to find the basis change matrix from $B$ to $C$ what u do is:
find the "coordinate vectors" of $(b_1,...,b_n)$ with regards to Basis $C$. that means: write $b_1$ as a linear combination of $c_1,...,c_n$ say $b_1  = a_1c_1 + ... + a_nc_n$ then $(a_1,...,a_n)$ ist your coordinate vector of $b_1$ with regards to basis $C$.(This is unique which follows directly from def. of basis) You do that for every basis vector of $B$ so u end with n row vectors. U transpose all of these vectors and write them in a matrix such that e.g. $(a_1,...,a_n)$ is the first column of ur matrix. (This might not be the best explanation so heres an example.
In your question (b) we have got the following:
$e_1 = 1/2(e_1+e_2) + 1/2(e_1-e_2)$
$e_2 = 1/2(e_1+e_2) - 1/2(e_1-e_2)$
resulting in the matrix
$\begin{pmatrix}
1/2 & 1/2 \\
1/2 & -1/2
\end{pmatrix}$
Of course I apologize for saying ur b) is correct bcs it is not but ur a) is correct.
Comment: The 1/2 just comes from basic calculation. As I already said, what u do is express the "old" basis vectors as a linear combination of the "new" basis and ur coefficients (written in the correct order and transposed etc..) build ur basis change matrix.
Comment: How did you get $e_1 = 1/2(e_1+e_2) + 1/2(e_1-e_2)$ and

$e_2 = 1/2(e_1+e_2) - 1/2(e_1-e_2)$ ? I don't quite see how you got the 1/2, is this linked to the change of basis ?


Função explode que ignora conteúdo dentro de aspas

Question: Estou trabalhando num projeto em PHP que precisa fazer import de arquivo CSV, cujo separador é por ;. Estou usando explode para fazer o processo, mas o problema é que em alguns casos o conteúdo pode vir com ; como no exemplo abaixo:
principio_ativo              | descricao
CIANOCOBALAMINA; DICLOFENACO | 50 MG + 50 MG COM REV CT BL AL PVDC INC

o arquivo gerado fica da seguinte maneira:
principio_ativo;descricao
"CIANOCOBALAMINA; DICLOFENACO";50 MG + 50 MG COM REV CT BL AL PVDC INC

 $lines = file($destinationPath.'/'.$result['file']);
 for($i=1; $i<count($lines); $i++){
     $line = $lines[$i];
     $explode = explode(',', $line);
     list($principioAtivo, $apresentacao) = $explode;
 }

//saída:
Array
(
    [0] => "CIANOCOBALAMINA
    [1] =>  DICLOFENACO"
    [2] => 50 MG + 50 MG COM REV CT BL AL PVDC INC
)

//saída ideal:
Array
(
    [0] => "CIANOCOBALAMINA; DICLOFENACO"
    [1] => 50 MG + 50 MG COM REV CT BL AL PVDC INC
)

Ao utilizar a função explode precisava que o conteúdo que estivesse entre " fosse ignorado pelo explode há alguma maneira de solucionar isso?
Neste link fiz um exemplo do que ocorre
Answer: Sim, utilizar as ferramentas certas para o trabalho. Se está processando um arquivo CSV, utilize a função fgetcsv para ler o conteúdo. Tal função possui um parâmetro que você define encapsulador de string:
fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\" ]]]] ) : array

Ou seja, basta fazer:
$stream = fopen("arquivo.csv", "r");

while (($data = fgetcsv($stream, 0, ";", '"')) !== false) {
    print_r($data);
}

E assim ter o retorno:
Array
(
    [0] => principio_ativo
    [1] => descricao
)
Array
(
    [0] => CIANOCOBALAMINA; DICLOFENACO
    [1] => 50 MG + 50 MG COM REV CT BL AL PVDC INC
)

Comment: Muito obrigado, funcionou direitinho!


Using CGAL to partition a non-simple polygon

Question: Suppose that I have a non-simple polygon,
how CGAL can help me to partition it into a set of simple polygons?
For example, give a polygon represented by a sequence of 2D points:
(1, 1) (1, -1) (-1, 1) (-1, -1)

I wish to acquire two polygons;
(1, 1) (1, -1) (0, 0)

and
(0, 0) (-1, 1) (-1, -1)

Is it doable for CGAL?
Answer: The question seems abandoned... Anyway, I'm adding a simple code to answer it:
#include <iostream>
#include <vector>

#include <CGAL/Arrangement_2.h>
#include <CGAL/Arr_segment_traits_2.h>
#include <CGAL/Exact_predicates_exact_constructions_kernel.h>
#include <CGAL/Polygon_2.h>

using Kernel = CGAL::Exact_predicates_exact_constructions_kernel;
using Traits = CGAL::Arr_segment_traits_2<Kernel>;
using Arrangement = CGAL::Arrangement_2<Traits>;
using Point = Traits::Point_2;
using Segment = Traits::Segment_2;
using Polygon = CGAL::Polygon_2<Kernel>;

int main()
{
  // ------ create a segment chain
  Point const p1(1, 1), p2(1, -1), p3(-1, 1), p4(-1, -1);
  std::vector<Segment> const cv = {{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}};
  // ------ create the arrangement
  Arrangement arr;
  CGAL::insert(arr, cv.cbegin(), cv.cend());
  // ------ iterate the arrangement bounded faces and create simple polygons
  std::vector<Polygon> polygons;
  for (auto fit = arr.faces_begin(); fit != arr.faces_end(); ++fit)
  {
    if (not fit->is_unbounded())
    {
      Polygon poly;
      auto const heitBeg = fit->outer_ccb();
      auto heit = heitBeg;
      do {poly.push_back(heit->source()->point());} while (++heit != heitBeg);
      polygons.push_back(poly);
    }
  }
  // ------ print simple polygons
  auto polyN = 1;
  for (auto const& p: polygons)
  {
    std::cout << "Polygon #" << polyN++ << ": ";
    for (auto const& v: p.vertices()) std::cout << '(' << v << ") ";
    std::cout << std::endl;
  }
}

The function CGAL::insert automatically computes the intersection point (0,0). The output is:
Polygon #1: (-0 -0) (-1 1) (-1 -1)
Polygon #2: (1 1) (-0 -0) (1 -1)

Answer: Your required two polygons do not make up the original hull. If you just want to break your original set into triangles using (0,0) as one of the vertices you can do this:
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Constrained_Delaunay_triangulation_2.h>
#include <CGAL/Delaunay_mesh_vertex_base_2.h>
#include <CGAL/Delaunay_mesh_face_base_2.h>
#include <vector>

typedef CGAL::Exact_predicates_inexact_constructions_kernel     K;
typedef K::Point_2                                              Point_2;
typedef CGAL::Delaunay_mesh_vertex_base_2<K>                    Vb;
typedef CGAL::Delaunay_mesh_face_base_2<K>                      Fb;
typedef CGAL::Triangulation_data_structure_2<Vb, Fb>            Tds;
typedef CGAL::Constrained_Delaunay_triangulation_2<K, Tds>      CDT;
typedef CDT::Vertex_handle                                      Vertex_handle;
typedef CDT::Face_iterator                                      Face_iterator;

int main(int argc, char* argv[])
{
    // Create a vector of the points
    //
    std::vector<Point_2> points2D ;
    points2D.push_back(Point_2(  1,  1));
    points2D.push_back(Point_2(  1, -1));
    points2D.push_back(Point_2( -1,  1));
    points2D.push_back(Point_2( -1, -1));
    points2D.push_back(Point_2( 0, 0));

    size_t numTestPoints = points2D.size();

    // Create a constrained delaunay triangulation and add the points
    //
    CDT cdt;
    std::vector<Vertex_handle> vhs;
    for (unsigned int i=0; i<numTestPoints; ++i){
        vhs.push_back(cdt.insert(points2D[i]));
    }

    int i=0;
    for (Face_iterator fit = cdt.faces_begin()  ; fit != cdt.faces_end(); ++fit) {
        printf("Face %d is (%f,%f) -- (%f,%f) -- (%f,%f) \n",i++,
               fit->vertex(0)->point().x(),fit->vertex(0)->point().y(),
               fit->vertex(1)->point().x(),fit->vertex(1)->point().y(),
               fit->vertex(2)->point().x(),fit->vertex(2)->point().y() );

    }

    return 0 ;
}

Which should give you output like this:
Face 0 is (0.000000,0.000000) -- (1.000000,-1.000000) -- (1.000000,1.000000)
Face 1 is (0.000000,0.000000) -- (1.000000,1.000000) -- (-1.000000,1.000000)
Face 2 is (-1.000000,-1.000000) -- (0.000000,0.000000) -- (-1.000000,1.000000)
Face 3 is (-1.000000,-1.000000) -- (1.000000,-1.000000) -- (0.000000,0.000000)


fivestar module get count

Question: I am interested in getting the average count for a node.
Currently I am able to show the nodes rating with:
<code>$fivestar = field_view_field('node', $node, 'field_cg_rating', 'basic');
render($fivestar);
</code>
But I just want to get the count instead of the entire html showing the vote. Just a numerical value.
Is there an easy way of doing this?
Answer: You can calc it with formula which is used by Fivestar on theme layer: http://drupalcode.org/project/fivestar.git/blob/refs/heads/7.x-2.x:/includes/fivestar.theme.inc#l132
<code>$fivestar = field_view_field('node', $node, 'field_cg_rating');
$stars = 5; // Stars count from your field instance settings. Settings can be loaded with field_info_instance() if needed.
$rating = round(($fivestar['#items'][0]['average']/100) * $stars, 1);
</code>
Comment: this should get me going in the right direction. I'll fiddle around with it. Cheers. +1
Comment: Just an fyi, using $fivestar['#items'][0]['average'] is incorrect unfortunately.
Comment: `$fivestar['#items'][0]['average']` always returns zero.
Comment: Please, dump `$fivestar['#items']`.

fivestar module get count


Dynamic text component data through JSON on A-Scene?

Question: Hi everyone how  to do it if so can you share demos or examples ...
How to do it ....
I tried many was using the text components but not able to find an exact way to do it ...
Comment: You need to provide more information on what you are trying to do with a code snippet.
Comment: @ngokevin I am trying to display text data which keeps updating  like I have done in Ajax in normal HTML ...
Answer: https://aframe.io/docs/0.4.0/guides/using-javascript-and-dom-apis.html
el.setAttribute('text', {text: 'Hello, World!'})
el.setAttribute('bmfont-text', {text: 'Hello, World!'})


Angular - RxJS : afterViewInit and Async pipe

Question: I tried to do the following in my component which uses   changeDetection: ChangeDetectionStrategy.OnPush,
@ViewChild('searchInput') input: ElementRef;

ngAfterViewInit() {
    this.searchText$ = fromEvent<any>(this.input.nativeElement, 'keyup')
      .pipe(
        map(event => event.target.value),
        startWith(''),
        debounceTime(300),
        distinctUntilChanged()
      );
}

And in the template

  results for "{{searchText}}"

It doesn't work, however if I remove the OnPush, it does. I am not too sure why since the async pipe is supposed to trigger the change detection.
Edit:
Following the answers, I have tried to replace what I have by the following:
this.searchText$ = interval(1000);

Without any @Input, the async pipe is marking my component for check and it works just fine. So I don't get why I haven't got the same behavior with the fromEvent
Answer: By default Whenever Angular kicks change detection, it goes through all components one by one and checks if something changes and updates its DOM if it's so. what happens when you change default change detection to ChangeDetection.OnPush?
Angular changes its behavior and there are only two ways to update component DOM.

@Input property reference changed
Manually called markForCheck()

If you do one of those, it will update DOM accordingly. in your case you don't use the first option, so you have to use the second one and call markForCheck(), anywhere. but there is one occasion, whenever you use async pipe, it will call this method for you.

The async pipe subscribes to an Observable or Promise and returns the
  latest value it has emitted. When a new value is emitted, the async
  pipe marks the component to be checked for changes. When the component
  gets destroyed, the async pipe unsubscribes automatically to avoid
  potential memory leaks.

so there is nothing magic here, it calls markForCheck() under the hood. but if it's so why doesn't your solution work? In order to answer this question let's dive in into the AsyncPipe itself. if we inspect the source code AsyncPipes transform function looks like this
transform(obj: Observable<any>|Promise<any>|null|undefined): any {
    if (!this._obj) {
      if (obj) {
        this._subscribe(obj);
      }
      this._latestReturnedValue = this._latestValue;
      return this._latestValue;
    }
    ....// some extra code here not interesting
 }

so if the value passed is not undefined, it will subscribe to that observable and act accordingly (call markForCheck(), whenever value emits)
Now it's the most crucial part
the first time Angular calls the transform method, it is undefined, because you initialize searchText$ inside ngAfterViewInit() callback (the View is already rendered, so it calls async pipe also). So when you initialize searchText$ field, the change detection already finished for this component, so it doesn't know that searchText$ has been defined, and subsequently it doesn't call AsyncPipe anymore, so the problem is that it never get's to AsyncPipe to subscribe on those changes, what you have to do is call markForCheck() only once after the initialization, Angular ran changeDetection again on that component, update the DOM and call AsyncPipe, which will subscribe to that observable
ngAfterViewInit() {
    this.searchText$ =
     fromEvent<any>(this.input.nativeElement, "keyup").pipe(
      map((event) => event.target.value),
      startWith(""),
      debounceTime(300),
      distinctUntilChanged()
    );
    this.cf.markForCheck();
  }

Comment: I am very confused, I really shouldn't have to do that, the async pipe should be marking the component for Check.
Without any Input, if I create a interval(1000) and async pipe on it, my template is getting updated with the OnPush
Comment: So you mean using interval, instead of fromevent?
Comment: are y sure that it's working?, because It's should be the same I think I'll test it
Comment: this.searchText$ = interval(1000)
      .pipe(map(() => this.input.nativeElement.value))
      .pipe(startWith(""), debounceTime(300), distinctUntilChanged());   //Thats the code right?
Comment: I just had this.searchText$ = interval(1000)  when I did the test
Comment: quite confusing though it doesn't work still, and It should not work definitely, because there is no difference between interval and fromEvent on this perspective
Comment: @Scipion , I finally found the answer and I'll update it. great question though :P
Answer: The changeDetection: ChangeDetectionStrategy.OnPush allow to the component to not triggered the changeDetection all the time but just when an @Input() reference is updated. So if you do all your stuff in the same component, no @Input() reference are updated so the view is not updated.
I propose you to Create your dumb component with your template code above, but give it the searchText via an @Input(), and call your dumb component in your smart component
Smart component
<my-dumb-component [searchText]="searchText$ | async"></my-dumb-component>

Dumb component
@Input() searchText: SearchText

template

  results for "{{searchText}}"

Comment: I have no doubt it would work, however I shouldn't have to do that. From my understanding the async pipe inside the component should do the work.
https://blog.angular-university.io/onpush-change-detection-how-it-works/
Comment: The issue here is not the async pipe but the changeDetection, because no input reference is updated, it's why the changeDetection is specially used for dumb component and not smart component, if you don't want to change your structure, you must remove the changeDetection onpush.
In your post, the smart-dumb component are used, and angular push for this structure
Answer: This is because Angular is updates DOM interpolations before ngAfterViewInit and ngAfterViewChecked. I know this sounds confusing a bit. It's because of the first change detection cycle Angular does. Referring to Max Koretskyi's article about change detection algorithm of Angular, in a change detection cycle these happens sequentially:

sets ViewState.firstCheck to true if a view is checked for the first time and to false if it was already checked before
checks and updates input properties on a child component/directive
instance
updates child view change detection state (part of change detection
strategy implementation)
runs change detection for the embedded views (repeats the steps in
the list)
calls OnChanges lifecycle hook on a child component if bindings
changed
calls OnInit and ngDoCheck on a child component (OnInit is called
only during first check)
updates ContentChildren query list on a child view component
instance
calls AfterContentInit and AfterContentChecked lifecycle hooks on
child component instance (AfterContentInit is called only during
first check)
updates DOM interpolations for the current view if properties on
current view component instance changed
runs change detection for a child view (repeats the steps in this
list)
updates ViewChildren query list on the current view component
instance
calls AfterViewInit and AfterViewChecked lifecycle hooks on child
component instance (AfterViewInit is called only during first
check)
disables checks for the current view (part of change detection
strategy implementation)

As you see, Angular updates DOM interpolations (at step 9) after AfterContentInit and AfterContentChecked hooks are called, so if you call rxjs subscriptions in AfterContentInit or AfterContentChecked lifecycle hooks (or earlier, like OnInit etc.) your DOM will be updated because Angular updates DOM at step 10, and when you change something in ngAfterViewInit() and you are using OnPush, Angular won't update DOM because you are at step 12 on ngAfterViewInit() and Angular has already updated DOM before you change something!
There are workaround solutions to avoid this to subscribe it in ngAfterViewInit. First, you can call markForCheck() function, so you basically say by using it on the first cycle that "hey Angular, you updated DOM on step 9, but I have something to change at step 12, so please be careful, have a look at ngAfterViewInit I have still something to change". Or as a second solution, you can trigger a change detection manually again (by triggering and event handler or using detecthanges() function of ChangeDetectorRef) so that Angular repeats all these steps again, and when it reaches at step 9 again, Angular updates your DOM.
I have created a Stackblitz example that you can try these out. You can uncomment the lines of subscriptions placed in lifecycle hooks 1 by 1, so that you can see after which lifecycle hook Angular updates DOM. Or you can try triggering an event or triggering change detection cycle manually and see that Angular updates DOM on the next cycle.


Como embaralhar todas as letras das palavras dentro de um arquivo .txt

Question: Estou criando um programa que embaralhe todas as letras das palavras dentro de um arquivo .txt em que a cada linha há apenas uma palavra.
Exemplo de um .txt (que chamei de wordlist.txt):
batata
limonada
áfrica

Como espero que seja o output:
atabat
adaoilmn
ficára

O que eu tentei fazer:
import random

with open('wordlist.txt', encoding='utf-8') as f:
    lines = f.readline()
    list = list(lines)
    random.shuffle(list)
    result = ''.join(list)
    print(result)

Output:
limonada
batata
áfrica

Na minha tentativa, o programa apenas embaralha a ordem com que as palavras são apresentadas.
Meu objetivo é que a ordem em que as palavras são apresentadas mantenha-se as mesmas, mas com cada palavra tendo suas letras embaralhadas.
Answer: São dois probleminhas aí:
Você confundiu o comando "with" com um "for": o "with", apesar de exigir um bloco de código, o bloco é executado uma única vez. Então, só a primeira linha é lida, e o programa acaba.
Pelo resultado que você descreveu, deve estar chamando o .readlines() (com "s" no fim) do arquivo, e não o ".readline" que leria apenas a primeira linha e iria embaralhar a primeira palavra.
Com o "readlines", é criada uma lista em que cada linha do arquivo é um item,e  essa lista é embaralhada.
Outra coisa é que você está chamando sua variável de list. A linguagem permite que você faça isso, mas depois que executar a primeira vez, a chamada original de list, que constrói uma lista a partir de uma sequência, é sobre-escrita pela sua variável. Você precisa usar outro nome para essa variável.
Então, como o comando with realmente só é necessário em programas mais complexos, para evitar vazamento de memória e recursos - e o for, se for passado um arquivo já lê um arquivo linha a linha, o seu programa pode ficar assim:
import random

for line in open('wordlist.txt', encoding='utf-8'):
    line = list(linha.strip())
    random.shuffle(line)
    result = ''.join(line)
    print(result)


plt.show() not working in Sublime 2

Question: I am attempting to display graphs without saving them using matplotlib in Sublime. For some odd reason, plt.show() is not working. There are no compilation errors or any other hints that would be useful.
import networkx as nx
import matplotlib.pyplot as plt
import random as r
randNum = r.randint(2,10)
randGraph = randStarGraph(randNum)
plt.show()

Anybody have any ideas?
Edit: I tried running Sait's code in Sublime. The graph failed to show. I ran the script from cmd, and the graph was successfully displayed on the screen, so it seems to be an issue with Sublime.
Comment: What is `randStarGraph` doing and where is it defined? Probably your issue is in that function as the rest looks pretty innocuous. Can't really say without seeing it though.
Answer: What is randStarGraph() doing and where is it defined?
Also, you don't call nx.draw() here, do you do it somewhere else?
You can test if sublime is working well with the following example:
import networkx as nx
import matplotlib.pyplot as plt

g = nx.complete_graph(5)
nx.draw(g)

plt.show()

Comment: randStarGraph() is a function that I created in order to a star shaped networkx graph.

Hm. It seems that your supplied code doesn't run either.
Answer: After trying the fixes suggested above, I Upgraded to Sublime 3, which fixed my problem. I had not really considered upgrading before, however I am now quite impressed by the new features that version 3 has to offer.
http://www.sublimetext.com/3

plt.show() not working in Sublime 2


Captura de um valor utilizando Select com Django

Question: Bom dia.
Criei um formulário e nele inseri os nomes dos meus clientes em um select. Ao selecionar um deles gostaria de real ziar um filtro, mas não está funcionando, parece que o valor do campo selecionado não está sendo enviado para a view.
Segue o código:
View
@login_required
def home_filtro(request):
    cliente = request.POST.get('cliente.id')
    atas = Ata.objects.filter(cliente=cliente)
    clientes = Cliente.objects.all()
    return render(request, 'core/index.html',
                  {'atas': atas, 'clientes': clientes)

HTML

<form action="{% url 'core_home_filtro' %}" method="post">
      {% csrf_token %}

      <select class="form-control" name="cliente_id">
              {% for cliente in clientes %}
                 <option value= "{{cliente.id}}" > {{cliente}} </option>
              {% endfor %}
      </select>

      <button type="submit" class="mt-3 btn btn-primary">Filtrar</button>
</form>

Vocês poderiam me ajudar a enter o que está havendo?
Obrigado
Answer: Se você alterar apenas a linha abaixo, veja se retorna algum erro.
if request.POST:
     cliente = request.POST['cliente.id']


DNS CNAME record - connection was reset

Question: I am quite new to DNS and have set up a CNAME record for a new domain that I have bought pointing at subdomain.domain2.com.
When I put in my URL http://www.domain1.com I get

The connection was reset The connection to the server was reset while
  the page was loading.

What could be the cause of this? I cannot see how to get it working. There are currently A Records set up for
"" - blank
*
ftp
mail
Do I need to delete some of these?
Comment: Before you put the URL into your browser, check that you are getting the correct DNS replies.
Answer: It looks like it's resolving the DNS address fine, but the webserver on that address doesn't recognize the name "www.domain1.com". You need to change its configuration so that it knows that it's serving that name.
Comment: Thanks for the info, could this be because I'm on shared hosting? Is there any easy way to configure this?
Comment: Not without getting the maintainer of your shared hosting to help. The web browser includes the domain name in its requests to the server (in the `Host` header). The server uses that header to decide which site should receive the request. If it doesn't recognize the name, it will do something by default. It sounds like your shared hosting server's default action is to reject the request. You'd like it to look up the CNAME record. It's easier to add the domain name to its configuration.
Comment: Thanks very much for your help - I didn't really know what I was doing with it, so all very useful. Will investigate further.

DNS CNAME record - connection was reset


Putnam type question: Invertible matrix

Question: Are the following matrices invertible?
(1) $A= (a_{ij})_{2003 \times 2003}$, where $a_{ii}=2003, a_{ij}=1$ for $i \not=j$.
(2) $B= (b_{ij})_{n \times n }$ with $b_{ii}= \pi$ and $b_{ij} \in \mathbb{Q}$ for $i \not= j$.
Thank you so much.
Answer: Hints: (1) $A$ is strictly diagonally dominant. (2) Let $C=B-\pi I$. If $B$ is singular, then $\lambda=-\pi$ is a zero of the characteristic polynomial $p(\lambda)=\det(C-\lambda I)$. However, $\pi$ is a transcendental number.
Answer: HINT
For the first one,
$$A = 2002 I + uu^T$$ where $u$ is a vector of $1$'s. In fact, you can get the inverse exactly. See Sherman Morrison Woodbury formula for more details.
For the second one,
$$B = \pi I + C$$ where $C_{ij} \in \mathbb{Q}$. If $B$ is not invertible, then there is $x \in \mathbb{R}^n$ such that $Bx = 0$ i.e. $\pi x + Cx = 0$. This means $-\pi$ is an eigenvalue of $C$. Is that possible?

Putnam type question: Invertible matrix


Eliminate removable discontinuity

Question: I have two rational functions which I have to examine for discontinuity and try to remove their domain gaps if possible.
$$f(x)=\frac{|x|-1}{x^3-x} $$
and
$$g(x)=\frac{sin (x)}{sin (2x)} $$
I determined the domain of the first function: $\mathbb{D}=\mathbb{R}\backslash \{-1,0,1\} $, and I also simplified it to a form: $f(x)=\frac{1}{x(x+1)}$ I tried to determine the limits for the undefined values next.
$$\lim\limits_{x \rightarrow 0}= \frac{1}{0(0+1)}=undefined$$
$$\lim\limits_{x \rightarrow 1}= \frac{1}{1(1+1)}=\frac{1}{2}$$
$$\lim\limits_{x \rightarrow -1}= \frac{1}{-1(-1+1)}=undefined$$
After removing the possible gaps my function looks like:
$$f(x)=\begin{cases}\frac{|x|-1}{x^3-x}&if x\neq0,x\neq-1\\ \frac{1}{2}&if x=1\\\end{cases} $$
Now, for the second function $g(x)$ I determined the domain which is: $\mathbb{D}=\mathbb{R}\backslash\{\frac{\pi n}{2}, n \in \mathbb{Z}\}$
But I can't really find a way to simplify this function, and also all of the limits seem to be undefined. Does it mean I can't remove the gaps here?
I just need to know if my approach to solve this kind of a problem is correct, or did I miss something?
Comment: $\sin(2x)$ or $\sin^2(x)$ ?
Answer: $f(x)$ does not simplify to a form $\frac{1}{x(x+1)}$. It simplifies into the form $$\frac{1}{x(x+1)} \cdot \frac{|x|-1}{x-1}$$
which is certainly not the same!
For the second, try to use the fact that $$\lim_{x\to 0}\frac{\sin x}{x} = 1$$
and multiply the whole function by $\frac{x}{x}$.
Comment: Can the downvoter explain why this answer is bad and deserving of a downvote?
Comment: But how can I remove the discontinuity if the $$f(x)=\frac{1}{x(x+1)}*\frac{|x|-1}{x-1}$$ I should be able to remove the discontinuity if the numerator and the denominator equals 0. Which in this case should be for 1 or -1, but if I try -1 or 1 as a value of x the equation becomes just undefined.
Comment: @MonsieurMolly You remove the discontinuity by calculating the limit. When calculating the limit of $x\to -1$, you can for example know that $|x|=-x$, which will greatly simplify the calculation. Similarly for $x\to 1$, when $|x|=x$. For $x\to 0$, look at the left and right limit separately.
Comment: I guess i don't get it like totally right. I just tried to calculate the limit for $x \rightarrow 1$ Which ist $\frac{1}{2}$ and also calculated the limit for $x\rightarrow -1$ which is undefined, but why? I get something like this when I substitute $\lim\limits_{x \to -1}{\frac{1}{x(x+1)}*\frac{-x-1}{x-1}}=\frac{1}{-1(-1+1)}*-1 $ which is again undefined. On the other hand wolfram alpha says $\lim\limits_{x\to -1}=-\frac{1}{2}$ Tell me... should I calculate the limits for 1 and -1 separately on the both sides for each one i.e $\lim\limits_{x\to -1^+}$ and $\lim\limits_{x\to -1^-}$?
Comment: What's the relevance of the second hint ?
Comment: @YvesDaoust $$\frac{\sin x}{\sin(2x)} = \frac{1}{2}\frac{2x}{\sin (2x)} \frac{\sin x}{x}$$ can help find the limit. Of course, addition formulas are another (I admit probably easier) way.
Answer: $$x^2-1=(|x|+1)(|x|-1),$$ hence you simplify as $$\hat f(x)=\frac1{x(|x|+1)},$$ which is only undefined at $x=0$.
Also, $$\sin(2x)=2\sin(x)\cos(x)$$ and
$$\hat g(x)=\frac1{2\cos(x)}.$$

Eliminate removable discontinuity


Will an incrementing integer PK produce uniform workload in DynamoDB

Question: I am looking to index some data in DynamoDB and would like to key on an incrementing integer ID. The higher IDs will get the most of the traffic, however this will be spread evenly across tens of thousands of the highest IDs. Will this create uniform data access which is important for DynamoDB?
AWS don't seem to publish details on the hashing algorithm they use to generate primary keys. I am assuming it is something akin to md5 where, for example, the hash for 3000 is completely different from 3001, 3002 and 3003 and therefore it will result it a uniformly distributed workload.
The reason I ask, is that I know this is not the case in S3 where they suggest reversing auto incrementing IDs in cases like this.
Answer: DynamoDB doesn't seem to expose the internal workings of the hashing in documentation. A lot of places seem to quote MD5, but I am not sure if they can be considered authoritative.
An interesting study of distribution of hashes for number sequences is available here. The interesting data sets are Dataset 4 and Dataset 5 which deal with sequence of numbers. Most hashing functions (and MD5 more so) seem to be distributed satisfactorily from the view point of partitioning.
Comment: Another place which says MD5 is the [Dynamo paper](http://www.allthingsdistributed.com/files/amazon-dynamo-sosp2007.pdf)
Answer: AWS have confirmed that using an incrementing integer ID will create an even workload:

If you are using incrementing numbers as the hash key, they will be distributed equally among the hash key space.

Source: https://forums.aws.amazon.com/thread.jspa?threadID=189362&tstart=0


DD broke my whole partition - boot failed: not a bootable disk . Any way to recover it?

Question: Im kind of freaking out here, if anyone can help me please help me...
This happened to a Windows 2012 KVM virtual machine. I had a very important database running in it, if I could only recover that DB it would be great.
The VM was struggling because it was running out of resources so I decided to transfer it to another node. I used this command to make a backup:
dd if=/var/lib/vz/images/402/vm-402-disk-1.raw | gzip | dd of=/var/lib/vz/images/402/vm-402-disk-1.gz bs=4096
I forgot to shutdown the VM before I executed the command above, so I I tried to stop the DD process, but it was refusing to stop so I killed the process (I know... :/ ). Then I decided to forget about DD and just use the Proxmox's backup tool. Since this backup tool can "stop" the VM before making the backup, I didn't shut the VM down, and asked the backup tool to do it for me.
The backup tool wasnt able to shutdown the VM by itself so the it did not proceeded with the backup.
Then I accessed that VM remotely using VNC and the VM was trying to boot but showing this message: boot failed: not a bootable disk after failed backup
I restarted the VM several times, but it still shows the same message.
I tried to mount the .qcow2 image but I failed. I converted the .qcow2 to .raw, downloaded ntfs-3g so debian could recognize the ntfs partitions and tried to mount the .raw image and it failed too. I tried running both Windows 2012 and Windows 7 isos and tried to repair the Windows installation but both failed too.
Is there any way I could at least access the files inside the image??? I had a firebird database running in it, I just need to recover a 3gb .FDB file so I can restore it in a new VM.
I loaded the Windows 7 ISO and it shows that my drive has 120gb of unallocated space.. does it mean that I lost everything ????????
Linux disk utility shows this:
Is there anything I can do to try to recover the files??
No backup was done since I stopped the DD process, and it seems like I was left with a broken image.. I tried to run a few data recovery programs but none of them worked.. They can find a few files but no more than 8gb, which is usuless to me since it's mostly Windows files..
Please help!
Thanks
Comment: That's a blank disk. Go back to your original raw VM image.
Comment: That is the original VM image. I stopped the DD process, no backup was done.
Comment: Did you mount it correctly? http://en.wikibooks.org/wiki/QEMU/Images#Mounting_an_image_on_the_host
Comment: @jgillich, this is what I did http://pastebin.com/09uNKQz9
Answer: I suspect you overwrote your VM image at some point while trying to "recover". Where isn't clear, but that's the most likely way you wound up with a "blank" disk image.
At this point I would run testdisk, followed by photorec. If you get as far as photorec, you will need a second disk to save recovered files onto.
And, in future, I would keep proper backups.
Comment: Thanks Michael, I will try it right now.

@Thread: Please if you have any other suggestion, do not hesitate to say it, I will do anything possible to recover this mess I made.
Comment: No guarantees. If you did overwrite the disk image, you may not get anything back at all.
Comment: Got nothing at all.. :(, testdisk and photorec couldn't even see the drive. fdisk was able to see it though, I'm not sure why.


Add an Excel file as a linked server in SQL 2012

Question: I'm trying to add a linked server to an Excel 2010 file from SQL Server 2012. Every reference I've found online for doing this is using older versions of SQL Server, and the driver that they tell you to use 'Microsoft.Jet.OLEDB.4.0', is not present in 2012 from what I can tell.
Can anyone tell me which provider I need to use and what the product name, data source, and provider string should be?
For reference, this is the screen I'm looking at:

Thanks.
Answer: It could be that you are running the 64-bit edition of SQL Server but only have the 32-bit Jet provider installed.  If this is the case you will need to remove the 32-bit provider and install the 64-bit provider.  The Access Database Engine will install the Jet provider which is the same provider used to connect to Excel.
Microsoft Access Database Engine 2010 Redistributable
Answer: You will want to use the driver Microsoft.ACE.OLEDB.12.0 according to this guide, http://www.excel-sql-server.com/excel-import-to-sql-server-using-linked-servers.htm
The driver is a part of the Microsoft Access Database Engine 2010 Redistributable that @squillman already linked.


What does the --filename option of mtr actually do?

Question: I was looking for a tool to display the continuous ping loss to multiple hosts, and I looked at mtr as it already has the display I was thinking about. I saw that it has this option which sounded promising:
  -F FILENAME, --filename FILENAME
          Reads the list of hostnames from the specified file.

Unfortunately, I cannot understand what mtr does with this list of hostnames. It seems to only pick up the first one from the list and report on it.
How is the "list of hostnames" used by mtr?
Answer: 4 years too late, but I figured it out.
https://github.com/traviscross/mtr/pull/169/commits/c419873aceb7c416cea91724f3e282befc56ecae
From the commit log:

[...] Also, multiple host names will now work in all non-interactive modes
(i.e. report, txt, json, xml, raw, csv) instead of just CSV mode.

In interactive mode it latches onto the 1st host. I was hoping I could just get a sidescrolling multi-host ping ... no dice


Tweedie distribution without zeroes

Question: Recently I've found the Tweedie distribution useful for modelling my plant shoot weight data in glmmTMB. I started using it because my shoot weight datasets have many zeroes, and it has yielded better fits than I was able to get with zero-inflated models.
One of my shoot weight datasets doesn't have zeroes, however (although it does have many <1 values). The Gaussian distribution fits this dataset well enough, but I don't think that the predictions it makes are correct. I tried this model with the Tweedie distribution, and I got a better fit and predictions that make more sense.
Despite the good fit, is it invalid to use the Tweedie distribution when your data doesn't have zeroes? This is the code I'm using:
<code>Model4 <- glmmTMB(Shoot.weight ~ Species + N.Level + Rhizobia + Species:N.Level +
                      Species:Rhizobia + N.Level:Rhizobia + N.Level:Rhizobia:Species +
                     (1 | Block), family = tweedie, data = SOY)
</code>
I believe that the specific Tweedie distribution that I'm using here is the compound Poisson-Gamma distribution, but correct me if I'm wrong about that.
Answer: Tweedie distributions don't always have zeros, but even when they do, often the proportion of zeros in fitted Tweedie models is often fairly small - at least in the cases I've seen it used to fit.  (Your post indicates you have $1<p<2$, so that would imply some zeroes in the model)
I think the Tweedie family is of relatively modest value for modelling data with zeroes: the proportion of zeroes you get in the model is not only affected by the proportion of zeroes in the data -- it's a function of $p$, $\mu$ and $\sigma^2$ and a GLM will work with a fixed $p$, while the estimates of $\mu$ and $\sigma^2$ will be affected by all the data.
However, the family can be quite handy if you want GLMs with variance functions that are a power of the mean.
You could attempt to identify the proportion of zeroes you're actually getting in your fitted model. I think that the proportion of zeroes is $\exp(-\frac{\mu^{2-p}}{(2-p)\sigma^2})$ (i.e. it varies with the fitted mean).
I wouldn't worry terribly much whether your data have zeros unless your fitted model suggests a fairly substantial proportion of them somewhere that you have a fair bit of data.

Tweedie distribution without zeroes


Re-creating Blocks Page for Content Authoring?

Question: I'm using Drupal 7.14, and the biggest complaint I get from people new to Drupal is visualizing where the content goes once its created.
It got me thinking of some clever/native ways to do this with the base installation. I looked into the Overlay module that the administrators have access to, then Blocks page, then Context page, and none seem to provide an easy to use interface for doing what I want. I remember the Themer module in Drupal 6 highlighted the regions in the Blocks page when you're moving components around, and my question begs whether or not this can easily be re-created somehow?
Now I'm familiar that Drupal 8 + Sparks helps with content authoring a bit, I've seen the demo's where users can edit content on the page/layout, but it still doesn't allow for adding new ccks, nodes to a specific region on a page.
I'm not sure this is an appropriate D.SE question, but has anyone heard of a module, or can think of a way to provide a GUI for users to attach their newly created content to the specific region in a theme, most preferably when they are creating the content?
Answer: The nodeblock and node-level-blocks modules may be a good starting point.
Comment: Thanks for sharing this - reading through some of the node-level-blocks led me to the Bean module. I have limited experience with JavaBeans, so I'll explore if its similar. I'm not sure I have my answer yet, but I'll explore what you sent!
Answer: If you want to do this on a node-by-node basis, the Panels In-Place Editor (IPE - part of the Panels project) will do exactly that.


Principle Components Analysis – using variance as a variable?

Question: I am following a collaborator's methods to analyze a set of audio recordings, and I have found that she is using principal components analysis in an unexpected way. I am confused by her approach, and would appreciate feedback on whether this is sound way to think about and use PCA.
I have several audio recordings each from different speakers and the ultimate goal is to use a canonical variates analysis to assign these recordings to the correct speaker based on a reduced set of variables. To obtain these variables, I divide each recording into 80 frames and take 20 different measurements for each frame. (Full disclosure, these 20 variables are mel-frequency cepstral coefficients, but you can think of them as typical acoustic parameters like pitch and amplitude to make this clearer.) This leaves me with 80×20 measurements for each recording, and I want to reduce these to a smaller set of variables that I will actually use to compare distinct recordings in my future canonical variates analysis. To me, using PCA seems like a reasonable approach here, and my collaborator agrees. However, what she does, under the title "PCA", is to calculate the eigenvalue of each variable across the 80 frames, and retain this variance value. Since there is only one variable, there is only one principle component, and only one variance value (which explains 100% of the variance). Therefore she is left with her same 20 variables, but with the variance across frames as the value for each variable. She then proceeds to reduce these 20 variables through canonical variates analysis (one could also imagine reducing them with another PCA, without classification).
I am 1) confused as to why this is termed PCA when all she is doing is taking the variance of her measurements and 2) unsure if this is a valid approach to reducing the number of variables in the dataset. This does not fit with how I typically use PCA, and I'm unsure if that's simply my inexperience or because this is an inappropriate use of PCA.
My collaborator is senior and extremely busy. I can ask her these questions directly, but wanted to exhaust all other options first, including appealing to the wider stats universe. What am I not getting here?
Edit:
There is a paper published with this method, but the details of why the authors reduced the multiple frames to one variance measurement are not provided and this step is not mentioned (although by looking at the data it is clear that this is what happened).
Performing a PCA on the time series data could be another useful approach. However, I am not sure it makes sense to use data for all of my speakers to reduce dimensions, since ultimately I am looking for consistent differences between speakers, whose variables may be substructured in different ways. My dataset consists of multiple recordings from multiple speakers – in the canonical variates analysis, I will be grouping according to speaker.
Comment: Is there a paper than can be cited or uses a similar approach? A standard approach would be to get $N$ ceptrums ($N$ being the number of users), perform dimensionality reduction to these ceptrums (eg. FPCA as to account for the time-varying ceptrum) and feed the PC scores into a classifier. One needs to use the recordings from the $N$ speakers together! This appears as a within-subject normalisation step first (from what I can tell, apologies if I misunderstood something) that probably is application specific. Can you please give more details about your goal (and define what CVA stands for)?
Comment: CVA stands for canonical variates analysis, or discriminant function analysis. I've addressed your other questions and suggestions in an edit in the original question.
Comment: Calculating statistical summarizations of MFCC coefficients (along the time axis) and then using this as features is quite common. This reduces from `n_mfccs*n_time_frames` to `n_mfccs`. mean+std is a common one, but also max+min, and sometimes skew/kurtosis.
Comment: I did however not understand your description of the "PCA" method in use. I got lost at the part about "since there is only one variable"
Answer: Summarizing MFCC frames (n_mfcc, n_timesteps) for an entire clip is done quite often (at least pre deep-learning). The most common summarization is to take the mean and standard deviation across time (for each MFCC coefficient). The result is a feature vector (2, n_mfcc) - often flattened to a 1D vector (2xn_mfcc,). Then any ML classifier can be used, such as LogisticRegression or RandomForest.
This however has nothing to do with PCA.


NumPy/OpenCV 2: how do I crop non-rectangular region?

Question: I have a set of points that make a shape (closed polyline). Now I want to copy/crop all pixels from some image inside this shape, leaving the rest black/transparent. How do I do this?
For example, I have this:

and I want to get this:
Comment: I believe you will want to work with an irregular ROI (region of interest). You might start here: http://stackoverflow.com/questions/10632195/define-image-roi-with-opencv-in-c
Comment: Just in case: this question is not duplicate, since referred one describes C API and not Python (that question is still helpful, though).
Answer: *edit - updated to work with images that have an alpha channel.
This worked for me:

Make a mask with all black (all masked)
Fill a polygon with white in the shape of your ROI
combine the mask and your image to get the ROI with black everywhere else

You probably just want to keep the image and mask separate for functions that accept masks. However, I believe this does what you specifically asked for:
import cv2
import numpy as np

# original image
# -1 loads as-is so if it will be 3 or 4 channel as the original
image = cv2.imread('image.png', -1)
# mask defaulting to black for 3-channel and transparent for 4-channel
# (of course replace corners with yours)
mask = np.zeros(image.shape, dtype=np.uint8)
roi_corners = np.array([[(10,10), (300,300), (10,300)]], dtype=np.int32)
# fill the ROI so it doesn't get wiped out when the mask is applied
channel_count = image.shape[2]  # i.e. 3 or 4 depending on your image
ignore_mask_color = (255,)*channel_count
cv2.fillPoly(mask, roi_corners, ignore_mask_color)
# from Masterfool: use cv2.fillConvexPoly if you know it's convex

# apply the mask
masked_image = cv2.bitwise_and(image, mask)

# save the result
cv2.imwrite('image_masked.png', masked_image)

Comment: @kju This seems limited enough that I just updated the answer instead of making a new question. I guess many people doing this probably also want a transparent mask.
Comment: You should use `cv2.fillConvexPoly` if your shape is a convex polygon. [The documentation](http://docs.opencv.org/3.0-beta/modules/imgproc/doc/drawing_functions.html#fillconvexpoly) states that this method is "much faster" than `cv2.fillPoly`.
Comment: For my fillPoly didn't work but fillConvexPoly did. Thanks @Masterfool
Comment: @kobejohn to create mask to make transparent background with this crop?
Comment: @kju do you mean you want transparent instead of black outside the ROI?
Comment: @KobeJohn yes, it is.
Comment: @Masterfool Good point! Since I am unaware of a built-in test for convexness, I will leave it with the general fill and add a comment for when to use `cv2.fillConvexPoly`. For anyone that is working with very large images, it would be worth the cost to implement a convex test. See [this SO question](http://stackoverflow.com/questions/471962/how-do-determine-if-a-polygon-is-complex-convex-nonconvex).
Comment: This way is very time consuming. I would search for another approach. Does it exists something similar to slicing but for irregular shapes?
Answer: The following code would be helpful for cropping the images and get them in a white background.
import cv2
import numpy as np

# load the image
image_path = 'input image path'
image = cv2.imread(image_path)

# create a mask with white pixels
mask = np.ones(image.shape, dtype=np.uint8)
mask.fill(255)

# points to be cropped
roi_corners = np.array([[(0, 300), (1880, 300), (1880, 400), (0, 400)]], dtype=np.int32)
# fill the ROI into the mask
cv2.fillPoly(mask, roi_corners, 0)

# The mask image
cv2.imwrite('image_masked.png', mask)

# applying th mask to original image
masked_image = cv2.bitwise_or(image, mask)

# The resultant image
cv2.imwrite('new_masked_image.png', masked_image)

Input Image:

Mask Image:

Resultant output image:
Comment: This is quite similar to the accepted answer.  Can you explain how this adds value to this question?
Comment: The following code would helpful for getting a white background mask image rather a black one.
Comment: This doesn't add anything new.  Simply invert the mask.
Comment: From the first answer if you can just create a mask inverted and be able to provide the same result would be helpful.
Comment: I appreciate this comment because it has representative pictures.


cflow can't recognize function call in loop

Question: int main() {

    for (int i = 1; i < 10 ; i++) {
      test1();
    }
    for (int i = 1; i < 10 ; i++)
      test2();

    return 0;
}

So for the code above, cflow can see test2() but not test1(). See output below:
$cflow tmp.c
main() <int main () at tmp.c:1>:
    test2()
$ cflow --version
cflow (GNU cflow) 1.7
Copyright (C) 2005-2021 Sergey Poznyakoff

Is this a bug or something very stupid I have done?
Thanks for you input!
Answer: If you remove int i from the loops and define i = 0 outside the for loop, it shows both calls.
Answer: Answering this a little bit late. I also ran into the same issue and got a work around.
I have a huge code base and can't change all for loops to C89 standard, plus I have thirdparty code I don't want to edit.
So just call cflow with the define -D"for(x,...)=for(;;)".