Redirect only Mobile devices with 51 Degrees

Question: I'm using 51 Degrees in .NET on MVC and it's only just come to my attention that 51 degrees redirects Tablets as default with what it classes as IsMobile.
I only want to redirect mobile traffic, ie phones etc and not tablets. Tablets should be using my default "Desktop" layout.
Is there anyway I can use the (Lite) 51 Degrees to only redirect mobile traffic and not tablet traffic?
Answer: I don't know anything about their normal redirect configuration, but you can handle this easily on the server side. 51Degrees adds the "IsTablet" and "IsSmartPhone" properties to request.Browser. You could do this where appropriate:
var request = HttpContext.Current.Request; //or wherever you're getting it from
bool smartPhoneFlag, tabletFlag;
bool.TryParse(request.Browser["IsTablet"])
bool.TryParse(request.Browser["IsSmartPhone"])

if(smartPhoneFlag && !tabletFlag)
{
    //redirect
}
//else continue on

Comment: Those are indeed properties that are available, however not in the LITE subscription as Chris originally indicated.

@Chris: did you find a solution for this problem yet? I could use it as well... ;-)
Answer: A bit late to this but i'm one of the engineers over at 51Degrees. We now offer a free basic Cloud service that gives access to the "IsTablet" property. This can then be used to tailor your re-direct options.
A basic example of calling against this option would look like:
https://cloud.51degrees.com/api/v1/*LICENCE_KEY*/match?user-agent=iphone&Values=IsTablet


mySQL locking for simple multiple selects

Question: I have the following simple two-selects sequence within a stored procedure:
SELECT * FROM mytable WHERE <conditions>;
SELECT id FROM mytable ORDER BY id DESC LIMIT 1;

where id is the primary key of mytable.
The overall purpose is to select some rows from mytable (including the newest ones - ie the ones with the heighest id values) and then, with the second select, get the id of the last/newest row in the same table.
Question: how do I ensure that no new records gets inserted between the first and the second select?
I was going to use:
TRANSACTION
select <1..> FOR UPDATE;
select <2..>;
COMMIT

but will that always work and is there a better way?
Or can do something different to achieve the goal of getting the heighest id value from the first select without having the second select?
Comment: I believe you want a table lock: https://dev.mysql.com/doc/refman/5.5/en/lock-tables.html *I may be wrong though
Answer: When you haven't changed your isolation level, you are using the default of REPEATABLE READ which already solves this problem.
To check which isolation level you're using you can execute the following query:
SELECT @@global.tx_isolation, @@session.tx_isolation;

The global value is the default value for newly created sessions. The sessions value is of course the value you are currently using.
You can set it explicitly for your session with
SET SESSION tx_isolation='REPEATABLE-READ';

With REPEATABLE-READ you can simply do this:
START TRANSACTION;
SELECT * FROM mytable WHERE <conditions>;
SELECT id FROM mytable ORDER BY id DESC LIMIT 1;
COMMIT;

When another session inserts rows into the table during your 2 selects, this row won't show up inside your transaction.
I posted more details about isolation levels in my answer here.
If you want to combine the two queries into one, you could do this:
SELECT m.*, s.maxid
FROM mytable m
CROSS JOIN (SELECT MAX(id) AS maxid FROM mytable) s
WHERE <conditions>;

Comment: Just to be clear, during **your** repeatable-read transaction other rows may be inserted, updated, or deleted by other processes. However, your transaction won't see them. If you really want to prevent other processes to make changes, then lock the table.
Comment: @TheImpaler Correct, yes. But **my** transaction is the standard behaviour :)


Expected value of X and Y for a given problem

Question: A couple decides to have children until they get a girl, but they agree to stop with a maximum of 5 children even if they haven't gotten a girl. If X and Y denote the number of children and number of girls, respectively, then what are E(X) and E(Y)?
What I have tried, though it is incorrect:
If X denotes the number of children. Then
f(1) = P(X = 1) = P(girl at first try) = $\frac{1}{2}$,
f(2) = P(X = 2) = P(1 boy and 1 girl) = $\frac{1}{2}\frac{1}{2}$ = $\frac{1}{4}$,
f(3) = P(X = 3) = P(2 boys and 1 girl) = $\frac{1}{4}\frac{1}{2}$ = $\frac{1}{8}$,
f(4) = P(X = 4) = P(3 boys and 1 girl) = $\frac{1}{8}\frac{1}{2}$ = $\frac{1}{16}$,
f(5) = P(X = 5) = P(4 boys and 1 girl) + P(no girl in 5 tries) = $\frac{1}{32}\frac{1}{32}$ = $\frac{1}{16}$
Then
\begin{align}
\begin{split}
E(X) = \sum_{x= 1}^{5} x\;f(x)=f(1) + 2 f(2) + 3 f(3) + 4f(4) + 5f(5)\\
&= \frac{1}{2} + \frac{2}{4} + \frac{3}{8} + \frac{4}{16} + \frac{5}{16}\\
\approx 1.9375
\end{split}
\end{align}
Comment: I don't agree with the book, I think your answer is correct.  Perhaps you should check with the book to make absolutely sure you read the question correctly.
Comment: Why do you say that is incorrect?  It looks fine as far as I can see.  Have voted to reopen.
Comment: @David Because I got the question from a book that says $E(X) = \frac{7}{4}$ and $E(Y) = \frac{7}{8}$ though the author did not explain why is that the answer.
Answer: They will have either 1 or 0 girls. Let $y$ be the probability that a child is a girl, then $E(Y) = 1-(1-y)^5$.
$E(X) = 5 (1-y)^4 + 4 (1-y)^3y + 3 (1-y)^2y + 2 (1-y)y + y$
Comment: y=1/2 is the usual approximation, yes, giving E(Y)=31/32=0.96875 exactly, though biology tells us it is not so simple, and on top of that a child need not be a boy or a girl.
Comment: Do you mean y = 1/2 and $E(Y) \approx 0.9688$?


Return Lastname when not definded

Question: I'm studying JavaScript combining functions. Supposed I have firstname
and lastName as two arguments of my function. I want the console to display Doe when lastname is undefinded . Here is my code but it printed out undefined. Any idea? Thank you!
let name = 'John'

function greetByDefault(firstname,lastname){
     return 'Hi ' + firstname +' '+ lastname + '!';
 }
  if (lastname === undefined){
        return 'Doe';
 }

console.log(greetByDefault('Jane', 'Doe'));
console.log(greetByDefault(name));

I want the console output to be:
Hi Jane Doe!
Hi John Doe!
Answer: you can do something like this using a default value

let name = 'John'

function greetByDefault(firstname,lastname = 'Doe'){
     return 'Hi ' + firstname +' '+ lastname + '!';
 }

console.log(greetByDefault('Jane', 'Doe'));
console.log(greetByDefault(name));
console.log(greetByDefault(name, 'Smith'))
Answer: You have to put everything in function
let name = 'John'
function greetByDefault(firstname,lastname){
  if (lastname === undefined){
      lastname = 'Doe';
  }
     return 'Hi ' + firstname +' '+ lastname + '!';
 }

console.log(greetByDefault('Jane', 'Doe'));
console.log(greetByDefault(name));

Answer: let name = 'John'
function greetByDefault(firstname,lastname=''){
 if (lastname== ''){
    lastname =  'Doe';
  }
return 'Hi ' + firstname +' '+ lastname + '!';

}
console.log(greetByDefault('Jane', 'Doe'));
console.log(greetByDefault(name));

Return Lastname when not definded


Integer predictors in Poisson regression

Question: I am trying to fit a model of total rental bike with ten predictors using Poisson Regression. Four of them are integer :

Season : 1-4
Month : 1-12
Day : 0-6
Hour : 0-23

I usually treat integer variable as factor in R. But in this case, if I treat 'Month' and 'Hour' as factors, they will have many levels. But if I divide them into several groups (say, for variable 'Hour' : peak hour and non-peak hour), I'm afraid that the data will lose information.
There might be some alternative ways to analyse this kind of data, such as periodic formula. But unfortunately, I'm only allowed to use Poisson regression here.
So, is there any suggestions to properly treat these integer predictors in my analysis?
Comment: There's no such thing as a "periodic formula" in terms of a set of regressors, but you can use methods for periodic modeling as have been discussed in other SE posts, one from me is [here](https://stats.stackexchange.com/questions/225653/periodic-splines-to-fit-periodic-data/319760#319760). These can be applied to Poisson GLMs.
Answer: I would use periodic splines to represent periodic function. Then I would use three of your variables, Month, Day, Hour leaving out Season (Season should be well enough represented by Month).  These three periodicities will then be added. Some pseudo-code in R (since we do not have data):
<code>library(pbs) # periodic splines basis functions
mod.bike <- glm(total_rental ~ pbs::pbs(Hour, df=5, Boundary.knots=c(0,24)) +
                pbs::pbs(Day, df=3, Boundary.knots=c(0,7)) +
                pbs::pbs(Month, df=5, Boundary.knots=c(0,12)),
                family=poisson, data= ...)
</code>
If you could post some data we could use that for an example. A worked example can be found here: circular periodic time series  or fit with periodic splines


Create drupal content programmatically with custom entity ( assets )

Question: I am using asset module : https://www.drupal.org/project/asset
I creates a new entity type = asset. I get a form where I can add ( document, image, video..).
How can I, from a custom module add a content of asset ? I think that I cannot do it the way we creat nodes ... like :
<code>$node = new stdClass();
$node->type = "asset";
node_object_prepare($node);
....
</code>
Please help
thank you
Answer: I think you can try to use core and EntityAPI methods for this task like this:
<code>$asset = entity_get_controller('asset');
$asset->type = 'MY_TYPE';
$asset->... = '...';
....

$asset->save();
</code>
Comment: I'am trying this. Get back  very soon.
Answer: this is the right code:
<code>function create_assets(){

$asset = entity_create('asset' , array('type' =>'image'));
$asset->title = 'image publication';
//$asset->field_asset_image = array(LANGUAGE_NONE => array(0 => array('value' => get_external_image("http://cdn.sstatic.net/drupal/img/logo.png"))));
$asset->field_alt["und"][0]["value"] = "alt image publication";
//$asset->save();
entity_save('asset', $asset);
}
</code>


How can I push a new value to a sub array in php?

Question: I have multiple posts with the same title but each one has a unique id. I am trying to make a new array with a title key and id key where id holds an array of the ids. My plan is to then loop over that new array to display my post data. I keep running into 2 problems:

Warning: array_push() expects parameter 1 to be array, null given in ..
Warning: Attempt to modify property 'ID' of non-object in ..

<code>//args
    $args = array(
        'post_type' => 'event',
        'post_status' => 'publish',
        'posts_per_page' => -1,
    );

    // The Query
    $the_query = new WP_Query( $args );

    // The Loop
    if ( $the_query->have_posts() ) {

        $stack = [];

        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            $title= get_the_title();
            $id= get_the_ID();

            //logic not working
            if(!in_array($title, $stack)) {
                array_push ($stack, array(
                    'title' => $title,
                    'ID' => array($id)
              ));
            }

            if(in_array($title, $stack)) {
                array_push ($stack->ID, $id); //error here
            }
        }
        print_r($stack);
    }
    wp_reset_postdata()
</code>
Comment: What is `in_array_r()` I dont think its vanilla PHP or vanilla WordPress
Comment: @RiggsFolly sorry typo there, code updated.
Comment: `$stack` is an array, so `$stack->ID` doesn't make sense.
Answer: <code>// The Query
        $the_query = new WP_Query( $args );

        // The Loop
        if ( $the_query->have_posts() ) {

            $titles = [];
            $ids = [];
            $day_starts = [];
            $day_ends = [];
            $time_ends = [];
            $time_starts = [];
            $ods = [];
            $vids =[];
            $imgs = [];
            $links = [];
            $lss = [];
            $cats = [];

            while ( $the_query->have_posts() ) {
                $the_query->the_post();
                $title= get_the_title();
                $id= get_the_ID();
                $vid = 0;
                $od = 0;
                $ls = 0;
                $img = get_the_post_thumbnail_url();
                $link = get_the_permalink();
                $cat = get_the_terms($id, 'event-categories');

                $post_options = get_post_meta( get_the_ID(), 'post_options')[0];
                print_r($post_options);

                if(isset($post_options['on_demand'])){ $od = 1;}
                if(!isset($post_options['on_demand']) && $post_options['featured_video'] !== ''){ $ls = 1;}
                if($post_options['featured_video'] !== ''){ $vid = 1;}

                $startDate = /* str_replace('-', '',  */get_post_meta( get_the_ID(), '_event_start_date')[0];
                $startTime = /* str_replace(':', '',  */get_post_meta( get_the_ID(), '_event_start_time')[0];
                $endDate = /* str_replace('-', '',  */get_post_meta( get_the_ID(), '_event_end_date')[0];
                $endTime = /* str_replace(':', '',  */get_post_meta( get_the_ID(), '_event_end_time')[0];

                array_push ($titles,$title);
                array_push ($ids, $id);
                array_push ($day_starts, $startDate);
                array_push ($day_ends, $endDate);
                array_push ($time_starts, $startTime);
                array_push ($time_ends, $endTime);
                array_push ($ods, $od);
                array_push ($vids, $vid);
                array_push ($lss, $ls);
                array_push ($imgs, $img);
                array_push ($links, $link);
                array_push ($cats, $cat[0]->name);

            }
        }
        wp_reset_postdata();

        $unique = array_unique($titles);
if($unique){
        foreach($unique as $name){
            $data[] = array_merge(['title' => $name ], array(
                'ID' => array_merge(array_intersect_key($ids, array_intersect($titles, [$name]))),
                'vid' => array_merge(array_intersect_key($vids, array_intersect($titles, [$name]))),
                'od' => array_merge(array_intersect_key($ods, array_intersect($titles, [$name]))),
                'start_day' => array_merge(array_intersect_key($day_starts, array_intersect($titles, [$name]))),
                'end_day' => array_merge(array_intersect_key($day_starts, array_intersect($titles, [$name]))),
                'start_time' => array_merge(array_intersect_key($time_starts, array_intersect($titles, [$name]))),
                'end_time' => array_merge(array_intersect_key($time_ends, array_intersect($titles, [$name]))),
                'link' => array_merge(array_intersect_key($links, array_intersect($titles, [$name]))),
                'media' => array_merge(array_intersect_key($imgs, array_intersect($titles, [$name]))),
                'ls' => array_merge(array_intersect_key($lss, array_intersect($titles, [$name]))),
                'cat' => array_merge(array_intersect_key($cats, array_intersect($titles, [$name])))
            ));
        }
    }
?>
</code>


L5.6 orderBy() in combination with paginate() returns the same row multiple times

Question: Controller:
public function index($devicetype)
{
    $devices = Device::where('device_type', $devicetype)
    ->orderBy('created_at', 'desc')
    ->paginate(config('myapp.pagination.items_per_page'));
    return view('devices.general.index', compact('devices'));
}

I am getting the same device multiple times on different pages in my blade.php view.
But dd(Device::where('device_type', $devicetype)->orderBy('created_at', 'desc')->get()); gives me a correct collection without multiple entries.
Any ideas/suggestions?
Answer: This is because there are many records with the same created_at value. To fix this, add a second order by id to remove the duplicated show in pagination:
$devices = Device::where('device_type', $devicetype)
->orderBy('created_at', 'desc')
->orderBy('id', 'asc')
->paginate(config('myapp.pagination.items_per_page'));
return view('devices.general.index', compact('devices'));

Comment: shame on me. How could I have overseen that?? THANK you very very much!!
Comment: @titonior, that's okay :) Happens to the best of us. Happy coding!


Prevent calling event for added class with jquery

Question: Here is my jquery code:
$(function () {
    $('.gridster li.gs-closed').on('click', function () {
        var ulCurrentHgt = $('.gridster ul').height();
        var ulNewHgt = ulCurrentHgt + 409;
        $('.gridster > ul').height(ulNewHgt);
        $(this).find('form').slideDown();
        $(this).removeClass('gs-closed').addClass('gs-openedx');
    });

    $(document).on('click', "li.gs-opened", function () {
        var ulCurrentHgt = $('.gridster ul').height();
        var ulNewHgt = ulCurrentHgt - 409;
        $('.gridster > ul').height(ulNewHgt);

        $(this).find('form').slideUp();
        $(this).removeClass('gs-opened').addClass('gs-closed');
    });
})

Here is the html:

As you see when I click the li.gs-closed, I am adding the class gs-opened. Later I have some other click handler for the gs-opened class. But, when I am clicking the li.gs-closed, it's adding the class gs-opened and also calling the $(document).on('click', "li.gs-opened", function() event, which is not supposed to be called yet. How can I prevent this?
Comment: your are adding class ...X -->  $(this).removeClass('gs-closed').addClass('gs-openedx');
Answer: Changing the class does not remove the event handler that is already bound to the element.
What you really need to do is attach one single event handler, and create some sort of toggling functionality within that handler:
$(function () {
    $('.gridster li').on('click', function () {
        var ulCurrentHgt = $('.gridster ul').height(),
            open         = $(this).data('open'),
            added        = open ? -409 : 409,
            ulNewHgt     = ulCurrentHgt + (added);

        $('.gridster > ul').height(ulNewHgt);
        $(this).find('form')[open ? 'slideUp':'slideDown']();

        $(this).data('open', !open);
    });
});

You could also delegate the first event handler :
$(document).on('click', "li.gs-closed", function (event) { ...

to make it work with dynamically added and removed classes.
Answer: I will suggest to use a separate class for attaching event. Because removing class will not remove already attached event on that element. You can use a flag to decide whch class to add and remove.


How to rewrite using preventDefault instead of return false?

Question: Just so I get a better understanding of how to write preventDefault as opposed to return false.  Here is an example of return false.  I would like to rewrite this code using preventDefault
My HTML:
<form name="myForm" action="formPracticePHP.php" method="post" onsubmit="return validateForm()">

Enter your Name: <input type="text" name="name" value="" placeholder="[your-name]" required="required" />

Enter your Age:  <input type="number" name="age" size="6" value="" />

Please Select Your Favorite Fruit

    <select name="fruit" id="fruit">
       <option value="nothing" selected="selected">Select A Fruit</option>
       <option value="Bannana">Bannana</option>
       <option value="Kiwi">Kiwi</option>
       <option value="Mango">Mango</option>
       <option value="Apple">Apple</option>
       <option value="Cherry">Cherry</option>
    </select>

    <input type="submit" name="submit" value="submit" id="submitBtn" />
</form>

My JavaScript
function validateForm() {
   var x = document.forms["myForm"]["age"].value;
   var x2 = document.forms["myForm"]["fruit"].value;
      if ((x==null || x=="") || (x2 == null || x2=="nothing")) {
        alert("Age and fruit selection must be filled out");
        return false;

      }
}

Comment: Where is validateForm being called from?
Answer: You have to pass the event argument into your handler
<form onsubmit="validateForm(event)" >

And change your function
function validateForm(e) {
   var x = document.forms["myForm"]["age"].value;
   var x2 = document.forms["myForm"]["fruit"].value;
    if ((x==null || x=="") || (x2 == null || x2=="nothing")) {
         e.preventDefault();
         alert("Age and fruit selection must be filled out");
      }
}

If you're setting the handler from JavaScript, the same function above will also work.
Comment: @godisgood I don't understand your edit. There is no guarantee that the OP is setting it from the HTML attribute
Comment: In his above code, he is.  I see `onsubmit="return validateForm()"` in his above code.
Comment: Oh, no problem.  It doesn't really matter to me anyway :)
Comment: Thanks, didn't expect quick response.  So now I know how to do this from now on.  I don't have a mentor, I'm learning all of this on my own. (:
Answer: Assuming that validateForm is registered as an onsubmit handler for your form, you should be able to do this:
function validateForm(e) {
   var x = document.forms["myForm"]["age"].value;
   var x2 = document.forms["myForm"]["fruit"].value;
   if ((x==null || x=="") || (x2 == null || x2=="nothing")) {
       alert("Age and fruit selection must be filled out");
       e.preventDefault(); // here
   }
}

If you are using an onsubmit attribute in your HTML to do this, you can remove the return portion and you will need to pass the event to it:
onsubmit="validateForm(event)"

However, I would strongly recommend not using your HTML attributes to specify event handlers and instead register the handler using your JavaScript code:
window.onload = function () {
    document.forms["myForm"].addEventListener("onsubmit", validateForm);
};


Create random variable Expo from Unif(0,1)

Question:
Working through some problems from Introduction to Probability (Blitzstein)
Let U~Unif(0,1). Using U, construct X~Expo($\lambda$).

My work:
(edited with updates on CDF and inverse function)

PDF of X is $\lambda e^{-\lambda x}$ by definition of exponential
distribution

CDF is therefore $1-e^{-\lambda x}$

Use Universality of the Uniform: find inverse function for F

$F^{-1}(x) = \frac{ln(1-x)}{-\lambda}$

( $y=1-e^{-\lambda x} -> 1-y = e^{-\lambda x}) -> x = \frac{\ln(1-y)}{-\lambda} $)

$F^{-1}(U) = \frac{ln(1-U)}{-\lambda}$

I am pretty confused by the process of getting a random variable from a Uniform distribution. Any help?
Comment: Your CDF and your $F^{-1}$ are incorrect. Please revise your work with **much** more care.
Comment: A very big red flag should be the fact that you're getting negative values for the CDF!
Answer: So there's a mistake in your CDF as has been pointed out (hint: you need to add something) and I'll leave it to you to correct subsequent errors. If you want to know why this method works, then consider the fact that the CDF is a mapping of the support on the interval $[0,1]$. Therefore, if you have a random variable $U\sim\text{Unif}[0,1]$, then the random variable $Z=F^{-1}_X(U)$ has the distribution $F_X$. So what you're doing is essentially this: you have the graph of the CDF of your distribution of interest. You pick a number $x\in[0,1]$ and you see where the CDF attains this value. This is your simulated random variable, and your $x$ is generated by the uniform distribution.


Is there a way to search Drupal's and contrib modules configuration settings?

Question: With so many different modules in use with configuring Drupal it is hard to keep track of which settings are configured where, such as whether some CSS is set by the Code per Node or CSS Injector.
It would be nice to have search pinpoint what configuration settings contain some keyword. Does search have such a facility? I understand that the search module is mainly used by content such as nodes and entities.
But is there some way something like this can be accomplished, even by some module, or do module developers need to configure their modules settings to be indexable by search?
Comment: Most would say this is trackable with Features, but only browseable via code. Someone may have built a UI?
Comment: You could search the variables table.
Answer: Useful fact: drush vget abc lists all variables with 'abc' in their name. So if you are looking for settings related to css, drush vget css might provide you with a clue. Likewise you can use the name of a module in your search to see all the settings from that module.
Some modules have complex settings that are stored in separate database tables. In that case I recommend using a tool such as SQLyog that has a search facility which will scan an entire database, or just specific tables, for a given input string.


How to bind data in dynamic multiple controls

Question: I start use reactive form in my angular project to make a simple form that help me to add employee time of work in his/here day and add time of breaks form: and to: maybe add one break or two or more than 2 breaks per work day. I face problem that I can't bind data from break controls.
in .ts file
export class AddAppointmentFormComponent implements OnInit{
  addAppointmentForm!: FormGroup
  constructor(private _fb:FormBuilder, private _wfmService:WFMService) {}
 ngOnInit(): void {
    this.addAppointmentForm = this._fb.group({
      typeOfDayId :['',Validators.required],
      appointMentDate: ['', Validators.required],
      from: ['', Validators.required],
      to: ['', Validators.required],
      breaks: this._fb.array([
      ]),

    })
  }

  get breaks(){
    return this.addAppointmentForm.get('breaks') as FormArray;
  }

  addBreak(){
    this.breaks.push(this._fb.group({
      from: ['', Validators.required],
      to: ['', Validators.required],
    }))
  }

  removeBreak(i:any){
    this.breaks.removeAt(i);
  }
}

in .html file

Add New Appointment

  {{ addAppointmentForm.value | json }}
  <form [formGroup]="addAppointmentForm">

      Date
      <input class="form-control" name="name" type="date" required formControlName="appointMentDate">

      Type Of Day
      <select class="form-select" name="dep" class="form-control" formControlName="typeOfDayId">
        <option value="">Select Type...</option>
        <option *ngFor="let type of typesOfDay" [value]="type.id">{{type.typeName}}</option>
      </select>

        <input class="form-check-input" type="checkbox" [value]="" (change)="onCheckChange($event)">

          All Day

          From
          <input type="time" class="form-control" formControlName="from" [readOnly]="addBreakBtn">

          To
          <input type="time" class="form-control" formControlName="to" [readOnly]="addBreakBtn">

    <button class="btn btn-success btn-sm" (click)="addBreak()" [disabled]="addBreakBtn">add break</button>

          Break({{i+1}}) From
          <input type="time" class="form-control" [formControlName]="i">

          Break({{i+1}}) To
          <input type="time" class="form-control" [formControlName]="i">

          <button type="submit" (click)="removeBreak(i)" class="btn btn-danger mt-4">Remove</button>

  </form>

    <button class="btn btn-danger" mat-dialog-close>Close</button>
    <button style="margin-left:10px ;" class="btn btn-primary">Create</button>

I need output from {{ addAppointmentForm.value | json }}
"breaks": [ { "from": "10:00", "to": "10:30" }, { "from": "14:00", "to": "14:30" } ] }
Answer: You are biding from and to to the same formControlName : [formControlName]="i".
You should have a div/ng-container with [formControlName]="n" and two other child div with [formControlName]="'from'" and [formControlName]="'to'"


Can we gain by merging validation and test set?

Question: Reading this,
Cross-validation including training, validation, and testing. Why do we need three subsets?
I realized that if we can reduce the variance of the model performance,
I wouldn't need the test set.
And we can get reduced variance of the model performance by
merging validation and test set to get the model performance.
So I wonder if it's true that
if model selection is not so competing enough to allow
the probability of picking one best model by chance,
would it be better to just merge the validation and test set,
use something like bootstrapping or CV to get estimates of variance of model performance?
But then again,
when the models are competing each other very hard,
if we merge the validation and test set together,
we would be better at picking the best model.
So I think if we report the variance of model performance,
It would be better to just merge the test and validation data and
pick the best model and report the variance of the model performance.
Is this conclusion right? or are there some holes?
Answer: Your conclusion's right if you do not want to know what will be the resulting accuracy of your model.
You will always get a better model by increasing the size of the validation set. Then, merging the test and validation test to select the better model by CV can be tempting.
But when your boss will ask you "So, what accuracy can I expect with that model of yours, given new data ?", you shouln't give him the score you got with the merged test-validation set, because when selecting the best model, you kind of overfitted your merged set
So you will need to finally test your model on brand new data that you never learnt from before, and that is the role of the test set.
Comment: Good point! But actually that part is what I don't understand. Let's say I have very small test set. Then I can't say the predicted accuracy is accurate bcoz of randomness it has. Again, let's assume we have infinite validation set. Then we can't overestimate the accuracy of best model. So as we get larger validation set, the test set is meaningless. But as we have small validation set, we will need enough test set to get enough accuracy. So there's some trade off going on. I think the biasedness comes from selection by chance.
Comment: If the candidate models are of almost same performance, then there's chance that one of the model is selected by chance and the performance is biased upward. But if there's almost zero chance that other models are selected, then there's no bias in estimated model performance from validation set. So we don't need test set. Do I make sense here?
Comment: So, are there any research about how much we should put data in validation set and how much in test set? It should be based on data but it looks not trivial...
Comment: There is no chance at play here. If you choose a model because it's better in the CV set, you chose it because it is better on the CV set, period. But the simple fact that you chose the model from accuracy on the CV set, makes you overfitting the CV set. You will never be able to say that _there's almost zero chance that other models are selected_, because you don't have the extra data to prove it.
Comment: So you know you're overfitting the CV set, no matter what, when selecting the best model. And you need new data to know what could be the actual accuracy of your model on data you didn't overfit
Comment: I don't think you understood me. Biasedness comes from randomness. Let's say we have N(0, 1^2) and N(0, 1^2). and the larger sample is biased upward because it's chosen from almost same distribution. But Let's say we have N(10,1^2) and N(-10, 1^2). Then the first one will be always picked and unless the second one is picked, it's never biased. And we can estimate the population variance, Of course it's just estimation.
Comment: Anyhow I've been looking around and found this http://www.win-vector.com/blog/2015/10/a-simpler-explanation-of-differential-privacy/
Comment: from this post http://stats.stackexchange.com/questions/19048/what-is-the-difference-between-test-set-and-validation-set?rq=1
Comment: But performance from test set is also an estimation, but unbiased. and ubiased but having large variance estimator can be useless :)
Comment: That makes me reason why they recommend proportion of the validation and test set to be 1:1. Say you picked the better model better by allocating more data on validation set, but the estimated performance from test set will be poor(large variance). Say you want to be more precise about the performance by allocating more data to test set, in this case your chosen model would be not the best even if you have precise estimation of the model performance...
Comment: That's it.
As for many problematics in science, it's a trade-off, and you have to chose the best proportion depending of what your goals are.


Undefined index notice for Smarty section loop

Question: I am getting undefined index error for my section loop when the loop results no data or empty from MySQL database.
Code as follow:
{section name=foo loop=$data}
//data goes here
{/section}

How can I use isset() in section loop?
Am using smarty 3.1.21 version
Thanks
Answer: You should really try with default variable handling as mentioned here
{section name=foo loop=$data|defalut:""}
//data goes here
{/section}

or
If you are not using {sectionelse} then use this one.
{section name=foo loop=$data|defalut:"No data found"}
 //data goes here
{/section}

Hope this helps :)


Select statment with SQL_CALC_FOUND_ROWS and UNION ALL

Question: So I'm  look for data bounded to email and account_id, if it has no result then look for just account_id. The code below doing this correctly.
 SELECT SQL_CALC_FOUND_ROWS account_id, email, latitude, longitude
 FROM call_module_location
 WHERE email = $email AND `account_id` = $account_id
 UNION ALL
 SELECT account_id, email, latitude, longitude
 FROM call_module_location
 WHERE  FOUND_ROWS() = 0 AND `account_id` = $account_id

But I need to process 3 case, if data by id not found as well, in this case I should fetch data by email:
  SELECT SQL_CALC_FOUND_ROWS account_id, email, latitude, longitude
  FROM call_module_location
  WHERE email = $email AND `account_id` = $account_id
  UNION ALL
  SELECT account_id, email, latitude, longitude
  FROM call_module_location
  WHERE  FOUND_ROWS() = 0 AND `account_id` = $account_id
  UNION ALL
  SELECT account_id, email, latitude, longitude
  FROM call_module_location
  WHERE FOUND_ROWS() = 0 AND email = $email";

But it's not working. Any solutions for this?
Answer: SELECT account_id, email, latitude, longitude
FROM (SELECT 1 priority, account_id, email, latitude, longitude
      FROM call_module_location
      WHERE email = $email AND `account_id` = $account_id
      UNION
      SELECT 2 priority, account_id, email, latitude, longitude
      FROM call_module_location
      WHERE `account_id` = $account_id
      UNION
      SELECT 3 priority, account_id, email, latitude, longitude
      FROM call_module_location
      WHERE email = $email) u
ORDER BY priority
LIMIT 1

It's also possible that your original query will work if you add SQL_CALC_FOUND_ROWS to the second query in the UNION.


Is there any reason why adding a footer to my emails is triggering some spam software to filter it?

Question: This seems an odd one but my emails are some how triggering various recipients spam software. This only happens if my email has a footer one it, if i send it without the footer the emails get delivered fine.
Any idea why this is happening? It seems to be the bigger email providers who do this, like Yahoo! and BT.
Answer: You will be triggering "spammy" characteristics - maybe with HTML code contained in your footer, maybe with images included there, maybe just with wording (just add some references to "Viagra" and "Rolex watches cheap" and see what happens).
In fact, it will be not that easy to tell without knowledge of the current filtering ruleset and having the complete message including the headers from the receiver side. But you might just post an example message source including headers that you've sent and that didn't get through. If you got an NDR, it would be of interest as well.


Boundedness of the norm of the Riemann curvature tensor

Question: Let $(M,g)$ be a Riemannian manifold and let $R(X,Y)Z$ be its $(3,1)$ Riemann curvature tensor given by
$$R(X,Y)Z=\nabla_X\nabla_YZ-\nabla_Y\nabla_XZ-\nabla_{[X,Y]}Z$$
Let the input vectors $X,Y,Z$ come from a compact subset of the tangent bundle. Then is the metric norm of the vector $R(X,Y)Z$ bounded?
If not, what extra conditions should we impose on $X,Y,Z$ to make $R$ bounded?
EDIT: The input vector fields $X,Y,Z$ won't have to be smooth or continuous, assume that the vector fields just come from a compact subset of the tangent bundle.
EDIT II: Since the Riemann curvature tensor does NOT depend on the values of vector fields $X,Y,Z$,but just depends on the pointwise values, I can re-ask my question by saying will $R(X,Y)Z$ be bounded if I just work with uniformly bounded values of $X,Y,Z$?
Thanks!
Comment: Hmmmm . . .  your added condition that $X, Y,  Z$ etc. needn't be confinuous may force we to edit my answer, which assumes all quantities *are* continuous.  Cheers!
Comment: Thanks for your answer, Robert! I think your proof goes through with minor modification, where you bound $X^\mu, Y^\nu, Z^\rho$ first, and then use the continuity to bound the coefficients of $R$.
Comment: Since the Riemann curvature tensor depends only on the pointwise values of its arguments, in edit II, I assumed that we only have pointwise values of $X,Y,Z$ and all these pointwise values are uniformly bounded.
Comment: Yes, I think you are correct.  I may write up a second answe. covering the more general case. Thanks!
Answer: This somehow 'depends'. If, as usual, in Riemannian Geometry, you are looking at a smooth ($C^\infty$) manifold with smooth metric, then the answer is, for sure, yes. Only if you are reducing the differentiability assumptions on the manifold and the metric you may run into trouble at a certain point.
What you are looking at (e.g. in local coordinates) is an expression with components from the metric and derivatives of the metric up to second order, combined with bounded coefficients from the vector fields. This is, locally, clearly bounded if the single factors entering the expressions are (e.g. if the metric is $C^2$). Then it is a matter of mathematical craftmanship to go from local to compact (if the vector field arise from a compact set, then this happens over a compact subset of the manifold in question, of course).
Comment: @RobertLewis Thanks for the endorsement. I have to admit I wasn't even aware of the fact that (non) continuity of the vector fields was an issue for the OP. But if it is, then the thing to note is that the curvature tensor is, as the name suggests, a tensor field. As such, it depends only on pointwise evaluation of it's arguments, and this in a mulitlinear fashion, which immediately implies that $$|R(X, Y)Z |\le ||R|| |X|_\infty |Y|_\infty |Z|_\infty$$ -- whatever $||R|| $ might be. But it should be clear that $||R||$ only depends on $M$ and the metric, not on the vector fields.
Comment: @Mathmath If $R_p$ is continuous, then yes. Continuity of $R$ is a consequence of the metric tensor being of class $C^2$.
Comment: Your answer thoughtfully covers the case $X, Y, Z$ not necessarily continuous, which mine did not.  Well done; ***endorsed!***
Comment: @Thomas: thanks for your answer, upvoted from me too! Yes I seemed to have overlooked/forgotten the fact that $R$, being a tensor field, depends only on the pointwise values of $X,Y,Z$ itself, rather than the values of vector fields themselves. And so $R_p$ is finite for every $p$ because $T_p{M}$ is finite-dimensional, and $R_p$ being a continous function of $p$, attains a maximum on a compact set. I think I just re-wrote your argument, but is it correct?
Answer: NB:  in the following, it is assumed that $X, Y, Z$ and $R$ are continuous.
If $C \subset TM$ is the compact subset from which $X$, $Y$ and $Z$ are taken, then $C \times C \times C$ is compact (Tychonoff's theorem), and the map
$R(X, Y)Z: C \times C \times C \to TM \tag{1}$
is continuous; this follows by virtue of the fact that in any local coordinate system $w_\alpha$ on $M$, with corresponding tangent basis vector fields $e_\alpha$ where
$e_\alpha = \dfrac{\partial}{\partial w_\alpha}, \tag{2}$
we may write
$R(X, Y)Z = e_\beta R^\beta_{\mu \nu \rho} X^\mu Y^\nu Z^\rho, \tag{3}$
where
$X = X^\mu e_\mu \tag{4}$
and so forth.  (The Einstein summation convention is understood as being operative in (3) and (4), as throughout this answer.)  Since all of the coefficients $R^\beta_{\mu \nu \rho}$, $X^\mu$ and so forth are continuous, as well as the vector fields $e_\alpha$, the continuity of $R(X, Y)Z$ follows.  Note that we are in essence drawing on the fact that a composition of continuous maps is itself continuous.
Denoting the metric norm by $\Vert \cdot \Vert_g$, we see in a manner similar to the above that
$\Vert \cdot \Vert_g:  TM \to \Bbb R, \tag{5}$
which takes tangent vectors $X \in TM$ to their metric norms $\Vert X \Vert_g = (g((X, X))^{1/2}$, is also continuous.  It then further follows that the composed map
$\Vert R(X, Y)Z \Vert_g: C \times C \times C \to TM \to \Bbb R \tag{6}$
is continuous, again since it is a composition of continuous functions.
It now follows from the compactness of $C \times C \times C$ that $\Vert R(X, Y)Z \Vert_g$ is bounded on this set, since a continuous function on a compact set is always bounded.
Note Added Friday 26 June 2015 1:47 PM PST:  In the light of our colleague Thomas well-framed answer and comments, as well as those of our OP Mathmath, I don't suppose it's necessary to say much more, so I will forgo adding another answer to address the case in which $X$, $Y$, $Z$ need not be continuous; but I would like to take this opportunity add a few (hopefully brief) words on the subject.  I was indeed aware that a bound should exist whether or not the continuity of $X$, $Y$, $Z$ binds, that that it would most likely take the form
$\Vert R(X, Y)Z \Vert_g \le \Vert R \Vert \Vert X \Vert_g \Vert Y \Vert_g \Vert Z \Vert_g, \tag{7}$
where $\Vert R \Vert$ may be taken to be some constant depending only on the tensor field $R$.  In fact, (7) holds pointwise, without any reference to continuity at all.  Whilst thinking about how to best write-up an explanation of (7), it occurred to me that in the case of $X$, $Y$, $Z$ continuous one can altogether dispense with the details of multilinearity and argue, more or less directly, from the fact that $R(X, Y)Z$ is a polynomial in the components of $X$, $Y$, $Z$ with continuous coefficients the $R^\alpha_{\mu \nu \rho}$; thus, $\Vert R(X, Y)Z \Vert_g$  is a continuous mapping on the compact set $C \times C \times C$.  And having spied that ball, I picked it up and ran with it, forgetting in my haste that continuity of $X$, $Y$, $Z$ is not essential here.  I must confess that I am not used to considering vector fields sans continuity, so I was pre-disposed to read it into the hypotheses of this question; but still, I think it worth noting that the general continuity argument can, in certain situations, replace the more linearity-specific methods which depend on estimates such as (7).   End of Note.


How to transform a list of business dates into a nested list of consecutives business dates?

Question: I have a list of working business dates that look like this:
list_of_dates = ["15/02/2021", "16/02/2021", "17/02/2021",
                 "19/02/2021", "22/02/2021"," 23/02/2021"]

I would like to transform it into a list of continued periods:
list_of_periods = [[start_date="15/02/2021", end_date="17/02/2021"],
                   [start_date="19/02/2021", end_date="23/02/2021"]

So whenever there's one or more business days between two dates, the prior period ends and a new period starts.
I thought about playing around calculating the differences between dates. What's the best way to go with this?
Comment: How do you know that the end of the first period is `"17/02/2021"` and not `"19/02/2021"` or even the last date of your list ?
Comment: @jusstol, he explains in the post: "So whenever there's a day between or more between two dates, the prior period ends and a new period starts."
Comment: @jusstol There is a day between `"17/02/2021"` and `"19/02/2021"` and it is not in the list, hence the period ends `"17/02/2021"`
Comment: @LoicRW My bad, I read that wrong.
Answer: To determine spans of continuous business days, you'll need to add in the weekends (and possibly holidays with the holidays= argument) that way you can check if there's 1 day between all of your dates to form your groups.
First turn your list into a Series of datetime64 values and concatenate all the weekends that are within your data. Sort and drop duplicates. Then find where the difference is !=1 to create your groups and you want the min and max to get the start and end.
import pandas as pd
list_of_dates = ["15/02/2021", "16/02/2021", "17/02/2021",
                 "19/02/2021", "22/02/2021", "23/02/2021"]

s = pd.Series(pd.to_datetime(list_of_dates, format='%d/%m/%Y'))
sweekend = pd.Series(pd.bdate_range(s.min(), end=s.max(), freq='C',
                                    weekmask='Sat Sun', holidays=None))

s = pd.concat([s, sweekend]).drop_duplicates().sort_values()

gps = s.diff().dt.days.ne(1).cumsum()
s.to_frame().groupby(gps).agg(start_date=(0, min), end_date=(0, max))

  start_date   end_date
1 2021-02-15 2021-02-17
2 2021-02-19 2021-02-23

Comment: Hi ALollz,
Thanks for the perfect response that also handles the non business days issue!
Comment: Hey ALollz, for a weird reason i couldn't figure out, your code doesn't work with this list:
list_of_dates = ["20/11/2020","23/11/2020","01/12/2020","02/12/2020","03/12/2020"]

It's exactly the same list format, i don't understand where's the issue.
Comment: @lostAtom that's because it gets confused with the format as days/months can get amibguous. Wasn't an issue in your first case since all days were > 12. You can change first line to `s = pd.Series(pd.to_datetime(list_of_dates, format='%d/%m/%Y'))` and it will know which value to infer as the day and which to use as the month. I updated the solution to reflect that.
Answer: Assuming your dates are datetime.date you can substract them and create a timedelta object which represents the number of days between 2 dates:
from datetime import date

d0 = date(2008, 8, 18)
d1 = date(2008, 9, 26)
delta = d1 - d0
if delta.days >= 1:
  # make time period

See https://docs.python.org/library/datetime.html.
This does not take business days into a count.
Answer: This seems to be what you are looking for: Find group of consecutive dates in Pandas DataFrame
If single dates can be their own period (e.g. '19/02/2021' in your example), then use:
import numpy as np
import pandas as pd

list_of_dates = ["15/02/2021","16/02/2021","17/02/2021","19/02/2021","22/02/2021","23/02/2021"]
df = pd.DataFrame({'dates': list_of_dates})
df.dates = pd.to_datetime(df.dates)
day = pd.Timedelta('1d')

breaks = df.dates.diff() != day
groups = breaks.cumsum()
[{'start_date': df.dates[groups==i].iloc[0], 'end_date': df.dates[groups==i].iloc[-1]}
for i in groups.unique()]

Comment: Thanks Loic! But 19/02/2021 is not considered a single date, since it is followed by 22/02/2021 (business days).
Allolz solution handles weekends


What is the formal name of this matrix product?

Question: Given two $m\times n$ matrices, I want to calculate the sum of the inner product of every pair of rows (or columns) in the two matrices, therefore the result is a real number. This matrix operation looks like below
$$\left(\begin{array}{cccc}
a_{11} & a_{12} & \cdots & a_{1n}\\
a_{21} & a_{22} & \cdots & a_{2n}\\
\vdots & \vdots & \ddots & \vdots\\
a_{m1} & a_{m2} & \cdots & a_{mn}
\end{array}\right)(\times)
\left(\begin{array}{cccc}
b_{11} & b_{12} & \cdots & b_{1n}\\
b_{21} & b_{22} & \cdots & b_{2n}\\
\vdots & \vdots & \ddots & \vdots\\
b_{m1} & b_{m2} & \cdots & b_{mn}
\end{array}\right) = \sum_{i=1}^m\sum_{j=1}^m\langle \boldsymbol{a_i}, \boldsymbol{b_j}\rangle$$
I want to know the formal name of this matrix product. I have looked up the definitions of Kronecker product and Frobenius inner product, but this is neither. The value falls between the Frobenius inner product and the sum of the Kronecker product.
Comment: If $e$ denotes the column vector $e = (1,1,\dots,1)$, then we can write this sum as
$$
A (\times) B = e^TAB^Te = \operatorname{tr}(AB^Tee^T).
$$
Comment: @BenGrossmann No this is not the Frobenius inner product. I have confirmed it using Numpy. For example, the $a_{11}b_{21}$ term (when calculating the inner product between the first row of $A$ and second row of $B$) is not summed in the Frobenius inner product. Frobenius inner product strictly sums $a_{mn}b_{mn}$
Comment: I misread the sum, you're right
Answer: $
\def\o{{\tt1}}
\def\p{\partial}
\def\E{{\cal E}}\def\F{{\cal F}}\def\G{{\cal G}}
\def\L{\left}\def\R{\right}\def\LR#1{\L(#1\R)}
\def\vec#1{\operatorname{vec}\LR{#1}}
\def\diag#1{\operatorname{diag}\LR{#1}}
\def\Diag#1{\operatorname{Diag}\LR{#1}}
\def\trace#1{\operatorname{Tr}\LR{#1}}
\def\qiq{\quad\implies\quad}
\def\grad#1#2{\frac{\p #1}{\p #2}}
$Consider the product of columns
$$\eqalign{
A\;(\times)\;B &= \sum_i\sum_j a_i:b_j \\
 &= \sum_i\sum_j \LR{Ae_i}:\LR{Be_j} \\
 &= A:B\LR{\sum_i\sum_j e_je_i^T} \\
 &= A:BJ \\
 &= \trace{A^TBJ} \\
}$$
Here $\{e_k\}$ are the standard basis vectors, $J$ the all-ones matrix, and the symbol $(:)$ denotes the trace/Frobenius product, i.e.
$$\eqalign{
A:B &= \sum_{i=1}^m\sum_{j=1}^n A_{ij}B_{ij} \;=\; \trace{A^TB} \\
A:A &= \big\|A\big\|^2_F \\
}$$
Similarly the product of rows would be
$$\trace{AB^TJ}$$


What is tonality when you're not playing with a diatonic scale?

Question: Is there any definition of tonality which generalizes beyond a diatonic scale?  For instance, can you have resolution from a dominant to a tonic if you're only using a pentatonic scale?  Clearly you can't just say a dominant is the chord rooted on the 5th scale degree for every scale, when in each scale "5" will mean something else.
I have read that even using a whole tone scale in Voiles Debussy was able to maintain a distinction between dominant and tonic, but I'm not sure exactly what that means.
Thanks!
Comment: Why this fixation on the dominant? IV-I is just as good a cadence to fix the key as V-I. Even ii-I will do the job pretty well. Or a bit more extreme, Ab7 Bb9 C is a perfectly satisfactory cadence ***in C major***.
Comment: Of the five pentatonic modes, only one doesn't have the interval of a (diatonic) fifth between its first and fourth scale degrees, so a typical dominant-tonic relationship is usually available when using a pentatonic scale.
Comment: right, but then what is the definition of a dominant-tonic relationship if it can be between the first and fourth (and not fifth) scale degrees of a scale?
Comment: I don't think you can define it by interval, because there are scales where a tritone serves as dominant and others where tritone serves as subdominant
Answer: Tonality doesn't really need any particular scale or harmonies. It mostly needs one thing: one note that feels like home. In many genres around the world, such a "home" is simply established with an all-underlying drone note, and all melody/harmony is developed around the overtones of that drone. In e.g. Indian music, this involves lots of notes that don't even exist in Western scales. Still there can be no doubt what would be the tonic, if you called it thus.
Pentatonic scales are in fact very often used in drone-based folk music. The most obvious examples are bagpipe or hurdy-gurdy tunes.
And (as alephzero already commented) if you do use harmonies, then there are lots of ways that clearly point to a tonic without using any dominant in the classical sense. The most common alternative is the plagal cadence Ⅳ-Ⅰ, which is quite common across pop/rock/country, again indeed often in connection with pentatonic scales.
Comment: It is certainly true that it is very possible to establish a tonic without relying on functional harmony; although I don't think that that's the complete answer to this question, it's definitely an important thing to recognize.
Comment: Pentatonic scales on bagpipes? I hear Mixolydian! And plagal cadence would miss the fairly important root of the IV.
Comment: @Tim sure you _can_ play full diatonic scales on bagpipes, just, many of the traditional tunes don't. — About the **Ⅳ** you're right; I said _in connection_ with pentatonic scale: those pieces generally don't restrict themselves to only notes from the pentatonic, but instead lay a pentatonic melody over an accompaniment with extra diatonic or even chromatic notes.
Comment: Maybe I hear the drones as representing the root note, which then means there's no leading note, but b7 instead?
Answer: I offer not a complete answer, but rather counter assertion: that key (tonality) is cultural. By way of argument i offer this just-so story told by one of my composition teachers:

During WWII René Leibowitz befriended a Moroccan living in the Free French territories. After the war, he invited this Moroccan friend to attend a concert in Paris where he was conducting. Knowing that this friend had limited art music experience, the performance that Leibowitz invited his friend to was of Beethoven 5. After the performance Leibowitz asked his friend what he thought of this example of European Art Music. "It was wonderful!" came the reply, "but why did it end on the wrong note?"

What this story demonstrates (along with Western, colonialist chauvinism) is that not even 8 perfect cadences in C in a row followed by 30-odd bars of C major chords will guarantee that your audience will hear C as the home key if their musical vocabulary is sufficiently different!
Additionally, i would posit that equally important as root movement to the feeling of harmonic motion, & by extension key, is the melodic movement of tendency tones. The motion 7→8, 2→1, 4→3, 6→5 all tend to reinforce the primacy of the tonic (or the tonic harmony) in the Western tradition. So your non-diatonic scale can leverage these tendency tones — in fact it could set up its own tendency tones (e.g. Poulenc & Bartok were fond of ♭2→1) — to build its own sense of key regardless of the chordal structures availed by the scale. In an example like Debussy's works exploiting modes of limited transposition like the whole-tone scale, this melodic movement, as well as the semi-tone offset relationship of the whole-tone scales (which is also an offset of a perfect 5th), can be exploited by a skilled composer in the Western tradition to give the impression of "tonic" & "dominant" harmonic regions despite the lack of harmonic motion in the whole-tone scale itself.
Comment: That is an interesting anecdote, but as it stands, there is plenty reason to be skeptical IMO. What did the Moroccan really mean? That the end note was the wrong note, or that the way the end note was played was wrong? You don't need to come from a different musical culture to find those over-the-top endings by Beethoven or Tchaikovsky ridiculous.
Comment: I doubt that Leibovitz would have got Beethoven 5 "wrong" with a major Parisian orchestra, even in the years soon after WWII. Oh, by the way, i don't maintain that the story is anything other than a tall tale that can be used to illustrate a point. Your cynicism is noted.
Answer: The general term for this is non-functional harmony. The term's meaning is fairly obvious if you understand the antonym: It means that the harmony does not readily (or usefully, if you prefer) match with functional harmonic descriptors, like "dominant", that are based more or less on the roles that chords play in diatonic scales or those that highly resemble diatonic scales, like the harmonic and melodic minor.
Truthfully, you are going to have a hard time finding a satisfying answer to your question as stated, because tonality outside of diatonic systems (non-functional harmony) is much more difficult to define than tonality within it, and oftentimes you're going to have to look into the theory of the idiom you're analyzing to find a sufficient answer to this question. The major pentatonic scale is a great example of this, and you touched on the problem: What use is there calling the fifth the dominant interval when you can't even form a dominant chord on it? The fact is that you can't really create a strong cadence out of the major pentatonic scale because there's no tritone and no leading tone to the root, so you have to come up with different ways to describe the relationship between notes and chords formed out of the pentatonic scale than T-S-D. What functional tonality does tell you about the pentatonic scale is, as I mentioned above, that with those combination of notes you'll be unable to reproduce a perfect cadence and that therefore you can't create any strong tension-resolve contrasts like you can in the major scale (and other scales that can replicate the V7-I relationship). It is more complicated to do this kind of analysis with the whole tone scale because its relationship to diatonic harmony is considerably more complex, but it is possible. For example, using the whole tone scale built a semitone away from the root gives a collection of notes that strongly suggest the dominant (since you can form V7#5 with them, as well as its tritone sub if you're a jazz person).
To say that this is a deep rabbit hole is an understatement. For example, you can look at twelve-tone as being a total rejection of functional harmony specifically because it is impossible to ascertain any tonality from twelve pitches given roughly equal emphasis. There's also the diminished scale, which reveals a number of connections between chords that are otherwise very difficult to explain within the bounds of functional harmony.
Comment: hmm... your comment makes me think that maybe we can loosen {S,D,T} to {resolves to something like a tonic, resolves to something unlike a tonic, is something like a tonic}, and see to what extent those categories hold.  Does that at all make sense to you?
Comment: @lightning I get what you're driving at, but I think it's more logical to simply acknowledge that the divisions in functional harmony don't really apply to non-functional harmony. There's some value in recognizing that something sounds like a perfect cadence (for example), but some information is invariably lost in the comparison when it's not actually a perfect cadence. Besides, as I've said, for many truly non-diatonic systems (see the other answer's reference to drones) there are already analytic frameworks in place.


Prove that the region of absolute stability for explicit Runge-Kutta methods is bounded

Question: That's what I've got:
We know, that the region of absolute stability are those $z \in \mathbb{C}$, for which $|R(z)| < 1$, where $R(z)$ is the stability function.
For explicit Runge-Kutta methods, this is a polynomial, to be more precise, if we have an explicit RK method of p-th order, we get
$$R(z) = 1 + z + \frac{z^2}{2} + ... + \frac{z^p}{p!} + \mathcal{O}(z^{p+1})$$
So what I did is:
$$|R(z)| = |1 + z + \frac{z^2}{2} + ... + \frac{z^p}{p!} + \mathcal{O}(z^{p+1})| \le 1 + |z| + \frac{|z|^2}{2} + ... + \frac{|z|^p}{p!} + |\mathcal{O}(z^{p+1})|$$
But this means, that $|R(z)| < 1$ iff. $|z| + \frac{|z|^2}{2} + ... + \frac{|z|^p}{p!} + |\mathcal{O}(z^{p+1})| < 0$, which is simply impossible!
So what should I do now? Where's the mistake?
Edit: I thought, that maybe the other way would be to find out the region for which $z + \frac{z^2}{2} + ... + \frac{z^p}{p!} + \mathcal{O}(z^p) < 0$, but I don't think this could work as $z \in \mathbb{C}$, so unless I take the absolute value, this does not make sense for $\mathbb{C}$
Answer: So first of all, your mistake is that $\vert R(z) \vert$ is not less equal 1 if and only if
$$ \sum_{j=0}^p \left \vert \frac{z^j}{j!} \right \vert + \left \vert \mathcal O (z^{p+1}) \right \vert \leq 0.$$
Consider the simple counterexample of Forward Euler with stability polynomial $1+z$. Then, for $z=-1$ you have that $| R(z) | = 0$ while $| z | = 1 > 0$.

The reasoning behind the fact that the region of absolute stability is always bounded for explicit Runge-Kutta methods follows from the observation that for any non-constant polynomial $R(z)$ we have that
$$ \lim_{| z | \to \infty} | R(z) | = \infty $$
Thus, the region of absolute stability is not unbounded = bounded.


Programmatically get input format in field template

Question: We change some output in our field.tpl-files for body fields, depending on the input format that was used on the node (which itself depends on the user being able to modify it).
Now this worked by drilling down to $element['#object']->body["und"][0]["format"] but that's hardly best practice as illustrated by helpful articles.
But – what is the correct way to get a reliable, language-agnostic variable like $ouptut['format']?
Thanks for any infos on that!
Comment: As an aside, however you get the data, the best place for this sort of processing is in a preprocess hook, not in a template file. In a template, you just want simple data variables as far as possible.
Comment: While this is probably correct from a technical standpoint, I kind of like the workflow of having everything together in a single template file instead of juggling with hooks and template files. Drupal 8 shall enforce my education.
Comment: It's not really a technical thing, just makes template files more readable and accessible to less skilled devs.
Answer: I would suggest you to create separate template based on field's text format.
Here is the way:

Create a TEMPLATE_preprocess_field function in template.php file of your theme.
Copy and paste a file named "field.tpl.php" and rename it to "field--[your-field-name]--[its-text-format].tpl.php.

The function is :
function MYTHEME_preprocess_field($variables) {
  switch ($variables['element']['#field_name']) {

case 'body':
  $element = $variables['element'];
  $entity_type = $element['#entity_type'];
  $field_name = $element['#field_name'];
  $language = $element['#language'];
  $entity = $element['#object'];
  $values = field_get_items($entity_type, $entity, $field_name, $language);
  $item = array_shift($values);
  $format = $item['format'];
  $variables['theme_hook_suggestions'][] = 'field__' . $field_name . '__' . $format;
  break;
      }
    }


Tag de bloco inválido

Question: Sou novo em Django e estou com um problema com as tags de Template
Meu código:
{% load static %}
{% block content %}

    {{ questao.afirmativa }}

    {% alternativas = questao.get_alternativas %}

        {% for alternativa in alternativas %}
          {{alternativa}}
        {% end for %}

{% endblock content %}

O objeto questao já vem no context da view. O método get_alternativas gera uma lista de alternativas que quero percorrer com o for e mostrar na página.
O que estou fazendo de errado?
Está dando erro nessa linha:
{% alternativas = questao.get_alternativas %}

Mensagem de erro:

"- Tag de bloco inválido na linha 7: 'alternativas', esperado 'endblock'. Você esqueceu de registrar ou carregar esta tag?"
Answer: As tags {% ... %} são exclusivas para os comandos do sistema de templates do Django (seja o que vem embutido nele, seja usando o Jinja2).
Para criar uma nova variável dentro do modelo, use a tag {% with ... %}:
{% with alternativas as questao.get_alternativas %}

    {% for alternativa in alternativas %}
      {{alternativa}}
    {% endfor %}

{% endwith %}

Aliás o {% endfor %} está grafado errado no teu código.

Tag de bloco inválido


Why do neural networks need feature selection / engineering?

Question: Particularly in the context of kaggle competitions I have noticed that model's performance is all about feature selection / engineering. While I can fully understand why that is in the case when dealing with the more conventional / old-school ML algorithms, I don't see why this would be the case when using deep neural networks.
Citing the Deep Learning book:

Deep learning solves this central problem in representation learning by introducing representations that are expressed in terms of other, simpler representations. Deep learning enables the computer to build complex concepts out of simpler concepts.

Hence I always thought that if "information is in the data", a sufficiently deep, well-parameterised neural network would pick up the right features given sufficient training time.
Comment: your brain is still more powerful than a machine, so a little help from a human goes a long way
Comment: who says they need feature selection/engineering? can you give any references? when you work with images, they pretty much work end-to-end...
Comment: @user2137591 that's the point. I get an impression that in the literature neural nets are often portrayed as a step up from conventional machine learning as they supposedly do feature engineering and selection automatically (as implied by Goodfellow, Bengio, Courville in the Deep Learning book). This is true in many tasks in CV or NLP where I believe information is still scarce.
On the other hand, in competitive data science (kaggle), where a lot of noisy data is available, a common belief is that the most important factor in building a competitive solution is finding the "magic feature".
Comment: I can speak for CompVis, where I cannot recall any project doing feature engineering to feed into networks afterwards... this holds for medical image data as well, where the image quality is usually lower. maybe this is different in other fields... do you have any papers or any published source you can refer to in this regard? I would appreciate it, thanks.
Comment: Related: https://stats.stackexchange.com/questions/350220/utility-of-feature-engineering-why-create-new-features-based-on-existing-featu/350238#350238
Comment: I'd argue that CV uses "semi" feature engineering because last I checked we're using convolutional layers instead of fully connected ones. Mathematically, anything the conv layer can learn and do, a fully connected one could learn and do as well. So we decide that "no, don't look at the full space of possible linear mappings. Just look at those that arise from convolving the input with a small-ish filter."
Answer:
What if the "sufficiently deep" network is intractably huge, either making model training too expensive (AWS fees add up!) or because you need to deploy the network in a resource-constrained environment?
How can you know, a priori that the network is well-parameterized? It can take a lot of experimentation to find a network that works well.
What if the data you're working with is not "friendly" to standard analysis methods, such as a binary string comprising thousands or millions of bits, where each sequence has a different length?
What if you're interested in user-level data, but you're forced to work with a database that only collects transaction-level data?
Suppose your data are the form of integers such as $12, 32, 486, 7$, and your task is to predict the sum of the digits, so the target in this example is $3, 5, 18, 7$. It's dirt simple to parse each digit into an array and then sum the array ("feature engineering") but challenging otherwise.

We would like to live in a world where data analysis is "turnkey," but these kinds of solutions usually only exist in special instances. Lots of work went into developing deep CNNs for image classification - prior work had a step that transformed each image into a fixed-length vector.
Feature engineering lets the practitioner directly transform knowledge about the problem into a fixed-length vector amenable to feed-forward networks. Feature selection can solve the problem of including so many irrelevant features that any signal is lost, as well as dramatically reducing the number of parameters to the model.
Answer: The key words here are priors and scale. As a simple example, imagine you're trying to predict a person's age from a photograph. With a dataset of images and ages, you could train a deep-learning model to make the predictions. This is objectively really inefficient because 90% of the image is useless, and only the region with the person is actually useful. In particular, the person's face, their body and maybe their clothing.
On the other hand, you could instead use a pre-trained object detection network to first extract bounding boxes for the person, crop the image, and then pass it through the network. This process will significantly improve the accuracy of your model for a number of reasons:
1) All of the networks resources (i.e. weights) can focus on the actual task of age prediction, as opposed to having to first find the person first. This is especially important because the person's face contains useful features. Otherwise, the finer features that you need may get lost in the first few layers. In theory a big-enough network might solve this, but it would be woefully inefficient. The cropped image is also considerably more regular than the original image. Whereas the original image has a ton of noise, its arguable the discrepancies in the cropped image are much more highly correlated with the objective.
2) The cropped image can be normalized to have the same scale. This helps the second network deal with scaling issues, because in the original image, people can occur near or far away. Normalizing scale beforehand makes it so that the cropped image is guaranteed to have a person in it that fills the full cropped image (despite being pixilated if they were far away). To see how this can help scale, a cropped body that's half the width and height of the original image has 4x less pixels to process, and hence the same network applied to this image would have 4x the original network's receptive field at each layer.
For example, in the kaggle lung competition, a common theme in the top solutions was some kind of preprocessing on lung images that cropped them as much as possible and isolated the components of each lung. This is especially important in 3D images since the effect is cubic: by removing 20% of each dimension, you get rid of nearly half the pixels!
Answer: My intuition about this phenomenon is connected to the complexity of the model to be learned. A deep neural network can indeed approximate any function in theory, but the dimension of the parameter space can be really large, like in the millions. So, actually finding a good neural network is really difficult. I like to think about feature engineering as giving a head start to the algorithm, providing it some extra information regarding the data representation which is good enough in some sense. Of course, this is not a formal explanation, this question might be really hard to answer with scientific rigor.


Como esconder uma senha no C#

Question: Quero esconder a minha senha.
O que eu quero que que aconteça é que enquanto eu digito o " * " seja mostrado no lugar dos caracteres, o problema é que isso acontece só quando eu clico no botão "Logar".
Sim, eu sei que isso acontece por que os comandos estão dentro do bloco do evento do botão, mas como posso tirá-los de lá?
Tentei fazer fora do evento mas não consigo usar a caixa de texto, o que posso fazer?
Answer: É só definir a propriedade PasswordChar do TextBox, não precisa de nenhum evento extra.
txtSenha.PasswordChar = '*';

Answer: Os campos TextBox possuem uma propriedade chamada UseSystemPasswordChar, altere ela para true.

Como esconder uma senha no C#


Javascript Object.Property logging undefined

Question: printPerson takes an object as an argument, its loop iterates trough all its properties and is suposed to print them all out.
As you can see I've logged both the person and property variables and they are working fine. person is identified as an object, and property as a string with the correct property name, indicating that the loop is also working fine. But when it comes to logging person.property, the return value is undefined.
What am I missing?
var bob = {
    firstName: "Bob",
    lastName: "Jones",
    phoneNumber: "(650) 777-7777",
    email: "email@example.com"
};

var mary = {
    firstName: "Mary",
    lastName: "Johnson",
    phoneNumber: "(650) 888-8888",
    email: "email@example.com"
};

var contacts = [bob, mary];

function printPerson(person) {
    for (property in person){
      console.log(person);
      console.log(property);
      console.log(person.property);
    }
}

function list(){
    for (var i=0;i<contacts.length;i++){
        printPerson(contacts[i]);
    }
}

list();

Answer: You need to use bracket notation when using variables as keys:
console.log(person[property]);

Here are the relevant docs: MDN on Objects Properties


Async testing with vows using the http.get library in Node.js

Question: I'm having a doozie of a time trying to get a basic http test to work with vows.
I think I've followed the async example from vows http://vowsjs.org/#-writing-asynchronous-tests and substitued the appropriate calls, but I must be missing something.
The test code looks like this:
var http = require('http'),
    vows = require('vows'),
    assert = require('assert');

vows.describe("homepage").addBatch({
  "Get the home page": {
    topic: function() {
      http.get({'host': "127.0.0.1", 'port': 5000, 'path': '/'}, this.callback);
    },
    'should respond with 200 OK': function(res) {
      assert.equal(res.statusCode, 200);
    }
  }
}).export(module);

I get the following error when I try to run the test for this:
/Users/<home_folder>/node_modules/vows/lib/vows.js:80
rrored', { type: 'promise', error: err.stack || err.message || JSON.stringify(
                                                                    ^
TypeError: Converting circular structure to JSON
    at Object.stringify (native)
    at EventEmitter.<anonymous> (/Users/<home_folder>/node_modules/vows/lib/vows.js:80:90)
    at EventEmitter.emit (events.js:64:17)
    at /Users/<home_folder>/node_modules/vows/lib/vows/context.js:31:52
    at ClientRequest.<anonymous> (/Users/<home_folder>/node_modules/vows/lib/vows/context.js:46:29)
    at ClientRequest.g (events.js:143:14)
    at ClientRequest.emit (events.js:64:17)
    at HTTPParser.onIncoming (http.js:1349:9)
    at HTTPParser.onHeadersComplete (http.js:108:31)
    at Socket.ondata (http.js:1226:22)

I can get a simple http example to work on it's own. I can get the vows example to work on it's own but I can't combine them for whatever reason. I'd really appreciate some help here. I've been trying to get this to work for a while now (including much googling).
UPDATE:
Apparently adding an error argument to the call back solves this problem, thanks to help from Alexis Sellier (creator of vows).
But I have no idea why. When writing out the http lib example on it's own no error argument is required. I can't find any documentation in vows to indicate why it's needed so I'm at a bit of a loss.
My new question is why is the error argument required when using the http lib in vows?
Answer: After checking vow's source code, I think I know why. Vows always ensure that when you call this.callback, the resulting receiver function's first argument is always an error object. Vows interpret the callbacks by these rules:

If the first argument of your originating callback is a boolean, use that to determine whether or not to append an error object to the receiving callback (e.g. path.exists(boolean) will emit callback(error, exists) instead)
If the first argument is an object, assume it's an error object and use that to determine whether to add the originating callback to the "error" or "success" list. The reason this list exists is to support promise based tests I guess?

While I can't confirm the above is correct, my experience is that vows' async style is made to support node-styled callbacks (e.g. err as the first arg), and 3rd party npm modules that don't conform to this standard will be hard to test.
Please don't take my answer as gospel, as this is my own experience. Another gotcha is when you have async operations inside the function that you want to test - unless you provide a callback, vows won't be able to handle it properly.
Personally, I think vows still make it hard to test async code. I wish it had some waitFor() or until() flow control functions though.
My suggestion? When dealing with async code, use Step. Don't let vows control your flow.
Comment: The interesting thing is I'm using the node.js built in http lib, I guess they've changed the error first convention, or at least allow for a separate error handler function using the .on() convention.
Answer: It is actually missing in the documentations which is still a bit short. But you can get a glimpse of it here in this page :
'when peeled *asynchronously*': {
        topic: function (banana) {
            banana.peel(this.callback);
        },
        'results in a `PeeledBanana`': function (err, result) {
            assert.instanceOf (result, PeeledBanana);
        }
    }

As it was said by Morten Siebuhr and Ruben Tan, this is how vows works and that is why it works like that.


Como obter e contar elementos que NÃO tem determinada propriedade CSS com js/jquery?

Question: Preciso realizar a contagem de elementos dentro de uma div que não contém a propriedade display:none para depois calcular e somar a largura de todos esses elementos.
A função de calcular e somar seria essa:
$('#gallery').children().each(function(){
        itemTotalWidth += $(this).outerWidth(true);
});
console.log("A largura total dos itens da galeria é: "+itemTotalWidth);

Mas dessa forma ela pega todos os elementos dentro da div#gallery e eu só quero o que não possui display:none setado como atributo inline.
Alguma ideia?
Comment: Mas você quer todos os que não possuem display:none ou apenas os que possuem display:inline ?
Answer: Selecionando o que é visível
O jQuery possui um seletor especial :visible que seleciona todos os elementos que ocupam algum espaço no documento. Não é exatamente seu requisito sobre display:none, mas é mais abrangente e provavelmente mais útil.
Veja um exemplo:

var qtd = $('#container').children(':visible').length;
console.log("Quantidade", qtd);

var itemTotalWidth = 0;
var qtd = $('#container').children(':visible').each(function() {
 console.log($(this).outerWidth(true));
 itemTotalWidth += $(this).outerWidth(true);
});
console.log("Largura total", itemTotalWidth);
#container span {
  width: 20px;
  margin: 0;
  padding: 0;
  display: inline-block;
}

.none {
  display: none !important;
}

  bla
  bla
  bla
  bla
  bla
  bla

Negando um atributo CSS
Não existem seletor para atributos CSS da mesma forma que existem para atributos HTML.
Uma alternativa que funciona se você tiver total controle sobre os estilos e eles forem inline é selecionar por comparação de texto.
O exemplo a seguir usa um seletor duplo :not([style*="display"]), :not([style*="none"]), ou seja, ele procura por ambos os valores display e none dentro do atributo style no HTML. Isto não funciona se o atributo for declarado em outro lugar ou alterado dinamicamente.

var qtd = $('#container').children(':not([style*="display"]), :not([style*="none"])').length;
console.log("Quantidade", qtd);

var itemTotalWidth = 0;
var qtd = $('#container').children(':not([style*="display"]), :not([style*="none"])').each(function() {
 console.log($(this).outerWidth(true));
 itemTotalWidth += $(this).outerWidth(true);
});
console.log("Largura total", itemTotalWidth);
#container span {
  width: 20px;
  margin: 0;
  padding: 0;
  display: inline-block;
}

  bla
  bla
  bla
  bla
  bla
  bla

Outra alternativa, se tiver total controle sobre os estilos e garantir que não há espaços em branco no valor inline é usar um único seletor :not([style*="display:none"]).
Entretanto, consideraria essas técnicas gambiarras. Seria melhor usar o :visible do jQuery ou, ainda melhor, se você tem controle sobre o processo, adicione classes diferentes nos elementos que são visíveis e invisíveis, assim fica muito mais simples executar operações nesses elementos sem gambiarras.
Answer: var elements_without_display_none = []

$('#gallery').children().each(function(i, el) {

    var $currentEL = $(el);

    if($currentEl.css("display") != "none") {
        elements_without_display_none.push($currentEL)
    }

});

elements_without_display_none agora deve conter todos os elementos dentro de #gallery que não tem display = none.


Problemas com Migration

Question: Estou desenvolvendo uma aplicação utilizando arquitetura DDD. Em minha camada de Infra, tenho os meus modelos de dados, todos baseados em Code First. Estou tentando utilizar o MySql como banco de dados. Já instalei tudo que foi necessário (EF, MySqlConnector) e outros mais que são necessários.
Acontece que quando tento aplicar o Migration obtenho o erro:
Caso 1: Quando aplico o Add-Migration
PM> Add-Migration
cmdlet Add-Migration na posição de comando 1 do pipeline
Forneça valores para os seguintes parâmetros:
Name:

O que deve ser fornecido para esse "Name":
Caso 2: Quando forneço o nome do banco de dados que consta na ConnectionString
OBS: Forneço tal valor, porque não sei o que deve ser passado conforme explicado acima.
The specified framework version '2.0' could not be parsed
The specified framework 'Microsoft.NETCore.App', version '2.0' was not found.
  - Check application dependencies and target a framework version installed at:
      C:\Program Files\dotnet\
  - Installing .NET Core prerequisites might help resolve this problem:
      http://go.microsoft.com/fwlink/?LinkID=798306&clcid=0x409
  - The .NET Core framework and SDK can be installed from:
      https://aka.ms/dotnet-download
  - The following versions are installed:
      1.0.11 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
      1.0.12 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
      1.1.8 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
      1.1.9 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
      2.0.3 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
      2.0.7 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
      2.0.9 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
      2.1.2 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
      2.1.4 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]

Como resolver tal problema?
Desde já agradeço a atenção.
Comment: Ele está te pedindo o nome da sua migration. Cada migration tem um nome próprio, para você conseguir identificar e reverter as modifcações.
https://docs.microsoft.com/pt-br/ef/core/managing-schemas/migrations/

No caso ficaria assim PM> Add-Migration MinhaMigration
Comment: Ok. Grato pela atenção. O problema foi resolvido.
Answer: No uso de migration tu terá de se habituar com alguns comandos:
Add-Migration <nome-da-migration>

Para voltar a uma versão específica:
update-database –target "<nome-da-migration>" -Script -Force

Atualizar a sua base com as alterações do domínio:
update-database -script

O parâmetro -Script: serve para te devolver o script a ser executado em banco, caso não coloque o parâmetro, será submetido automaticamente em banco.
O parâmetro -Force é necessário quando houver algum tipo de conflito ou modificação de estrutura que com script simples não seja possível de se modificar. Com o uso do -Force ele cria um script da quebra do possível relacionamento. Essa ação, caso você esteja usando um banco de produção, irá apagar os dados contidos no banco. Sempre bom ter cautela no uso do Migrations e aconselho a não usar em base de produção. Somente para desenvolvimento.
Existem outros parâmetros ainda como o -Verbose: Serve apenas para exibir um log do que o migrations está executando durante a execução do update-database.

Problemas com Migration


Is it possible to make jackson 2 recognize @codehause...JsonIgnoreProperties?

Question: I am using Jackson 2, but need use one library which uses Jackson 1(codehause), and makes call to its remote server.
But  because the client-server version mismatches, the server side returns fields that are not recognized by client mode class.
So it failed with error like:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:
  Unrecognized field

The client model class is actually annotated with @codehause...JsonIgnoreProperties(ignoreUnknown = true)
So I am wondering is there a way to make Jackson 2 recognizes Jackson 1 @codehause...JsonIgnoreProperties, and just ignore unknown properties?
Thanks very much for your help.
Answer: In Jackson 2, You can configure the ObjectMapper to ignore unknown fields as follows:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

Comment: Thanks for your response, Amila, The problem is that we are using a client library, which wraps all these stuff: it uses httpClient to send request, and deserialize the json data to its object. - but it uses jackson 1 @JsonIgnoreProperties. We can't change the code.  I tried ContextResolver> approach, but the client code is not aware of the customized ObjectMapper at all - instead creates a new default ObjectMapper


Naming conventions for fields machine name in Drupal

Question: There is a naming convention for the fields machine name such as:
entity_name_field_name

for not shared fields
or
field_name

for shared fields.
When I go to start a project, what should be the naming convention I must use on it?
Answer: TL;DR Always use a short succinct but entity agnostic machine name for your fields because requirements will change.
I would never put the entity name in the field name. While today you might think that a field will only ever be used on a node. Requirements change over time. Today's assumptions will bite you tomorrow.
For example you might have a "Hero image" field and decide to use "node_hero_image" (or worse "node_blog_hero_image") because it is only used for nodes.  Later someone decides that they want to use hero images on another entity type - say taxonomy terms to create nice "category landing pages".  You have hard coded the entity type into the field. You have 2 choices, either keep the poorly named field or create a new one - both options are less than idea an increase the technical debt in your project.
If you had've used "hero" as the machine name for your field it would remain flexible. The purpose of the field is clear to anyone who sees it in the UI. You don't need "_image" in the name either as most places in the UI will tell you it is an image field.
Comment: @AdrianCidAlmaguer TL;DR is "too long, don't read" ...
Comment: What is the meaning of "TL;DR" ?
Comment: Actually, it's "Too long, *didn't* read" (subtle but important difference). It is a presumption by the writer the reader might find the explanation too long to read. It's *not* a recommendation by the writer it should not be read :) The origin is actually that it might be used by a commenter, meaning they found something too long to read.
Answer: Unless your entity is resuable (like say apart of a Feature) I typically name my fields as "field_PROJECTNAME_SOMETHING_DESCRIPTIVE" that fits within the 25-ish character limit for field names.
If I put the content type into a Feature then yes I use a consist naming pattern for all fields. If I have a Feature for a content type called DIET (short for Digital Identity) I can make a field called field_diet_presidential_number.
For example I'm working on a project I call internally the "Presidency Project". I may name my fields with a prefix of prez. This is true for anything that requires a machine_name. This way when making Features or exporting code I can at a glance see some piece of configuration that is project specific and I know to export it somehow.
Machine names should at the least be globally distinguisable from Core fields and other configuration values (such as system variables, and Pattern machine names, Rule machine names, etc).
Comment: As per the [documentation](http://cgit.drupalcode.org/drupal/tree/modules/field/field.module?h=7.x#n65), the maximum length of a field name is 32 characters.
Comment: @skwashd Sure,although my reply included discussion of "machine names" and not all machine related names (entity names, views display names, rules names, etc) are limited to 32 characters. For example, http://drupal.stackexchange.com/questions/14406/views-blocks-machine-name-is-being-hashed
Answer: Have a look at the (illuminating) article "Relativity Model for Drupal", especially the related page about "Wrapping Information Architecture and Documentation". Here is a quote from it:

To create an Event content type in Drupal is a simple task. But there's a nuance to that task that is overlooked very often. That nuance is the machine name. But why is the machine name of a content type such an important step?

It gives the content type an explicit name of your choosing and allows database indexing to act on that machine name while being queried.
All fields contained within that content type will share the same machine name before the field name. This allows the Views module to clearly gather field data in a very defined manner using the indexed machine name.
Fields that are entity references out to other content types also begin with the same machine name followed by their own machine name. This allows simple and visual identification for origination and destination of data relationship.

It also contains an interesting example of what seems to be a great naming convention.
Comment: thanks Pierre I will read all the article, I think that the machine name is very important in large projects and in the use of the module features . Thanks a lot
Comment: Too weird that the article doesn't exists anymore, maybe it was only an assumption? Therefore the article was erased?
Answer: There is no generally accepted convention as far as I am aware, but clearly it makes very good sense to develop some internal standards within your project or company.
The field_ prefix is, in my opinion, not necessary nor useful. It's a legacy from Drupal 6's CCK module, which was the forerunner of Drupal 7's field subsystem. Although that prefix is included by default when creating fields via the standard core UI, that behaviour can be changed, for example with this module: Remove field name prefix
It would probably make sense to use a short initial prefix that you can expect to be unique, to help avoid possible conflicts with field ids or database table names used by other modules. I often use a prefix of ng_ which is short for my own domain name and so hopefully won't be used by anybody else. Of course, this does not guarantee that there will be no conflicts, but it helps.
If you are developing a Drupal module or distribution for general use, then using a short initial prefix representing the name of that module or distribution would make sense, again to help avoid name conflicts with other modules. This is very common practice for naming PHP functions within module and theme code, where the full project name of the module or theme is usually used as a prefix.
Answer: I use one of those options:

field_type_function#

field_img_heroimage1
field_img_figure1
field_img_icon1
field_longtext_details1
field_longtext_details_exp1
field_longtext_details2
...

field_type#

field_img1
field_img2
field_img3
field_longtext1
field_longtext2
field_longtext3
...

Also you could add the project name before the type: field_projectname_type# .
I don't recommend to put the entity name in the field name like skwashd said.


How to remove spaces and beginning 0 from a contact number in Views PHP view?

Question: I have tried multiple variations and I cannot get this right. I have a contact number field that is user input; therefore, I need to clean it up so that I can use it in a tel: link on mobile devices.
Users could add numbers using different formats, such as:

021 457 7890
+27 21 567 7089
0214577898

What I want to do (using Views PHP) is to strip the spaces, +27, and 0 at the beginning. My PHP skills are limited, but the confusing part for me is the Value code input and the Output code input and getting this to output correctly.
Note: if there is a non-Views PHP workaround, that would be preferred.
Comment: I re-opened the question, since the given answer suggests using a template file.
Comment: Is it possible for you to provide separate fields for country code, local area code and contact number? This will let you reduce the confusion and you can use these fields in view easily.
Comment: besides the spaces, you want to remove the +27 and 0, if it starts with a zero?
Comment: What are you expecting as answer, the PHP code necessary to take off the eventual plus sign at the beginning of the number and the 0?
Comment: @RDP it's user entered so can't seperate.
Comment: @No Sssweat, yes as I need a uniform number.
Comment: @kiamlaluno, the end result needs to be 213456789 so yes if the php code is available it would be amazing.
Comment: @kiamlaluno, if there is a non-php views drupal workaround, that would be preferred. Thanks
Comment: @RickHarington there is, you need to use template files.
Comment: @kiamlaluno YAY!!!
Answer: You can do it using the PHP function str_replace
$number = $row->field_contact_number;
// Remove the spaces.
$number = str_replace(' ', '', $number);
// Grab the first number.
$first_number = substr($number, 0, 1);
if ($first_number == 0) {
  // Check if the first number is 0.
  // Get rid of the first number.
  $number = substr($number, 1, 999);
}
// Remove the + sign.
$number = str_replace('+', '', $number);
echo $number;

Although the question asked using Views PHP, it is not a good idea to enable the Views PHP and PHP Filter module. In Drupal 7, the alternative/preferred method would be to add the following code to the bottom of your template.php file (located in /sites/all/themes/yourtheme/ folder).
function themename_preprocess_views_view_fields($vars){
  if ($vars['view']->name == "view_name" && $vars['view']->current_display == "block_1") {
    $number = $vars['fields']['field_contact_number']->content;
    // Remove the spaces.
    $number = str_replace(' ', '', $number);
    // Grab the first number.
    $first_number = substr($number, 0, 1);
    if ($first_number == 0) {
      // Check if the first number is 0.
      // Get rid of the first number.
      $number = substr($number, 1, 999);
    }
    // Remove the + sign.
    $number = str_replace('+', '', $number);
    $vars['fields']['field_contact_number']->content = $number;
  }
}

Replace themename with your theme name
Replace view_name with your view name
Replace block_1 with your machine name

Remember to flush the cache to see the changes.
Comment: @RickHarington updated my answer, with alternative/preferred method.
Comment: Thanks for getting back to me. Would this just go in the Output code input? My field variable is $row->field_contact_number
Comment: @RickHarington I haven't used Views PHP in a long while. Should go on the 2nd (last box) if my memory is correct.
Comment: you're a genius!!! Thank you so much. That worked perfectly.
Comment: You left a `echo $number;` inside the preprocess hook. Check the code as I edited it is the correct one.
Comment: @kiamlaluno thx for formatting it, and yeah no need to echo there, looks good.


Javascript character counter help

Question: I have some code that I am using to count characters in an input/textarea and display a countdown on my page. My problem is that I want the ability to define which div I want the counter displayed in.
How can I add a variable to this code in which I can define which div I want the counter to appear in????
Help me geniuses!!!
<code>(function($) {

    $.fn.charCount = function(options){

        // default configuration properties
        var defaults = {
            allowed: 150,
            warning: 25,
            css: 'counter',
            counterElement: 'span',
            cssWarning: 'warning',
            cssExceeded: 'exceeded',
            counterText: ''
        };

        var options = $.extend(defaults, options);

        function calculate(obj){
            var count = $(obj).val().length;
            var available = options.allowed - count;
            if(available <= options.warning && available >= 0){
                $(obj).next().addClass(options.cssWarning);
            } else {
                $(obj).next().removeClass(options.cssWarning);
            }
            if(available < 0){
                $(obj).next().addClass(options.cssExceeded);
            } else {
                $(obj).next().removeClass(options.cssExceeded);
            }
            $(obj).next().html(options.counterText + available);
        };

        this.each(function() {
            $(this).after('<'+ options.counterElement +' class="' + options.css + '">'+ options.counterText +'</'+ options.counterElement +'>');
            calculate(this);
            $(this).keyup(function(){calculate(this)});
            $(this).change(function(){calculate(this)});
        });

    };

})(jQuery);
</code>
Answer: mayby special jquery plugins can help in your case to reduce the code as they calculate the number of chars automatically:
http://plugins.jquery.com/taxonomy/term/360
http://plugins.jquery.com/project/apTextCounter
Answer: Try this. Really only useful to call this against a single input element. Different inputs would require different containers passed in.
http://jsfiddle.net/GEJ29/
Usage:
<code>  // Pass in a selector string for the container
$('input').charCount({container:'#container'});
</code>
Plugin:
<code>(function($) {
    $.fn.charCount = function(options){
        // default configuration properties
        var defaults = {
            allowed: 150,
            warning: 25,
            css: 'counter',
            counterElement: 'span',
            cssWarning: 'warning',
            cssExceeded: 'exceeded',
            counterText: '',
            container: undefined // New option, accepts a selector string
        };

        var options = $.extend(defaults, options);

        function calculate(obj,$cont) {
              // $cont is the container, now passed in instead.
            var count = $(obj).val().length;
            var available = options.allowed - count;
            if(available <= options.warning && available >= 0){
                $cont.addClass(options.cssWarning);
            } else {
                $cont.removeClass(options.cssWarning);
            }
            if(available < 0){
                $cont.addClass(options.cssExceeded);
            } else {
                $cont.removeClass(options.cssExceeded);
            }
            $cont.html(options.counterText + available);
        };

        this.each(function() {
         // $container is the passed selector, or create the default container
            var $container = (options.container)
                    ? $(options.container)
                        .text(options.counterText)
                        .addClass(options.css)
                    : $('<'+ options.counterElement +' class="' + options.css + '">'+ options.counterText +'</'+ options.counterElement +'>').insertAfter(this);
            calculate(this,$container);
            $(this).keyup(function(){calculate(this,$container)});
            $(this).change(function(){calculate(this,$container)});
        });

    };
})(jQuery);
</code>

Javascript character counter help