Theming Print PDF module output when used on non-content page (views)

Question: I have a View that has an enabled PDF version feature provided by the Print module (http://drupal.org/project/print). Its ok, but I'd like to tweak the output table with theming. According to the module documentation pdf output can be altered using these files:
- To modify the template of printer friendly pages, simply edit the
print.tpl.php or the css/print.css files.

- It is possible to set per-content-type and/or theme-specific templates
  which are searched for in the following order:
   1. print_[format].node-[type].tpl.php in the theme directory
   2. print_[format].node-[type].tpl.php in the module directory
   3. print_[format].tpl.php in the theme directory
   4. print_[format].tpl.php in the module directory
   5. print.node-[type].tpl.php in the theme directory
   6. print.node-[type].tpl.php in the module directory
   7. print.tpl.php in the theme directory
   8. print.tpl.php in the module directory (supplied by the module)

  format is either html, mail or pdf, and type is Drupal's node type (e.g.
  page, story, etc.)

My question is how to do the same when I use this module not on a specific node type but on a view? The views module's theming information table is unaware of the Print module so the possible theming *.tpl.php files are not shown there.
Supposing that the name of my view is foobar, what tpl.php file should I use?
(Views PDF module is not an option for me as it fails on my special characters..)
Answer: The .tpl file for a View with machine name "myview" would be views-view--myview--page.tpl.php. Following that convention and what the print module reports, I would try creating a .tpl called print.views-view--myview--page.tpl.php. Include <?php print $content; ?> in this file, clear Drupal's cache, visit the View's print page, and see if it registers.
Edit: Try and throw something like this in your theme's template.php file:
function mythemename_preprocess_node(&$vars) {
  // Something to make sure they're on your View.
  if (arg(0) == 'my_view' && arg(1) == 'print') {
    // Add a new template suggestion...
    $vars['theme_hook_suggestion'] = 'print__view_page'; // and then make a print--view-page.tpl.php file.
  }
}

Comment: Tried `print.views-view-myview--page.tpl.php`, `print.views-view-myview.tpl.php`, `print.views-view-myview--default.tpl.php`, `print.views-view-myview--.tpl.php` but none of them worked.. I flushed the the cache between the calls.
Comment: I'm trying to figure out from the source how does it work, but I lack the necessary Drupal API knowledge.. :(
Comment: You can manually suggest the .tpl file to Drupal. I will throw some code in my answer.
Answer: I have achieved this implementing template_preprocess_print() function in my theme's template.php file.
function MYTHEME_preprocess_print(&$variables) {
  // Check if the page is not a node
  if (!isset($variables['node']->type)) {
    // Remove all other template suggestions, since they are for nodes, we don't need them.
    $variables['theme_hook_suggestions'] = array();
    // Check if the page is a view page
    $views_page = views_get_page_view();
    if (is_object($views_page)) {
      // Add template suggestions
      $variables['theme_hook_suggestions'][] = "print__view";
      $variables['theme_hook_suggestions'][] = "print__view__" . $views_page->name;
      $variables['theme_hook_suggestions'][] = "print__view__" . $views_page->name . '__' . $views_page->current_display;
    }
  }
}

With this code in template.php, after flushing the theme registry cache, you have following template suggestions:

print--view.tpl.php
print--view--VIEW-NAME.tpl.php
print--view--VIEW-NAME--DISPLAY-NAME.tpl.php


Theming a view of comments

Question: I have a view which creates a block of comments.  I have a comment.tpl.php in my theme folder which I use to theme the comments on the node.
To theme the view, I need a variant of comment.tpl.php and have tried the following:
comment-view.tpl.php
comment-views.tpl.php
comment-view--name-of-view.tpl.php
comment-view-name-of-view.tpl.php
After cache clearing each option the template is still not picked up.
How can I theme this view please?  By the way I am using the Omega theme.
Comment: I don't have time to look into it too deeply right now, but basically you'll be implementing `hook_preprocess_comment()` at the theme/module layer, trying to find some sort of reference to the `$view` object inside the `$vars` array that's passed in, and adding something like: `$vars['theme_hook_suggestions'][] = 'comment__' . str_replace('-', '_', $view->name);`. After a cache flush the corresponding template file should work (e.g. `comment--name-of-view.tpl.php`)
Comment: what version of views are you running? have you explored `Theme:Information` that is available for each view? You are probably interested in the field content template file. just a guess there.
Comment: Using views 3, the templates in theme:information do not contain the variables in comment.tpl.php.  That is why i need to override comment.tpl.php
Comment: any reason for voting this down or do you not really have a reason?
Comment: I'm pretty sure there's no built-in support to override comment.tpl.php on a per-view basis (if it's not in theme:information then that's true). You'll need to implement the [theme hook suggestions](http://drupal.org/node/1089656) yourself
Comment: Hi @Clive, thanks a lot for the advice, sounds right - but what does this actually mean, could you explain a little more please?  I need to access the variables in comment.tpl.php but in a template made just for the view.  THanks
Comment: +1 for clive. i was actually just thinking the same thing for this to be done in preprocess
Comment: I've added an answer to this, thanks a lot @clive for your help.  Not sure if it's best practice though?
Comment: @rix That's absolutely spot on :)
Comment: Thanks so much for your help, i just had a breakthrough today in terms of theming :)
Answer: Ok, I came up with some sort of solution, thanks to @clive.
<code>function hook_preprocess_comment(&$vars){
    if (isset($vars['view'])) {
        $view = $vars['view'];

            if ($view->name == "my_view_name"){
            $vars['theme_hook_suggestion'] = 'comment__' . str_replace('-', '_', $view->name);
    }
  }
}
</code>
I tried to do $vars['theme_hook_suggestions'][] but those templates were never picked up.  Is it ok to directly set theme_hook_suggestion.
Really hope this helps someone else out there..
Answer: When in the views UI, under 'advanced' on the right hand side, down the bottom you will see 'Theme' with a link next to it saying 'information' (under the 'Other' heading). Click the information link to see many template file name suggestions.
Comment: As stated, I need to override comment.tpl.php as it contains the variables needed for theming.

Theming a view of comments


How can I programmatically reorder active menu items?

Question: I have an 'audience' menu which has 4 links. When a user visits one of these links, it becomes active, and I want to push it to the front of the menu item list. Outcomes would like like;
Pitchers | Catchers | Hitters | Coaches
Coaches (active) | Pitchers | Catchers | Hitters
Catchers (active) | Pitchers | Hitters | Coaches
Hitters (active) | Pitchers | Catchers | Coaches

How can I accomplish this programmatically? I can't seem to find the right theme_ or hook_ api function to pull this off.
I've tried this, and changing the '#original_link' weight didn't seem to make a difference (note, I have other things going on here):
function apple_menu_link__menu_audience_gateway(&$vars) {
  $element = $vars['element'];
  $submenu = '';

  if($element['#original_link']['in_active_trail'] == TRUE) {
    $element['#original_link']['weight'] = 50;
  }

  if ($element['#below']) {
    unset($element['#below']['#theme_wrappers']);
    $submenu = '
' . drupal_render($element['#below']) . '
';
  }

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);

  return '
' . $output . $submenu . '
';
}

Also, I'm using Panels, Panels Everywhere, Page Manager, and MiniPanels — this could inform the ultimate solution.
Thanks all.
Answer: You need to use hook_menu_alter.
Make sure you declare the function with the & in front of items argument, this is what allows the function to modify the $items array passed to the function:
function MYMODULE_menu_alter(&$items)

In your function you can access every menu item in an array structure like so:
   $items['node/%/edit/schedulenew'] = array(
            'title' => 'Schedule1',
            'access callback'=>'user_access',
            'access arguments'=>array('view cssswitch'),
            'page callback' => 'cssswitch_schedule',
            'page arguments' => array(1),
            'type' => MENU_LOCAL_TASK,
            'weight'=>4,
        );

If you just redefine the 'weight' property, it will allow you to re-order your menus.

Be sure to clear your cache after each menu changes, or go to the menu page, load the menu edit page and save it, this also rebuilds the menu.
Comment: I'm under the impression that hook_menu() and hook_menu_alter() are only invoked when Drupal rebuilds the menus. When a user visits one of the links it becomes 'active' and then I want it to reorder based on that interaction — not based on menu rebuilds.

My post may not be clear enough: suggest an edit?
Comment: Also, I'm using Panels Everywhere (& Page Manager, MiniPanels), which may alter the ultimate solution.
Comment: I saw your edit. You would need js for this, it seems. There is possibly a module that does something similar you could check the code for inspiration.
Comment: Thanks @stefgosselin. After 5 years of Drupaling, this is one of a handful of times Drupal hasn't had a straight-forward way of doing something. Maybe I'll package this into a module!


error implementing strstr() function

Question: I  have implemented strstr() but the code has is not working please help:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
char* mystrstr(char*,char*);
int main()
{
    char *s1,*s2,*flag;
    printf("Enter a string:\n ");
    gets(s1);
    printf("Enter a word to find in it:\n");
    gets(s2);
    flag=mystrstr(s1,s2);
    if(flag)
        printf("Word found\n");
    else
        printf("Word not found");
    getch();
    return 0;
}
char* mystrstr(char* s1,char* s2)
{       int flag=0,j,i;
    char* temp;
    for(i=0;i<strlen(s1);i++)
     {  if(*(s1+1)==s2[0])
        {
            for(j=1;*s2;j++)
            {
            if(*(s1+i)==*(s2+j))
            flag=1;
            else
            flag=0;
            }
        }
     }
     if(flag)
     {
     temp=(char*)malloc(sizeof(char*));
     itoa(j,temp,10);
     return *temp;
     }
     return 0;

}

Comment: very bad code, consider studying.
Comment: what problem are you facing?Is it not working the way you want?
Comment: What you have written is not strstr but i get the intent. Break the problem into steps.
Comment: I think You cal that as a function but where you declare your function  in the program
Comment: from code it looks like you are trying to find the substring s1 in string s2 then i don't think your logic of internal loop is correct.
Answer: Some quick tips:

Allocate memory to pointers or use arrays
Read more on pointer arithmetic here
Read about strstr and think of an algorithm to do so or google
More on itoa, specifically read the return value.
Answer: For starters, you might want to read on how 'gets' works:
http://en.wikipedia.org/wiki/Gets
You're just declaring pointers on the stack in your main-method. These pointers will probably point to some random memory. As mentioned in the comments above you will have to allocate memory either on the heap using 'malloc' (s1 = malloc(256);) or on the stack with f.ex. 'char s1[256];' etc. and then passing the address to it to gets with 'gets(&s1);' instead
Comment: What I meant was that you'll have to use gets(&s1); if you're allocating memory on the stack with 'char s1[256]'. Not when using pointer and malloc, then you're correct
Comment: No. this has nothing to do with stack vs malloced memory. gets(&foo); is wrong if it's a char foo[32]; and it's wrong when it's a char *foo = malloc(32);
Comment: Sorry about that! you're correct. Guess you'll have to write gets(&s1[0]) if you want a similar effect =)
Answer: conio.h is not ANSI C
getch is not ANSI C
itoa is not ANSI C
Your function returns a string contains a positionnumber in s2. Is this right for you?
The return must be freed.
Do you know an array-access? Better than *(s2+j) is s2[j].
if(*(s1+1)==s2[0]) should be if(*(s1+i)==s2[0]) or not?
for(j=1;*s2;j++) should be for(j=1;s2[j];j++) or not?
In the case flag=0 a break is missing, see other answers.
Answer: for(i=0;i<strlen(s1);i++)
 {

        for(j=0;strlen(s2);j++)//and here
        {
        if(*(s1+i+j)==*(s2+j)){//here
        flag=1;}
        else{
        flag=0;break}
        }
 if(flag){break;}

 }

Comment: Correct me if i did something wrong because I didn't hear about c very much.
Answer: Did you check for the first characters?
if(*(s1+1)==s2[0]) // you are checking s1[1] against s2[0]

This is infinite loop unless s2[0] is a null character in the first place or you break from the loop using break;
for(j=1;*s2;j++)

A recrusive approach for your reference:
char* my_strstr(char* s1, char* s2) {
  // return null pointer for empty strings
  if (strlen(s1) == 0 || strlen(s2) == 0)
    return 0;

  // recursive part
  if (s1[0] == s2[0]) {
    if (strlen(s2+1) == 0 || (strlen(s2+1) != 0 && my_strstr(s1+1, s2+1) == s1+1))
      return s1;
  }
  else return 0;
}

Comment: Your code doesnt seem to work my friend.Its not finding the string.
Answer: Java code to implement strstr()
class Solution {
public int strStr(String haystack, String needle) {
    String res ="";
    int pos = 0;
    if(needle.length() == 0){
        return 0;
    }
    if(haystack.equals(needle)){
        return 0;
    }
    if (needle.length()>haystack.length()||haystack.length() == 0){
        return -1;
    }
    for(int i =0; i<haystack.length();i++){
            if(haystack.charAt(i) == needle.charAt(0)){
                if(i+needle.length() <= haystack.length()){
                res = haystack.substring(i,i+(needle.length()));
                if (res.equals(needle)){
                pos = i;
                return pos;
                }
        }
                else{
                    return -1;
                }
            }
            else{
                continue;
            }
        }
        return -1;

}
}

error implementing strstr() function


Optional OrderBy parameter in MySql Stored Procedure

Question: I'm being passed in an optional OrderBy value that should default to DESC, and if set to false, should ORDER BY ASC. I'm not really sure how to do this ordering based off the input. Here is what I have currently:
CREATE DEFINER=`app`@`%` PROCEDURE `BLAH`(
pWithdrawalTransactionId INT,
pLimit INT,
pSortDescending TINYINT
)
BEGIN
    DECLARE vLimit INT DEFAULT COALESCE(pLimit, 100);
    DECLARE vSort TINYINT DEFAULT COALESCE(pSortDescending, 1);

    SELECT
        f.WithdrawalFulfillmentId, f.PaymentStatusId, f.PaymentProcessorId, f.PaymentTypeId, r.Amount, r.RequestedAmount, r.NativeAmount, r.NativeRequestedAmount, r.RefundTransactionId, r.UpdatedDate
    FROM
        FinOps.UserWithdrawalFulfillment f
    INNER JOIN
        FinOps.UserRefundTransaction r ON f.RefundTransactionId = r.RefundTransactionId
    WHERE
        f.WithdrawalTransactionId = pWithdrawalTransactionId
    LIMIT
        vLimit;
END

Comment: It depends on what column(-type) you want to order by and if you need your indexes to work with the ordering (e.g. if you have a composite index that includes `WithdrawalTransactionId` or `RefundTransactionIdand` and your ordering column)
Comment: I would want to order by the WithdrawalTransactionId, if that helps. But the real struggle is the optional part
Answer: So the correct way to do this would be like this:
CREATE DEFINER=`app`@`%` PROCEDURE `BLAH`(
pWithdrawalTransactionId INT,
pLimit INT,
pSortDescending TINYINT
)
BEGIN
    DECLARE vLimit INT DEFAULT COALESCE(pLimit, 100);
    DECLARE vSort TINYINT DEFAULT COALESCE(pSortDescending, 1);

    SELECT
        f.WithdrawalFulfillmentId, f.PaymentStatusId, f.PaymentProcessorId, f.PaymentTypeId, r.Amount, r.RequestedAmount, r.NativeAmount, r.NativeRequestedAmount, r.RefundTransactionId, r.UpdatedDate
    FROM
        FinOps.UserWithdrawalFulfillment f
    INNER JOIN
        FinOps.UserRefundTransaction r ON f.RefundTransactionId = r.RefundTransactionId
    WHERE
        f.WithdrawalTransactionId = pWithdrawalTransactionId
    ORDER BY CASE WHEN pSortDescending = 1 THEN WithdrawalFulfillmentId * -1 ELSE WithdrawalFulfillmentId END ASC
    LIMIT
        vLimit;
END


Get page title of view and panel page via url

Question: Is there any way to get page title of view and panel page using url. I tried
<code>$normal_path = drupal_get_normal_path($path);
$item = menu_get_item($normal_path);
$title = $item['title'];
</code>
and it is giving empty title while it is working well for normal node.
Please suggest.
Answer: For pannel you can pass the page title in url
let say xyz/page_title
then add content to panel and choose New custom content in the body field your code will somewhat look like
<code><?php
  $title = arg(1);
  drupal_set_title($title);
?>
</code>
check screenhot for better understanding:
For views its a simple 2 step process
step1: Set the view path to take the title as wildcard
i.e. your view path will be view_path/%

step2: now change the title field on views to use the title wildcard by changing it to %1 as this is the first argument in the url

hope it helps you :)
Comment: I missed out to put
,"to use php in the body field you should have php filter module enabled."
Comment: Thank you arpitr. It can be helpful for new panels and views. But I cannot turn on php filter. :-(
Comment: cissharp you don't need php filter turned on for changing title in views.


String from input tag on JSP work don't correct in SQL query

Question: i have some trouble when trying to search some data in my data base.
I have input tag where i write some text, then it from JSP gets to controller, service, and in dao i have a query where put this String into the query, when this String is in English - all works fine, but when i write String in Ukrainian searching don't work. Can someone help ?
JSP page
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form"
uri="http://www.springframework.org/tags/form" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
     pageEncoding="UTF-8"%>
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Головна сторінка</title>

<link href="<c:url
value="../../resources/bootstrap/css/bootstrap.min.css"/>"
rel="stylesheet"/>

<c:url var="addUrl" value="/main/mainFrame/new"/>
<c:url var="searchResult" value="/main/resultOfSearching"/>

<button type="button" class="btn btn-primary btn-
lg btn-block" style="margin-left:auto;

margin-right:auto;

width:250px;

margin-top:50px;">Додати звернення</button>

<form:form method="GET" action="${searchResult}"
modelAttribute="ListOfAppeals">

    <input type="text" formenctype="text/plain" name="searchChar"
class="form-control" placeholder="Введіть ідентифікатор для пошуку">

    <button class="btn btn-primary" type="submit">Пошук</button>

</form:form>

searchingResult JSP page

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<link href="<c:url value="styles/searchingResultPage.css" />"
rel="stylesheet">
<link href="<c:url
value="../../resources/bootstrap/css/bootstrap.min.css" />"
rel="stylesheet">
<title>Результати пошуку</title>

Список звернень (запитів)

    #
    Номер звернення (запиту)
    Вхідний номер
    П.І.Б. народного депутата
    Резолюція керівника
    Тип документу
    Дії з
документом

<c:forEach items="${ListOfAppeals}" var="Appeals">

        <c:out value="${Appeals.id}"/>

        <c:out
value="${Appeals.number}"/>
        <c:out
value="${Appeals.incomingDate}"/>
        <c:out
value="${Appeals.nameOfDepute}"/>
        <c:out
value="${Appeals.resolutionOfChief}"/>
        <c:out
value="${Appeals.typeOfAppeal}"/>
        <button type="button" class="btn
btn-danger btn-sm">видалити</button>
            <button type="button" class="btn btn-warning btn-sm"
style="margin-left: 5px;">редагувати</button>

</c:forEach>

Controller method
@RequestMapping(value = "/resultOfSearching", method =
RequestMethod.GET)
public String getSearchResult(Model model,
@ModelAttribute("searchChar")String searchResult)  {
    List<DeputesAppeal> deputesAppeals =
deputesAppealService.abstractSearch(searchResult);
    model.addAttribute("ListOfAppeals", deputesAppeals);
    return "searchingResultPage";
}

Service method
public List<DeputesAppeal> abstractSearch(String searchingChar) {
    return deputesAppealDao.abstractSearch(searchingChar);
}

and DaoLayer
public List<DeputesAppeal> abstractSearch(String searchingChar) {
    Query query = sessionFactory.getCurrentSession().createQuery("from
DeputesAppeal where concat(NumberOfAppeal, DateOfIncomingAppeal,
NameOfDepute, ResolutionOfChief, TypeOfAppeal)  like '%" +
searchingChar + "%'");
    return query.list();
}

when sql logs
  from DEPUTES_APPEAL deputesapp0_ where concat(NumberOfAppeal,
    DateOfIncomingAppeal, deputesapp0_.NameOfDepute,
    deputesapp0_.ResolutionOfChief, TypeOfAppeal) like '%[B@7c815681%'

Comment: Do you have UTF-8 encoding?
Comment: where ? i am work on ubuntu
Comment: I had a problem with Russian language due to improper encoding - I set UTF encoding in MySQL (you can read this manual http://gahcep.github.io/blog/2013/01/05/mysql-utf8/), during connection to database (something like this jdbc:mysql://127.0.0.1:3306/database_name?useUnicode=true&characterEncoding=UTF8&characterSetResults=UTF-8) and also added Filter for application in WebInitializer (you can see example here https://github.com/lenach87/Ochumailoc/blob/master/src/main/java/mailoc/config/WebInitializer.java). Hope this would be helpful to you
Comment: this word doesn't have any bind with data base
Comment: `formenctype="text/plain"` might be the culprit. Also you should not use string concatenation to build query
Comment: please debug and see which type is passed to getSearchResult method, because i see 'like '%[B@7c815681%'' in your log means that was passed as an object other than string.
Answer: I think you can use Character encoding filter like this (in your web.xml file):
<filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

and put this filter the first filter in your web.xml
Comment: i have this filter, what do you mean under "And also replace UTF-8 with your desired character encoding"
Comment: I didn't know which character encoding must be used for your language
Comment: Did you define mapping for UTF-8 filter?

CharacterEncoding
/*


HTML nested lists in Wordpress

Question: I'm trying to do nested, ordered lists using ol types and though the code looks right in the Wordpress preview, it doesn't show correctly when I preview in Firefox and IE, the lists all show as numbered lists instead of the types I specified in the code. My code is below. Can someone help me find what's wrong?
Thanks in advance for any help!
Kelly
Teaching your kids about money isn't always child's play. But helping them make smart choices early will pay off later.
Baby Steps

Even the cartoon set can learn the value of a dollar. Some simple ideas:

Show your toddler the various coins in your pocket or change purse and see if the clever tyke knows what each one can buy.

Gum machines or mechanical rides still take coins. Or try old-fashioned "penny candy" shops, even if that bubble gum goes for a dime now.

How many coins are necessary to buy a popsicle or frozen yogurt at the ice cream truck?

Field trip: checking the prices at the grocery store can be instructive for kids —and their parents, too!

Where does money come from (besides the ATM machine)? Discuss getting paid for work and how your salary lets you buy things for the family.

Lemonade stands still do a thriving business for first-time entrepreneurs.

Old toys can be contributed to Mom's and Dad's yard sale to score a profit.

Discuss the best way to invest the proceeds with your tiny mogul. Hint: don't blow it all on candy or games.

Older kids can understand the difference between necessary and optional purchases. Milk or gummi bears?

Here's Your Allowance

Yep, it's still a great teaching tool after all these years. Some ways to get with the program:

Doling out the cash on a weekly basis makes sense. Even older kids may find it tough to budget a month in advance.

Decide whether there will be strings tied to the stipend. Will Junior have to complete household chores before you fork over the cash?

Some families think helping around the house should be expected and unrelated to the weekly payout.

Other parents think it's a good way to introduce the idea of working for money and getting paid for a job well done.

In coming up with a dollar amount, savvy parents will not fall for reports of what the other parents are shelling out. Multiplying your own allowance in the distant past by the rate of inflation may be a good starting point.

Answer: To nest one list inside another, you have to place it inside a
 element. You can't put it directly inside an
 element.
In other words, replace this:

...

with this:

...

Answer: I tested both a non wordpress html page and wordpress entry.  My guess is wordpess is stripping your type tag so try using CSS. Give each
 a class and for your css use list-style-type to declare the list-item marker type.
ie:
ol.lower-alpha {list-style-type:lower-alpha}
li.lower-latin {list-style-type:lower-latin}

HTML nested lists in Wordpress


How to hook on paragraph deletion?

Question: I'm on D9 and I've a paragraph inside a content type node.
I need to hook when the paragraph is deleted to do some custom logic and set up a queue.
I've tried hook_entity_delete, hook_entity_predelete or hook_paragraph_delete, hook_paragraph_predelete:  those hooks run during cron, if the node containing the paragraph is deleted.
However, it seems to me those aren't triggered if an existing paragraph is deleted via the widget inside the edit form of the node.
Is there a way to intercept that case/solve my problem?
Comment: when you remove the paragraph from content you delete the reference not the paragraph item, so it's normal that none of those hooks is triggered
Comment: @berramou That's true, but I expected they would trigger during cron, because I supposed paragraphs with no references were deleted. However after checking the DB effectively they don't seems to be deleted.
Answer: You need to implement a node update hook and compare the paragraph IDs:
use Drupal\node\Entity\NodeInterface;

/**
 * Implements hook_ENTITY_TYPE_update() for node entities.
 */
function mymodule_node_update(NodeInterface $node) {
  if ($node->getType() == 'my_content_type') {
    $ids = array_column($node->field_paragraph->getValue(), 'target_id');
    $original_ids = array_column($node->original->field_paragraph->getValue(), 'target_id');
    // compare IDs
  }
}

If this is a nested paragraph then use hook_paragraph_update() for the parent paragraph type.
Comment: In case if site is multilingual and asymmetric workflow for paragraph is used.

Use this $node->original->getTranslation($node->language()->getId())->field_paragraph->getValue(); to get the original ids before update

How to hook on paragraph deletion?


How to remove Page cached by boost message in view source

Question: I installed Boost and the page cached by boost will have a line of message at the bottom of view-source.

How to remove the above line?
Answer: This is not possible in the 7.x-1.x version of the module (unless you patch the code). You should file a feature request in the Boost issue queue.
If you want to temporarily patch the code, open the file boost.module, around line 1145:
  $types['text/html'] = array(
    'title'           => t('HTML'),
    'description'     => t('HTML output, usually a webpage'),
    'extension'       => 'html',
    'enabled'         => TRUE,
    'gzip'            => TRUE,
    'lifetime_max'    => 3600,
    'lifetime_min'    => 0,
    'comment_start'  => NULL, // <--- set to null
    'comment_end'    => NULL, // <--- this too
    'variants'        => array(),
  );

If you would like to contribute a patch, which would be greatly appreciated, the right way to do this would be to modify the boost_exit() function, around line 315:
  // Add note to bottom of content if possible.
  if ($_boost['matched_header_info']['comment_start'] && $_boost['matched_header_info']['comment_end'] && $_boost['matched_header_info']['comment_footer_enabled']) {
    $expire = $_boost['matched_header_info']['lifetime_max'];
    $cached_at = date('Y-m-d H:i:s', REQUEST_TIME);
    $expires_at = date('Y-m-d H:i:s', REQUEST_TIME + $expire);
    $note = "\n" . $_boost['matched_header_info']['comment_start'] . 'Page cached by Boost @ ' . $cached_at . ', expires @ ' . $expires_at . ', lifetime ' . format_interval($expire) . $_boost['matched_header_info']['comment_end'];
    $data .= $note;
  }

You would also have to set the default (TRUE) in boost_boost_storage_types(), and to the $keys in boost_get_storage_types() so that it does the variable_get(). Bonus points for also exposing it to the admin interface.


ASP.Net MVC Model Binder - Ignore Properties

Question: I have an ASP.Net MVC5 site using Entity Framework 6.
I am using ASP.Net Identity role-based security that performs granular security checks within the page to determine if certain input fields should be visible to the user.  i.e.
@if (User.IsInRole(MyProj.Security.Roles.ViewSocial)) {
   @Html.TextBoxFor(m=> m.SSN)
}

If the user does not have the permission, the input field is not created and thus the model binder will blank out the value of this property.
How can I work this so that it ignores these properties in the case where they are not being displayed for edit?
@Html.HiddenFor() will not work because I can't have the tags included in the client-side HTML where the values can be seen in the source.
Will I need a custom model binder in this scenario?
Comment: I would argue its the ideal approach. A view model is always the best approach to render the view, and on post back, the data model is retrieved, updated based on the view model, and saved. The custom `ModelBinder` in the Jenish's answer may help encapsulate some of the authorization logic, but it still leaves the value of `SSN` null if `User.IsInRole` is `false` so your still facing the same problem - the saved value will be `null`.
Comment: Do you mean that you have validation attributes that are causing you model to be invalid when you post back?
Comment: I think OP means that a malicious user could post back form values that they shouldn't have access to. Trying to make it so that model binding only occurs for fields with which they are authorised.
Comment: When these fields are not created in the page, on post-back (for edits) the associated value in the database is set to NULL when it should retain its existing value.  This is the case when the initial record is created by someone with the permission, and subsequently edited by someone without it.
Comment: Then you should get the original model from the database, and update its  relevant properties from the view model
Comment: Ok, I can re-pull the original model in the POST on edit and put original values back if they don't have permissions (the ones the model binder wiped out).  I was just wondering if there was a better approach, it doesn't seem ideal.
Comment: @StephenMuecke return new instance is just for example. he would first get the instance he want to update by id from the db and then update the property in binder so in this way it wont be null.
Comment: Exactly, but OP was stating _it doesn't seem ideal_ (and all that's needed in the POST method is `@if (User.IsInRole(MyProj.Security.Roles.ViewSocial)) { model.SSN = viewModel.SSN };` (in which case the custom `ModelBinder` is not required)
Comment: @StephenMuecke  I am recommending that approach because it would be reusable. any time he would access that model in controller, logic will not be required to be written again.
Comment: @JenishRabadiya, I not arguing against it (as I noted above in my 3rd comment). Just pointing out that it does not solve the problem of `NULL` being saved in the database.
Comment: @StephenMuecke it will solve that problem if he would fetch data from database in BindModel method and then assign relavant properties from request.
Comment: @JenishRabadiya, Yes I know. That's the whole point of all my comments (In response to OP's second comment)
Answer: Yes you should do something because even HTML input can be injected through developer tools in modern browser and it will get posted to the controller and you would believe he is authorized but he is actually not.
Yes definitely you need to prevent malicious user to do so. Two option is there.

you can do right logic of validating user by checking if he is authorized to do so or not.
As you suggested in the code apply custom model binder for that and only set that property if he is authorized to do so.
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    if (bindingContext.ModelType == typeof(HomePageModels))
    {
        HttpRequestBase request = controllerContext.HttpContext.Request;

        string title = request.Form.Get("Title");
        string day = request.Form.Get("Day");
        string month = request.Form.Get("Month");
        string year = request.Form.Get("Year");
        if(User.IsInRole("Admin"))
        {
        string SSN = request.Form.Get("SSN");
        }
        return new HomePageModels
        {
            Title = title,
            Date = day + "/" + month + "/" + year,
            SSN = SSN
        };
        //// real time HomePageModels instance should be loaded from database here to avoid saving null if person is not authorized to do so
    }
    else
    {
        return base.BindModel(controllerContext, bindingContext);
    }
}

Comment: Good point about injection of the secured fields.  I went with this approach but cleaned it up a bit.  I called to the default model binder and then simply overwrote values with the values from the original model where the user did not have the proper security.  It works as expected.
Comment: I know this is old but a better solution would be to override GetModelProperties() and then exclude any properties that shouldn't be bound from the return value - thus inheriting from the defaultbinder does most of the work. You could create an attrib to put on the property which security role applies to the field thus the custom binder would not have to be so tightly coupled and could be generalised more.


Set autotcomplete textbox text programmatically with Angular Material

Question: I'm using Angular Material for creating a form. For some fields the user should get a autocomplete function. Those fields should be also populated from the backend, if the user provides a serial number.
My question is, how can I set the text of a textbox which is linked to a autocomplete via code?
I copied a StackBlitz and modified it to match my scenario:
https://stackblitz.com/edit/angular-material-autocomplete-async1-jxrahv?file=src%2Fapp%2Fapp.component.ts
If you click on the "click me!" Button, I want the text of the textbox to change to "Windstorm" (which doesn't happen).
Thanks!
Comment: well your actual form control value is an object and you are trying to set the value with a string, so it won't work. If you enter it as an object, it will work: https://stackblitz.com/edit/angular-material-autocomplete-async1-8nneha?file=src/app/app.component.ts
Comment: @AJT_82 is right. Once you added `[matAutocomplete]="auto"` to input MatAutocompleteTrigger  value accessor starts handling all forms events. And MatAutocompleteTrigger uses displayWith method to write in input value. https://github.com/angular/material2/blob/57aadc2588c3a745278c368d22c6d5a4471c3a3b/src/lib/autocomplete/autocomplete-trigger.ts#L521
Comment: Being agains the rules and totally off-topic: Very nice to see you again @yurzui Long time no see. All good I hope! :)
Comment: @AJT_82 Yes, all goes well, thanks. Have you decided to remember the angular forms?)
Comment: @yurzui Haha :D Yeah! My newest passion is ionic though. Work has gotten me into learning and developing with ionic, and I love it! :)
Comment: @AJT_82 Thanks man! This was really great! Could you please post an answer to this question so I can mark it as answer and you earn some points?
Answer: You are feeding your autocomplete with array of objects, so when you are trying to set the value with "just" a string:
this.usersForm.get('userInput').setValue("Windstorm");

... it will not work. Set the whole object as value, and you're good! :)
this.usersForm.get('userInput').setValue({ id: 1, name: 'Windstorm' });

Modified StackBlitz
Comment: Haha :D Yeah, was good! BTW, glad we got your problem sorted out, have a good end of the weekend and happy coding! :)


How to Apply an equation to a Pandas dataframe ByGroup

Question: Its that time of the day when I have been banging my head against the keyboard too long and I would appreciate any advice.  My over all goal is to ingest a datafile of hourly Temperature which has gaps in it.   I want to fill those gaps using a linear regression with Temperature from a nearby site.  But I want to do this BY YEAR and BY MONTH.  So with help from folks here I have been able to do much of this.
Now I have applied a linear regression function BY YEAR AND MONTH like
Corr_grouped=DF_grouped.apply(lambda x: stats.linregress(x [Labels[0]], x [Labels[3]]))

This has produced the following which has outputs of slope, intercept, r_value, p_value, std_err and displays like this.
> 2010  1     (0.806190897504, 5.75672188581, 0.901179913935...
>       2     (0.739906365408, 8.05204746237, 0.894050112908...
>       3     (0.773199101365, 6.88505178697, 0.898475211997... ...
>       10    (0.87497855294, 4.10227036556, 0.939948762031,...
>       11    (0.793072407801, 6.38604194806, 0.923659962858...

I have been reading all day by cant find and exact solution.  Now my question is how do apply this back to the original data frame.  I would like a new column in the DF that applies the linear regression y=mx+c to each line in the original data using the column 3 as the input BUT to do that using the specific coefficients (slope, intercept) that are different for each YEAR and MONTH.  Any ideas most welcomed :)
Cheers
Jason
EDIT:
Great.  So the DF looks like this.  It has timestamps every 30 minutes for multiple years.  It has gaps (NaN) that may be 1 or multiple intervals.  I need to fill in the gaps in the original column (T_original) using a relationship with a nearby station (T_nearby). But it is not a simple substitution.  The site is often some distance away and the temperatures are correlated but not the same (i.e. one may be 2oC hotter).  SO the T_nearby station has to be adjusted first then used to fill the gap.
                        T_original  T_nearby
2010-01-01 00:00:00  25.87873       25.4
2010-01-01 00:30:00  25.73089       25.4
2010-01-01 01:00:00  25.56144       25.4
2010-01-01 01:30:00  NaN         25.4
2010-01-01 02:00:00  25.24789       25.6
2010-01-01 02:30:00  25.17758       25.4
2010-01-01 03:00:00  NaN         25.6
2010-01-01 03:30:00  NaN         25.6
2010-01-01 04:00:00  25.07633       25.6
2010-01-01 04:30:00  24.99211       25.5

I want to breakdown the analysis by YEAR and MONTH.  So for each month of each year to calculate a linear regression fit between T_original and T_nearby.  This gives the grouped object above which has the linear regression parameters. For example year 2010 and month 1 the intercept is 5.75 and the slope is 0.806.
So I would like to apply that relationship back to all the Year=2010 and Month=1 to look like this.  Then for the rest of the DF apply the same approach for each month of each year.
    T_original      T_nearby    T_adjusted
1/01/2010 0:00  25.87873    25.4    26.2224
1/01/2010 0:30  25.73089    25.4    26.2224
1/01/2010 1:00  25.56144    25.4    26.2224
1/01/2010 1:30  NaN             25.4    26.2224
1/01/2010 2:00  25.24789    25.6    26.3836
1/01/2010 2:30  25.17758    25.4    26.2224
1/01/2010 3:00  NaN             25.6    26.3836
1/01/2010 3:30  NaN             25.6    26.3836
1/01/2010 4:00  25.07633    25.6    26.3836
1/01/2010 4:30  24.99211    25.5    26.303

Then I will use the T_adjusted column to fill in the gap in T_original.
Thanks
Jason
Comment: I don't think it's entirely clear (to me) what you are asking, perhaps it would help to provide an example DF and what you want it to be? Perhaps you want an `apply` which refers to `Corr_grouped` (?)
Comment: Thanks I just edited the post to make it clearer and give an example
Answer: Your first step is to merge the grouped object with DF. To do that first create a common grouping column.
For the grouped object:
from datetime import date
grouped['common'] = grouped.index.map(lambda x : date(x[0],x[1],1))

For DF:
DF['common'] = DF.index.map(lambda x : date(x.year,x.month,1))

Now you can merge it:
merged = DF.merge(grouped)
del merged['common']

I am not sure what the exact formula for working out T_adjusted column is but now that the regression parameters are matched with T_nearby values it could be worked out with array operations.
To fill the gaps in T_original using T_adjusted:
merged['T_original']=merged['T_original'].combine_first(merged['T_adjusted'])


Can we derive a formula for the volume of revolution in polar coordinates.

Question: Can we derive a formula for the volume of revolution in polar coordinates?
My attempt was so consider a very small piece of a circle that is bounded by the counterclockwise angles $\theta$ and $\theta+d \theta$ in the $xy$ plane. Then the lines forming those angles are $y=(\tan \theta) x$ and $y=\tan (\theta+d \theta) x$. So I suppose to get the (approximate) volume obtained by rotating this little about the $x$ axis.  We should consider,
$$\int\limits_{0}^{r \cos \theta} (\tan (\theta+d \theta) x)^2-(\tan (\theta) x)^2 dx$$
This is a bit sloppy and even so, I'm not sure where to go from here.
Answer: Can't say I have seen it come up befor, but:
$V = \pi \int_{x_0}^{x_1} y^2 dx$
$y = r\sin\theta\\
x = r\cos\theta \\
dx = -r\sin\theta\  + \cos\theta \frac {dr}{d\theta}d\theta $
$v = \pi \int_{0}^{\pi} r^3\sin^3\theta\ - r^2\sin^2\theta\cos\theta \frac {dr}{d\theta} d\theta$
The limits of integration might not necessarily be $0$ to $\pi.$  But frequently enough it would be.
Comment: Thanks! ${}{}{}{}{}{}{}{}$


What does "2x and 4x with chorus" mean in music notation?

Question: I am looking at "Eight days a week" by the Beatles and here in the B section of the verse there is this "2x and 4x with the chorus" above the vocal melody and I don't know what it means. Can anyone else make sense of it? Also, in the recording I have of this song that top line really is not audible to me. I hear the main melody as the one starting on F# not A (ie: alto voice) and that top line when I play it sounds wrong so I don't know if it is just very soft in the recording. Can anyone else hear it?
Comment: While phoog solved the riddle, I'd like to point that the question bases on an assumption that the music notation is very well formalized and there is a well defined way to write everything. This is not true. There are various notations used by various communities, editors, or individual musicians. Many musicians have no or very little formal education. In case of a popular song like this there is no better way than to listen to the original. The score is there only to help to figure out how to perform (or "fake") the tune.
Comment: @Laurence got this right, +1. It has the upper harmony (sung by Paul) the second and fourth time. Both voices are double tracked which was very common on Beatles recordings. The problem is this is a very poorly written instruction. It should read "2nd and 4th time with upper harmony". The harmony is written with parentheses around it. It was not unusual for the Beatles to harmonize above the melody, it is actually a common practice in pop music.
Comment: Maybe "chorus" doesn't mean a part of the song, but a choir? Maybe this is an arrangement?
Answer: Not at all clear. Nothing to do with repeating those bars, though. As in repeating them 2x or 4x. It actually means there's harmony at that part of the song the 2nd and 4th times it comes round. As opposed to single voice (possibly double tracked, more likely unison) 1st and 3rd times. 'To chorus'? 1st and 3rd times will go into another verse, so probably that's what 2x/4x is supposed to signify.
I've also a niggle about the G♭ , maybe G6 after the Bm(?).
Yep, the bracketed notes are those sung in harmony only on 2nd and 4th times. Solved!
Comment: armani - the harmonies definitely happen on the 2nd & 4th times this section is sung, not on the 1st & 3rd. If you've got a stereo version [which the linked YouTube version is], the harmony is on the right.
Comment: Yup, unison 1 & 3, harmony 2 & 4. I think it's Paul on the DT/hrm right the way through, rather than John DT. I think 'with chorus' is just the 2 & 4 are before a chorus, 1 & 3 go round another verse. Maybe the score splits again where we can't see it from the snippet.
Comment: @Tetsujin - was listening to the track as you wrote! Edited accordingly.
Comment: Yeah - I dragged it out for a quick listen too. They were a bit good, weren't they, even just with a 'live band' setup.
Comment: @Tetsujin - I remember singing this in groups in the '60s, but never picked up on the unison/harmony. Must listen more carefully...
Comment: ok so is that why those top notes are in brackets? like they would only be sung 2nd and 4th times? Although from memory I dont recall hearing those notes in any of the verses. I will listen again when I get to the studio. To me the melody IS the one starting on F#
Comment: Went back for another listen and to me, the second time this verse is sung, the same melody is used and any doubling sounds like a unison not like a 3rd above.. perhaps have a listen and see what you think for yourself?
Comment: Tim - Bm, G6, Bm, E, I always thought. [I'm always open to correction, as I have cloth ears;)
Answer: It means "second time, fourth time with chorus."  This agrees with the fact that the second and fourth times these measures are sung, there is harmony, but if that's really what it means, it's a bit of an odd way to say it, because, while the first and third renditions don't have harmony, they do have multiple voices—singing in unison.
The idea that this indicates when must go on to the chorus isn't borne out by this video, at least, where the bridge follows instances 2 and 3, while 4 is followed by the coda and the end of the song.
Comment: If the 2nd and 4th verses did have "harmony" then I would totally understand but the 1st verse is exactly the same as the second, there is no A sung above the F#, at least not to my ears... maybe somebody hears something I don't but at least listen to the recording to confirm that is in fact what it is saying.
Comment: Ah, OK, the 'chorus'/break [whatever you want to call it] is after 'verses' 2 & 3, but this section happens 4 times, harmonies on 2nd & 4th - at least we all agree on that ;)  It's exactly the same as the version I was listening to… I just can't count ;)) This makes the 'with chorus' more mysterious.
Comment: @armani I did listen to the recording, the one linked in this answer, probably 5 or 6 times as I was confirming the roadmap and trying to ignore my amazement at the screaming fans, and the harmony is very clearly and distinctly present in the second and fourth appearances of that bit while being absent from the first and third.  Have you tried a different set of speakers, a different headset, or something like that?  Sometimes specific frequency ranges can be difficult to hear through specific hardware.
Comment: @phoog I have a very professional sounding set up with proper studio monitors in an acoustically treated room. I honestly can't hear that A note sung in the second verse. I hear a unison with F# in both verses... I tried, I really did :(  Also, not sure if this means anything but Allan Pollack says in his notes about the song "· When Paul is not harmonizing with John's lead vocal he's singing it with him in unison. The specific
content of the backing vocals and their exact placement is different from the official version."
Comment: @armani just to be clear, the first time (in unison) is at 21 seconds or so.  The second time (harmony) is at 50 seconds.
Comment: Beatles songs always have two "official versions" from the original releases- the 'important' mono mix & the 'for hifi fans only mix', which was a very restricted market in 1965 - in stereo. The YouTube version is the 'official stereo' as far as i can tell. if you have decent monitoring, try panning it all over to the left. If you fiddle with your pan law, you can make the right channel 6dB louder in the centre compared to the left channel panned … ermm… more left. [It's physics, but don't ask me to explain it ;)
Answer: Something happens when that section is played the 2nd and 4th time through. That's clear enough.  It's also pretty clear that what happens are the extra upper notes.
The only unclear point is what is meant by 'chorus'.  Does a choir join in?   Luckily we can listen to the record and confirm that it simply means one of the Beatles sings harmony.   Is it quite as clear-cut as the music copy (from 'The Beatles - Complete Scores' I think?) says?   Possibly not.  That book occasionally notates what they think the boys SHOULD have played rather than what they actually did!


Sed not working in usual way - Shell scripting

Question: I have two sed command which includes in my cook.sh script. One command is
sed -E -i "s/^(\\\$mainDomain=\")[^\"]+(\";)$/\1$MainDomain\2/" /var/config.php

This is working fine.
But the below command which is almost same. But it is not working.
sed -E -i "s/^(\\\$authURI=\")[^\"]+(\";)$/\1$duo_auth\2/" /var/config.php

That give the below error message

sed: -e expression #1, char 36: unknown option to `s'

Any idea on this ?
Comment: Provide the sample file on which the 2nd command was not working, seems OK and the value of variable `$duo_auth`
Comment: It's probably `$duo_auth` that contains an unescaped `/`. Why do you use `-i`? If you're testing things, it's a sure way of screwing up.
Comment: @Kusalananda thanks for the facts. Can u give me a sollution for this ?
With a sample example. I am totally new for this sed commands.
Comment: What's the value of the sed command after the variables are evaluated? Depending on what the variables are set to all of these strings could be valid or invalid commands.
Comment: Thanks All. Below answer which posted by @Inian worked fine for me.
Answer: The issue is likely due to your replacement variable $duo_auth having a un-escaped /, change the default sed separator from / to ~ as
sed -E -i "s~^(\\\$authURI=\")[^\"]+(\";)$~\1$duo_auth\2~" /var/config.php

Try it without -i for seeing if the replacement is as expected and put it back after confirmation.
Example:-
cat /var/config.php
<?php
$authURI="dev.digin.io";

now setting the variable
duo_auth="http://auth.uri.digin.io:3048/"

Now the replacement, without -i
sed -E "s~^(\\\$authURI=\")[^\"]+(\";)$~\1$duo_auth\2~" /var/config.php
<?php
$authURI="http://auth.uri.digin.io:3048/";

Comment: Working perfect! Thanks @Inian
Answer: The problem is probably due to $duo_auth containing an unescaped /.  This means that the sed editing script will have a syntax error.
You may pick any other character to use as a delimiter in the s/.../.../ command, for example #:
sed "s#....#....#"

Just make sure that you pick a character that is not ever going to turn up in either $duo_auth or $authURI.
While testing, I'd recommend that you avoid using in-place-editing (-i) with sed. Also, the -i switch is horribly non-portable between sed implementations (some requires an argument).
Instead, do the slightly more cumbersome
sed -e "s#...#...#" data.in >data.in.tmp && mv -f data.in.tmp data.in

While testing, check the data.in.tmp file before moving it.
Comment: @Inian There's the `$authURI` variable too to be aware of. That can't contain the delimiter either.
Comment: For some reason `@` de-limiter is causing the same error, revered to `~` seems fine, and `@` is not a meta-character too! strange!
Comment: @Inian Does `$duo_auth` contain a `@` by any chance? If so, yes, it would fail in the same way.
Comment: Nope, tested it even without it.


HTML Simple DropDown list and Result

Question: I am trying to create a simple calculator with drop down list and JavaScript and I'm having trouble getting a result.
In JavaScript, I wrote the code to return 1411.21 if the setting value is Office. Otherwise it should return 500.
However, when I click calculate button, it doesn't do anything.
This is my HTML code.

<form method="post">
    Setting :
        <select name="Setting" id="Setting">
                <option value="Office">Office</option>
                <option value="HOPD">HOPD</option>
        </select>

    Facility :
        <select name="Facility" id="Facility">
                <option value="100015">Mount Sinai, 123 Main Street, New York</option>
                <option value="100016">NYU Medical, 25 North Broadway, New York</option>
        </select>

            Product Size :
            <100sq cm

            Number of DFU patients :
            10

            Patient co-pay % (based on wage adj.rate) :
            20%

            Co-Pay percent actuallly collected :
            75%

            <input type="button" id="button" value="calculate" onclick="settingValue();">

            Result :

            <input type="text" id="result" placeholder="result">

            Medicare Payment Category	  High	   Low

            Medicare Payment

</form>

And here is the java script code.

Answer: It looks like you're trying to get document.getElementById("setting").value but the actual ID is "Setting" as per
    <select name="Setting">
            <option value="Office">Office</option>
            <option value="HOPD">HOPD</option>
    </select>

Try changing the getElementById to document.getElementById("Setting").value
EDIT
Ok, I made a JSFiddle for you:
https://jsfiddle.net/dktoxtne/1/
Let me know if that works!  I don't remember all I changed, but I do remember you need to change the name="Setting" to id="Setting" and a few other things.
Comment: And additionally, the result element is declared readonly (though this is typo'd) and the element is never closed.
Comment: I changed it to document.getElementById("Setting").value and it still doesn't work..
Comment: As @Devsman suggested, the Result Input is typo'd, try changing that
Comment: I added a JSFiddle that works how I think you want it to work.  See my edit above
Answer: function settingValue(){
                //settingValue=document.getElementById("setting").value;
                var e = document.getElementById("Setting");
                var settingValue = e.options[e.selectedIndex].value;
                document.getElementById("result").value=medicarePaymentCal(settingValue);

            }

HTML Simple DropDown list and Result


EWS SearchFilter.ContainsSubstring to filter on Sender Email Address

Question: I'm trying to filter emails on Exchange Web Services using SearchFilter.ContainsSubstring as follows:
sfilter = New SearchFilter.ContainsSubstring(EmailMessageSchema.Sender, EmailAddress, ContainmentMode.Substring, ComparisonMode.IgnoreCase)
MailItems = service.FindItems(Folder.Id, sfilter, view)

Unfortunately this doesn't work, and I don't want to use Queries, because I can't guarantee that I can use features of Exchange Server 2013.
Composing a variety of requests in Fiddler, I can observe that if I remove the last character of the email address, then the filter works, remove the first character instead, works - put them back, broken.
So perhaps it's pedantic, and it has to be a true substring to qualify, so if I change the Containment mode to FullString - it doesn't work, so I can't do anything like a collection with Substring OR FullString.
It looks like I'll be able to do (Substring with last char missing AND Substring with first char missing), but it surely can't be that broken can it?
What can I do to get this to work?
Note that my code is in VB.NET, but I can't imagine that this is the problem.
Cheers,
Mark
Answer: I worked out that the IsEqualTo filter works with From/Sender, and it doesn't care about case-sensitivity issues, so it's probably what I should have tried to begin with.
The code to match an email address is:
sfilter = New SearchFilter.IsEqualTo(EmailMessageSchema.From, New EmailAddress(Message.FromAddress))
MailItems = service.FindItems(FailureFolder.Id, sfilter, iv)

I still don't know how to find all emails from users at the same domain though.
More Info:
I really needed to filter by Sender Domain and did that by pulling the entire folder contents down and filtering in .Net code. Even that causes problems.
Basically to keep things quick and tight, I tried to pull all the data with a PropertySet:
New PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.Sender)

Filtering still didn't work, yet email addresses still showed in my list of items view. Well it turns out that the value of Message.Sender contains some kind of ActiveDirecty path in it until you call LoadPropertiesForItems. After LoadPropertiesForItems, it's an email address.
Note that my earlier attempt to filter at the server was scuppered because filtering would have to occur against the ActiveDirectory path style of string.
This is all highly confusing, and not at all user friendly.
If anybody has any idea on how to filter by email domain at the server, let me know!
Mark
Comment: In Java - I used similar approach and it worked for me:

if(emailSenderList.size() == 1) {
      return new SearchFilter.IsEqualTo(EmailMessageSchema.From,
      emailSenderList.get(0));
}

return new SearchFilter.SearchFilterCollection(LogicalOperator.Or,
       emailSenderList.stream()
      .map(em -> new
       SearchFilter.IsEqualTo(EmailMessageSchema.From,
       em))
      .toArray(SearchFilter.IsEqualTo[] :: new)
);
Answer: What is your goal? Sender isn't a string property, so I'm not surprised that the results are odd with ContainsSubstring. I tried it against Office 365 and it worked, but older versions of Exchange may not be as "smart" about handling this kind of query. Depending on what you're trying to achieve, there may be a better filter.
Comment: I've noticed that there's more to the From/Sender properties than a simple text string, but to use SearchFilter, you need a propertyBase object. What is the PropertyBase object for the From Email Address String? I can't find one.
Answer: if(emailSenderList.size() == 1) {
    return new SearchFilter.IsEqualTo(EmailMessageSchema.From, emailSenderList.get(0));
}
return new SearchFilter.SearchFilterCollection(LogicalOperator.Or,  emailSenderList.stream().map(em -> new SearchFilter.IsEqualTo(EmailMessageSchema.From, em)).toArray(SearchFilter.IsEqualTo[] :: new));


Fade Out 2 elements on click with jQuery

Question: I am trying to fade out both a full screen overlay and an info box div when pressing the close button, for some reason the code below isn't working. Thanks in advance for your help, I am a noob when it comes to JQuery!
CSS:
.full_page_overlay {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0px;
    left: 0px;
    background: #626262;
    opacity: 0.9;
    z-index: 2147483646;
}

.cart_over {
    width: 60%;
    height: 60%;
    margin-top: 20%;
    margin-left: 20%;
    position: fixed;
    float: left;
    border: 1px solid black;
    box-shadow: 1px 1px 10px black;
    background: white;
    z-index: 2147483647;
    border-radius: 10px;
}

HTML:

      Close

jQuery:
$( document ).ready(function() {
    $("#close_box").click(function(){
    $("#full_page_overlay").fadeOut();
    $("#cart_over").fadeOut();
})
});

Answer: $( document ).ready(function() {
    $("#close_box").click(function(){
    $(".full_page_overlay").fadeOut();
    $(".cart_over").fadeOut();
})
});

It's because you were using hash tags to refer to the elements - hash tags # look for elements by their ID's, dots . look for elements by their class name.
Try jQuery is a very nice and free resource that will help you learn the basics. It's free and only thing you need is your browser.
Comment: It's kinda disappointing that jQuery can't just use a comma in the selector to fade out multiple items. But I guess it works just having them fade out with a new line of code.
Answer: Those are classes  not Ids
# -->  selects Id's
. --> select classe's

$( document ).ready(function() {
    $("#close_box").click(function(){
    $(".full_page_overlay").fadeOut();
    $(".cart_over").fadeOut();
})
});

Working demo
Answer: $( document ).ready(function() {
    $("#close_box").click(function(){
    $(".full_page_overlay").fadeOut();
    $(".cart_over").fadeOut();
})
});

full_page_overlay and cart_over are classes, not *id*s. They should be referenced using ".", not "#".


how to give a space by joining 2 columns having repeated data

Question: I have a table structure like this
CREATE TABLE `test` (
  `id` int(11) NOT NULL,
  `userid` int(11) DEFAULT NULL,
  `loan` int(11) DEFAULT NULL,
  `name` varchar(90) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

+----+--------+------+--------+
| id | userid | loan | name   |
+----+--------+------+--------+
|  1 |      1 |  100 | x |
|  2 |      1 |  200 | X|
|  3 |      2 | 2000 | y|
|  4 |      3 | 1000 | z|
|  5 |      1 |  500 | a|
|  6 |      2 |  700 | b|

As you can see userid is repeating.For example userid 1 is having loan 100,200 and 500
My requirement is to get userid,loan and name and if the userid is repating then loan will be the sum of the repeating userid and name should be space
for example,In the above table userid 1 is repeating so sum is (100+200+500=800)
similarly for userid 2 the sum is 2700
The output i want should be like the below
+--------+-----------+----+
| userid | SUM(loan) |name|
+--------+-----------+----+
|      1 |       800 |    |
|      2 |      2700 |    |
|      3 |      1000 |z   |
+--------+-----------+

I can do with userid and loan but I dont know how to put a space in name field if the userid is repeating
I tried like this
SELECT userid,SUM(loan) FROM
testforsum
GROUP BY userid

and the ouput I am getting is like this
+--------+-----------+
| userid | SUM(loan) |
+--------+-----------+
|      1 |       800 |
|      2 |      2700 |
|      3 |      1000 |
+--------+-----------+

I tried to create a sqlfiddle for it but I dont know why insertion is not happening.You can see the table here
Comment: So, you're wanting to display a space in the name field if they have more than one loan, and the actual name if they only have one?
Answer: SELECT userid, IF(COUNT(*) > 1, ' ', name) AS name, SUM(loan)
FROM testforsum GROUP BY userid;

Comment: Thanks for the answer,+1.I could not understand this part *IF(COUNT(*) > 1, ' ', name) AS name*.It would be nice if you please explain this in your answer
Comment: @rocking as said by Multisync, it's a MySQL function, see the docs here: http://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html#function_if
Answer: select q.userid, q.s,
       case when q.n > 1 then ' ' else q.name end
from
(SELECT userid, SUM(loan) s, count(loan) n, max(name) name
FROM testforsum GROUP BY userid) q;

Some explanation:
(...) q is a subquery which calculates for each userId sum of loans (NULLS are ignored), number of loans (NULLS are ignored).
max(name) it's a "fake" aggregate function, I used it to get any name for each userId (they are all the same for each userId so I can do that) because in ANSI SQL this query is wrong:
SELECT userid, IF(COUNT(*) > 1, ' ', name) AS name, SUM(loan)
FROM testforsum GROUP BY userid;

as all the expressions in the SELECT list should be either aggregate functions (for several rows return a single value) or expressions from the GROUP BY clause. As I know MySQL lets you break these rules, but I prefer to follow ANSI whenever it's possible.
So the subquery q results in a table with unique userIds with their names + sum and number of their loans.
Finally, the parent query filters the result of the q subquery using CASE.
Comment: @rocking To be honest, my answer came first.
Comment: There's no need for the subquery. Just do the `CASE` directly on the `COUNT`.
Comment: @Patrick Q Thanks for info. I used a subquery to make it clearer
Comment: @Multisync yes sorry your answer came first.The other answer is having less code and the output is exactly as per requirement.YOur answer is also helpful
Comment: @Multisync can you explain the answer?
Comment: @Multisync thanks,I could not understand this line *IF(COUNT(*) > 1, ' ', name) AS name* of the other answer.Can you please explain this?
Comment: @rocking It's just a MySQL function which results in some expression: IF([condition], [expr1], [expr2]) = IF [condition] is true THEN [expr1] ELSE [expr2]. An example: if(1 > 2, 'hmm', 'rabbish') = 'rabbish'


Area of a triangle using 1/2 bh on a lattice graph

Question:
I'm trying to find the area of this triangle using the $\frac{1}{2} \times b \times h$ formula, but for some reason, it isn't quite working out. My workings:
My working:

$$\alpha = \sqrt{1^{2}+1^{2}} = \sqrt{2}$$
$$\beta = \sqrt{2^{2} + 2^{2}} = 2\sqrt{2}$$
$$\frac{1}{2} \times \sqrt{2} \times 2\sqrt{2} = 2?$$
I know the area is supposed to be 0.5 units^2, so what am I doing wrong here?
Comment: $\beta$ is clearly not the height if you take $\alpha$ to be your base.
Comment: @Shane You can use [Pick's theorem](https://en.wikipedia.org/wiki/Pick%27s_theorem)
Answer: In your diagram, why did you take $\beta$ to be the diagonal of a $(2,2)$ square instead of the diagonal of a $(1,1)$ square? What it should be is the distance from the upper right end of $\alpha$ to the other side of the triangle.  You can evaluate that by choosing one of the dots to be the origin of a coordinate system and writing the equations for $\beta$ and the base of the triangle, then finding the intersection.  You should then find the distance from the upper right of $\alpha$ to that point to get the height of the triangle.
Answer: The altitude is measured perpendicular to the (extended) base line.
In your case, $h=\dfrac{\sqrt2}{2}$
Comment: If we call alpha the base then, by running the third point parallel to the base down to the bottom row, the height is  $\frac{ \sqrt{2}} 2$
Comment: https://i.stack.imgur.com/O7An3.png

Like this?
Answer: You have misunderstood. $\alpha$ an $\beta$ must be at $90$ degree. BUt the angle between your $\alpha$ and $\beta$ is not $90$. Instead you could have taken this figure

Here $\alpha$ and $\beta$ form 90 degree angle. Just now use the formula $$ \frac{1}{2} \cdot \beta \cdot (\alpha + \text{dotted line length}) $$
Comment: Dotted line length? That's not needed, is it?
Comment: See if you inclue in $\alpha$ length the dotted part then dotted part isn't needed however if you take alpha only as the connected line not the dotted line then it is not needed


are there common techniques to make a piano version of a song that has very little musical content?

Question: I'm looking at doing a piano version of very simple rock song and since there is really not much in the original song, this is not a problem I have approached before:
here is a cover of the song so you can see the music itself:

obviously, playing the same on the piano will sound extremely noisy and annoying; it's roughly 140bpm now, I'm thinking dropping to 115 or so, but even with that tempo, I can't do a 1:1 piano version.
since it is quite repetitive, arpeggios may not be the best either. as the singing is also very monotonic, there is not much to extract in term of melody.
are there common ways to approach this kind of situation?
Comment: One word: improvisation. If you have the notes/tabs for the song, you can determine the underlying structure and build/improvise chords on top of it. The easiest (and, probably, most suitable in this case) for piano would be playing chords with the left hand and melody with the right. But you could even develop it further and play melodies with both hands ([counterpoint](https://en.wikipedia.org/wiki/Counterpoint)). Can't say it's a rock song, by the way. Sounds more like gothic/darkwave to me (or Rammstein disco if you like).
Comment: yes, I think the rock definition was a bit loose here :) the problem with playing the chords, as it is, on the left hand, is that it will just be hammering the same things over and over. It can work for some songs, but in this case, I think it'll be just heavy and noisy. What I'm looking for is if there are common ways, etc to build something for the left hand that is matching the chords and melody. Since this process is probably done quite often, I was hoping there's be some 'classic' go-to approaches
Answer: This is a very broad question, the answer to which largely depends on the composer and the end result they are aiming for. Given your clarification, I can provide some directions that I would personally go for.
First of all, you should determine the key the piece is in. This particular one sounds like E minor to me (I don't have perfect pitch, so correct me if I'm wrong).
There are many extending techniques when it comes to making covers and composing your own tracks.
For "traditional" piano (left hand plays chords, right hand plays melody) I would follow this algorithm:

Write down the chord progression for the track
See if you can invert some chords or dilute the progressions to make it more "interesting"

I am assuming you are familiar with chord inversions, so I will not explain the concept here. I am going to give you a list of how chords can be substituted ("diluted") instead:

Go into a relative key (E minor → G major) and borrow chords therefrom
Go into a parallel key (E minor → E major here)
Play around with chords that have the same root (like Esus here instead of Em)
Play around with chords that have similar notes (similar to using chord inversions) and omit notes therefrom if they don't fit the key
Use (common) chord progressions instead of playing the same chord bar after bar (an example would be playing, say, Em-F#dim-Bsus-Em instead of Em-Em-Em-Em)

A more "complex" way to approach the problem would be to compose a counterpoint instead of playing chords. You could construct one by using "chord theory" or by simply developing a countermelody for the left hand. This is a more "destructive" approach if you are trying to make a cover, even more destructive than using "chord dilution". It might make the initial piece unrecognisable, but it all depends on what you're aiming for.
If you are familiar with blues progressions (and lazy like me), you can use blues chord substitutions for most "rock" compositions. Just run a search for blues chord matrices. I usually use 16-bar ones. The regular matrix for 16-bar blues is I-I-I-I | IV-IV-I-I | V-IV-V-IV | V-IV-I-I. There are plenty of options out there to create transitions and substitute chords within this matrix. Just compare the different ones and see which chords and progressions can be exchanged with other ones and apply them to your composition.
Comment: Huh. From the way the question was written, I would have expected more of an arranging/orchestration-based answer, but the substitution/"recomposition" angle (much more involved in the creation of new elements) is well expressed in this answer. +1
Answer: "Common arrangement techniques" are largely the same regardless of how much material the original piece contains -- you'll simply need to do more to a piece containing less material.
I don't think starting with songs like this is a good idea. I think it's better to start with pieces that already have a lot of interesting material, so that they require relatively little compositional effort to transform into something interesting on piano; and as you develop your vocabulary arranging those pieces, take up pieces containing less material as a challenge.
That said, the most useful starting point is probably to note where the changes that generate interest are -- where does the instrumentation change, where do the licks go, etc.. This isn't necessarily something for you to copy directly, but a rough guide for where you might want to do something to generate interest.
For what it's worth, I'd argue the song suffers from exactly the same problems you are worried about even in its original form. It's repetitive, lyrically uninteresting, amelodic, harmonically cliched, and texturally pretty limited. Maybe it's okay to replicate these flaws if that's what you or your audience wants.


Removing placeholder view from RecyclerView on notifyDataSetChanged?

Question: I'm working on a project where I have a RecyclerView displaying items from a SQLiteDatabase. So I have build a custom adapter that uses a cursor instead of a list of data so I can update it straight from database queries. Additionally, I have a "placeholder" view that gets put into the recyclerView if the cursor is empty (no rows returned) that basically says "nothing here, add something by clicking +".
My issue is that when I add an item in that state (when the RecyclerView is initially empty) and call notifyDataSetChanged, the RecyclerView attempts to recycle the placeholder view instead of inflating the correct view item and I get a NullPointerException because I am attempting to update UI elements that were never initialized.
Here's what my adapter looks like now:
public class TextItemListAdapter extends RecyclerView.Adapter<TextItemListAdapter.ViewHolder> {

    private List<TextItem> dataList;
    private Cursor cursor;
    private Context context;
    private boolean empty = false;
    private TextItemDataLayer dataLayer;

    /**
     * Constructor
     * @param c Context
     * @param curs The cursor over the data (Must be a cursor over the TextItems table)
     */
    public TextItemListAdapter(Context c, Cursor curs) {
        context = c;
        dataLayer = new TextItemDataLayer(c);
        dataLayer.openDB();

        if (curs != null) {
            switchCursor(curs);
        }

        empty = isEmpty(cursor);
    }

    /**
     * ViewHolders populate the RecyclerView. Each item in the list is contained in a VewHolder.
     */
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        View parent;
        TextItem textItem;
        TextView location;
        TextView text;
        TextView time;

        /**
         * Create the viewholder for the item
         * @param itemView the view contained in the viewHolder
         */
        public ViewHolder(View itemView) {
            super(itemView);
            this.parent = itemView;

            if (!empty) {
                itemView.setClickable(true);
                itemView.setOnClickListener(this);
            }

            location = (TextView) itemView.findViewById(R.id.textItem_item_title);
            text = (TextView) itemView.findViewById(R.id.textItem_item_text);
            time = (TextView) itemView.findViewById(R.id.textItem_item_time);
        }

        /**
         * Handle a click event on an TextItem
         * @param v
         */
        @Override
        public void onClick(View v) {
            Intent i = new Intent(context, EditTextItemActivity.class);
            i.putExtra("textItem", textItem);
            context.startActivity(i);
        }
    }

    /**
     * Creation of the viewholder
     * @param parent
     * @param i
     * @return
     */
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int i) {
        View view;
        if (empty) {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.text_item_list_item_empty, parent, false);
        } else {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.text_item_list_item, parent, false);
        }
        ViewHolder vh = new ViewHolder(view);
        return vh;
    }

    /**
     * When the viewholder is bound to the recyclerview, initialize things here
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        if (!empty) {
            if (!cursor.moveToPosition(position)) {
                throw new IllegalStateException("couldn't move cursor to position " + position);
            }

            holder.textItem = dataLayer.buildTextItem(cursor);
            holder.location.setText(holder.textItem.getLocation().getName());
            holder.text.setText(holder.textItem.getMessage());
            holder.time.setText(holder.textItem.getTime());
        }
    }

    /**
     * Get the number of items in the dataset
     *
     * If the dataset is empty, return 1 so we can imflate the "empty list" viewHolder
     * @return
     */
    @Override
    public int getItemCount() {
        if (empty) {
            return 1;
        }
        return cursor.getCount();
    }

    /**
     * switch the existing cursor with a new one
     * @param c
     */
    public void switchCursor(Cursor c) {
        // helper method in TextItemDataLayer that compares two cursors' contents
        if (TextItemDataLayer.cursorsEqual(cursor, c)) {
            c.close();
            return;
        }
        if (cursor != null) {
            cursor.close();
        }
        cursor = c;
        cursor.moveToFirst();
        empty = isEmpty(cursor);
        notifyDataSetChanged();
    }

    /**
     * Check to see if the cursor is empty
     *
     * @param c the cursor to check
     * @return
     */
    private boolean isEmpty(Cursor c) {
        return (c == null || c.getCount() == 0);
    }
}

Some things I've tried that I haven't gotten to work:

notifyItemRemoved(0); if the list changes from empty to not empty
Changing switchCursor to compare the two cursors and call either notifyDataSetChanged() or notifyItemRemoved(0) like this
// helper method in TextItemDataLayer that compares two cursors' contents
if (OterDataLayer.cursorsEqual(cursor, c)) {
    c.close();
    return;
}
if (!isEmpty(c) && isEmpty(cursor)) {
    empty = false;
    notifyItemRemoved(0);
    // or notifyDataSetChanged();
}

if (cursor != null) {
    cursor.close();
}
cursor = c;
cursor.moveToFirst();
empty = isEmpty(cursor);
notifyDataSetChanged();

I've also considered having the empty placeholder view not be in the RecyclerView but instead be in the parent view to avoid the issue altogether, although I think it's better in terms of the overall structure of the app for it to be handled in the RecyclerView.
Comment: see how `android.widget.AdapterView` handles such cases: `AdapterView#setEmptyView`
Answer: Your problem is simply in understanding how RecyclerView.Adapter works. Please have a look at this for clarification pertaining to your problem.

My issue is that when I add an item in that state (when the RecyclerView is initially empty) and call notifyDataSetChanged, the RecyclerView attempts to recycle the placeholder view instead of inflating the correct view item

Your are right about that, and it's happening because you did not override getItemViewType (int position), and the RecyclerView has no way to know that there are actually two different ViewHolder types or states.
I suggest following the above linked answer, refactor your code to provide two different ViewHolders, and then implement getItemViewType (int position). Something along these lines:
 @Override
    public int getItemViewType(int position) {

        if(empty)
            return EMPTY_VIEW_TYPE_CODE;

        return REGULAR_VIEW_TYPE_CODE;
    }


Why is $\int \cos(n\arccos(\sin(x)) = \int \cos(nx)$ on $[-1, 1]$?

Question: I would like to evaluate

$$\int \cos(n\arccos(\sin(x)) dx$$

with $x \in [-1, 1],$ and I used a calculator do to so. At the very beginning, the calculator simplifies
$$\int \cos(n\arccos(\sin(x)) dx = \int \cos(nx) dx.$$
This looks like $\arccos(\sin(x)) = x$, but I don't see where this comes from.
Comment: Note that if $y=\arccos(\sin(x))$, then $\cos(y)=\sin(x)$.
Answer: Not a full answer, but couldn't fit it in a comment.
As I wrote above, recalling that $\sin(x)=\cos(\pi/2-x)$ we obtain that
\begin{align*}\cos(n\cdot \arccos(\sin(x)))& =\cos(n\cdot\arccos(\cos(\pi/2-x)))=\cos(n\pi/2-nx )\\& =\cos(n\pi/2)\cos(nx)+\sin(n\pi/2)\sin(nx)\end{align*}
which is equal to $n\cos(x)$ iff $n=0\mod 4$.
Are we sure that the substitution is correct?
Comment: You  have a typo: $\cos(n\cdot\arccos(\cos(\pi/2-x)))=\cos(n\pi/2-n x )$.
Comment: You are right! Thank you


Azure AD; no global admin

Question: I've got a new Azure instance up and running. I've got a few services running in it and I've decided I need a Azure AD environment too.
On opening up the Azure AD Admin panel I immediately get told I don't have some rights to view the dashboard elements and I need a global admin to configure that for me.
On navigating to the users panel (more services > Users and Groups > All Users) all my configured users (Everyone in my 365 subscription) are listed as 'member', including both administrator accounts I have configured on 365 (one of which I am currently logging into azure as).
If I got to the 'directory role' option under any of my user accounts (including the one I'm pretty sure I started the Azure account under) the three options are greyed out and only member is selected.
The first line in the Microsoft Docs 'Assign a user to an admin role' is simply 'login with a global admin account'.
Doc here : https://docs.microsoft.com/en-us/azure/active-directory/active-directory-users-assign-role-azure-portal
Catch 22, I can't get a global admin without already having a global admin.
How am I able to elevate a user to the global admin role from this position?
Comment: Have you tried logging in with an onmicrosoft.com account? If you haven't changed it, then your initial admin account you setup would be @yourdomain.onmicrosoft.com. You'll have to contact Microsoft support if you can't figure out your username and password for global admin.
Answer: I had the same issue and it took me a while to figure it out.
The problem was, that my domain ownership could not be verified.
For me it works this way:

Login to the microsoft partner center with my work/school account.
Go to Account Settings / User Management. There you find a link how you become the Global Admin
Follow the desriptions in the link and add a txt entry to your dns entries of your domain provider.
Get a coffee and wait some minutes till the dns server a synchronized ...et voila.
Comment: This worked for me as well, but I used the [Office 365 Admin Center](https://admin.microsoft.com/) to become a domain administrator.
Answer: I encountered a similar situation. I had just set up my azure account, with my account set as global administrator. I was able to register an application, allowed power bi api access, setup power bi workspace etc.
I think I clicked an Office 365 link sometime after setup. When I logged in again to the azure portal, some functionalities are now grayed out. Had to do some backtracking and fiddling. It appears that I needed to finish setup of the Office 365 account. I had to claim or verify that the domain I registered is indeed mine. Instructions included added a TXT value to my account at enom then clicked the verify button at the office 365 setup. When this was done, I went back to the azure portal. This fixed my issue.
Answer: Ensure the account which you have logged in is already a global admin. Pay attention to the step 1 in that document:

Sign in to the Azure AD admin center with an account that's a global admin for the directory.

Your scenario:

Catch 22, I can't get a global admin without already having a global
  admin.

If you have not a global admin account, you cannot assign other accounts to a global admin. Only global admin can assign global admin role to other accounts. I suggest  that you could contact the global admin in your directory to help you .
Hope this helps!
Comment: @Patrick OK,In my answer,I said that "Only global admin can assign global admin role to other accounts ",Can you understand this? What do you want to achieve should be avoided.
Answer:
How am I able to elevate a user to the global admin role from this
  position?

No,You are not able to do this. It's just caused by azure design. As @Wayne Yang said, This action should be avoided and you should understand the rule that you can do something or not in azure. Just contact your global admin. If you still want to do something with out admin's consent since you are just a user in that directory, I really couldn't understand it.

Azure AD; no global admin


Problems with closing a process with a timer for a screenlocker on public pc's for a company vb.net

Question: So i am working on a project to create a screenlocker for a company using belgian eID. I am using a second program without interface to check wether someone has closed it and the program will restart when it did. The problem right now is that i can't seem to shut the  2nd program down when i put the eID in(i'm using the eID wrapper from jdt from github)
i looked it up but so far found 0 answers to my problem. The 2nd program uses a timer and checks every so often if the eID is still plugged in.
Now when i plug my eID in the main form (the screenlock) should shutdown but it doesnt it will close down and all but after a few seconds when the timer from the 2nd program is checking it starts it up again even though i wrote some code that shuts down the timer and exits the application.
I can provide code if someone needs it. It would mean the world if someone could help me with this as this has been a persistent problem for a few days now. Thanks in advance
Comment: require mode details to provide an answer , its too vague currently
Answer: Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles tmrProcess.Tick
        teller += 1
<code>    If teller Mod 75 = 0 Then
        data = wrapper.GetCardData()
        If Not data.FirstCard Is Nothing Then
            tmrProcess.Stop()
            Application.Exit()
            tmrProcess.Enabled = False

        End If
    End If
    Me.Hide()
    If teller Mod 10 = 0 Then

        Dim p() As Process
        p = Process.GetProcessesByName("zScreenLocker")
        If p.Count > 0 Then
            lstHowBoDah.Items.Add("Process is running")

        Else
            lstHowBoDah.Items.Add("Process is not running")
            Process.Start("\\secr14fs\Users$\fabian.lagaeysse\Documents\Visual Studio 2015\Projects\zScreenLocker\zScreenLocker\bin\Debug\zScreenLocker.exe")
            Me.Close()

        End If
    End If
End Sub
</code>
this is what i currently use. The reason i used both process.stop and timer.enable = false is because none of them work. I tried everything yet the timer keeps going and reopening the program. It's getting frustrating


Wait for jquery .html method to finish rendering

Question: I have div with vertical scroll bar. Div is being updated dynamically via ajax and html is inserted using jQuery's .html method.
After div is updated scroll bar returns to top and I am trying to keep it in the previous position.
This is how I'm trying it:
var scrollPos = $('div#some_id').scrollTop(); //remember scroll pos
$.ajax({...
    success: function(data) {
        $('div#some_id').html(data.html_content); //insert html content
        $('div#some_id').scrollTop(scrollPos); //restore scroll pos
    }
});

This fails. My best guess is that it is failing due to inserted html not rendered (ie. no scroll).
For example this works.
setTimeout(function(){
    $('div#some_id').scrollTop(scrollPos);
}, 200);

But this is dirty hack in my opinion. I have no way of knowing that some browsers won't take more then these 200ms to render inserted content.
Is there a way to wait for browser to finish rendering inserted html before continuing ?
Comment: http://stackoverflow.com/questions/2030497/how-can-you-get-your-code-to-wait-for-html-and-append-functions-to-complete should help
Answer: It's still a hack, and there really is no callback available for when the HTML is actually inserted and ready, but you could check if the elements in html_content is inserted every 200ms to make sure they really are ready etc.
Check the last element in the HTML from the ajax call:
var timer = setInterval(function(){
   if ($("#lastElementFromAjaxID").length) {
       $('div#some_id').scrollTop(scrollPos);
       clearInterval(timer);
   }
}, 200);

For a more advanced option you could probably do something like this without the interval, and bind it to DOMnodeInserted, and check if the last element is inserted.
Comment: Well, there is the native [DOMNodeInserted](http://help.dottoro.com/ljmcxjla.php) event that will fire every time an element is inserted, You can bind a function to that event that checks the target element to see if it's the last element from the ajax call, and then do your scroll thing, but it will probably be less efficient then the interval, and there are some cross browser issues as well. I'd just go for the interval, it takes little resources to run an interval like that, and it will probably run max a couple of times, checking every inserted element will be worse IMO.
Comment: Thanks, it's sad no such callback exists.
Answer: I will just like to point out one difference here: One thing, is when the .html() have completed loading, but the browser actually render the content is something different. If the loaded content is somewhat complex, like tables, divs, css styling, images, etc - the rendering will complete somewhat later than all the dom ellements are present on the page. To check if everything is there, does not mean the rendering is complete. I have been looking for an answer to this by myself, as now I use the setTimeout function.
Answer: Such callback does not exists because .html() always works synchronously
Answer: If you are waiting for images loading, there's one approach https://github.com/desandro/imagesloaded


Equation with complex number

Question: How would you be able to solve this equation?
$$
z^2 \overline z = z
$$
for $z \in \mathbb{C}$?
Thanks in advance!
Comment: Have you tried anything towards solving the question? If you have you may edit your question to include it.
Comment: $z=e^{i\theta}$.
Answer: A trivial solution is $z=0$. Now suppose $z\neq 0$. Then since $\mathbb{C}$ is a field you may divide by $z$ and solve the easier equation
$$ z\bar{z}=1 $$
Therefore the solutions are $0$ and all complex numbers with norm $1$.
Answer: Let $$z=x+iy$$ then you have to solve $$(x+iy)^2(x-iy)-(x+iy)=0$$
It is equal to $$\left( x+iy \right)  \left( {x}^{2}+{y}^{2}-1 \right) =0$$

Equation with complex number


If X is domain and Y is range, what is Z?

Question: This is a really small stupid question, but I'm currently self-teaching myself Multivariable Calculus, and I'm just curious if there is a term for this. I did a small google search and didn't find anything, so I would appreciate anything thanks!
Thanks!
Comment: $Z$ is the letter coming after $X$ and $Y$...
Comment: Do you mean if $Z$ is used as a standard letter to indicate something? I think not. But also $X$ and $Y$ are not standard, they are just common. If you have a composition of functions $f:X\to Y$ and $g:Y \to Z$, you usually use $Z$.
Comment: Lower case $z$ is often used for complex domains, if your question is about that.
Comment: Generally, when talking about functions, when something asks for the domain, you tell where the x-values are defined. Same thing for range with y-values. What would be the equivalent term for z-values?
Comment: In multivariable calculus you might have $x$ and $y$ as independent variables (so the domain consists of pairs $(x,y)$) and the $z$ axis for the codomain. With more context we might be able to give you a better answer.
Answer: In single-variable calculus, X is the domain and Y is the range. In 3-D coordinates, X and Y are the domain (i.e., $\mathbb{R}^2$) and then Z is the range.