How to query the last 5 nodes of multiple content types?

Question: I want to query last 5 nodes of multiple content types, say, typeA, typeB, typeC, typeD.
It was originally only one content type, and I did it using EntityFieldQuery:
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'typeA')
  ->propertyCondition('status', 1)
  ->propertyOrderBy('created', 'DESC')
  ->range(0, 5);

$result = $query->execute();

But now I need to include 3 other content types to the list.
Is there any way to expend this query to include the last 5 nodes of the other 3 content types as well. So that the result will have 5 last nodes from all 4 content types, altogether 20 nodes.
Or should I do it with 4 individual queries?
Comment: Probably easiest to do it with 4 individual queries.
Comment: Yeah I guess probably we have to run the same query 4 times (running query inside foreach loop, as only the content type is going to rest and rest everything is as it is) in order to get the desired result.
Comment: Yeah you'll need 4 different queries here, whether you roll them all into one with sub-queries or not. Definitely can't do it with EFQ (unless you alter the query), it wouldn't be able to express the necessary grouping
Comment: I guess you can give a try to `union` once if you want to do it with the single query.
Comment: Thanks, for your comments. Then, I'll do it with 4 individual queries. @Clive, should I keep this question or delete it? Seemingly there is no way other than what I already proposed in my question.
Comment: Nah leave it open...you never know, someone might come up with an interesting way to solve it
Answer: I think the only thing you need is alter the second line of your EntityFieldQuery to this:
->entityCondition('bundle', array('typeA', 'typeB', 'typeC', 'typeD'), 'IN')

Haven't tested this particular though, but you can query multiple content types this way.
Cheers
EDIT: Maybe this can help you more: https://www.drupal.org/node/2048345
Comment: No, I want to get exactly 5 nodes from each type. Your suggestion would return 5 nodes of any given types,
Comment: Maybe this can help you then! https://www.drupal.org/node/2048345
Comment: That seems interesting. I didn't think about UNION. I'll give it a try as soon as I get the time for it. Thanks. Please edit your answer and add this link with a short description. After I try it, I'll give you a feedback.
Comment: Hey Adrian,
I really don't have the time to add short description because this is not my case and I haven't tried that. I bounced in this question for querying multiple content types only. Not exactly your case. But I will add the link to my answer as proposed by you! Again, cheers!
Answer: Try something like the following codes:
$types= array('type1','type2','type3');

foreach ($types as $type) {
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'typeA')
    ->propertyCondition('status', 1)
    ->propertyOrderBy('created', 'DESC')
    ->range(0, 5);
  $temp = $query->execute();

  if (isset($temp['node'])) {
    $result[$type]['nids'] = array_keys($temp['node']);
    $result[$type]['nodes'] = node_load_multiple($result[$type]['nids']);
  }
}

/// then you can load them by

Answer: I think as other have suggested using UNION is going to be the easiest way to do it with one query:
$nids = db_query("(SELECT nid FROM node WHERE type = 'typeA' ORDER BY changed LIMIT 0, 5)
UNION
(SELECT nid FROM node WHERE type = 'typeB' ORDER BY changed LIMIT 0, 5)
UNION
(SELECT nid FROM node WHERE type = 'typeC' ORDER BY changed LIMIT 0, 5)
UNION
(SELECT nid FROM node WHERE type = 'typeD' ORDER BY changed LIMIT 0, 5)")->fetchCol();
$nodes = node_load_multiple($nids);

I was playing with a way to do it using numbered rows but it doesn't get the latest nodes so I gave up, but here is the sql in case your interested in fixing it:
SELECT nid, title, type, changed
FROM (
    SELECT nid, title, type, changed,
    @num := if(@group = type, @num + 1, 1) as row_number,
    @group := type as dummy
    FROM   node
    WHERE type IN ('typeA', 'typeB', 'typeC', 'typeD')
    ORDER BY type, title
) AS x
WHERE  row_number <= 5
ORDER BY type

Also see this very relevant SO question MySQL:How to get n latest rows of a distinct type
Answer: the best way you can do it is to user db_select();
I would do something like this:
Set the array with the content type machine names.
$arrayofnodetypes = array('page','post','poll');

here you select the table
$query = db_select('node','n');
$query->fields('n',array('nid','title','status','type')); // this are the fields your want to fetch
$query->condition('n.status','1','='); // node is published
$query->condition('n.type',$arrayofnodetypes,'IN'); // this is where you call the content types.
$query->orderBy('created','DESC');
$query->range(0,20);

$results = $query->execute()->fetchAll();

Then you have 2 options.
the first:
if you want to fetch all fields in the node, you need to manualy join the fields in the $query see the following resource if you want to learn more: https://www.drupal.org/node/1848348
the second:
the $results variable will have the results of the query.
I would then foreach each result of the array.
like the folowing;
$nodes = array();
foreach($results as $item) {
  $nodes []= node_load($item->nid);
}

then the $nodes array will contain the results you need.
Comment: Thanks for your attempt, however this way I won't get 5 nodes from each content type, but 20 nodes, which can also be from the same type.. I need explicitly 5 from each content type.
Comment: that's easy create 5 queries and mix the results in an array.
Comment: That was already what I proposed in my question. I've asked if there were any other way to do it using only one query. Seemingly there isn't.
Answer: You could also use node_load_multiple.

$types = array('content_type_1', 'content_type_2', 'etc');
$query = db_select('node', 'n')
  ->fields('n', array('nid'))
  ->condition('type', $type, 'IN');
$result = $query->execute()->fetchAll();
$nids = array();
foreach ($result as $row) {
  $nids[] = $row->nid;
}
$nodes = node_load_multiple($nids);
Comment: This is not the result I wanted to reach. I wanted to get **exactly** 5 nodes from each content type. Your solution doesn't provide that.


JPype: how to convert the boolean value from python to java

Question: I want to run java class in my python code and I use the tool JPype.
I have a java method with a boolean argument.
It works in java code but when I call it in python, I get the error message:
RuntimeError: No matching overloads found. at src/native/common/jp_method.cpp:121

I even use the jpype wrapper JBoolean, but it still fails.
For example, the code in java is:
item.myMethod(true);

and I have tried to convert it in python as:
item.myMethod(1)
item.myMethod(True)
item.myMethod(jpype.JBoolean(True))
item.myMethod(jpype.JBoolean(1))

but all of above get the same error message.
Could anyone help me to convert the boolean argument from python to java??
thank you!!
Answer: Is the argument of your Java method defined as a boolean or a java.lang.Boolean?
If it is boolean, then all the possibilities you have tried should work (if not there might be something wrong with the way you import the Class in your Python code). However, if it's a java.lang.Boolean, then you have to call your method as such:
item.myMethod(jpype.java.lang.Boolean(True))


I can't understand professor's code about malloc

Question: Professor give me a homework about malloc, dynamic memory allocate...
So He give me some hints about code but I can't understand his code and hints.
I think my code needs another 'def' or 'for loop'...
Anyway.
question Now I can gets_s some string with pointer. but I can't build.
   Print like alien language...
 last of this page I hope this code would be work.
  for (j=0;j<3;j++)
    printf("your sentence is %s ", *parray[i])
I tried some of codes with friends. he also can't figure out..
Professor told me This code is for beginner, "IT's easy to solve"
#include<stdio.h>
#include<stdlib.h>

void main() {
    char* parray[3];
    int i, j;
    char str[70]; // temporary save place
    for (i = 0; i< 3; i++) {        //
        printf("sentence, please. : ");
        gets_s(str, sizeof(str));   //dynamic memory allocate
        parray[i] = (char*)malloc(sizeof(char)**str);
        printf("\n");

free(parray[i]);

I hope this code work.
for (j=0;j<3;j++)
    printf("your sentence is %s ", *parray[i])

Answer: You should be allocating the amount of characters there was in the input string, +1 for the null terminator.
parray[i] = malloc(strlen(str)+1);
Then copy the data from temporary str to the new memory location.
Also avoid gets_s and use fgets instead. The bounds-checking interface of C11 is poorly supported in general, but this particular function was just some placeholder when rewriting old code using obsolete gets.
Comment: thanks! I'll try it again! and, If you had time, can you tell me about how to save another memory location? just parray[i] = another location[j] would be okay?
Comment: I don't like the `_s` functions, either, but if you tell someone to use `fgets`, you also have to teach them how to strip the newline.  (An unfortunate nuisance for both you and them.)
Comment: @SteveSummit It's not just me but C11 annex K explicitly recommends us not to use the function. As for fgets tutorials, feel free to contribute to this community wiki FAQ: https://stackoverflow.com/questions/35178520/how-to-read-parse-input-in-c-the-faq
Comment: Thanks for the link.  I see more and more questioners using the `_s` functions these days, though, so somebody's getting through to them... :-(
Comment: @SteveSummit Microsoft has been preaching these `_s` functions for some 20 years. And one problem is that they aren't 100% compatible with C11 annex K "bounds checking interface" (which was quite a fiasco).


Can I compare Pearson's r and Spearman's rho with Fisher's r to z transformation?

Question: I'm using the tool in the following website to compare correlation coefficients:
http://vassarstats.net/rdiff.html
The tool uses Fisher's r to z transformation to ultimately compare two correlation coefficients.
Let's say I want to compare a correlation coefficient that was calculated with Pearson's correlation and a correlation coefficient that was calculated using Spearman's correlation. Is that ok to do? Or do both need to be calculated using the same correlation procedure (i.e., both Pearson's or both Spearman's?).
Thanks.
Comment: In what situation would it make sense to compare a linear correlation with a correlation between ranks?
Comment: Using $z$ on both is **assuming**that correlations $r$ on both methods are comparable, as it's the same transformation. It is not a way of **ensuring** that both are comparable. It is on all fours with having two Fahrenheit temperatures and converting them both to Celsius. By all means do that if it helps. A way forward is to realise that Spearman's method is, or should be, just Pearson's method applied to the ranks. The small print is how ranks are calculated when there are ties.
Comment: This is an example of the X-Y problem.  You should indeed care what kind of correlation between IQ and biomarker is more appropriate for the data, but looking  a scatter plot and knowing how variables are measured tells you immensely more than using a transformation. But on the big question, I don't think it makes much sense to compare a rank correlation on one group with a linear correlation on another.
Comment: Sorry, no: I didn't say that and I can't say that because I have no idea what the data look like and I don't work in that science (although my bias is to doubt that there is any interesting correlation at all).  I don't follow that you are committed to anything here.  Another simpler take is that if Pearson and Spearman correlations are very different you probably need something different again, e.g. a transformation of one or both variables.
Comment: If you were actually interested in comparing linear correlations (you started with Pearson), a monotonic, non-linear correlation (Spearman) would not be how I'd do that. It might be a good idea to take one step further back still and carefully consider whether it's actually correlations you wish to compare, rather than something else. What's the underlying research question? If you do conclude that you wish to compare correlations, you need to be clear about whether it's linear or monotonic correlation that you want to compare. Then ask about a way to achieve that aim.
Comment: Abandoning Pearson due to non-normality is not necessary (and especially not only to one side of the comparison). If you do want to pick up monotonic relationships, then Spearman should generally be okay.
Comment: @Glen_b: Thanks. So I have two groups (group A and group B) and I want to compare correlations of the same two variables across groups. So let's say I want to compare the correlation between IQ and level of some biomarker across the groups. But let's say in group A I calculated Pearson's r while in group B I calculated Spearman's rho because in group B I failed to meet the assumptions to run Pearson's correlation. Continued in next comment...
Comment: I was thinking that since I'm using Fisher's r to z to normalize each correlation coefficient, then that should allow for comparisons regardless of which correlation method I used to calculate the two coefficients that I'm comparing. Are you saying that I can't do this? If so, then what are my options for comparing the correlations? Should I just run Spearman's for both?
Comment: @NickCox Many thanks for your reply. I get how informative simply looking at the scatterplots can be. But I will likely still choose to compare the correlation coefficients because I already did it for a previous analysis that my current analysis is connected to, and so I'm kind of committed. In that case, correct me if I'm wrong, but it seems like you're saying that if I still end up deciding to go ahead with the comparisons of the correlation coefficients that the best way forward is to just use Spearman's for everything.
Comment: @Glen_b: I want to look at the association between certain biomarkers and different types of IQ in two different groups of people to see firstly if levels of the biomarkers are linked with IQ within each group, and then also make comparisons between the two groups. I simplified my problem a bit. There are multiple types of IQ (e.g., math IQ, verbal IQ, general IQ, etc) and multiple types of biomarkers (biomarker 1, biomarker 2, biomarker 3, etc). And I'm measuring correlations between each possible combination of IQ types and biomarkers. Continued in next comment...
Comment: In certain cases I decided that Spearman's would be more appropriate than Pearson's because either one or both of the variables are non-normal and/or have outliers and/or I think that the relationship between the two variables will likely be monotonic (instead of linear) based on past literature. I realize multiple regression would probably be a better approach for this... but it's for a class project and I need to use correlations for reasons too long to explain...
Comment: @Glen_b Thanks!
Comment: That said, it doesn't imply that you can *always* use the usual tests of Pearson correlation. Sometimes you can stick to Pearson but need to modify the test. Doesn't affect you if you're using Spearman.
Answer: These two coefficients don't measure the same thing, so your comparison will be more appropriate if you use the same correlation in both cases. If you're worried about model assumptions, use Spearman. However keep in mind that model assumptions are always idealisations, so it is wrong to say that for example you can only use Pearson correlation if data are normal. Even if you want a formal comparison, I'd look at plots first to see whether there is anything that makes the Pearson correlation really misleading at least in one of your cases, such as domination by an outlier.
Note also that the tool you cite is about significance testing and will give you a misleading comparison at least if sample sizes are different. Also it doesn't solve the problem that not the same thing is measured by the two correlations.
Comment: I'd say the main use of the z transformation was getting confidence intervals, although significance tests clearly could be linked.


pmd gradle basic config

Question: I want to add a PMD task to my gradle build, that would give me a pmd report in csv format. I found the pmd gradle docs too subtle and couldn't figure out how to achieve this. Can someone post a simple example?
Answer: Figured out:
<code>task pmd << {
    println 'Running PMD static code analysis'
    ant {
        taskdef(name:'pmd', classname:'net.sourceforge.pmd.ant.PMDTask', classpath: configurations.pmdConf.asPath)

        pmd(shortFilenames:'true', failonruleviolation:'true', rulesetfiles:'conf/pmd-rules.xml') {
            formatter(type:'csv', tofile:'myreport.csv', toConsole:'true')
            fileset(dir: "src/main/java") {
                include(name: '**/*.java')
            }
            fileset(dir: "src/test/java") {
                include(name: '**/*.java')
            }
        }
    }
}
</code>
Answer: The Gradle PMD plugin, I believe will only create XML and HTML reports.  You can look at the DSL reference for more information on the PMD task.

pmd gradle basic config


How do you programmatically get the shipping information from a placed order?

Question: So far I have a working piece of code that sends me an email ($to variable) when a new order has been placed on my drupal 8 commerce.
This is not the email the person that places the order gets.
As part of the body of the email, i was able to find and use variables like a custom attribute, sku, quantity, product name etc...
I realize that in the orderCompleteHandler(), i might have to change what i send as a parameter, instead of $items having to possibly send $order.
But where can i find/how can i get the shipping information, like shipping address, shipping date and the user's that placed the order name : I would like to add them to the email i send.
More importantly is also: how do i find all this info and others by myself? i tried to kint($order) and it either freezes or runs out of memory. I tried dpm($order) and i get 10K lines of info but nothing that is obvious.
I tried to look in those 10k lines for some unique data that i knew was part of the shipping info but it wont show up, most likely because that value will be the return value of a get function.
Basically, how should i look and where should i look if i want various information from the order placed variable aka $order?
Any help in debugging and pointing me in the right direction would be appreciated.
<code>public function orderCompleteHandler(WorkflowTransitionEvent $event) {

        // @var \Drupal\commerce_order\Entity\OrderInterface $order
        $order = $event->getEntity();
        $items = $order->getItems();

        $mail_manager = \Drupal::service('plugin.manager.mail');
        $to = 'firstname.lastname@example.com';
        $langcode = \Drupal::currentUser()->getPreferredLangcode();
        $type = 'order_placed';

        $mail_manager->mail('my_custom_order', $type, $to, $langcode, $items, NULL, TRUE);

    }

/**
 * Implements hook_mail()
 * Prepares emails sent by the MailHandler service.
 * Emails are sent within the OrderComplete Event Subscriber.
 */
function my_custom_order_mail($key, &$message, $params) {
    switch($key) {
        case 'order_placed':
            $options = array(
                'langcode' => $message['langcode'],
            );
            // Creating an html formatted email.
            $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';
            $message['from'] = 'staff@myCompany';
            $message['subject'] = t('Order @order_number confirmed', array('@order_number' => $params[0]->getOrderId()), $options);

            $entire_email_display = '';
            foreach ($params as $product) {
                // Get the Custom Location.
                $productLocation = $product->getPurchasedEntity()->getAttributeValueIds()['attribute_custom_location'];
                $order_item['sku'] = $product->getPurchasedEntity()->getSku();
                $order_item['quantity'] = (int)$product->getQuantity();
                $order_item['product_name'] = $product->getPurchasedEntity()->getTitle();

                // HERE I BUILT an entire email body and stored in the $entire_email_display.
            }

            $message['body'][] = $entire_email_display;
    }
}
</code>
Comment: ok alll things will come form the $order = $event->getEntity(); ... the shipping is in user profile, helpfull to install the devel module then you can inspect the order i like to use symphony var dumper as (devel setting) dsm sucks
Comment: Commerce also has a MailHandler that makes sending emails easier: https://www.drupal.org/node/3030431

Shipping information is in $order->shipments, and sometimes Devel chokes, setting up xdebug is often a worthy time investment.
Comment: Bojan Zivanovic, it was as you said: shipments... how do you go from here though in order to find the right info by using devel? do you dpm($order->shipments) ? or dpm($order->shipments->getValue()) ? how do you know which one to go for? how do you choose how to go deeper? array vs object? or when to go for ->entity? i know those are a lot of questions but the documentation on HOW TO DEBUG is so bad for Drupal 8, and commerce in particular? or do you look in the commerce module code at the class and methods? trying to get a better idea on how to go from point A to point B when debugging
Answer: You can have the shipping information with :

$shippement = $order->shipments->first()->entity;
$shipping_profile = $shippement->shipping_profile->first()->entity;


SSRS - Moving subscriptions only to new server

Question: We have SSRS server which has got 100 plus reports and 95 subscriptions.
Subscriptions query are very process intensive. We want to move subscriptions to new server.
Can we just move subscriptions only to new server....
Because when you move report server database, it will include everything reports, subscription etc...
Answer: Have you checked the execution plans and other metrics of the queries on the database servers? Are you running SSRS and the database engine on the same server?
Comment: SSRS and database engine are on different server. Amount of data processed/aggregated is in millions.
Comment: Please clarify. Are you referring to the SQL Agent jobs or the actual work done on the report server when a subscription is processed or the work done in the data source database to execute the queries inside the reports? What "part" do you want to move to a new server.
Comment: we mean... actual work done on report server when subscription is processed.....how can we move that.. bcos reporting server is already fully utilized in running reports


Count of nodes by type

Question: I am looking for a snippet that lets me display the total count for a specific node type, e.g. "Pages = 167" or "Products = 10630."
What code should I use to achieve this?
Answer: You can use the Views module to do this.

Create a new view, remove sort options, fields and other default settings
Add a field for "Content: Type"
Expand the "advanced" part on the right and set "Use aggregation" to "Yes"
Add yet another field for "Content: Type"
On the second "Content: Type" field, click "Aggregation settings"
Set the aggregation type to "count"
The second "Content: Type" should now look like "COUNT(Content: Type)"

That should be it! If needed, adjust some more settings like field labels and row style settings.
Here is an export of such a view, so you can easily import it and try it out:
$view = new view;
$view->name = 'nodecounts';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Node counts';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Node counts';
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['row_options']['inline'] = array(
  'type_1' => 'type_1',
  'type' => 'type',
);
$handler->display->display_options['row_options']['separator'] = ': ';
$handler->display->display_options['row_options']['hide_empty'] = 0;
$handler->display->display_options['row_options']['default_field_elements'] = 1;
/* Field: Content: Type */
$handler->display->display_options['fields']['type_1']['id'] = 'type_1';
$handler->display->display_options['fields']['type_1']['table'] = 'node';
$handler->display->display_options['fields']['type_1']['field'] = 'type';
$handler->display->display_options['fields']['type_1']['label'] = '';
$handler->display->display_options['fields']['type_1']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['external'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['type_1']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['type_1']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['trim'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['html'] = 0;
$handler->display->display_options['fields']['type_1']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['type_1']['element_default_classes'] = 1;
$handler->display->display_options['fields']['type_1']['hide_empty'] = 0;
$handler->display->display_options['fields']['type_1']['empty_zero'] = 0;
$handler->display->display_options['fields']['type_1']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['type_1']['link_to_node'] = 0;
$handler->display->display_options['fields']['type_1']['machine_name'] = 0;
/* Field: COUNT(Content: Type) */
$handler->display->display_options['fields']['type']['id'] = 'type';
$handler->display->display_options['fields']['type']['table'] = 'node';
$handler->display->display_options['fields']['type']['field'] = 'type';
$handler->display->display_options['fields']['type']['group_type'] = 'count';
$handler->display->display_options['fields']['type']['label'] = '';
$handler->display->display_options['fields']['type']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['type']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['type']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['type']['alter']['external'] = 0;
$handler->display->display_options['fields']['type']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['type']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['type']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['type']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['type']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['type']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['type']['alter']['trim'] = 0;
$handler->display->display_options['fields']['type']['alter']['html'] = 0;
$handler->display->display_options['fields']['type']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['type']['element_default_classes'] = 1;
$handler->display->display_options['fields']['type']['hide_empty'] = 0;
$handler->display->display_options['fields']['type']['empty_zero'] = 0;
$handler->display->display_options['fields']['type']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['type']['separator'] = '';
$handler->display->display_options['fields']['type']['format_plural'] = 0;

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');

Comment: @Fedir, if you think that, you need to learn more about the Views module. This is just exported configuration and setting properties on an object is not heavy on the server at all. It is true that the Views module as a whole will use more resources than a custom block, but it's nothing that the smallest shared server couldn't handle.  There are good reasons to use views throughout your site: maintainability, security, faster development and caching options. Custom code is fine too, but do not discard Views just because an export takes 81 lines.
Comment: I'm agree, the Views module could be quite useful in many situations. For current task, I'll use simple query to count the object, as it will be lighter. I don't like to overhead where I could it faster.
Comment: That's looks to "heavy" for the server performance.
Answer: Here is a function that will return the number of nodes for a specific content type:
function YOURTHEME_get_node_count($content_type) {
  $query = 'SELECT COUNT(*) ' .
           'FROM {node} n ' .
           'WHERE n.type = :type';
  return db_query($query, array(
      ':type' => $content_type
  ))->fetchField();
}

To use this code in your theme, add the function into your template.php and then you can call the function like this:
echo 'Pages: ' . YOURTHEME_get_node_count('page');
echo 'Products: ' . YOURTHEME_get_node_count('product');

Answer: The preferred, programmatic way, is to use the EntityFieldQuery class. Learn why EntityFieldQuery is superior to db_query().
Here's an example of counting Nodes of type Blog.
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node') // grab nodes
->entityCondition('bundle', 'blog') // filter by blog type
->propertyCondition('status', 1) // filter by published
->count(); // count

$result = $query->execute();

See similar question.
Answer: Using Drush is simple and quick.
drush sqlq 'select count(node.nid) as node_count, node_type.type from node inner join node_type on node.type = node_type.type group by node_type.type'

This gives output similar to:
node_count  type
17  category_2012
20  category_2013
19  category_2014
3   competition
19  entry_2012_breakthrough
89  entry_2012_digitalother
50  entry_2012_directdirect
19  entry_2012_filmsecscn
17  entry_2012_insights
12  entry_2012_outdoor
31  entry_2012_promo
19  entry_2013_breakthrough
100 entry_2013_digitalother
40  entry_2013_directdirect

And then if you want filter by a specific type, just use grep like this:
drush sqlq 'select count(node.nid) as node_count, node_type.type from node inner join node_type on node.type = node_type.type group by node_type.type' | grep 2014

Answer: I did this using EntityFieldQuery.
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
    /* this is the content type machine name */
    ->entityCondition('bundle', 'product')
    /* You can set extra properties using fieldCondition and properties with propertyCondition */
    ->fieldCondition('field_product_status', 'tid', key(taxonomy_get_term_by_name('New')))
    ;

$result = $query->execute();
if (isset($result['node'])){
    $count_of_new_product_nodes = count($result['node']);
}

Comment: EntityFieldQuery unfortunately will have to fetch all the nodes from the databases and then count how many are there. So this is really heavy. Use the views or the SQL answers above they're much lighter.
Answer: For anyone who is interested, another solution is to use the countQuery method of the SelectQuery class (via db_select).
$count = db_select('node')
  ->condition('type', 'some-type')
  ->countQuery()->execute()->fetchField();

However, I do prefer the EntityFieldQuery solution posted by timofey. I am only providing this as a reasonably sensible alternative.
Answer: SELECT
  COUNT({node}.nid) AS node_count,
  {node_type}.type
FROM {node}
  INNER JOIN {node_type} ON {node}.type = {node_type}.type
GROUP BY {node_type}.type;

Use this query in your code
Answer: The Node Type count module do the same as you require.

This module is used to Show a count of nodes of a particular content-type
  and also number of Users of particular role type.
This module will be used for statistical and dev purposes only.
Answer: As a variation to the answer about using the Views module, you could "use" the view that comes with the Charts module. Simply install / enable it, no additional configuration, coding, etc needed. Some more details about this view, included in the Out-of-the-box examples (quote from this link):

... navigate to charts/examples/views in your site. You should
  then see a column chart and a pie chart, which are followed by a
  tabular display also. Both charts and the table display contain data
  about the total number of nodes for each of the available content
  types.

Notes:

As a bonus, apart from the tabular format, you also get a chart to visualise the number of nodes by content type.
If you like the view, and/or it is close to what you want, you might also clone the view, and then just disable the Charts module again.

Disclosure: I'm the maintainer of this module,
I hope this does not violate the site's policy on self-promotion.

Count of nodes by type


How many solutions does equation $g(c-x) = ax+b$ have?

Question:
Let $g: \mathbb{R} \to \mathbb{R}$ be convex and increasing function. How many solutions does equation $g(c-x) = ax+b$ have? where $a, b, c$ are constant.

I think the answer is at most two if $g$ is not linear function.
Answer: Consider $g(x) = x + \max\{0,x\}$. This is stricly increasing and convex, but not strictly convex. Then,
$$g(c - x) = -2 \, x + 2\,c$$
for $c-x \ge 0$
and
$$g(c-x) = -x +c$$
for $c-x \le 0$.
Hence, you have infinitely many solutions for
$$a = -2, b = 2 \, c$$
and
$$a = -1, b = c.$$
Comment: Of course, but the author wanted a function which is not linear.
Comment: Yep. Even $g(x)=x$ would suffice here.
Comment: Ah, I missed that last "if"
Comment: So really, probably the condition the OP really needed to correct his guess is strict convexity.
Answer: Yes, there is a maximum of two intersections.
One function can go above and then below the other function if the second derivative is decreasing.
One function can go below and then above the other function if the second derivative is increasing.
We cannot get a third intersection, because that would require a switch of the concavity of the function.
Comment: it's so intuitive, can you prove it formally?
Comment: gotcha lemme type it up
Answer: First, I'm not sure why we want to solve $g(c-x) = ax+b$ instead of $g(x) = ax+b$. Indeed, we could make the substitution $y=c-x$ in the first (given) equation to get
$$ g(y) = a(c-y)+b = (-a)y + (b+ac) $$
which is of the form I mentioned above, so unless there are any bounds on $a$, $b$, or $c$, Let's solve $g(x) = ax+b$, where $g$ is strictly increasing and convex.
Suppose there were three solutions $x_1 < x_2 < x_3$. Since $g$ is strictly increasing, we must have
$$ g(x_1) < g(x_2) < g(x_3) ,$$
which is
$$ ax_1 + b < ax_2 +b < ax_3 + b ,$$
which means that $a > 0$. Now since $g$ is strictly convex, we have that for any $t \in (x_1, x_3)$,
$$ g(t) < \frac{x_3-t}{x_3-x_1} g(x_1) + \frac{t-x_1}{x_3-x_1} g(x_3) .$$
In particular, for $t=x_2$, we have
$$ g(x_2) < \frac{x_3-x_2}{x_3-x_1} g(x_1) + \frac{x_2-x_1}{x_3-x_1} g(x_3) ,$$
$$ ax_2 + b < \frac{x_3-x_2}{x_3-x_1} (ax_1+b) + \frac{x_2-x_1}{x_3-x_1} (ax_3+b) ,$$
$$ x_2 < \frac{x_3-x_2}{x_3-x_1} x_1 + \frac{x_2-x_1}{x_3-x_1} x_3 = x_2 ,$$
a contradiction. So when $g$ is strictly increasing and strictly convex, there can be at most two solutions.
Go through the above proof and see what you find when you replace strictly increasing with increasing, and similarly with convexity, and what edges cases then appear. The main case to expect is the case where $g$ is a linear function. This should appear as a case of the modified proof.


Converting Integer to Binary and storing values into an array

Question: What I am trying to do is to convert an integer to binary and store these values into an array. What I have done so far is I have created a for loop to get the range of numbers and used an algorithm to convert these to binary. However here are my problems: my program only prints 1 value (0 or 1) on each line when I want each integer to be converted to binary in one line and in the form 0000 0001. Another thing I am struggling with is storing these values into an array.
 for(m=0;m<10000;m++)
    {
        const char baseDigits[2]= {'0','1'};
        int convertedNumber[1000];
        int numberToconvert;
        int NextDigit = 0;
        int base = 2;
        int index = 0;
        //get number and base;
        numberToconvert = m;
        //convert to base2
        do
        {
            convertedNumber[index] = numberToconvert % base;
            ++index;
            numberToconvert = numberToconvert / base;

        }
        while(
            numberToconvert != 0
        );

        //display results in reverse order
        for(--index;index>=0;--index)
        {
            NextDigit = convertedNumber[index];
            printf("%c \n", baseDigits[NextDigit]);
        }

    }

Answer: Remove \n from printf with improved for loop as below:
index--;
for(;index>=0;--index) {
    NextDigit = convertedNumber[index];
    printf("%c", baseDigits[NextDigit]);//you could have used %d and printed directly convertedNumber[index]
}
printf("\n");

Comment: You'll probably want to add `printf("\n");` after this code as well.
Comment: Optional but as you say ;-)
Comment: Thanks for the answer it worked, However I'm still struggling to get this in the format of binary e.g 1 should be 0000 0001
Comment: your could use if to check index value and if its less than 8 then you can pad '0' in loop and then follow your for loop.
Answer: int i = 0;
for(--index;index>=0;--index)
{
    NextDigit = convertedNumber[index];
    printf("%c", baseDigits[NextDigit]);
    if(index && ++i % 4 == 0)
        printf("%c", ' ');
}
printf("\n");


delete row permanently from database with delete button(laravel)

Question: i want to delete row permanently from database via delete button.
this is my button code in a form that sends id to destroy function.
{!! Form::open(array('url' => 'admin/newsmaster/'.$value->id, 'class' => 'form-horizontal create_form', 'files' => true)) !!}
    <input type="hidden" name="_method" value="delete">
    <button type="submit" class="btn red">Delete</button>
</form>

this is my destroy function:
public function destroy($id)
    {
        $feed= Feed::find($id);
        $feed->delete();
        Session::flash('message', 'News Deleted Successfully.');
        $redirect = 'admin/newsmaster';
        return Redirect::to($redirect);
    }

this is my Feed model:
protected $table = 'feed_news';
use SoftDeletes;
protected $softDelete = true;
protected $dates = ['deleted_at'];

my problem is when i click on delete option my row in database doesn't get deleted, instead it updates the deleted_at column.
Comment: Because you are using `SoftDeletes`
Answer:
To permanently remove a soft deleted model from the database, use the forceDelete method:

$feed= Feed::find($id);
$feed->forceDelete();

Documentation
Answer: You are using Eloquent's Soft Delete Trait. Therefore, you specified in your FeedModel to soft delete the records. By removing its from the model, Eloquent will permanently delete the specific row.
FeedModel
protected $table = 'feed_news';

protected $dates = ['deleted_at'];


solve for $y$ in $e^{xy}+x^2+y-1.2$

Question:
I cant figure out how to make $y$ the subject in this equation:
  $$e^{xy}+x^2+y-1.2=0$$

I did these steps,
$$\begin{align}&y=1.2-x^2-e^{xy}\\
&\ln(y)=\ln(1.2)-\ln(x^2)-\ln(e^{xy})\\
&\ln(y)=\ln(1.2)-\ln(x^2)-xy\\
&\ln(y)+xy=\ln\frac{1.2}{x^2}\end{align}$$
ahead of this I am lost and would appreciate any and all help.
Comment: This function is not linear! In other words, the log of a sum (ie, the right hand side) is NOT the sum of the logs.
Comment: that means the second step should be $ln(y)=ln(1.2-x^2-e^{xy})$? How do i proceed ahead of this though? There should be another way to handle this since it doesnt bring me any nearer to solve for y
Comment: That is what the seconds step *would* be. I agree that it doesn't seem to move you in the right direction.
Answer: Let $a=1.2$, rearrange a little and we have
\begin{eqnarray*}
e^{-xy} (a-x^2-y)=1.
\end{eqnarray*}
Multiply by $xe^{ax-x^3}$
\begin{eqnarray*}
 (\color{red}{ax-x^3-xy})e^{\color{red}{ax-x^3-xy}}=xe^{ax-x^3}.
\end{eqnarray*}
Now recall the Lambert $W$ function is defined by $\color{red}we^{\color{red}w}=z$ gives $w=W(z)$. So we have
\begin{eqnarray*}
ax-x^3-xy =W(xe^{ax-x^3}) \\
y=\frac{ax-x^3-W(xe^{ax-x^3})}{x}.
\end{eqnarray*}
Answer: This equation has no solutions in terms of elementary functions. Mathematica returns
$$y=\frac{-5 W\left(e^{-x \left(x^2-\frac{6}{5}\right)} x\right)-5 x^3+6 x}{5 x}$$
where $W$ denotes the Lambert W function.
Comment: Im sorry you started with the wrong equation, which was primarily my fault since I've used math jax for the first time. I've edited the equation since to the reflect the correct one.
Comment: thankyou so much for the answer. Could you please provide the steps leading up to the lambert function too?
Comment: @TheChaz2.0 The question was edited after I posted this answer.
Comment: @BlitzMee I cannot. This is not an equation one can solve by hand.

solve for $y$ in $e^{xy}+x^2+y-1.2$


Images can't be resolved in Sass when using CSS modules

Question: I'm using Webpacker in my Rails project and want to use CSS modules to obfuscate the CSS classes for my CSS and SASS files in my components.
./config/webpack/development.js looks like:
process.env.NODE_ENV = process.env.NODE_ENV || 'development'

const environment = require('./environment')

/// Use CSS modules and obfuscate CSS class names
const cssRule = environment.loaders.get('css')
const sassRule = environment.loaders.get('sass')
const cssLoader = cssRule.use.find(loader => loader.loader === 'css-loader')
const sassLoader = sassRule.use.find(loader => loader.loader === 'css-loader')

cssLoader.options = Object.assign(cssLoader.options, {
  modules: true,
  localIdentName: '[path][name]__[local]--[hash:base64:5]'
})

sassLoader.options = Object.assign(sassLoader.options, {
    modules: true,
    localIdentName: '[path][name]__[local]--[hash:base64:5]'
  })
///

module.exports = environment.toWebpackConfig()

Now this works fine for just the CSS and SASS and obfuscates them fine... however when I reference something such as an image inside my CSS I get the error:

ERROR in
  ./node_modules/css-loader??ref--2-2!./node_modules/postcss-loader/lib??ref--2-3!./node_modules/sass-loader/lib/loader.js??ref--2-4!./app/javascript/components/menu/main.scss
      Module not found: Error: Can't resolve 'background.png' in '/Users/cameron.drysdale/Projects/webpack_test/app/javascript/components/menu'
       @ ./node_modules/css-loader??ref--2-2!./node_modules/postcss-loader/lib??ref--2-3!./node_modules/sass-loader/lib/loader.js??ref--2-4!./app/javascript/components/menu/main.scss
  7:785-805

Inside main.scss I have:
.element {
    background-color: #ffffff;
    background-image: url('background.png');
    background-position: left center;
    background-repeat: no-repeat;
}

If I turn off the CSS modules, then it works fine...
What's causing the error?
Answer: you'll need to use resolve-url-loader to have the url resolve correctly


Function related problem

Question: Let $g:N \to N$ be defined as
$g\left( {3n + 1} \right) = 3n + 2$
$g\left( {3n + 2} \right) = 3n + 3$
$g\left( {3n + 3} \right) = 3n + 1$, for all $n \ge 0$.
Then which of the following statement is true?

There exist an onto function $f:N \to N$ such that $f\circ g=f$.

There exist a one-one function $f:N \to N$ such that $f\circ g=f$.

$g\circ g\circ g=g$.

There exist a one-one function $f:N \to N$ such that $g\circ f=f$.

I tried to make $f(x)=x+1$, the first two condition will satisfy it but the third will will not do so as it will satisfy the condition $f(x)=x-2$.
Comment: I don't understand.  Are you trying to make $f=g$?  That's not what the question is about.
Answer: I won't answer this question for you, but I'll try to get you started, because from what I can tell, you don't see what it's about.
The first couple of options ask about a function such that $f\circ g=f$.  What would such a function be like?  We'd have
$$
\begin{align}
f(3n+1)&=f(g(3n+1))=f(3n+2)\\
f(3n+2)&=f(g(3n+2))=f(3n+3)\\
f(3n+3)&=f(g(3n+3))=f(3n+1)
\end{align}
$$
Is there a one-to-one function or an onto function that satisfies these requirements?
For the other two parts, proceed as above.  Start by unraveling the formulas to see what the question is really asking.

Function related problem


Do a Calculation using table calculation in tableau

Question: I have 2 calculated fields A & B they both are calculated using Table calculation.
Now I want is to make bins using them like:
Example: My Table calculation A & B
What I want to do is:-
IF A > 0 & B > 0 Then Case 1
IF A < 0 & B < 0 Then Case 2
IF A > 0 & B < 0 Then Case 3
IF A < 0 & B > 0 Then Case 4
Thank you for your response & apologize for not attaching the Workbook.
Answer: This should be fairly simple using IF + ELSEIFs - try the formula below:
<code>IF (A > 0 & B > 0) THEN "Case 1"
ELSEIF (A < 0 & B < 0) THEN "Case 2"
ELSEIF (A > 0 & B < 0) THEN "Case 3"
ELSEIF (A < 0 & B > 0) THEN "Case 4"
END
</code>
This should return 4 distinct values Case 1, Case 2, Case 3, Case 4 based on the input variables A and B. Hope this helps!


Atualização no MongoDB

Question: Existe alguma função que permita enviar alguma mensagem quando algum dado for adicionado na collection?
Meio que um logs
Por exemplo:

data = {
    "_id": 12345678910
}

return db.insert_one(data)

Terminal:
Um novo documento foi adicionado na collection!:
"_id": 12345678910

Comment: pq voce nao adiciona uma funcao no seu backend, ao adicionar a collection envia uma notificacao algo do tipo
Answer: Com as informações que você forneceu fica praticamente impossível te responder. Explico:
1) Você não deu nenhuma informação sobre o contexto (você vai incluir um documento na collection e quer saber se o documento foi corretamente inserido? Ou um outro usuário vai adicionar um documento e você quer enviar uma notificação para ele? Entre outras diversas opções...)
2) Na sua pergunta você cita collection, mas no seu exemplo você usa a database. Você quer saber se um documento foi inserido na collection ou na database como um todo?
Se você estiver inserindo e quiser checar que a operação foi bem-sucedida, considere checar acknowledged e se você consegue acessar o id do novo documento.
>>> new_document = collection.insert_one({'teste0': 'teste0'})
>>> new_document.acknowledged
True
>>> print(new_document.inserted_id)
5d8df5f3d6866c94867acc3b

De acordo com a documentação oficial, acknowledged == False indica que todos os outros atributos da classe acusarão InvalidOperation quando acessados.
É claro que você também pode usar a mesma lógica quando inserir mais de um documento na mesma operação:
>>> new_documents = collection.insert_many([{'teste1': 'teste1'}, {'teste2': 'teste2'}])
>>> new_documents.acknowledged
True
>>> for id in new_documents.inserted_ids:
...     print(id)
...
5d8df7a3d6866c94867acc3c
5d8df7a3d6866c94867acc3d

De fato, você até pode tentar prever outros erros quando for realizar uma operação. Uma abordagem bem genérica é a seguinte:
try:
    #Qualquer uma de suas operações
except pymongo.errors.PyMongoError as erro:
    logging.error(f'Erro inesperado com o Mongo: {erro.__class__};\n{erro}')
    #Código para tratar alguma exceção genérica

pymongo.errors.PyMongoError é classe base para todas as exceções do pymongo.
Se você não tiver acesso direto a operação, considere usar count_documents:
>>> num_docs = collection.count_documents({})
#Como não passamos nenhum filtro, checamos todos os documentos da collection
>>> num_docs
7
...
...
...
...
'''
Checando se um novo documento foi inserido
'''
>>> new_num_docs = collection.count_documents({})
>>> if new_num_docs > num_docs: #Novo documento inserido!
...     print('Um novo documento foi adicionado.')
...     print(new_num_docs, num_docs)
...
Um novo documento foi adicionado.
8 7

Comment: Queria fazer com que cada documento adicionado na collection(db) fosse printada algo no terminal
Comment: Coloquei um exemplo melhor
Comment: Como, por onde e por quem os documentos vão ser adicionados?

Atualização no MongoDB


Generating points in rectangle

Question: I am trying to generate $N$ points randomly and uniformly distributed in an $m \times n$ rectangle. How can this be done? I have tried to split the initial rectangle into as many rectangles i could, but this didn't work.
Answer: For each point, independently generate two numbers: $l_i\sim U(0,m)$ and $h_i\sim U(0,n)$. The resulting point $(l_i,h_i)$ is a point in the rectangle and the joint distribution is uniform over the entire rectangle.
Comment: could you prove the distribution is uniform ? To me, you're taking the uniform distribution on a square, and stretch it to a rectangle. Unlikely to produce a uniform distribution on the rectangle (e.g., consider a highly stretched rectangle)
Comment: The joint density on the rectangle is the product of the densities $\frac{1}{m}\frac{1}{n}=\frac{1}{mn}$. Thus the density is uniform over the entire rectangle.

Generating points in rectangle


How should the logo of Magento.Stackexchange look like?

Question:
Should and can we include the official Magento logo?
Or something derived?
Feel free to submit suggestions.
Comment: Had to be asked a while a go!
Answer: My idea is that site  has to be named mageoverflow :) and logo can be something in between of SO and Magento. Like sliced Magento logo overflowing the SO logo box.
Comment: Seems better to stick with the "oops" theme... I like `flushed-cache` since that's pretty much step #1 in Magento debugging.
Answer: We need eBay branding all over this site. Settle down, I'm just kidding.
Magento Orange is a given - but perhaps utilize the theme presented at the 2013 Imagine - triangles interlocking to form a mesh-like structure. I can see that across the masthead of the SE site.
The logo could be extended like they do for the hackathons - something protruding from the bottom of the Magento logo. Perhaps it could be forming an implicit question mark (perhaps upside down?), to reference the Q&A nature of the site.
As for the name, I like Magento.SE.
If we do the 'oops' sort of a theme - we need to reference reindexing or out of memory PHP errors.
Comment: if there were a Magento CoC in place I would *so* ban you for trolling


Extrema of $f(\theta)=cos(\theta)$

Question: What is the minimum and maximum of $$f(\theta)=\cos(\theta)$$ and what values of theta do they occur at?
I have tried multiple ways to solve this and seem to continue to get it wrong. I feel that I am making a very simple mistake and would like to see each step so I can learn.
Comment: "I have tried multiple ways to solve this", like what?
Comment: What is $f'(\theta)$ ?
Comment: You have to say that $\theta$ is real because for complex $\theta$, the question may not even make sense.
Comment: Look at its graph, maybe?
Answer: Recall from trigonometry
$$
| \cos \theta | \le 1.
$$
The plot of $\cos \theta$ is shown below for $-2\pi < \theta < 2\pi$.

In calculus we look for extrema by identifying the points where the first derivative is zero. Solve
$$
 f'(\theta) = D_{\theta}\left( \cos \theta \right) = - \sin \theta = 0
$$
The solution is
$$
  \theta = 2 k \pi, \quad k \in \mathbb{Z}
$$
Are the extrema maxima or minima? We must look at the second derivate. If $f''(\theta) > 0$, we are at a minimum. When $f''(\theta) < 0$, we are at a maximum.
Evaluate
$$
 f''(\theta) = D_{\theta}\left(D_{\theta}\left( \cos \theta \right)\right) = D_{\theta}\left( - \sin \theta \right) = - \cos \theta
$$
at the $\theta$ values from above.
When the angle is an even multiple of $\pi$,
$$
  \theta = 2 k \pi, \quad k \in \mathbb{Z}
$$
we have a maximum. When the angle is an odd multiple of $\pi$,
$$
  \theta = (2 k + 1) \pi, \quad k \in \mathbb{Z}
$$
we have a minimum.

Extrema of $f(\theta)=cos(\theta)$


"This entity (node: id) cannot be referenced" error

Question: I use Drupal 8 and I have a content type which has a field that references another content type as a entity reference field. I use a rest endpoint to create the node and the referenced node which works fine.
I also have the workbench module installed so I can change the moderation state of the nodes.
The problem is that when I change the moderation state from draft to review I get the error This entity (node: {ID}) cannot be referenced.
Why am I getting this?
Answer: The view_unpublished "module allows you to grant access for specific user roles to view unpublished nodes of a specific type. Access control is quite granular in this regard."
<code>composer require drupal/view_unpublished
drush en -y view_unpublished
</code>
At /admin/people/permissions set permissions as required:

Finally, at /en/admin/reports/status/rebuild rebuild the permissions, which may take some time:
Answer: The issue was that the field was used to reference unpublished nodes and kept throwing the error. I updated the field to allow unpublished nodes too. It worked.
Comment: Where exactly did you update the field to allow unpublished content as well?
Comment: I only see "Default" and "Views: Filter by an entity reference view": https://i.stack.imgur.com/zBzPm.png I've found another way, which I'll post as an answer.
Comment: Having just been in this situation, I'll second @Hugo 's observation that I also didn't see what Harnamc suggests looking for. I'm wondering if Harnamc has enabled a module, and now is taking this functionality extension for granted? Regardless, this suggestion isn't valid on our D8.3 site.
Comment: In the drupal menu select structure and then content type. Select the content type in question and about half way down he page there is a option selection box. In that box you select unpublished
Comment: I must be missing it, here's what I see at /admin/structure/types/manage/article: https://i.stack.imgur.com/3qCgH.png Please could include a screenshot?
Comment: https://www.drupal.org/files/issues/field_settings_0.png it's the option that says default. Change that to unpublished
Answer: We can use this module entity_reference_unpublished.
Or add "bypass node access" permission.

!!! This is very powerful permission that you may not want to give to your
editors.
Answer: Check that the view does not have a filter for 'Content: Published (=Yes)'.
The validator uses an entity_reference view to get a list of valid entity ids. If the entity selected (e.g. from entity_browser view) is not in the list of valid ids, then this error will be displayed.
Ensure that both views have the same criteria.
If you are working in workflow, the default 'Published' may not be the filter criteria that you want.
Answer: The views_unpublished module (from this answer) has an ominous bug for multilingual sites and translations with different published status.
An alternative is to use a patch from 'Move permission "view any unpublished content" from content moderation to core: this is something which is currently targeting Drupal Core 8.5. At the time of writing, I've used this patch in Drupal 8.3.7.
Answer: I was getting this when the Manage fields > Reference Type wasn't set.  There are 2 kinds of reference:  Reference method and Content type and it is possible to not select anything here - selecting the correct content type solved the issue for me.
Answer: I had received the same error during form submission of a content type.
I was using an entity reference field with Ajax that is set to display values of two other taxonomy reference fields in the same content type. The field could only show terms selected in the other two fields.
On form submission I was getting this error. I found that the root cause of the problem was that the ajax field was not set to reference one of the vocabulary in the other field.
I proceeded to edit the field settings and enable the vocabulary in the checkboxes. The error was resolved after that.
Answer: Many of the other answers here require installing new modules and making configuration changes.  If you're comfortable with adding patches to your site, see the patches at the bottom of this issue:
https://www.drupal.org/project/drupal/issues/2845144
In theory this is ready to be committed to Drupal Core as of May 2020.  However, my guess is that there will be debates about whether this breaks backwards compatibility, and ultimately won't be committed until Drupal 10.


How to convert decimal to 64bit binary and load it to a bitarray (not byte array)

Question: Please provide me the code to convert 15698 which is stored in a Int64 and load the binary bits to a bitarray
please see the image here chart
Comment: Use `Convert.ToString(15698, 2).PadLeft(64, '0')`
Comment: Be carefull with your title, [decimal](https://msdn.microsoft.com/en-us/library/xtba3z33.aspx) is not the same as [Int64](https://msdn.microsoft.com/en-us/library/System.Int64(v=vs.110).aspx).
Comment: I have no idea how to do it that's why I asked, atleast tell me if there's a vb function to get it converted ..
Comment: Read the documentation of the [BitArray constructor](https://msdn.microsoft.com/en-us/library/b3d1dwck(v=vs.110).aspx) on MSDN. There is no version that creates a `BitArray` from an `Int64`, but there is one that creates one from an array of `Int32`. All you need to do is create an array of two `Int32` and store the high order bits in one element and the low order bits in the other.
Answer: Since the BitArray constructor does not take an Int64 argument, you need to first convert it to a byte array.  You can use the BitConverter class to do that:
Dim input As Long = 15698
Dim b As New BitArray(BitConverter.GetBytes(input))

Obviously, when converting to byte and bit arrays, you may need to concern yourself with endianness.
Comment: Nice use of endianness
Comment: I searched google for endianness ... since most of the computers use little-endian as I see, will it be a problem?
Comment: I don't know if it would be a problem because I don't know for what you are doing it.  Usually you only care about endianness if you are writing to a standard file format which dictates proper byte-order, or if you are sending the data to another computer.
Comment: I'll save those data to a file using `File.WriteAllBytes` to the hard-disk
Comment: It all depends what byte order you expect/want them to be in.  As long as you expect them to be in little-endian order, and you only ever run your application on a little-endian machine, then, yes, you'll be fine.
Comment: is there a method to bypass this endian scenario ? just like a check to see if the machine uses little or big then changing the loading to bitarray order
Comment: The `BitConverter.IsLittleEndian` lets you know the endianness of the current machine.
Answer: Some different way.
Dim valueToConvert As Int64 = 15698
Dim bitArray = New Boolean(63) {}
For i As var = 0 To bitArray.Length - 1
    bitArray(i) = (tempVal Mod 2) = 1
    valueToConvert =  valueToConvert >> 1
Next
Dim result as New BitArray(bitArray);

Comment: Yes, there was small mistake. Bitwise shift operators are not only c++ operators. From my perspective it's more clear then fighting with bytes and -endian.
Comment: You'd still need to be careful of the endianness, even in your example.  Also, your method is significantly less efficient since it's having to perform a division operation to calculate each bit.  Even with using a bit-shifting algorithm, it would be better to use a bit-wise *and* operation to calculate each bit.
Comment: You seem to be missing something. You are using the value in `tempVal` to set the bits in the array, but nowhere do you set or change the value of `tempVal`.


Ranking undergrad students by their future income - Mixture distribution

Question: I would be very grateful for some advice on how to model mixture distributions with R.
Given a problem to create a ranking of graduate students by their yearly income after completing their education, what are some suited models for this task?
Specifically, my data has a distribution with a point mass at 0 (the majority of graduates doesn't find, or start, a full-time job right away). The rest of the data is sort of nicely distributed. The data $x$ was transformed $\log(x+1)$.

My first approach was a simple regression model
My second approach were two models (one for classifying whether they get a job - is very weak, and second to predict the income) Simply chaining these two models works much worse than the simple model.

My next step would be a Bayesian mixture model to predict income. I was thinking about fitting a mixture with 2 Gaussians, where I would set the mean for one of them to be known as equal to 0. Would that make sense? Has anyone a good experience with some package?
Another problem might be that I am always predicting the income using a regression and building a ranking from that, rather than running an ordinal regression. What is the best way handle this situation - if the target variable (income) that the ranking is based on is itself available for training data?
Full disclosure: This is a fictitious scenario, as I cannot discuss the exact details of the real case.
Comment: For fitting mixture models I use mixtools package in R and it works well
Answer: Mixture models of only two distributions, $D_1$ and $D_2$, can be considered to have the density $p D_1+(1-p) D_2$, where $0<p<1$. Now $p\neq0,1$ because it would no longer be a mixture. In general for any mixture distribution, software is available to find the best mixture model, e.g., FindDistribution in Mathematica, or mixtools in R as suggested by @omidi. However, in the case given by the OP, there is no overlap between distributions, as a salary of zero is not a salary. There is no particular need to add one to the income to take logarithms, as there is no need to take logarithms. Instead, all that need be done is to assign a Dirac $\delta$ for the $D_1$, zero salaries, i.e., $p \delta(x=0) +(1-p)D_2$, and then find $p$ and $D_2$. Finding $p$ is trivial, as $p=\frac{N_{no}}{N_{no}+N_{yes}}$, where $N_{yes}$ and $N_{no}$ are the number of subjects with and without income, respectively. Finding the best distribution for those with incomes can use software, or prior literature to search for models. However, even then, the distribution of those with income, $D_2$ here, can itself a mixture distribution. Moreover, use of an empirical distribution may be enough to answer the some of the questions the OP needs to answer, and although it's nice to have a theoretical distribution, it would not be absolutely required.
That is, the final distribution could be $p \delta(0) +(1-p)D_{Emp}(x)$, where $p=\frac{N_{no}}{N_{no}+N_{yes}}$. To be clear, that formulation is identical to what the data is, as the empirical distribution is $\frac{\delta(x_i)}{N_{yes}}$.
Other questions: "...set the mean for one of them [Sic, Gaussian distributions] to be known as equal to 0." That is what the Dirac $\delta(0)$ is; although the first distribution used to create it was historically Cauchy, it makes little difference which limit one uses to create the $\delta$, because its standard deviation is zero. Regarding using a Gaussian for the second distribution, not a good idea as the right tail of income is notoriously heavy, e.g., see Pareto distribution. If a theoretical distribution is desired in R for the OP's data for those having an income, see this.
Finally, I do not fully understand "Another problem might be that I am always predicting the income using a regression and building a ranking from that, rather than running an ordinal regression. What is the best way handle this situation - if the target variable (income) that the ranking is based on is itself available for training data?"
If one desires to predict income using regression, transforming variables may be desirable, but no transformation of $p \delta(0) +(1-p)D_{Emp}(x)$ will have "nice" residuals. That is, the residuals will not be Gaussian or homoscedastic, so the usual default regression techniques will not yield accurate answers. Maybe the way to treat this is to use classifiers to find the probability of finding a job with a yes/no Y-axis variable, and if yes use glm to find what that salary is for a best theoretical distribution of non-zero salaries. That is, one can then use classifiers to determine predictors of non-zero salary, and when finished, one then has two cases, predictors of getting a job, and predictors of salary if one secures a position.


Linha muda de cor quando o valor é igual a false

Question: Tenho uma lista de usuários e cada usuário pode ser inativado ou ativado.
Eu gostaria que o usuário quando estivesse com o valor 'false' (desativado) mudasse a cor para cinza.
HTML:

         {{user.user}}
         {{user.email}}

            <button class="btn btn-danger" data-toggle="modal" (click)="getUser(user)" data-target="#exampleModal">Recuperar Senha</button>

            <button [hidden]="user.active == false" class="btn btn-danger" (click)="desativarUsuario(user)" >Desativar</button>
            <button [hidden]="user.active == true" class="btn btn-danger" (click)="desativarUsuario(user)" >Ativar</button>

Answer: Não é muito elegante, mas você pode colocar um ngClass em cada coluna (td) com uma condição ternária.

         {{user.user}}
         {{user.email}}

            <button class="btn btn-danger" data-toggle="modal" (click)="getUser(user)" data-target="#exampleModal">Recuperar Senha</button>

            <button [hidden]="user.active == false" class="btn btn-danger" (click)="desativarUsuario(user)" >Desativar</button>
            <button [hidden]="user.active == true" class="btn btn-danger" (click)="desativarUsuario(user)" >Ativar</button>

E, depois, é só utilizar o css para definir a cor de fundo.


Differential Calculus - Swapping a sup and a limit.

Question: Well, I'm doing some exercises on differential calculus and I'm stuck.
(a) Let $U \subset \mathbb R^m$ and $f: U \rightarrow \mathbb R^n$ be a continuous function on a line segment $[x, x+h]\subset U$ and differentiable on $]x, x+h[$. Show that if $T:R^m\rightarrow R^n$ is a linear map, then:
$$ ||f(x+h)-f(x)-T(h)\leq \sup_{t \in ]0, 1[}||df(x+th)-T||\,||h|| $$
(b) Let $U \subset R^m$ and $f:U\rightarrow \mathbb R^n$ a continuous function differentiable on $U- \{x\}$, where $x$ is a interior point of $U$. Suppose $\lim_{y \rightarrow x}df(y)=T$ for some linear map $T: \mathbb R^m \rightarrow \mathbb R^n$. Show that $f$ is differentiable on $x$ and $df(x)=T$. Suggestion: Use item (a).
Progress:
I had no problems with (a) but I'm stuck at be. I must show that:
$$\lim_{h \rightarrow 0} \frac{f(x+h)-f(x)-T(h)}{||h||}=0$$
We know that:
$$\lim_{h \rightarrow 0} \frac{f(x+h)-f(x)-T(h)}{||h||}\leq \lim_{h \rightarrow 0}\sup||df(x+h)-T||$$
If I can swap the sup and the limit then I'm done, but I don't know if I'm allowed to.
Ps: I don't know why, but I cant tag this question properly.
Answer: Hint: Let $\epsilon > 0$ be arbitrary and $\{h_n\}$ be any sequence $0 \neq h_n \to 0$. Then you can find $t_n \in \,]0,1[$ such that $\|f(x+h_n)-f(x)-Th_n\| \leq \big(\|df(x+t_nh_n) - T\|+\epsilon\big)\|h_n\|$ (why can we find such a $t_n$?). Deduce that $t_nh_n$ also $\to 0$ and then use this to conclude that
$$
\overline{\lim_{n \to \infty}} \frac{\|f(x+h_n) - f(x) -Th_n\|}{\|h_n\|} \leq \epsilon.
$$
Since $\epsilon$ and $\{h_n\}$ were chosen arbitrarily, you'll be done after this!
Comment: Can we say that this limit exists? I think we should use the lim sup...
Comment: @ViniciusRodrigues You're correct.. we don't a priori know that the limit exists. I've edited the post to reflect your point.
Answer: Let $\epsilon>0$ be given and let $h_n$ be an arbitrary sequence such that $h_n\neq 0$ and $h_n \rightarrow 0$.
For each $n$, there exists a $t_n \in ]0, 1[$ such that $$\|f(x+h_n)-f(x)-Th_n\|\leq(\|df(x+t_n h_n)-T\|+\epsilon)\|h_n\|$$
(Otherwise, we would have that $\forall t\in (0, 1), \, \|f(x+h_n)-f(x)-Th_n\|>(\|df(x+t h_n)-T\|+\epsilon)\|h_n\|$, therefore  $ \|f(x+h_n)-f(x)-Th_n\|\geq(\sup_{t \in (0, 1)}\|df(x+t h_n)-T\|+\epsilon)\|h_n\|$ $>\sup_{t \in (0, 1)}\|df(x+t h_n)-T\|\|h_n\|$, which is absurd).
Since $t_n$ is bounded, $x+t_n h_n\rightarrow x$ as $n\rightarrow \infty$. Therefore, by our hypothesis, $\limsup\frac{\|f(x+h_n)-f(x)-Th_n\|}{\|h\|}\leq \epsilon $. Since $\epsilon$ is arbitrary, $\limsup\frac{\|f(x+h_n)-f(x)-Th_n\|}{\|h_n\|}\leq 0 $. But $\liminf\frac{\|f(x+h_n)-f(x)-Th_n\|}{\|h_n\|}\geq 0 $, therefore $\lim_{n\rightarrow \infty}\frac{\|f(x+h_n)-f(x)-Th_n\|}{\|h_n\|}= 0 $. We conclude that $\lim_{n\rightarrow \infty}\frac{f(x+h_n)-f(x)-Th_n}{\|h_n\|}= 0 $, and since $h_n$ was arbitrary, we have shown that $\lim_{h\rightarrow 0}\frac{f(x+h)-f(x)-Th}{\|h\|}= 0$. $\square$
Comment: Your proof looks good!


Alternative to "Pattern" Attribute for Input

Question: I'm creating a web form that I'd like to add field verification to. The current approach involved specifying a "pattern" attribute in the input tags as follows:
 <input id="foo" class="span7" type="text" pattern="^[0-9]*\.?[0-9]*$">

However, this approach has unexpected behavior, and as I've read from MDN, is not supported in all major browsers. Is there an alternative to this functionality?
To be clear, I'd like to trigger a stylistic effect if the contents of the text box does not match a specified regex. I realize this can be achieved with Jquery and add/remove class, but this feels rather inefficient.
Answer: there's really no efficient way to do this; you either need to employ pattern or do your own event listener which runs its own regex on a key event.
Comment: In this case, do you know why the example provided above does not work correctly? The :invalid pseudo-class is applied for all inputs, even those that seem to follow the regex.
Comment: you'll have to put it up on jsfiddle or codepen so I can see what you're talking about.
Answer: Try this:
HTML:
<input id="foo" class="span7" type="text" onblur="checkInput(this.value,'^[0-9]*\.?[0-9]*$');">

JavaScript:


What is the discrepancy function in structural equation modeling?

Question: Excerpt from Book
I am currently trying to improve my knowledge of structural equation modeling, and have been reading through Structural Equation Modeling with Lavaan by Gana & Broc to do so. They have the following simple model:

The table they reference thereafter looks like this, which is a collection of iteration cycles:

To explain this table, they give the following details:

Question
However, I'm still not entirely sure what they are getting at here. Does SEM software simply start off with some prior estimate of what a regression path should be, then take multiple "guesses" until it is the most accurate? It appears the residual matrix is based off the "misfires" of these guesses, which seems functionally similar to how residuals normally work in regression.
My previous assumption was this wasn't pre-specified by the user other than your normal constraints (fixing a path to be 1, etc.). I also noticed that they mentioned the iterations stop and so I assume that is just when the guessing is found to not improve. Or is there something I'm missing here? To summarize this into one question, how does the discrepancy function in SEM work? Please explain like I am a small child if possible.
Answer:
I am currently trying to improve my knowledge of structural equation modeling, and have been reading through Structural Equation Modeling with Lavaan by Gana & Broc

Be wary; there are some major problems with that book that were never caught/fixed during peer review.
Jorgensen, T. D., & Jak, S. (2020). Review of Gana & Broc's Structural Equation Modeling with lavaan. Psychometrika, 85, 373–377. https://doi.org/10.1007/s11336-020-09705-6
Preprint and spreadsheet of inaccuracies available on the OSF: https://osf.io/9up3s/

Does SEM software simply start off with some prior estimate of what a regression path should be, then take multiple "guesses" until it is the most accurate?

There are many different methods to choose starting values.  Some are simple, like setting all variances to 1 and all covariances and regression slopes to 0.  Others utilize sample statistics to make smarter guesses.
How an optimizer searches for better estimates might vary with the specific algorithm (e.g., Fisher scoring, expectation--maximization, quasi-Newton), but generally the first derivative of the (log-)likelihood function provides a gradient, which is a vector that points the optimizer in a specific direction in the parameter space that leads to larger (log-)likelihood.  After "going there", the (log-)likelihood is recalculated, then the gradient is calculated again to point further.  This continues until the likelihood changes only negligibly, according to some minimum-change criterion.

how does the discrepancy function in SEM work?

The ML discrepancy function typically used is the average casewise log-likelihood ratio comparing the SEM being fitted to the unconstrained sample statistics (a saturated model). That is the (log-)likelihood function I referred to above, evaluated each time new estimates are chosen by "following" the gradient through the parameter space.
Comment: I like Beaujean's book, very practical with lavaan syntax.  He also coauthored the most recent edition of Loehlin's classic SEM book (Latent Variable Models), which covers more technical details quite well.
Comment: Thank you for the excellent answer and the warning about the book. I'll try to find better material. Any suggestions? I have Beaujean's book and a few others, but I'm never sure which is best for beginners. I understand the basics of CFA/SEM but beyond that I am lacking.
Comment: Thanks. I'll give those a read then.


When does restriction of scalars induce flat Modules?

Question: Let $f:Y\rightarrow X$ be a ring homomorphism, and let us consider $X$ to be a $Y$-module via restriction of scalars, i.e. given some $y\in Y$, this element acts on $X$ via $f(y)\cdot x$, for $x\in X$
I'm trying to determine what conditions we must put on $f$ in order for $X$ to be a flat $Y$-module. By definition, this means that given an injective morphism $m:N\rightarrow M$ of $Y$-modules, we have that $1\times m: X\otimes_Y N \rightarrow X\otimes M$ is also injective.
I did a bit of computation that seemed a bit off to me, and I just wanted a bit of a sanity check. To prove what conditions on $f$ would be necessary in order for $1\times m$ to be monic, suppose we had $x_1\otimes m(n_1)= x_2\otimes m(n_2)$. We want to see how we might obtain the equation $x_1\otimes n_1 = x_2\otimes n_2$.
I would like to prove this in a setting more general than vector spaces (really, I'd like to work in the category of sup-lattices, as found in Joyal-Tierney), but for now let's just follow the characterisation provided in the answer here: Necessary and sufficient condition for equality of two tensor products
Then, there are three cases in which $x_1\otimes m(n_1)= x_2\otimes m(n_2)$:

Suppose $m(n_1)\neq 0$, and $\exists y\in Y$ such that $y\cdot m(n_1)=m(n_2)$. Then this forces the relation that $f(y)\cdot x_2 = x_1$. Since $Y$-module morphisms respect the action, we have that $m(n_2)=y\cdot m(n_1)= m(y\cdot n_1)$, which implies that $n_2=y\cdot n_1$ since $m$ is injective. Since $f(y)\cdot x_2=x_1$, this means that $x_2\otimes n_2 = x_2\otimes y\cdot n_1 = f(y)\cdot x_2\otimes n_1 = x_1\otimes n_1$.

Suppose $m(n_1),m(n_2)$ are linearly independent. Then, $x_1=x_2=0$, which implies that $x_1\otimes n_1 = x_2\otimes n_2$.

Finally, suppose $m(n_1)=0$. Then, we have that either $m(n_2)=0$ or $x_2=0$. Since $m$ is monic, we have that $n_1=0$, and thus $x_1\otimes n_1=0$. If $m(n_2)=0$, then $n_2=0$ as well, and thus $x_2\otimes n_2=0$; and if $x_2=0$, then $x_2\otimes n_2=0$ as well.

This little computation seems to imply that restriction of scalars always induces a flat module in this way - is that right? But that seems strange. For instance, take the quotient map $f:\mathbb{Z}\rightarrow\mathbb{Z}/n\mathbb{Z}$. It is well-known that for $n>1$, $\mathbb{Z}/n\mathbb{Z}$ is not flat over $\mathbb{Z}$ since while $n:\mathbb{Z}\rightarrow\mathbb{Z}$, $x\mapsto nx$ is injective, the map $1\times n:\mathbb{Z}/ n\mathbb{Z}\otimes \mathbb{Z}\rightarrow \mathbb{Z}/ n\mathbb{Z}\otimes \mathbb{Z}$ is not injective.
Have I done something silly in the process?
Answer: The problem is that linearly dependency is subtler when you work with rings.
You could have $m(n_1)\neq 0$ and $m(n_1),m(n_2)$ linearly dependent, but having $m(n_2)\neq y\cdot m(n_1)$ for all $y\in Y$.
For example, in $\mathbb{Z}$, $2,3$ are linearly dependent since $2.3-3.2=0$, but $2\neq m\cdot 3$ for all $m\in\mathbb{Z}$.
(Also, I hope you know that even if your three cases work (for example in the case of vector spaces), it is not enough to prove injectivity of of $1\times m$, since an element of the tensor product is a sum of elementary tensors.)
What you need to prove is for all $\sum_i x_i\otimes n_i$, $\sum_i x_i\otimes m(n_i)=0$ implies $\sum_i x_i\otimes n_i=0$.
You hae compelte characterization of flat modules, but the easiest case to handle is when your module is finitely presented (ie isomorphic to $F/F'$, where $F$ is free of finite rank and $F'$ is finitely generated). In this case, flat is equivalent to finitely generated and projective (which is equivalent to : isomorphic to a direct factor a free module of finite rank)
Comment: Hmm... interesting. So just to be clear, the case-splitting suggested in the linked answer not quite correct, then? Because it assumes that linear dependence can be captured by Case 1, which is not true?
Comment: I guess I'm still not entirely comfortable with tensor products. I understand that an element of the tensor product is a sum of elementary tensors, but I can't quite see how that's not sufficient to demonstrate injectivity of $1\times m$ - how do we go about demonstrating injectivity of the maps of tensored modules in general? I've tried using the universal property of tensor products as codomains of bilinear maps but not sure how to use the universal property to demonstrate injectivity...
Comment: the linked answer deals with vector spaces, that is where the base ring is a field, so no problem . However this cannot be used to prove flatness even in this case.


Can I rollback last update on SQL database?

Question:
Possible Duplicate:
How to rollback a deleted table data?

I accidentally ran an update statement against my database.  Is there a way to roll back this single update without disrupting the rest of the database?
Comment: And that kids is why we always back up our database and test our update queries to see if they do what we want them to do!
Comment: What RDBMS? If SQL Server what is your recovery model and have you ever taken a full database backup?
Answer: Were you in a transaction? If yes, try entering
ROLLBACK WORK;
If you were not, than restore from backup
Answer: no, if the update has been completed successfully, I assume you used SQL Server Management Studio, the changes have been applied.
if it's really important that you revert those updates, you should restore the last backup if you have one and don't bother to loose changes done between backup time and now.
Answer: Get a backup restored, and rollforward to the point just before your accidental update. See http://msdn.microsoft.com/en-us/library/ms191455.aspx
Answer: Not if you don't have a backup.
Answer: Yes. You must shutdown your database and, using db admin tools, restore the database from the latest backup and roll forward through the log to a point in time just before your update. You will lose all updates made after that point of course, not just your accident.
I can't be more specific than that because you haven't shown which database you are using, but all databases have a log that can be used in this way.


Best way to access properties from property file in java

Question: I have properties file app.properties and it has 50 different properties.
I am accessing those in my java class using
Properties prop = new Properties();
prop.load("app.properties");

System.out.prinltn(prop.getProperty("APPNAME"));

Actually, I want to get rid of accessing property like prop.getProperty("APPNAME"). Is there any best way in java to access properties.
I can declare all variables as static in java class.
static String appName = prop.getProperty("APPNAME");

Any other best way available?
Comment: If you store your variables in `Properties()` then not really. You could make the variables `static final String appName = ...;` which would give you code along the way of `String appName = Properties.appName;`
Comment: I would encapsulate your properties in a class with getters and setters. This way you can access the data as the right type and possibly change the name of the property and or getter without changing the other.
Comment: Use a static initializer to load from the file
Comment: No, I am not using spring.
Answer: I can suggest two approaches:
1. Define a utility method which will take String as parameter and return value from properties.
For Example:
public static String GetValue(String key) {
    return properties.getProperty(key);
}

And now you can use this function on callers
String value = GetValue("key"); // properties.getProperty("key");

Define above method and in addition create one class Called Constants(or something suitable). Define all your Keys here as Static final variable.
public class Constants
{
   public static final String KEY = "key";
   public static final String KEY2 = "key2";
}

and now make call for getting value using these variable instead of string:
String value = GetValue(KEY); //GetValue("key");

If you do only option 1, your code is becoming more readable. But I will recommend 2nd option, which is making your code readable as well as maintainable.
You can easily do following operation :

Update property name
No need to worry about mistyping key etc.
Answer: You may use "resourceBundle" package as
First import the resourceBundle API:
import java.util.ResourceBundle;

Create an instance of your property file:
private static ResourceBundle resource = ResourceBundle.getBundle("app");

Now you can get the value of the property:
String appName = resource.getString("APPNAME");

Answer: IMO, your approach of using static variables to hold the values is the best. The following structure was what I was using in a project for the same functionality.
package snippet;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class Constants {

    public static final String APPNAME;
    public static final String VERSION;
    public static final int DEFAULT_TIMEOUT;

    static {
        Properties p = new Properties();
        try {
            p.load(new FileInputStream("constants.properties"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        APPNAME = p.getProperty("APPNAME");
        VERSION = p.getProperty("VERSION");
        DEFAULT_TIMEOUT = Integer.parseInt(p.getProperty("DEFAULT_TIMEOUT"));
    }
}

Of course, there were checks for NumberFormatException etc.
Comment: Loading any resource from the static block is a bad idea, see [here](https://stackoverflow.com/questions/2070293/why-doesnt-java-allow-to-throw-a-checked-exception-from-static-initialization-b#comment54228450_15289277).


unpacking dependencies is taking very very long time

Question: Hi I have a maven with a module and while building that module using clean install in intellij it is taking very very long time to complete the build.
here is my pom file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.blah.cdo.hook</groupId>
    <artifactId>committerIdentityHook</artifactId>
    <version>0.11-SNAPSHOT</version>

    <organization>
        <name>CTO - blah</name>
        <url>http://www.blah.com/</url>
    </organization>

    <name>blah test Hook-5.16.3</name>
    <description>Verify commit author's email address against HR Feed. Functional accounts adhere to this format:
        email@example.com
    </description>
    <packaging>atlassian-plugin</packaging>

    <dependencies>
        <dependency>
            <groupId>com.atlassian.sal</groupId>
            <artifactId>sal-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.atlassian.bitbucket.server</groupId>
            <artifactId>bitbucket-api</artifactId>
            <version>${bitbucket.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.atlassian.plugins</groupId>
            <artifactId>atlassian-plugins-osgi-testrunner</artifactId>
            <version>1.2.3</version>
        </dependency>

        <dependency>
            <groupId>com.atlassian.bitbucket.server</groupId>
            <artifactId>bitbucket-spi</artifactId>
            <version>${bitbucket.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>apache-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>

        <dependency>
            <groupId>oracle.jdbc</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>22.214.171.124.0</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>jsr311-api</artifactId>
            <version>1.1.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.2.2-atlassian-1</version>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <version>1.7.4</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito2</artifactId>
            <version>1.7.4</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito</artifactId>
            <version>1.7.4</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.jacoco</groupId>
            <artifactId>org.jacoco.agent</artifactId>
            <classifier>runtime</classifier>
            <scope>test</scope>
            <version>0.8.0</version>
        </dependency>
        <dependency>
            <groupId>com.blah.cto.bbengarch</groupId>
            <artifactId>AppEncryptDecrypt</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>com.atlassian.maven.plugins</groupId>
                <artifactId>bitbucket-maven-plugin</artifactId>
                <version>${amps.version}</version>
                <extensions>true</extensions>
                <configuration>
                    <products>
                        <product>
                            <id>bitbucket</id>
                            <instanceId>bitbucket</instanceId>
                            <version>${bitbucket.version}</version>
                            <dataVersion>${bitbucket.data.version}</dataVersion>
                        </product>
                    </products>
                </configuration>
            </plugin>
            <plugin>
                <groupId>com.atlassian.plugin</groupId>
                <artifactId>atlassian-spring-scanner-maven-plugin</artifactId>
                <version>1.2.6</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>atlassian-spring-scanner</goal>
                        </goals>

                        <phase>process-classes</phase>
                    </execution>
                </executions>
                <configuration>
                    <scannedDependencies>
                        <dependency>
                            <groupId>com.atlassian.plugin</groupId>
                            <artifactId>atlassian-spring-scanner-external-jar</artifactId>
                        </dependency>
                    </scannedDependencies>
                    <verbose>false</verbose>
                </configuration>
            </plugin>

            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>${maven.compiler.source}</source>
                    <target>${maven.compiler.target}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19.1</version>
                <configuration>
                    <systemPropertyVariables>
                        <jacoco-agent.destfile>${project.build.directory}/jacoco/jacoco.exec</jacoco-agent.destfile>
                        <testEnvironment>true</testEnvironment>
                    </systemPropertyVariables>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.8.0</version>
                <executions>
                    <execution>
                        <id>default-instrument</id>
                        <goals>
                            <goal>instrument</goal>
                        </goals>

                    </execution>
                    <execution>
                        <id>default-restore-instrumented-classes</id>
                        <goals>
                            <goal>restore-instrumented-classes</goal>
                        </goals>

                    </execution>
                    <execution>
                        <id>report</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                        <configuration>
                            <dataFile>${basedir}/target/jacoco/jacoco.exec</dataFile>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <properties>
        <bitbucket.version>5.16.2</bitbucket.version>
        <bitbucket.data.version>${bitbucket.version}</bitbucket.data.version>
        <amps.version>6.2.0</amps.version>
        <plugin.testrunner.version>1.2.3</plugin.testrunner.version>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <java.version>1.8</java.version>
    </properties>

    <scm>
        <connection>https://bitbucketdc-cluster04.blah.net/scm/bbengarch/committervalidator-hook.git</connection>
        <developerConnection>
            scm:git:https://bitbucketdc-cluster04.blah.net/scm/bbengarch/committervalidator-hook.git
        </developerConnection>
        <url>https://bitbucketdc-cluster04.blah.net/scm/bbengarch/committervalidator-hook.git</url>
        <tag>HEAD</tag>
    </scm>

    <distributionManagement>
        <snapshotRepository>
            <id>JULES</id>
            <url>https://repo.blah.net/maven/content/repositories/BBENGARCH-SNAPSHOT/</url>
        </snapshotRepository>
        <repository>
            <id>JULES</id>
            <url>https://repo.blah.net/maven/content/repositories/BBENGARCH/</url>
        </repository>
    </distributionManagement>
</project>

While building the jar in  --- bitbucket-maven-plugin:6.2.0:copy-bundled-dependencies (default-copy-bundled-dependencies) @ committerIdentityHook --- phase It is taking very long time like 1hr -2hrs. Everytime i change something if want to rebuild the jar with new changes it is becoming very tough for me.
Below are the unpacking dependencies which are taking long time.there are few more as well but i observed this is taking long time.
Unpacking c:\FAST\maven_repo\v360\oracle\jdbc\ojdbc6\22.214.171.124.0\ojdbc6-22.214.171.124.0.jar to H:\Susmitha\Projects\commhookcode-nov7\committervalidator-hook\commiterValidator-5.16.3\target\classes with includes "" and excludes "atlassian-plugin.xml,META-INF/MANIFEST.MF,META-INF/.DSA,META-INF/.SF"
Please let me know why it is taking long time and how to build my jar in easy way.
Thank you.
Answer: I think the root of your problem is the performance of your H: file system.   Based on the drive name, I am guessing that it is actually a Windows network share; i.e. when you access H: your system is using SMB to talk to a file system on a separate file server,
The problem is that SMB is not a fast protocol, particularly when you are creating lots of files.  And when you unpack a JAR file into a network share, you will be creating lots of relatively small files.
My advice:

Change your build setup so that the build directory is on a local drive.

If builds are still not fast enough, consider changing your build platform to a Linux machine ... because Linux generally has better file system performance than Windows.
Comment: Thanks a lot. I moved my code to other drive and tried to build. It actually worked. it took only 46s time.


How to keep track of videos watched with Node.js and Mongodb

Question: I'm building a MEAN stack video app (I'm pretty new to Node and Mongodb) and I need a way to keep track of videos watched. How do I do this?
I was thinking I could have an array of Ids in the user collection that references videos but I'd like to be able to return videos with a watched: true key value pair that's dependent on the user making the request. If this is a good way to do it, how do I return a key value pair that's dependent on another document in another collection?
User model:
let UserSchema = new mongoose.Schema({
email: {
    type: String,
    required: true,
    minlength: 1,
    trim: true,
    unique: true,
    validate: {
        validator: VALUE => validator.isEmail(VALUE),
        message: '{VALUE} is not a valid email'
    }
},
password: {
    type: String,
    required: true,
    minlength: 6
},
admin: {
    type: Boolean,
    default: false
},
vid_inprogress: {
    type: mongoose.Schema.Types.ObjectId
},
vid_completed: [{ type : mongoose.Schema.Types.ObjectId, ref: 'Attachment' }],
tokens: [{
    access: {
        type: String,
        required: true
    },
    token: {
        type: String,
        required: true
    }
}]
});

Video Model:
var Video = mongoose.model('Video', {
url: {
    type: String,
    required: true,
    minlength: 1,
    trim: true
},
title: {
    type: String,
    required: true,
    default: '',
    trim: true
},
description: {
    type: String,
    default: '',
    trim: true
},
img: {
    type: String,
    default: '',
    trim: true
},
attachments: [{ type : mongoose.Schema.Types.ObjectId, ref: 'Attachment' }]
});

vid_completed on the User model is where I'd like to keep track of the video ids that have been watched. And the Video model is what would be returned with a key: value pair based on whether the video id is found in the user vid_completed array. Let me know if that makes sense. Thanks in advance!
Answer: I ended up just using an array in the User model like so:
vid_inprogress: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Video'
},
vid_completed: [{ type : mongoose.Schema.Types.ObjectId, ref: 'Video' }]

I'll just have to add watched: true on the front end. Let me know if you have a better way. I'd be interested to hear.