text:
Q: Django - aggregate fields value from joined model my goal here seems to be simple: display the Sum (aggregation) of a foreign model particular field.
The difficulty consist in the current set-up, kindly take a look and let me know if this need to be changed or I can achieve the goal with current model:
class Route(models.Model):
name = models.CharField(max_length=50)
route_length = models.IntegerField()

class Race(models.Model):
race_cod = models.CharField(max_length=6, unique=True)
route_id = models.ForeignKey(Route, on_delete=models.CASCADE, related_name='b_route')

class Results(models.Model):
race_id = models.ForeignKey(Race, on_delete=models.CASCADE, related_name='r_race')
runner_id = models.ForeignKey(Runner, on_delete=models.CASCADE, related_name='r_runner')

Now, I am trying to have like a year summary:

Runner X have raced in 12 races with a total distance of 134 km.

While I was able to count the number of races like this (views.py)
runner = Runner.objects.get(pk=pk)
number_races = Results.objects.filter(runner_id=runner).count()

For computing the distance I have tried:
distance = Results.objects.filter(runner_id=runner).annotate(total_km=Sum(race_id.route_id.route_length))

This code error out stating that on views.py - distance line

Exception Type:   NameError
  Exception Value:  name 'race_id' is not defined

I am sure I did not u/stood exactly how this works. Anybody kind enough to clarify this issue?
Thank you

A: My workaround is the following :
    tmp_race_id = Results.objects.filter(runner_id=runner).values('race_id')
    tmp_route_id = Race.objects.filter(pk__in=tmp_race_id).values('route_id')
    distance = Route.objects.filter(pk__in=tmp_route_id).aggregate(Sum("route_length "))['route_length __sum'] or 0.00

Thank you Jorge Lopez for the hint.

A: you don´t need a Results Model, you can calculate using the data in the models, can you share your Runner Model? that model needs to have a foreign key to a Race. if that is so, you can go from Route's -> Race -> Runner in your query, and you can use the query for the count, so you will have a variable where you stored the count and a variable where you stored the distance. To do a Sum in your query do not use annotate, use aggregate, something like this:
.aggregate(total=Coalesce(Sum('route_lenght'), 0))['total']

A: do like this
from django.db.models import Sum, Count

u = Runner.objects.annotate(
    tot_result=Count('r_runner'),
    tot_km=Sum('r_runner__race_id__route_id__route_length')
)

for i in u:
    print('Total_race {} -- Total_Km {}'.format(i.tot_result, i.tot_km))


text:
Q: Valid placement of System.ComponentModel.DataAnnotations on properties and Encapsulated fields I'm using various syntaxes of System.ComponentModel.DataAnnotations within my Model. Wondering if there's any implications on DataAnnotations placement using this short hand syntax and also the placement seen further below where DataAnnotations are on the Attributes and not Accessor & Modifier methods.
My Model with what I believe is best practice placement for DataAnnotations and this works as expected when I add OData support to my Database Context class not posted here
public class WebOrder
{
    private Guid _id;
    private float _total;
    private string _name;

    [Key]
    public Guid Id { get; private set; }

    [Required]
    public float Total
    {
        get { return _total; }
        set { _total = value; }
    }

    [Required]
    public string Name { get => _name; set => _name = value; }
}

Would this placement of DataAnnotations also be considered valid
public class WebOrder
{
    [Key]
    private Guid _id;
    [Required]
    private float _total;
    [Required]
    private string _name;

    public Guid Id { get; private set; }

    public float Total
    {
        get { return _total; }
        set { _total = value; }
    }

    public string Name { get => _name; set => _name = value; }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: ! Missing \endcsname inserted while using showkeys Using showkeys of my MikTeX 2.9, the code below
\documentclass{article}

\usepackage{showkeys}

\begin{document}
    section \ref{sec:methods} section \ref{methods}
    \section{Methods}
    \label{sec:methods}
\end{document}

yields weird results:

As you see, only the first reference is detected by the package, and I get
! Missing \endcsname inserted.
<to be read again>
                   \BooleanFalse
l.20    section \ref{sec:methods} section \ref{
                                             methods}
The control sequence marked <to be read again> should
not appear between \csname and \endcsname.

LaTeX Warning: Reference `\endcsname ' on page 1 undefined on input line 20.

My file does not include any non-UTF character. What's the problem here?

A: In a correctly installed LaTeX you should get no error from the posted example, however if you use the optional argument of \usepackage to force loading an old version with a new latex, you do get the error shown.
\documentclass{article}

\usepackage{showkeys}[=2014-10-28]

\begin{document}
    section \ref{sec:methods} section \ref{methods}
    \section{Methods}
    \label{sec:methods}
\end{document}

Produces
! Missing \endcsname inserted.
<to be read again>
                   \BooleanFalse
l.6     section \ref{sec:methods} section \ref{
                                               methods}
?

So it appears that you have an old showkeys in your input path.


text:
Q: Reason of having high AUC and low accuracy in a balanced dataset Given a balanced dataset (size of both classes are the same), fitting it into an SVM model I yield a high AUC value (~0.9) but a low accuracy (~0.5).
I have totally no idea why would this happen, can anyone explain this case for me?

A: I guess you are miss reading the correct class when calculating the roc curve...
That will explain the low accuracy and the high (wrongly calculated) AUC.

It is easy to see that AUC can be misleading when used to compare two
  classifiers if their ROC curves cross. Classifier A may produce a
  higher AUC than B, while B performs better for a majority of the
  thresholds with which you may actually use the classifier. And in fact
  empirical studies have shown that it is indeed very common for ROC
  curves of common classifiers to cross. There are also deeper reasons
  why AUC is incoherent and therefore an inappropriate measure (see
  references below).

http://sandeeptata.blogspot.com/2015/04/on-dangers-of-auc.html

A: Another simple explanation for this behaviour is that your model is actually very good - just its final threshold to make predictions binary is bad.
I came across this problem with a convolutional neural network on a binary image classification task. Consider e.g, that you have 4 samples with labels 0,0,1,1. Lets say your model creates continuous predictions for these four samples like so: 0.7, 0.75, 0.9 and 0.95.
We would consider this to be a good model, since high values (> 0.8) predict class 1 and low values (< 0.8) predict class 0. Hence, the ROC-AUC would be 1. Note how I used a threshold of 0.8. However, if you use a fixed and badly-chosen threshold for these predictions, say 0.5, which is what we sometimes force upon our model output, then all 4 sample predictions would be class 1, which leads to an accuracy of 50%.
Note that most models optimize not for accuracy, but for some sort of loss function. In my CNN, training for just a few epochs longer solved the problem.
Make sure that you know what you are doing when you transform a continuous model output into a binary prediction. If you do not know what threshold to use for a given ROC curve, have a look at Youden's index or find the threshold value that represents the "most top-left" point in your ROC curve.

A: The ROC curve is biased towards the positive class. The described situation with high AUC and low accuracy can occur when your classifier achieves the good performance on the positive class (high AUC), at the cost of a high false negatives rate (or a low number of true negatives).
The question of why the training process resulted in a classifier with poor predictive performance is very specific to your problem/data and the classification methods used.
The ROC analysis tells you how well the samples of the positive class can be separated from the other class, while the prediction accuracy hints on the actual performance of your classifier.

About ROC analysis
The general context for ROC analysis is binary classification, where a classifier assigns elements of a set into two groups. The two classes are usually referred to as "positive" and "negative". Here, we assume that the classifier can be reduced to the following functional behavior:
def classifier(observation, t):
    if score_function(observation) <= t:
        observation belongs to the "negative" class
    else:
        observation belongs to the "positive" class

The core of a classifier is the scoring function that converts observations into a numeric value measuring the affinity of the observation to the positive class. Here, the scoring function incorporates the set of rules, the mathematical functions, the weights and parameters, and all the ingenuity that makes a good classifier. For example, in logistic regression classification, one possible choice for the scoring function is the logistic function that estimates the probability p(x) of an observation x belonging to the positive class.
In a final step, the classifier converts the computed score into a binary class assignment by comparing the score against a decision threshold (or prediction cutoff) t.
Given the classifier and a fixed decision threshold t, we can compute actual class predictions y_p for given observations x. To assess the capability of a classifier, the class predictions y_p are compared with the true class labels y_t of a validation dataset. If y_p and y_t match, we refer to as true positives TP or true negatives TN, depending on the value of y_p and y_t; or false positives FP or false negatives FN if y_p and y_t do not match.
We can apply this to the entire validation dataset and count the total number of TPs, TNs, FPs and FNs, as well as the true positive rate (TPR) and false positive rate rate (FPR), which are defined as follows:
TPR = TP / P = TP / (TP+FN) = number of true positives / number of positives
FPR = FP / N = FP / (FP+TN) = number of false positives / number of negatives

Note that the TPR is often referred to as the sensitivity, and FPR is equivalent to 1-specifity.
In comparison, the accuracy is defined as the ratio of all correctly labeled cases and the total number of cases:
accuracy = (TP+TN)/(Total number of cases) = (TP+TN)/(TP+FP+TN+FN)

Given a classifier and a validation dataset, we can evaluate the true positive rate TPR(t) and false positive rate FPR(t) for varying decision thresholds t. And here we are: Plotting FPR(t) against TPR(t) yields the receiver-operator characteristic (ROC) curve. Below are some sample ROC curves, plotted in Python using roc-utils*.

Think of the decision threshold t as a final free parameter that can be tuned at the end of the training process. The ROC analysis offers means to find an optimal cutoff t* (e.g., Youden index, concordance,  distance from optimal point).
Furthermore, we can examine with the ROC curve how well the classifier can discriminate between samples from the "positive" and the "negative" class:
Try to understand how the FPR and TPR change for increasing values of t. In the first extreme case (with some very small value for t), all samples are classified as "positive". Hence, there are no true negatives (TN=0), and thus FPR=TPR=1. By increasing t, both FPR and TPR gradually decrease, until we reach the second extreme case, where all samples are classified as negative, and none as positive: TP=FP=0, and thus FPR=TPR=0. In this process, we start in the top right corner of the ROC curve and gradually move to the bottom left.
In the case where the scoring function is able to separate the samples perfectly, leading to a perfect classifier, the ROC curve passes through the optimal point FPR(t)=0 and TPR(t)=1 (see the left figure below). In the other extreme case where the distributions of scores coincide for both classes, resulting in a random coin-flipping classifier, the ROC curve travels along the diagonal (see the right figure below).

Unfortunately, it is very unlikely that we can find a perfect classifier that reaches the optimal point (0,1) in the ROC curve. But we can try to get as close to it as possible.
The AUC, or the area under the ROC curve, tries to capture this characteristic. It is a measure for how well a classifier can discriminate between the two classes. It varies between 1. and 0. In the case of a perfect classifier, the AUC is 1. A classifier that assigns a random class label to input data would yield an AUC of 0.5.
* Disclaimer: I'm the author of roc-utils

A: If this is happening every single time, may be your model is not correct.
Starting from kernel you need to change and try the model with the new sets.
Look the confusion matrix every time and check TN and TP areas. The model should be inadequate to detect one of them.


text:
Q: TypeError: jQuery.subscribe is not a function on shopware5 I have created a custom theme on shopware5 using the "Bare" theme as the parent theme. I have added "Jquery" library on my theme.
However, I am getting "TypeError: jQuery.subscribe is not a function" Error when I load some pages on the site.
I can see there is no such an issue when I switch back to the Responsive theme.
I need to use a image zoom plugin on my detail page but I am unable to setup the plugin because of this issue.

A: Your JS file should be included in the Theme.php file of your theme.
Example:
protected $extend = 'Responsive';
...
protected $javascript = array(
        'src/js/jquery.my-js-file.js',
    );
...
protected $name = <<<'SHOPWARE_EOD' ...

Then you shouls clear caches and compile your theme. After that you can use your library.


text:
Q: insert data in sql server from other table I've some records in table_3 and I want to insert that record to table_2 but value of first column (Id) will be (NUMBER+1) of table_1. My code is
INSERT INTO TABLE_2(Id,NAME)
SELECT (SELECT MAX(NUMBER) FROM TABLE_1)+1 AS Id,name
FROM TABLE_3

Count of table_1 is 200. and count of TABLE_3 is 10. I want new inserted Ids are like
(201,202,203,204,205,206,207,208,209,210)
but from query am getting is like...
(201,201,201,201,201,201,201,201,201,201)

A: you can do it simply with only one select using ROW_NUMBER() and a group by
INSERT INTO TABLE_2(Id,NAME)
 SELECT MAX(NUMBER) + ROW_NUMBER() OVER (ORDER BY name),name
 FROM TABLE_3
 group by name

A: In your query (SELECT MAX(NUMBER) FROM TABLE_1)+1 is always the same, since MAX(NUMBER) is just 200.
If you want to increment by 1 for each new record inserted, starting at (SELECT MAX(NUMBER) FROM TABLE_1)+1, try this:
INSERT INTO TABLE_2 (Id, NAME)
SELECT Id + rn, name
FROM (
   SELECT (SELECT MAX(NUMBER) FROM TABLE_1) AS Id, name,
          ROW_NUMBER() OVER (ORDER BY name) AS rn
   FROM TABLE_3 ) t


text:
Q: How can I load my PHP file for any HTTP requests inside a directory? I have a proxy I've been writing with PHP for a while.
Right now, requesting a url like www.mysite.com/proxy/?folder/page.html on my server will return the page at www.theirsite.com/folder/page.html.
I basically am having my index.php file use everything past /proxy/? as the request URI for www.theirsite.com. Any images are copied to the folder /proxy/images/ and the src attributes of the <img> tags are changed accordingly. All this is working great.
Now I would like to change my script so that I will not need the ? anymore. However, the url www.mysite.com/proxy/folder/page.html would result in an HTTP request to page.html, which doesn't exist on my server.
This isn't what I want. I need index.php to be loaded instead, so it can return the page at www.theirsite.com/folder/page.html. To accomplish this, I imagine I would need to use Apache's mod_rewrite, which is working with my WordPress installation.
What would I need in my .htaccess file to do this correctly, while still allowing access to files that exist in the /proxy/images/ directory? Would this affect $_SERVER['REQUEST_URI'] at all?

A: RewriteEngine on
RewriteRule   ^/$  /index.php  [R]

A: Well, I got it working how I wanted. Here's the full contents of my .htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /proxy/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /proxy/index.php [L]
</IfModule>

Now for the url www.mysite.com/proxy/folder/page.html, index.php is loaded, and $_SERVER['REQUEST_URI'] returns /proxy/folder/page.html. Files that actually exist in the /proxy/ folder or any subfolders do not rewrite to index.php, which is what I wanted.


text:
Q: How to collapse dataframe columns by character in the middle of column name with varying column names? This is similar to a question I asked earlier, but I left out a couple of important pieces: an ID column and the XYZ variables.
I have a dataset with the following layout (strange column titles, I know):
ID <- c(1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0)
XYZ1_a <- c(1, 2, 1, 2, 1, 2, 4, 2, 5, 1)
XYZ1_b <- c(2, 1, 1, 1, 2, 2, 4, 2, 1, 5)
ABC1a_1 <- c(1, 5, 3, 4, 3, 4, 5, 2, 2, 1)
ABC1b_1 <- c(4, 2, 1, 1, 5, 3, 2, 1, 1, 5)
ABC1a_2 <- c(4, 5, 5, 4, 2, 5, 5, 1, 2, 4)
ABC1b_2 <- c(2, 3, 3, 2, 2, 3, 2, 1, 4, 2)
ABC2a_1 <- c(2, 5, 3, 5, 3, 4, 5, 3, 2, 3)
ABC2b_1 <- c(1, 2, 2, 4, 5, 3, 2, 4, 1, 4)
ABC2a_2 <- c(2, 5, 5, 1, 2, 1, 5, 1, 3, 4)
ABC2b_2 <- c(2, 3, 3, 2, 1, 3, 1, 1, 2, 2)

df <- data.frame(ID, XYZ1_a, XYZ1_b, ABC1a_1, ABC1b_1, ABC1a_2, ABC1b_2, ABC2a_1, ABC2b_1, ABC2a_2, ABC2b_2)

I want to collapse all of the ABC[N][x]_[n] variables into a single ABC[N]_[n] variable like the below, but I also need to do the same for the columns with the XYZ naming convention:
ID <- c(1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0,
        1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0)
XYZ1 <- c(1, 2, 1, 2, 1, 2, 4, 2, 5, 1, 2, 1, 1, 1, 2, 2, 4, 2, 1, 5)
ABC1_1 <- c(1, 5, 3, 4, 3, 4, 5, 2, 2, 1, 4, 2, 1, 1, 5, 3, 2, 1, 1, 5)
ABC1_2 <- c(4, 5, 5, 4, 2, 5, 5, 1, 2, 4, 2, 3, 3, 2, 2, 3, 2, 1, 4, 2)
ABC2_1 <- c(2, 5, 3, 5, 3, 4, 5, 3, 2, 3, 1, 2, 2, 4, 5, 3, 2, 4, 1, 4)
ABC2_2 <- c(2, 5, 5, 1, 2, 1, 5, 1, 3, 4, 2, 3, 3, 2, 1, 3, 1, 1, 2, 2)

df2 <- data.frame(ID, XYZ1, ABC1_1, ABC1_2, ABC2_1, ABC2_2)

What's the best way to achieve this, ideally with a tidyverse solution?

A: We can use rearrange the substrings in those column names that starts_with 'ABC' by capturing the letter as a group followed by the underscore and one or more digits (\\d+) as second group, in the replacement specify the backreference in reverse while adding a new _.  In pivot_longer, specify the sep to match the _ that precedes a letter
library(dplyr)
library(stringr)
library(tidyr)
df %>%
   rename_with(~ str_replace(., "([a-z])_(\\d+)$", "_\\2_\\1"),
      starts_with('AB')) %>%
   pivot_longer(cols = -ID, names_to = c(".value", "grp"),
      names_sep = "_(?=[a-z])", values_drop_na = TRUE) %>%
   select(-grp)

-output
# A tibble: 20 x 6
      ID  XYZ1 ABC1_1 ABC1_2 ABC2_1 ABC2_2
   <dbl> <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
 1   1.1     1      1      4      2      2
 2   1.1     2      4      2      1      2
 3   1.2     2      5      5      5      5
 4   1.2     1      2      3      2      3
 5   1.3     1      3      5      3      5
 6   1.3     1      1      3      2      3
 7   1.4     2      4      4      5      1
 8   1.4     1      1      2      4      2
 9   1.5     1      3      2      3      2
10   1.5     2      5      2      5      1
11   1.6     2      4      5      4      1
12   1.6     2      3      3      3      3
13   1.7     4      5      5      5      5
14   1.7     4      2      2      2      1
15   1.8     2      2      1      3      1
16   1.8     2      1      1      4      1
17   1.9     5      2      2      2      3
18   1.9     1      1      4      1      2
19   2       1      1      4      3      4
20   2       5      5      2      4      2

In the older version use rename_at
df %>%
   rename_at(vars(starts_with('AB')),
        ~ str_replace(., "([a-z])_(\\d+)$", "_\\2_\\1")) %>%
   pivot_longer(cols = -ID, names_to = c(".value", "grp"),
      names_sep = "_(?=[a-z])", values_drop_na = TRUE) %>%
   select(-grp)

-output
# A tibble: 20 x 6
      ID  XYZ1 ABC1_1 ABC1_2 ABC2_1 ABC2_2
   <dbl> <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
 1   1.1     1      1      4      2      2
 2   1.1     2      4      2      1      2
 3   1.2     2      5      5      5      5
 4   1.2     1      2      3      2      3
 5   1.3     1      3      5      3      5
 6   1.3     1      1      3      2      3
 7   1.4     2      4      4      5      1
 8   1.4     1      1      2      4      2
 9   1.5     1      3      2      3      2
10   1.5     2      5      2      5      1
11   1.6     2      4      5      4      1
12   1.6     2      3      3      3      3
13   1.7     4      5      5      5      5
14   1.7     4      2      2      2      1
15   1.8     2      2      1      3      1
16   1.8     2      1      1      4      1
17   1.9     5      2      2      2      3
18   1.9     1      1      4      1      2
19   2       1      1      4      3      4
20   2       5      5      2      4      2


text:
Q: Let a daemon simulate keypress with xdo I'm trying to make a daemon simulate a keypress. I got it already working for a non daemon process.
#include <xdo.h>

int main()
{
    xdo_t * x = xdo_new(NULL);
    xdo_enter_text_window(x, CURRENTWINDOW, "Hallo xdo!", 500000);

    return 0;
}

If I try the same code for my daemon I get the following error
Error: Can't open display: (null)

Is there a way to still make it work with xdo or something else?

A: Your process must know the $DESKTOP environment variable specifying the desktop session to send these keys to, and yours doesn't seem to have that environment set.
Which also means you must realize it needs to have all the necessary privileges, which means access to ~/.Xauthority of the owner of the session, and the sockets in /tmp/.X11-unix


text:
Q: Word-Embeddings compression for deep learning models Can anyone suggest any techniques/concepts to compress word-embedding like Glove 300d?
As it increases the size of model.

A: A decent option to go through where deep com-positional code learning neural network is helpful to reduce word embedding size drastically.
This github link will help you and give more insights . it is quite beneficial in Sentimental Analysis tasks.
Need to test on more different NLP tasks.


text:
Q: Null object reference while trying to pass array list using interface Hello so I am trying to pass an array list from my activity to the fragment and this is what I did :
FirstActivity :
AdminInterface instanceForInterface;

OnCreate
//
System.out.println(results.size) ; //works fine
instanceForInterface.onDataRecieved(results);  // here I am getting the exception
//

public interface AdminInterface {
    void onDataRecieved(ArrayList <Result> response);
}

public void setInterface(UserFragment anInterface) {
    this.instanceForInterface = anInterface;
}

Fragment
 OnActivityCreated
((FirstActivity) getActivity()).setInterface(this);

 @Override
public void onDataRecieved(ArrayList<Result> response) {
    processData(response);
}

Exception
Attempt to invoke interface method 'void **************.onDataRecieved(java.util.ArrayList)' on a null object reference

What I think :
I am calling this line
instanceForInterface.onDataRecieved(results); in  OnCreate()
before the initialisation of
((FirstActivity) getActivity()).setInterface(this); in OnActivityCreated()
Solution Please ??
Thank You

A: The problem is that your fragment's onActivityCreated() method is invoked after your activity's onCreate() method.
The smallest change you can make to achieve the behavior you want is to use the onResumeFragments() method in your activity. That is, delete the line instanceForInterface.onDataRecieved(results); from your onCreate and add this code:
@Override
protected void onResumeFragments() {
    super.onResumeFragments();
    instanceForInterface.onDataRecieved(results);
}

onResumeFragments() will be invoked by the system after both your activity's onCreate() and your fragment's onActivityCreated() methods.
That being said, chances are quite good that you would be better off with a different approach entirely. For instance, you could have your activity expose a getter for results and have your fragment retrieve the results to work with (rather than have your activity store a reference to your fragment).
Further reading about the Activity and Fragment lifecycles:
https://developer.android.com/guide/components/activities/activity-lifecycle.html
https://developer.android.com/guide/components/fragments.html


text:
Q: automatic labeling a node with a text Hi i would like after dropping my Symbols from Palette, that my symbol to be automatic labeled with Text.
Here is the Code:
protected void DiagramWebControl1_NodeDropFromPalette(object sender, Syncfusion.Web.UI.WebControls.Diagram.NodeDropFromPaletteEventArgs e)

{

   if (e.Node is PathNode || e.Node is Group)

   {

      PathNode node = e.Node as PathNode;

      if (node != null)

         node.Labels.Add(new Syncfusion.Windows.Forms.Diagram.Label( node, node.Name));

      else

      {

        Group gnode = e.Node as Group;

        node.Labels.Add(new Syncfusion.Windows.Forms.Diagram.Label (gnode, gnode.Name));

      }

  }

}

the problem is that every symbol (node) if its a PathNode or Group after the first dropping they are not labeled, after the second drop, third, etc.... from the same node, then they will be automatic labeled.
Need help!

A: Refer the Syncfusion's public forum regarding your requirement of adding label automatically to the node. Here's a link.


text:
Q: VF Page not working in Partner Community Page I have a VF page which is working fine in my Salesforce org, but when I try to open it via Partner Community login, I get an error saying "Page is under construction". On further research I found that this is due to the Custom button which actually invokes the page via Javascript as the URL has been coded as '/apex/page/params' but the partner community URL would be '/partnercommunity/page/param'. I am posting my Custom button javascript code below:
{!REQUIRESCRIPT ("/soap/ajax/13.0/connection.js")}
var selected = {!GETRECORDIDS($ObjectType.Custom_Obj__c)};
if (selected[0] == null) {
alert("Please select at least one record!")
}
else {
window.open('/apex/myVFPage?rec='+selected.join(','), '_blank');
}

This custom button will be available on a list view which when pressed will opena  vf page which downloads all the currently selected records. As mentioned, the code is working fine in my org, its only the Partner community which is causing the issue.
Could anyone please suggest as to how I need to change the button code so that it works for both internal and external users.
Let me know in case any other info is needed.

A: Replace the below line
window.open('/apex/myVFPage?rec='+selected.join(','), '_blank');

With
window.parent.location.href="{!URLFOR($Site.Prefix+'/apex/myVFPage?rec=')}"+selected.join(',')

Let me know if it work for you and please do not forget to mark as answer if it works ! :)
Cheers,
Rajeev :)


text:
Q: Is currency filter works with numbers only using $scope.$eval()? I was trying to create a custom directive with options passed as attributes..
I've noticed that currency filter works with numbers only and it don't work if it is used with some string property only. And if i try to use this filter with property having string it don't generate any result.. is it so?
and how can i use currency filter with string value if i wants to?

var app = angular.module('myApp', []);

app.controller('defaultCtrl', ['$scope', function($scope) {
  $scope.products = [
    {
      name: "Apples",
      category: "Fruits",
      price: 1.20,
      expiry: 10
    }, {
      name: "Bananas",
      category: "Fruits",
      price: 2.42,
      expiry: 7
    }, {
      name: "Pears",
      category: "Fruits",
      price: 2.02,
      expiry: 6
    }
  ];
}]);

app.directive('unorderedList', function() {
  return function(scope, element, attrs) {
    var data = scope[attrs["unorderedList"]];
    if(angular.isArray(data)) {
      var listElem = angular.element('
');
      var propertyExpression = attrs["listProperty"];

      element.append(listElem);

      for(var i = 0; i < data.length; i++) {
        listElem.append(angular.element('
').text(scope.$eval(propertyExpression, data[i])));
      }
    }
  }
});

Products

A: The source code of that filter (currency) stand as
currencyFilter.$inject = ['$locale'];
function currencyFilter($locale)
{
    var formats = $locale.NUMBER_FORMATS;
    return function(amount, currencySymbol, fractionSize)
    {
        if (isUndefined(currencySymbol))
        {
            currencySymbol = formats.CURRENCY_SYM;
        }

        if (isUndefined(fractionSize))
        {
            fractionSize = formats.PATTERNS[1].maxFrac;
        }

        // if null or undefined pass it through
        return (amount == null)
            ? amount
            : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).replace(/\u00A4/g, currencySymbol);
    };
}

Now the code for formatNumber starts as follow
function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {

  if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';

and angular.isNumber states that

Determines if a reference is a Number.
This includes the "special" numbers NaN, +Infinity and -Infinity

Thus, formatNumber(...) with your apples and bananas simply return '' (empty string)

A: Since list-property is not defined in the scope with the @ it won't get evaluated.
So as you put it there : YES you need scope.$eval.
However you can change it to :
list-property="{{price | currency}}"

And remove the scope.$eval in your directive. This should work.


text:
Q: Routing Laravel namepsace issue When I remove the inital use Illuminate\Http\Request and add use App\Item instead in the Controller file, the items/create route responds with a 404.  How can I still use the App\Item namespace and get to the items/create route? I've tried adding both, but does not work.
web.php
Route::get('items', 'ItemsController@index');
Route::get('items/{item}', 'ItemsController@show');
Route::get('items/create', 'ItemsController@create');

ItemsController.php
<?php

namespace App\Http\Controllers;

use App\Item;

class ItemsController extends Controller
{
    public function index(){
      $items = Item::all();
      return view('items.index', ['items' => $items]);
    }

    public function show(Item $item){
      return $item->body;
    }

    public function create(){
      return view('items.create');
    }
}

Item.php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    //
}

A: The problem is that laravel tries to match the routes in the order they are declared and the items/{item} route will match all routes starting with items/, including items/create. And because of the route model binding, Laravel tries to load an Item with ID create which obviously doesn't exist, so it throws a 404 error.
Route model binding in the docs:

Since the $user variable is type-hinted as the App\User Eloquent model
  and the variable name matches the {user} URI segment, Laravel will
  automatically inject the model instance that has an ID matching the
  corresponding value from the request URI. If a matching model instance
  is not found in the database, a 404 HTTP response will automatically
  be generated.

To fix it simply change the order of your routes and put items/{item} after all other item/* routes:
Route::get('items', 'ItemsController@index');
Route::get('items/create', 'ItemsController@create');
Route::get('items/{item}', 'ItemsController@show');

A: Can you try this, please.
<?php

namespace App\Http\Controllers;
use App\Item;
class ItemsController extends Controller
{
    public function index(){
      $items = Item::all();
      return view('items.index', ['items' => $items]);
    }

    public function show($id){
      $item= Item::find($id);
        return $item->body;
    }

    public function create(){
      return view('items.create');
    }
}


text:
Q: Load images from folder and use them as sprites in unity I have an idea about a game, where you need to catch flags. In the game I want to give the user the opportunity to use his own images. I was thinking the user could input a folder directory and I would access the directory and use the images stored there. Is this possible in C#? If so, how could I do it?
For example, the user would input "C:\Users\Bob\Documents\GameImages" and I would use the images stored there to create the falling flags.

A: either of those should work on standalone
http://docs.unity3d.com/ScriptReference/WWW.LoadImageIntoTexture.html
http://docs.unity3d.com/ScriptReference/Texture2D.LoadImage.html


text:
Q: How to move inside subplot Draggable within main subplot Matplotlib after a lot of search and getting help from here as well as from stackoverflow i got a something but still solution is not proper way.
Here is my code:
i am using RectangleSelector to move and stretch the the inset axes of main axes of matplotlib.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.widgets as widgets

def onselect(eclick, erelease):
    if eclick.ydata<erelease.ydata:
        erelease.ydata,eclick.ydata=eclick.ydata,erelease.ydata
    if eclick.xdata<erelease.xdata:
        erelease.xdata,eclick.xdata=eclick.xdata,erelease.xdata
    axes2.set_ylim(eclick.ydata,erelease.ydata)
    axes2.set_xlim(eclick.xdata,erelease.xdata)
    axes2.set_position([eclick.xdata,eclick.ydata,erelease.xdata,erelease.ydata])
    fig.canvas.draw()

fig = plt.figure()
axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8])
axes2 = fig.add_axes([0.2, 0.2, 0.4, 0.3])

axes2.autoscale(enable=True, axis='both', tight=None)

rp = dict(facecolor='white',edgecolor = 'black', alpha=0.5, fill=True)

rs=widgets.RectangleSelector(axes1, onselect, drawtype='box',interactive=True,
                             spancoords='pixels',rectprops = rp )

plt.show()

here it RectangleSelector suppose to be with axes2 and it should draggable and stretchable along with it. When i am moving RectangleSelector separately in axes1 and at time the when i am releasing RectangleSelector at that time axes2 also changing it's position and size also changing.what i suppose to do now.please help me out on this.thanks in advance.


text:
Q: Is there a way to render HTML code that is written in an ACE editor I am working on a React app that uses ACE as a code editor. I would like the user to input their HTML into the editor and click a run button to render that HTML on a split screen, much like Codepen. I don't really know where to start.
I have messed around with ACE in a side project but want to flesh it out more before implementing it into my Main project so I do't break anything.
<AceEditor
            placeholder="Placeholder Text"
            mode="javascript"
            theme="monokai"
            name="blah2"
            onLoad={onLoad}
            onChange={onChange}
            fontSize={14}
            showPrintMargin={true}
            showGutter={true}
            highlightActiveLine={false}
            value={`function onLoad(editor) {
  console.log("i've loaded");
}`}
            setOptions={{
              enableBasicAutocompletion: true,
              enableLiveAutocompletion: true,
              enableSnippets: true,
              showLineNumbers: true,
              tabSize: 2
            }}
          />

Any help would be appreciated


text:
Q: What is the exact meaning of component initialization in angular 2+, when we talk about OnInit? According to Angular.io Angular Documentation on Life cycle hooks The purpose of OnInit :
 Initialize the directive/component after Angular first displays the data-bound properties and sets the directive/component's input properties.
So what exactly happens when it is said component has initialized. Does it mean all the variables are initialized or the component's template is displayed or both?

A:
So what exactly happens when it is said component has initialized.
  Does it mean all the variables are initialized or the component's
  template is displayed or both?

Markup is rendered, bindings are bound, child view/components are injected. In other words, you can do everything from component code from now on. You can threat it as "Angular Construction" method and do all component initialization stuff there. It is very similar to @PostConstruct concept from EJB.

A: ngOnInit is useful after angular is done with creation of the component. So, when constructor finishes its work, the component is said to be initialized and it has specified properties which you can initialize in ngOnInit now.
I hope this helps!


text:
Q: How to open an activity on the lock screen after FCM notification How can I open an activity on the lock screen without the user having to click on it? Like for example an alarm or a call.
In my code I can get the FCM notification and if the user clicks on the notification it is possible to open an activity, but I wanted the user not to have to click on it.
FirebaseService.java
//--- Notificacao
    public void createNotificationChannel(){
        mNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){

            //create a notification channel
            NotificationChannel notificationChannel = new NotificationChannel(PRIMARY_CHANNEL_ID,
                    "Mascot Notification", NotificationManager
                    .IMPORTANCE_HIGH);

            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.enableVibration(true);
            notificationChannel.setDescription("Notification from Mascot");

            mNotifyManager.createNotificationChannel(notificationChannel);

        }

    }

    public void sendNotification(String taskName){

        NotificationCompat.Builder notifyBuilder = getNotificationBuilder(taskName);

        //agora temos que entregar a notificacao
        mNotifyManager.notify(NOTIFICATION_ID, notifyBuilder.build());

    }

    public NotificationCompat.Builder getNotificationBuilder(String taskName){

        Intent intent = new Intent(this, TesteActivity.class);
        PendingIntent p = getPendingIntent(NOTIFICATION_ID, intent, getApplicationContext());

        return new NotificationCompat.Builder(this, PRIMARY_CHANNEL_ID)
                .setSmallIcon(R.drawable.notification_icon)
                .setContentText("titulo teste")
                .setContentIntent(p)
                .setCategory(NotificationCompat.CATEGORY_ALARM)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);

    }

    private PendingIntent getPendingIntent(int id, Intent intent, Context context){
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(intent.getComponent());
        stackBuilder.addNextIntent(intent);

        PendingIntent p = stackBuilder.getPendingIntent(id, PendingIntent.FLAG_UPDATE_CURRENT);
        return p;
    }

TesteActivity.java
public class TesteActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_teste);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
            setTurnScreenOn(true);
            setShowWhenLocked(true);
            KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
            keyguardManager.requestDismissKeyguard(this, null);

        }

A: instead of mNotifyManager.notify( call, which shows your Notification, just use startActivity(..? you may need also WakeLock and showOnLockScreen attribute set for this Activity in manifest
edit: and HERE you can find article with exactly your case tutorial


text:
Q: How to get Per Month data from firestore with JS I want to get the Per month Water data from firestore for all the documents i try but nothing work i think i can get data by the help of timestamp and water field which are present in my database can anyone help me with it.
This is my database.

I try this from the last answer but nothing is showing in console

const cloudDb = app.firestore();
var time="1638297000"
var lasttime="1640845799"

cloudDb.collection('AKVO_RND')
    .where('timestamp', '>=', time)
    .where('timestamp', '<=', lasttime )
    .orderBy('timestamp', 'desc')
    .get().then(function(querySnapshot){
      querySnapshot.forEach(function(doc){
        water= (doc.data().water)
        console.log(water);
      })
    })

A: You can make query something like this with help of firebase functions:
firestore().collection('AKVO_RND')
    .where('timestamp', '>=', time)
    .where('timestamp', '<=', lastdate)
    .orderBy('timestamp', 'desc')
    .get();

Make sure of using runTimeOptions. It will allow your function to run more time than recommended time


text:
Q: Decimal to exact fraction converter in c# So I have started a project where I make a quadratic equation solver and I have managed to do so. My next step is to convert the value of X1 and X2 eg.(X+X1)(X+X2) to an exact fraction, if they become a decimal.
So an example is:

12x2 + 44x + 21
gives me,
X1 = -3.10262885097732
X2 = -0.564037815689349

But how would i be able to convert this to an exact fraction?
Thanks for the help!

A: You can solve this problem using Continued Fractions.
As stated in comments, you can't obtain a fraction (a rational number) that exactly represents an irrational number, but you can get pretty close.
I implemented once, in a pet project, a rational number type. You can find it here. Look into TryFromDouble for an example of how to get the closest rational number (with specified precision) to any given number using Continued Fractions.
An extract of relevant code is the following (I will
Not post the whole type implementation because it is too long, but the code should still be pretty understandable):
public static bool TryFromDouble(double target, double precision, out Rational result)
{
    //Continued fraction algorithm: http://en.wikipedia.org/wiki/Continued_fraction
    //Implemented recursively. Problem is figuring out when precision is met without unwinding each solution. Haven't figured out how to do that.
    //Current implementation computes rational number approximations for increasing algorithm depths until precision criteria is met, maximum depth is reached (fromDoubleMaxIterations)
    //or an OverflowException is thrown. Efficiency is probably improvable but this method will not be used in any performance critical code. No use in optimizing it unless there is
    //a good reason. Current implementation works reasonably well.

    result = zero;
    int steps = 0;

    while (Math.Abs(target - Rational.ToDouble(result)) > precision)
    {
        if (steps > fromDoubleMaxIterations)
        {
            result = zero;
            return false;
        }

        result = getNearestRationalNumber(target, 0, steps++);
    }

    return true;
}

private static Rational getNearestRationalNumber(double number, int currentStep, int maximumSteps)
{
    var integerPart = (BigInteger)number;
    double fractionalPart = number - Math.Truncate(number);

    while (currentStep < maximumSteps && fractionalPart != 0)
    {
        return integerPart + new Rational(1, getNearestRationalNumber(1 / fractionalPart, ++currentStep, maximumSteps));
    }

    return new Rational(integerPart);
}


text:
Q: Locate an element text by XPath I am using Webdriver in Ruby and I want to locate an element by its xpath, below is an example html:

    123456

How do I get 123456 by xpath or ID?
I have tried below and it does not work:
element = driver.find_element :xpath => "//li[@id='ID1']/"
puts element.text

Thanks.

A: I would suggest you to use cssselector over xpath since there are numerous advantages. However, there are certain situations where you can only use xpath like selecting parent element, selecting by text etc. In your case you can certainly get away with cssselector
Css for your html would be li#ID1>label[for='accountNumber'] or just simply label[for='accountNumber']
If you insist on xpath, it should be .//li[@id='ID1']/label[@for='accountNumber']
or by text
.//li[@id='ID1']/label[text()='123456']

A: Try this:
"//li[contains(.,'123456')]"
or
"//li[@id='ID1']"
In both cases I was able to the get the text '123456' from the text nested inside the element.
Tested code in C#:
    [TestMethod]
    public void FindByText()
    {
        IWebElement li = driver.FindElement(By.XPath("//li[contains(.,'123456')]")); //Returns correct element
        li = driver.FindElement(By.XPath("//li[@id='ID1']")); //Also returns correct element

        string text = li.Text; //Result: "  123456"
    }

A: Please try following, it's working for me:
element = driver.find_element(:xpath, "//li[@id='ID1']")
puts element.text


text:
Q: How can I use the boolean value in the "jump" method? I made a jumping system to my rpg. --> problems with detecting when player is grounded.
I have tried to make the system return boolean value and add it with if method to the jump method, unfortunately im stuck
bool isGrounded ()
{
    return Physics.Raycast(transform.position, Vector3.down, distToGround);
}

//jump Force
if(Input.GetButton("Jump"))
{
    if(isGrounded == true)
    {
        GetComponent<Rigidbody>().AddForce (Vector3.up * 100);
    }
}

Error message here.

bool isGrounded()
  Operator '==' cannot be applied to operands of type 'method group' and 'bool' (CS0019) [Assembly-CSharp]

A: Adding this as an answer so this doesn't sit on the unanswered question list until the end of time
bool isGrounded ()
{
    return Physics.Raycast(transform.position, Vector3.down, distToGround);
}

//jump Force
if(Input.GetButton("Jump"))
{
    if(isGrounded == true)
    {
        GetComponent<Rigidbody>().AddForce (Vector3.up * 100);
    }
}

The line
if(isGrounded == true)

Tells the compiler to find a symbol named isGrounded and compare its value to true. Since isGrounded is a method, and not a boolean property or field, you're basically asking the compiler to compare the address of isGrounded() to true, which makes exactly zero sense (even if it was allowed in C#, which it is not).
If you change this to,
if(isGrounded() == true)

or, more succinctly,
if(isGrounded())

It'll call isGrounded() and test the return value.
Parenthesis are important.


text:
Q: Why is Get-DnsClientServerAddress | select AddressFamily output not IPv4 and IPv6 When I type the cmdlet Get-DnsClientServerAddress I get all the interfaces my PC has like for example
InterfaceAlias               Interface Address ServerAddresses
                             Index     Family
--------------               --------- ------- ---------------
Ethernet                             7 IPv4    {10.10.15.40, 10.10.25.44}

So when I  type in Get-DnsClientServerAddress | where AddressFamily -Like "4" I would expect to see the Ethernet Adapter.
But for any reason it didn't show up. So I typed Get-DnsClientServerAddress | select AddressFamily and what I got was
AddressFamily
-------------
            2
           23
            2
           23

Can anyone explain this to me ?

A: As you found, the AddressFamily is categorised internally using a (not obvious) numbering scheme, where IPv4 addresses are type '2'.  This comes from the underlying WMI type (MSFT_DNSClientServerAddress) and is not an issue with PowerShell.
The default display helps you out by translating this to IPv4, etc, but you can't filter on that as it's for display only.  You can, however, still filter if you use the correct value:
Get-DnsClientServerAddress | Where-Object AddressFamily -Like 2

This formatting of data for display purposes happens all the time in PowerShell and is acheived through Format.ps1xml files.  For example, compare the output of the Working Set values from Get-Process in table and list format:
PS C:\> Get-Process powershell

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
    662      31    97928     110256       1.27  11452   2 powershell

PS C:\> Get-Process powershell | Format-List *

Handles                    : 705
VM                         : 2204040044544
WS                         : 113082368
PM                         : 100356096
NPM                        : 31512

The property (itself added by PowerShell for convenience) is called WS, but is shown as WS(K) in the table and the actual value is stored in bytes, but is displayed in KB, so some manipulation is going on for the default output.

A: Following from my comment, I would use Get-NetIPAddress instead.
Get-NetIPAddress -InterfaceAlias "Ethernet" | Select-Object FamilyAddress


text:
Q: Add customer rule in .htaccess automatically with php
I'm working on the website and after I submit something in the website php bring me some URL like this:
www.example.com/text
and I make this URL with mod_rewrite apache and the orginal file is www.example.com/file.php?number=text
I add this rule manually:
RewriteEngine on
RewriteRule ^ABC$ file.php?number=ABC
RewriteRule ^DEF$ file.php?number=DEF

But I want to php add these rule to the .htaccess automatically when user submit something.
How can I do this?

A: You can use this generic rule:
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ file.php?number=$1 [L,QSA]

Reference: Apache mod_rewrite Introduction


text:
Q: How to get reference of the second window opened by a window in JavaScript? I have a page opened in a browser's tab, running some JavaScript code which opens a google meet link. The meeting's URL looks something like this :- https://meet.google.com/lookup/xxxxxxxxxxxxxxx?authuser=x&hs=xx, which is a lookup one, so it first lands me on a Sign in using page, and then redirects me to the actual meeting. Now what I want to do is, execute some code as soon as that meeting tab gets closed. To check the state of that tab, I used the following piece of code.

let windowRef = window.open(url, "_blank");
if(windowRef.closed) {

//Execute some code

}

But what ends up happening is that this windowRef gets assigned to the state of the "Sign in using" page, so as soon as I log in with my mail id to reach the actual meet URL, JavaScript thinks that my window is closed, and it executes the block. I want the same thing to happen but only after this redirection completes.
I am a beginner in JavaScript, so very very sorry if it's a bad question.

A: First you need to create a timer to check if the pop up has been closed.
https://developer.mozilla.org/en-US/docs/Web/API/Window/open
I have an example of this problem, but in react
https://medium.com/@enetoOlveda/open-a-popup-window-react-db81c8c180e5


text:
Q: Using column-count and border-style does not work together So I'm trying to have a list of items with a bottom line on every item. I am also trying to set the items into 3 columns.
Here is an example of what I'm trying to do:
HTML:

A

B

C

D

E

CSS:
.ul_div{
    -webkit-column-count: 4;
    column-count: 3;
    border-style: solid;
}

.the_ul{
    padding: 0;
    margin: 0;
    list-style-type: none;
}

li{
    border-bottom-style: solid;
    border-bottom-color: red;
    border-bottom-radius: 1px;
}

And here is a demo of it: jsfiddle
As you can see, for some reason, the bottom line is not 'stuck' to its respective li item. Can anyone tell me why this is happening and how I can fix it?
Thank you!

A: First of all, there is no such thing as border-bottom-radius, there's only border-bottom-left-radius and border-bottom-right-radius, which is logical considering the fact that the radius is applied to the corners of the element.
Now, for your question, you should use column-break-inside: avoid; to make sure that the li element doesn't get divided into columns, having a part of it into one column and one part into the next column:
column-break-inside: avoid;
-webkit-column-break-inside: avoid;

The fiddle.
And here is more information about column breaks.

A: You need to add a width to the li border. You can do this buy adding border-bottom-width: 1px; to your li class. You could instead change you li class to:
li{
  border: 0px solid red;
  border-bottom-width: 1px;
  border-radius: 1px;
}

You could also use border-bottom-left-radius and border-bottom-right-radius.


text:
Q: Realtime Database returning deleted values [EDITED] I deleted everything in my database. Then, I queried the data that was just deleted and I get results! How is this possible?
I am using the Realtime Database Unity SDK. For testing purposes, I want to regularly purge the whole database and populate it with new data. Imagine my surprise when my queries returned some old, deleted data. It is as if the deleted data persists in some void that can still be accessed.
I have been tinkering with this issue for days now. Here are my steps:

*

*I'm using GetReference(item).Push().Key; which auto-generates a unique key.

*I write the new item to the database with GetReference(item).SetValueAsync().

*I check my Firebase console, and indeed, the data was correctly recorded.

*I create a query that returns the JSON value of item. I works fine.

*I delete item from the data base.

*I run the query again and item is returned. ITEM IS NOT SUPPOSED TO EXIST ANYMORE!
Out of curiosity, I write a query to return all the data in my database (which should be empty) and it returns every object I have create over the last few days. This is literally hundreds of items....from an empty database.
It seems like data persists for a few days after it is deleted.
Realizing this I decided to test what would happen if I manually made an object that uses an existing key from one of the deleted objects.
My query returns the new object. Yay!
I take a break and come back 15 minutes later. I run the exact query again. I get the old, deleted object and not the new one. WHAT THE HECK IS GOING ON?
At this point I am questioning whether Realtime Database is even a real database. It seems to break the rules of both consistency and integrity.
I've also considered that I might be deleting the data incorrectly. I was mostly doing it manually, through the browser. I also have tried RemoveValueAsync() and SetRawJsonValueAsync(null). Nothing seems to make a difference.
Please, please, please can someone tell me what is going on? I will be forever grateful.

EDIT: It turns out that the phantom data was coming from the cache on my device. Turning persistence off solved the problem. Apparently, performing the same query multiple times only retrieves the data for the database the first time. The subsequent queries look into the cache.

A: It turns out that the phantom data was coming from the cache on my device. Turning persistence off solved the problem. Apparently, performing the same query multiple times only retrieves the data for the database the first time. The subsequent queries look into the cache.


text:
Q: Clicking a link in RadGrid using JavaScript I bind records using RadGrid, and each row it has a link button. If I click the link, it will open the moalpopup (it is dynamic one based on some condition). When I close the popup using close button, it should continue with the link button event.
Code Behind:
protected void grid_ItemDataBound(object sender, GridItemEventArgs e)
{
    if (e.Item.ItemType == GridItemType.AlternatingItem || e.Item.ItemType == GridItemType.Item)
    {
        LinkButton link = ((LinkButton)gridDataItem.FindControl("link"));
        ModalPopupExtender popup = (ModalPopupExtender)e.Item.FindControl("popup");
        Image imageClose = (Image)e.Item.FindControl("imageClose");
        popup.TargetControlID = link.ID;
        link.Attributes.Add("onclick", "return false;"); // to avoid postback and stay in page and show popup
        imageClose.Attributes.Add("onclick", "proceed('" + link.ClientID + "')");
    }
}

Javascript:
function proceed(id)
{
    window.document.getElementById(id).removeAttribute("onclick"); // Link button - to remove "onclick" attribute
    window.document.getElementById(id).click(); //  trigger click event
}

I tried with the above code, the attribute not removed and not continue with link button event.

A: Finally I have done. This one worked perfectly as I expected.
function proceed(id)
{
    document.location.href = $('#' + id).attr("href");
}


text:
Q: Module Not Found when the Module Exists import io

import requests
from pyPdf import PdfFileReader

url = 'http://www.arkansasrazorbacks.com/wp-content/uploads/2017/02/Miami-Ohio-Game-2.pdf'

r = requests.get(url)
f = io.BytesIO(r.content)

reader = PdfFileReader(f)
contents = reader.getPage(0).extractText().split('\n')

is resulting in
Traceback (most recent call last):
  File "C:\Users\james\eclipse-workspace\homework\proj2.py", line 4, in <module>
    from pyPdf import PdfFileReader
  File "C:\Users\james\AppData\Local\Programs\Python\Python310\lib\site-packages\pyPdf\__init__.py", line 1, in <module>
    from pdf import PdfFileReader, PdfFileWriter
ModuleNotFoundError: No module named 'pdf'

I'm at whits end about what this could possibly be, I have just installed pip install pyPdf, I don't know how it could find the module missing when Eclipse IDE isn't throwing erorrs and CMD is noting that the module is there.

A: This is a known bug for pyPDF. pyPDF is no longer supported, you should use pyPDF2 as suggested in the official page of pypDF. This problem is solved in pyPDF2


text:
Q: Add padding to table (Maintain cell collapsed) I'm making a table with a border between each row, I've been trying to edit the table so the row borders don't touch the outer border of the table and I can't figure it out for the life of me. I feel like there's probably a solution that I have completely overlooked.
What I'd like it to look like:

What it looks like at the moment:

A: IF the borders are set to TD inner elements
tr td:first-child {
     padding-left:25px;
}
tr td:last-child {
     padding-right:25px;
}

Otherwise a nice way to do it would be to use a transparent table inside a
gray DIV that has the padding you need

.tableContainer{
  padding:15px;
  position:relative;
  margin:0 auto;
  background:#353033;
  border:1px solid #000;
  box-shadow:0 5px 15px rgba(0,0,0,0.3);
}

table{
  color:#B3B3B3;
  table-layout:fixed;
  border-collapse:collapse;
  width:100%;
}

td, th{
  text-align:left;
  padding:5px 0;
  border-bottom: 1px solid #000;
}

/* --------------------- */

html, body{
  height:100%;
}
body{
  font: 16px/1 sans-serif;
  color: #fff;
/* Permalink - use to edit and share this gradient: http://colorzilla.com/gradient-editor/#6da5ce+0,9c7bac+50,ec8e99+100 */
background: #6da5ce; /* Old browsers */
background: -moz-linear-gradient(45deg,  #6da5ce 0%, #9c7bac 50%, #ec8e99 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left bottom, right top, color-stop(0%,#6da5ce), color-stop(50%,#9c7bac), color-stop(100%,#ec8e99)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(45deg,  #6da5ce 0%,#9c7bac 50%,#ec8e99 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(45deg,  #6da5ce 0%,#9c7bac 50%,#ec8e99 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(45deg,  #6da5ce 0%,#9c7bac 50%,#ec8e99 100%); /* IE10+ */
background: linear-gradient(45deg,  #6da5ce 0%,#9c7bac 50%,#ec8e99 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#6da5ce', endColorstr='#ec8e99',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */
}

      Title
      Title

      Text goes here
      and here also

A: .tableContainer {
    padding: 15px 0px;}
td, th {
    padding: 5px 10px;}


text:
Q: Null pointer dereferencing void func()
  {
    char *p = "Test String 2";
    if (p != NULL) { }
    p[0] = 0;
 }

Does the p[0]=0 Statement nullify the character? Are we dereferencing a null pointer on the p[0]=0 line?

A:
char *p = "Test String 2";

This is ill-formed in C++. String literals are arrays of const chars which do not implicitly convert to a pointer to non-const char (since C++11; such conversion was allowed but deprecated in older standard versions).
Avoid using pointers to non-const for pointing to string literals.

Does the p[0]=0 Statement nullify the character?

It would assign the character with the null terminator character. For clarity, I would recommend using a character literal instead of integer literal:
p[0] = '\0';

However, since you modify a string literal, the behaviour of the program is undefined. Don't modify string literals.

Are we dereferencing a null pointer on the p[0]=0 line?

No. A pointer initialised with a string literal is not null pointer.

P.S. Don't use NULL macro in C++. Use nullptr instead which has replaced all use cases that NULL may used to have had.

A: Creating a C-style string like char *p = "Test String 2"; does a couple of things

*

*Allocates some memory space statically to hold the sequence of characters T,e,s,t, ,S,t,r,i,n,g, ,2, \0 - this may happen well before this function actually runs.

*Sets the value of p to the address of the start of that sequence.

That is, p will be some memory location, and p[0] will be the character T.
This has some implications for your code:

*

*p will not ever be NULL. If it is, something terrible has happened. For almost any compiler you care about, the sequence of characters will have been loaded as part of the executable when it was launched.

*p[0] does not dereference a NULL pointer, for the same reason.

*p points to a chunk of memory that you really shouldn't be modifying - it will possibly work, but that's not the same as "it's guaranteed to work". It can break in surprising ways.


text:
Q: Heroku - Flask - Bcrypt error I am attempting to deploy a flask app on Heroku and it always errors at the same place. GCC fails to install and compile the Bcrypt module so I removed it from my requirements.txt (it is not used in the app). When I view the requrements.txt file, there is no mention of Bcrypt but when I push to heroku, it still tries to install it. I have committed the most recent version of requirements.txt to Git. Any help would be greatly appreciated.

A: I was able to solve this by using this custom heroku build pack:
heroku config:add BUILDPACK_URL=git://github.com/mfenniak/heroku-buildpack-python-libffi.git

A: I was able to get around it kind of, by successfully installing the following: "Successfully installed z3c.bcrypt python-bcrypt py-bcrypt-w32".  Installing one of these (likely the second one) is what probably included the main bcrypt library that I guess needed to be compiled? I not 100% sure...  I noticed this post is from July, I was able to download those libraries all using PIP.

A: Add cffi or cryptography in requirements.txt .That solved the problem in my case.


text:
Q: what is the purpose of using JSON in android? I need to know the purpose of using JSON in android ?
Please anyone tell me in a simple way...
Thanks

A: The same reason you'd use it on any platform. JSON is a way of storing and expressing information. It uses attribute-value pairs in a hierarchical structure. In Android specifically, you may need to download some information from a database, which could be stored in JSON and then read by your app. Alternatively, you could store data locally in JSON but there are probably better and more efficient ways to do that if you're not sending data across a network.
https://en.wikipedia.org/wiki/JSON

A: For example, you can get data Json if you work with database. Or if you work with some API's then you can get data in format Json.

A: For example an app could fetch data from a server. When using JSON to get the data, the traffic is quite small and the app can easily work with it.
For example you have a server with a database with recipes, and your app displays recipes, the app could ask the server for recipes, and it gets a JSON in return. for example:
{
    name: 'Cookies'
    ingredients: { 'Butter', 'Eggs', ... /* I don't know, I'm not a chef :D */
    ...
}

The app can then just read the properties and display them in a neat list ;)

A: JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging. It is also a subset of JavaScript's Object Notation (the way objects are built in JavaScript
Pls go through this link: http://www.copterlabs.com/blog/json-what-it-is-how-it-works-how-to-use-it/
JSON stands for JavaScript Object Notation
JSON is lightweight text-data interchange format
JSON is language independent *
JSON is "self-describing" and easy to understand
*   JSON uses JavaScript syntax for describing data objects, but JSON is still language and platform independent. JSON parsers and JSON libraries exists for many different programming languages.

A: Using JSON in Android is not different than using it on any other platform. The main advantage of the format (in comparison to XML for example) is the small size of the data. This is very important for mobile devices due to the scarce resource those application use - i.e. your mobile app should be able to run with little memory usage, slow internet connection and so on.
Besides Android's framework has built-in tools for parsing / creating JSON objects. Thus it is both easy and efficient to use JSON rather than XML. If you have any project specific reason to prefer another data presentation format - don't worry. It is perfectly fine NOT to use JSON as long as some other format is more suitable for your project.
In short JSON is usually the right choice due to its small footprint and easy of use.

A: JSON is very light weight, structured, easy to parse and much human readable. JSON is best alternative to XML when your android app needs to interchange data with your server


text:
Q: NoSuchPortException problem for serial port I tried to connect to SerialPort COM6 using (Windows XP)  javax.comm library with this piece of code
portId = CommPortIdentifier.getPortIdentifier(commName);
        port = portId.open("", Integer.parseInt(timeout));
        serialPort = (SerialPort) port;
        serialPort.setSerialPortParams(Integer.parseInt(baudRate), SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

but I got exception NoSuchPortException and error
Error loading SolarisSerial: java.lang.UnsatisfiedLinkError: no SolarisSerialParallel in java.library.path
Caught java.lang.UnsatisfiedLinkError: com.sun.comm.SolarisDriver.readRegistrySerial(Ljava/util/Vector;Ljava/lang/String;)I while loading driver com.sun.comm.SolarisDriver
Error loading SolarisSerial: java.lang.UnsatisfiedLinkError: no SolarisSerialParallel in java.library.path

What is wrong with this ? Can anybody please help ?

A: The implementation of this API is not available on all platforms.

A: you need to use rxtx libraries for windows.
http://rxtx.qbang.org/wiki/index.php/FAQ


text:
Q: Bootstrap-sass on Rails can't scroll pages on mobile browser Most of my app won't let me scroll at all and it cuts off a lot of content. The one exception is on the home page, where I use skrollr. I hope that's not causing a conflict.
After installing Bootstrap-Sass, the app wasn't being responsive at all to mobile (everything was tiny) and I had to add this to application.html.erb:
<meta name="viewport" content="width=device-width, initial-scale=1">

I don't know if that has something to do with it. Maybe I need to set a device-height?
Everything works fine on my desktop browser. If I shrink the browser there, I can scroll fine.
Anyone ever experience this or have any ideas on how to fix it?

A: Seems that skrollr was causing the problem. I was initializing it everywhere when I should have only been initializing it on the page I need.


text:
Q: SQL Server - Selecting random rows in batches for page numbering without duplicates I have the below query which extracts random rows without duplicates.
My issue is, when I want to load more for subsequent pages, how do I avoid getting duplicates?
SELECT TOP ($limit) Min(c.id)           AS id,
                    s.id                AS skid,
                    s.name,
                    Min(b.sector)       AS sector,
                    Min(s.currency)     AS currency,
                    Min(s.url)          AS url,
                    Min(sd.description) AS description
FROM   coupons AS c
       INNER JOIN users AS s
               ON c.USER = s.id
       INNER JOIN business AS b
               ON s.id = b.USER
       LEFT JOIN groups AS g
              ON g.couponid = c.id
WHERE  ( c.[public] = 'True' )
       AND ( c.valid = 'True' )
       AND ( s.currency = '$curr' )
GROUP  BY s.id,
          s.name
ORDER  BY Newid()

Many thanks

A: You must save the returned record ids in an array and send them as a parameter when you load new data.
If you want to solve it with only sql, you may create a temporary table to save returned record ids. When you load more data simply add this:
"SELECT TOP ($limit) Min(c.id)           AS id,
                s.id                AS skid,
                s.name,
                Min(b.sector)       AS sector,
                Min(s.currency)     AS currency,
                Min(s.url)          AS url,
                Min(sd.description) AS description
FROM   coupons AS c
   INNER JOIN users AS s
           ON c.USER = s.id
   INNER JOIN business AS b
           ON s.id = b.USER
   LEFT JOIN groups AS g
          ON g.couponid = c.id
WHERE  ( c.[public] = 'True' )
   AND ( c.valid = 'True' )
   AND ( s.currency = '$curr' )
   AND ( s.id NOT IN (SELECT id FROM temporary_table))
GROUP  BY s.id,
      s.name
ORDER  BY Newid()";

If you are allowed to use php than it is easier. Just use an array variable and post it when you connect to loading page.
"SELECT TOP ($limit) Min(c.id)           AS id,
                s.id                AS skid,
                s.name,
                Min(b.sector)       AS sector,
                Min(s.currency)     AS currency,
                Min(s.url)          AS url,
                Min(sd.description) AS description
FROM   coupons AS c
   INNER JOIN users AS s
           ON c.USER = s.id
   INNER JOIN business AS b
           ON s.id = b.USER
   LEFT JOIN groups AS g
          ON g.couponid = c.id
WHERE  ( c.[public] = 'True' )
   AND ( c.valid = 'True' )
   AND ( s.currency = '$curr' )
   AND ( s.id NOT IN (" . implode(',', $used_Ids) ."))
GROUP  BY s.id,
      s.name
ORDER  BY Newid()";


text:
Q: Access 2010 database with Visual Studio 2010 I have an Access 2010 database that I am trying to access in a Windows Form Visual Studio application.
Here is my code:
         strDB = " Provider=Microsoft.ACE.OLEDB.12.0;Data Source="

        strDB = strDB & pstrPathName

        ' the connection object
        mdbDatabase = New OleDbConnection(strDB)

        ' open the connection
        mdbDatabase.Open()

It fails to work. The Message I get is  "Microsoft.ACE,OLEDB.12.0" provider is not registered on the local machine.
I was advised in another Forum to try to install AccessDatabaseEngine.exe. That program  installed ok but it didn't help. Any thoughts?
Bob

A: I found the answer in another Forum
1) Right Click on the Project, choose Properties
2) Choose Compile
3) Click on Advance Compile
4) Under Option, pick Target CPU
5) Chnage to x86.
Bob


text:
Q: Square root of several variables analytic function The question is as follow:

Let $H\subset \mathbb{C}^n$ be an simply-connected region. If $f$ is a nowhere vanishing analytic function on $H$, with $f(z)>0$ for all $z\in H\cap\mathbb{R}^n$, does there exist an anlytic function $g$ defined on H such that $g(z)=\sqrt{f(z)}$, for all $z\in H\cap\mathbb{R}^n$?

For the one variable case, the answer is yes. But can we extend this fact to the general case?


text:
Q: Know coordinate of Z from XY value and angle I am using XY coordinate of drawing to draw object using Ink. Now I have one requirement. I have one Object, which is slope of 30 degree and I need to write some text for e.g. 'ABC' on the slope. What I have is XY coordiate and Angle and I want to find the Z from this information. Could you please suggest me some proper way to find the Z from the given information?
While Marking on the slope I need to down the Z axis to remain focus on Slope and for the same I will need value of Z at every point. As of now I have XY coordinate and Angle and I wanted to find the Z coordinate.
Looking forward to hear the experts suggestion/direction.

A: So, I guess it looks somewhat like this:
      /|
     / |
  x /  |
   /   | z
  /    |
 /     |
/γ)____|
     y

You might want to use this:
z = sqrt(x² + y² - 2 * x * y * cos(γ))

... or this (at any offset s):
z = ((y - s) / sin(90 - γ) * sin(γ)

UPDATE:
So, let's say  point P1 is the start of your triangle (bottom left corner) and point P2 is any point on the slope:
        /
    P2 .< P2.y
      /|
     / |
    /  |
   /   |
  .γ)__|___
P1     ^
       P2.x

P2.x goes from P1.x to P1.x + <the width of your triangle>. Now, the only thing you need is coordinate y of P2. And (knowing the slope/angle γ) you can get it with the formula from above:
P2.y = ((P2.x - P1.x) / sin(90 - γ) * sin(γ) + P1.y


text:
Q: Why does this pointer swap fail in string reverse? I wanted to implement a reverse function for a null-terminated char* string (null-terminated char string, is that redundant?) and came up with the following solution.
The final swap swap(&tmp, &str) in the reverse function does not have any effect. What's the reason, how is it done probably?
Remark: I have already reimplemented the reverse function by using only the string itself, a temporary char and indices only, but I am so interested in why this does not work. What haven't I considered in this pointer matter?
#include <stdlib.h>
#include <stdio.h>

int strlen(char* str)
{
        int len = 0;
        char* ptr = str;
        while (ptr[0] != '\0')
        {
                len++;
                ptr++;
        }

        return len;
}

void swap(char **a, char **b)
{
        char* c = *a;
        *a = *b;
        *b = c;
}

void reverse(char* str)
{
        int len = strlen(str);
        char* tmp = malloc(sizeof(char) * (len + 1));
        int i;
        for (i = 0; i < len; i++)
        {
                tmp[i] = str[len - 1 - i];
        }

        tmp[len] = '\0';
        // printf(tmp); => "wolfrevOkcatS olleH"
        swap(&tmp, &str);
}

int main(int argc, char** argv)
{
        char* str = "Hello Stackoverflow\0";
        reverse(str);
        printf("%s", str);
        return 0;
}

A: You can just do an in place reverse, and you won't need that pointer swap you're doing:
void reverse(char* str, int len)
{
        int i;
        for (i = 0; i < len; i++)
        {
                char tmp = str[i];
                str[i] = str[len - 1 - i];
                str[len - 1 - i] = tmp;
        }
}

To answer your question, you need to pass a char** to your reverse function, because you're changing what it will point to, and pointers are copied by value, so if you want to reflect the change of pointee you need a double pointer.


text:
Q: Visual Studio Code Does Not Format .cs files couple of weeks ago I installed Visual Studio Code on my Windows machine. It is lightweight and I love it. But there is one problem that drives me crazy. The program cannot format .cs files. If I open .Net Core project, there is no problem on formatting. I changed the language from bottom right to C# and saved the file locally still no success. Is there any way to format code in single .cs file? I know there is already an asked question here for this problem but the solutions does not apply if there is no project created.

A: Use the command pallet (crtl-shift-P), type "format" and select "format code". Assuming the extension for the current language supports that.
TypeScript does, but C# does not.
You could raise an issue (if one does not already exist).


text:
Q: SharePoint: Why the value of my field wasn't changed? SharePoint 2013
Why the value of my field wasn't changed?
using Microsoft.SharePoint;
using System;
using System.IO;

namespace SharePoint2013_sandbox {
    internal static class Example {
        // I have some site for learning
        const String sitePath = "http://sharepoint2013/sites/sandbox2";
        // The Id of the field that is used by uploaded files
        static readonly Guid fieldId = new Guid(
            "{126801d9-c5c7-48a5-ab82-5ef48a76f934}");
        internal static void WorkWithFields() {

            if (!SPSite.Exists(new Uri(sitePath))) {
                Console.WriteLine("The {0} site not found.", sitePath);
            }
            else {
                using (SPSite siteCollection = new SPSite(sitePath)) {
                    using (SPWeb site = siteCollection.OpenWeb()) {

                        SPFieldChoice fldProjCode = site.Fields[fieldId]
                            as SPFieldChoice;

                        SPList list = site.Lists["Some document collection"];
                        using (FileStream fs = new FileStream(
                            @"C:\Public\Data\Drawing1.dwg",
                            FileMode.Open, FileAccess.Read, FileShare.Read)) {
                            SPFile file = list.RootFolder.Files.Add(
                                "Drawing1.dwg", fs, true);

                            // Now I set the value for the field of the file...
                            String fldValue = fldProjCode.Choices[1];
                            file.Item[fldProjCode.Id] = fldValue;

                            file.Update();
                        }
                        site.Update(); // But field value of my file wasn't updated.
                    }
                }
            }
            Console.WriteLine("Press any key for exit...");
            Console.ReadKey();
        }
    }
}

A: I added the file.ListItemAllFields.Update(); code row before the file.Update(); line and now the field is updated too.


text:
Q: Export data from Powerapps to Excel I have a table with data in my Power apps application and I would like to export this table to an excel sheet. Can you anyone help for this?

A: There isn't a pure-native way to do it, but it is possible by stringing some things together.  Check this post:
https://learn.microsoft.com/en-us/powerapps/user/export-data-excel


text:
Q: Show that convolution of two $L^1(\mathbb{R})$ functions is continuous Suppose $f, g \in L^1(\mathbb{R})$. I want to show that their convolution is continuous.
I can show continuity if one of the functions were in $L^\infty(\mathbb{R})$.
I have tried to approximate one of the functions, say $f$ with $f_M = f\cdot \mathbb{I}\{ |f(x)| \leq M\}$. But I have problem bounding the residual, which would be of form:
$$ \int_\mathbb{R} |f(x-z) - f_M(x-z)|\cdot |g(z)| dz$$
Any help/hint would be greatly appreciated!

A: This is not true. The counterexample I know is:
$f(x) = g(x) = \begin{cases}
x^{-3/4}&0<x< 1\cr
0& \text{otherwise}
\end{cases}$
then $\lim_{x \to 0^+}f*f(x) = \infty$ and $\lim_{x \to 0^-}f*f(x)=0$.
I guess you need at least one of $f$ or $g$ to be $L^{\infty}.$

A: $f*g$ is not a well defined function from $\mathbb R$ to itself, in general. For example, if $f(x)=g(x)=\frac 1 {\sqrt {|x|}}$for $0<|x| \leq1 $ and $0$ elsewhere then $(f*g)(0)=\infty$.


text:
Q: Include and edit a pdf in LaTeX-Beamer I want to include an excerpt of a pdf-document in my Beamer-presentation. Furthermore, I want to highlight a part of this document, i.e. draw a red rectangle around it, maybe even have an arrow point towards it.
I only have the free version of Adobe Acrobat Reader, so I don't even know how to do this without LaTeX. Except, of course, I can take a screenshot of the excerpt and then edit it using PowerPoint:
Is there a nice way to do this in Beamer ?

A: A little while ago I wrote some code for annotating images that works equally well for annotating PDF files inside beamer. My macros define an AnnotatedImage environment where the coordinates are scaled so that the rectangular image fits inside a suitably scaled unit square, which makes it pretty easy to draw on the image. For example, you can produce the following "beamer slide"

using the essentially the code:
  \begin{AnnotatedImage}[width=0.8]{abacus.pdf}
    \draw[red, rounded corners, thick](0.2,0.85) rectangle(0.5,0.71);
    \draw[<-,red](0.2,0.78)--++(-0.1,0);
  \end{AnnotatedImage};

[This MWE will not compile as I used a random PDF file abacus.pdf on my computer and you won't have this...unfortunately, nice packages like mwe don't supply PDF files.] The optional argument to the environment allows you set the mage dimensions and inside the environment you can use arbitrary tikz commands. In addition, there is also a \annotate command. See Image with some overlaid text for more details.
For a multi-page PDF file this almost certainly won't work but it will work if you extract the pages that you want to annotate. The other option would be to be use pdfpages to extract only the pages that you need. If you need this let me know as it shouldn't be hard to modify my code to use pdfpages directly.
Here is the full code:
\documentclass{beamer}
\usepackage{tikz}
\usepackage{xparse}

\tikzset{% styling for the overlay
  annotatedImage/x/.initial = 0.7,% default overlay position
  annotatedImage/y/.initial = 0.7,
  annotatedImage/width/.initial = 1,% default image width
  annotatedImage/.unknown/.code = {% unknown keys are appended to style
    % to append to a style we need to expand everything first
    \edef\tikzappend{\noexpand\tikzset{annotatedImage/.append style =
                {\pgfkeyscurrentname=\pgfkeyscurrentvalue}}}
    \tikzappend
  },
  annotatedImage/.style = {% default overlay style
    draw=red, ultra thick, rounded corners, rectangle,
  }
}

\newsavebox\annotatedImageBox% need to calculate the width and height

% internal helper functions
\newcommand\AnnotatedImageVal[1]{\pgfkeysvalueof{/tikz/annotatedImage/#1}}
\newcommand\SetUpAnnotatedImage[2]{% set keys and dimensions to scale image
    \tikzset{annotatedImage/.cd, #1}%
    \sbox\annotatedImageBox{\includegraphics[width=\AnnotatedImageVal{width}\textwidth,
                                          keepaspectratio]{#2}}%
    \pgfmathsetmacro\annotatedHeight{\ht\annotatedImageBox/28.453}% convert from px to a tikz length
    \pgfmathsetmacro\annotatedWidth{\wd\annotatedImageBox/28.453}%
}

% usage: \annotatedImage[node options]{image}{text}
\NewDocumentCommand\annotatedImage{ O{} m m}{%
  \bgroup% start a group to keep tikz changes local
    \SetUpAnnotatedImage{#1}{#2}%
    \begin{tikzpicture}[xscale=\annotatedWidth, yscale=\annotatedHeight]%
        \node[inner sep=0, anchor=south west] (image) at (0,0) {\usebox{\annotatedImageBox}};
        \node[annotatedImage] at (\AnnotatedImageVal{x},\AnnotatedImageVal{y}) {#3};
    \end{tikzpicture}%y
  \egroup%
}

% usage: \annotate <insert favourite node commands>;
\newcommand\annotate[1][]{\node[annotatedImage,#1]}

% usage: \begin{AnnotatedImage][width(default 1)]{image} tikz commands....\end{AnnotatedImage}
\newenvironment{AnnotatedImage}[2][1]{%
  \SetUpAnnotatedImage{#1}{#2}%
  \tikzpicture[xscale=\annotatedWidth, yscale=\annotatedHeight]
    \node[inner sep=0, anchor=south west] at (0,0) {\usebox{\annotatedImageBox}};
}{\endtikzpicture}

\begin{document}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{PDF example}

  \begin{AnnotatedImage}[width=0.8]{abacus.pdf}
    \draw[red, rounded corners, thick](0.2,0.85) rectangle(0.5,0.71);
    \draw[<-,red](0.2,0.78)--++(-0.1,0);
  \end{AnnotatedImage};

\end{frame}

\end{document}


text:
Q: Should I delete a branch after merging it? After merging a branch, do you delete it from the repository?
Is it a good practice or not?
I usually create a lot of branches, since I don't want to break my current release, and I'd wish to delete them to keep things in order.
However, if you work with Assembla or GitHub, your merge requests from old branches will be saved on the site, so if you delete them you'll get an error since it won't be able to fetch them...
Usually how do manage that?

A: Just take care of
All hyperlinks URLs references of your DELETED branches, will be BROKEN.
For example
If you delete branch_feature_x branch from your repo
The corresponding hyperlink URL of this branch will be broken
https://github.com/username/project/tree/branch_feature_x

A: I definitely clean up my branches after they've been merged in.
We use GitLab and merge requests at work, so the historical information about branches is stored there; I don't need them cluttering my branch list, and when I look at a coworker's fork, ideally I'd like only to see the branches of their current active development.  If I'm trying to look at some code on their branch, I want to be able to look through just a few currently active branches, and not every feature or fix they've ever started work on.
The above applies to BitBucket and GitHub, too.
The only reason you might have for not deleting a branch post-merge is so you know where a given feature ended, but merge commits (and git merge --no-ff if you really want) make that irrelevant.

A: Just to clarify, branch, from git point of view, is just link onto some commit.
By deleting branch, you will not delete commits from git repo. Of course, detached commits will be cleaned after some time via git garbage collector.
FYI: We're usually merging branches into master via bitbucket interface. There you can set delete feature branch after merge flag.
If you need to deal with too old branches, you could have a look for some utilities, for example this one .

A: There's no problem in deleting branches that have been merged in. All the commits are still available in the history, and even in the GitHub interface, they will still show up (see, e.g., this PR which refers to a fork that I've deleted after the PR got accepted).


text:
Q: How to calculate efficiently using every combination of a String, Integer pair where the Integer has a maxiumum in Java? Imagine you have 3 items: a pen, a box and a car. You can have up to 9 pens, up to 5 boxes and up to 2 cars. How do you calculate the total value of every combination of items you could have?
Here's the code I currently have:
        int maxPens = 9;
        int maxBoxes = 5;
        int maxCars = 2;

        Double penPrice = 1.5;
        Double boxPrice = 50.0;
        Double carPrice = 150.0;

        int penCount = 0;
        int boxCount = 0;
        int carCount = 0;
        int totalCount = 1;

        while (penCount <= maxPens) {
            boxCount = 0;
            while (boxCount <= maxBoxes) {
                carCount = 0;
                while (carCount <= maxCars) {
                    Double totalPrice = (penCount * penPrice) + (boxCount * boxPrice) + (carCount * carPrice);
                    System.out.println(totalCount + " = " + totalPrice);

                    totalCount++;

                    carCount++;
                }
                boxCount++;
            }
            penCount++;
        }

This works and gives the output as the count of the combination, plus the total price, but feels really messy and if I then want to add another item I have to add more repeating into the method. Is it possible, for example, to do this using Maps where you might have:
Map<String, Integer> maxCountMap = new HashMap<String, Integer>();
Map<String, Double> priceMap = new HashMap<String, Integer>();

and iterate through these?

A: You can iterate through Map, but in my opinion the cleanest solution is to create a new class Item:
public class Item {
   String name;
   int max;
   double price;

   Item(String name, int max, double price) {
       this.name = name;
       this.max = max
       this.price = price;
   }

}

This class should contain getters and setters.
And use for loop instead of while:
Item pen = new Item(Pen, 5, 1.5)
Item box = new Item(Box, 5, 50.0)
Item car = new Item(Car, 2, 150.0)

for (int i; i<=pen.getMax; i++){
  for (int j; j<=box.getMax; j++){
    for (int k; k<=car.getMax; k++){
      Double totalPrice = (i * pen.getPrice()) + (j * box.getPrice()) + (k * car.getPrice());
      int total = i+j+k;
      System.out.println(total + " = " + totalPrice);
    }
  }
}


text:
Q: Angular mat-sidenav-container fullscreen scrollbar not working I have a problem with my scrollbar and fullscreen attribute on mat-sidenav-container.
Here is my code (my app-root):

<mat-sidenav-content class="main-content">
     <mat-toolbar fxLayout="column">
        .
        .
        .
     </mat-toolbar>
     <!-- The 'overflow-y: hidden;' is here because i had 2 scrollbars-->
     <mat-sidenav-content style="overflow-y: hidden;">
        <div>
           <router-outlet>
           </router-outlet>
         </div>
     </mat-sidenav-content>
</mat-sidenav-content>

In my index.html :

<head>
</head>

<body>
    <app-root></app-root>
</body>

</html>

And the problem with my scrollbar is :Not entire scrollbar
I don't have the entire scrollbar and i don't see the bottom of my page.
Do you have a solution to get a proper scrollbar with the fullscreen attribute on mat-sidenav-content.
Ty.


text:
Q: Is the DCEF3 being kept up to date? When I go to chrome://version/ in my chromium wrapper component (DCEF3) I get this:

My question is: Are these versions up to date or dcef3 project is not active?
I want to start a windows project with Chromium, I prefer Delphi for this but CefSharp seems a more active project. I'm wonder if it would be more advantageous to use it instead DCEF3.

A: Unfortunately this project seems to be dead. I could contact the owner by email sometime ago, i even offered to donate to help, but at the time he did not have a paypal account.
It's sad because it's a very good and stable component, but if no updates are made, at least using new Chromium versions, it will become obsolete soon.


text:
Q: Hibernate mapping exception: Could not determine type for columns: [org.hibernate.mapping.Column] I'm want to do a one-to-many mapping between two tables BookStock and Book, but I'm getting the following exception
Exception in thread "main" org.hibernate.MappingException: Could not determine type for: java.util.List, at table: book_stock, for columns: [org.hibernate.mapping.Column(books)]

The bookStock entity is
@Entity
@Table(name = "book_stock")
public class BookStock {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private Long stock;
    private List<Book> books;

    @Column(name = "id")
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Column(name = "stock")
    public Long getStock() {
        return stock;
    }

    public void setStock(Long stock) {
        this.stock = stock;
    }

    @OneToMany
    @PrimaryKeyJoinColumn
    public List<Book> getBooks() {
        return books;
    }

    public void setBooks(List<Book> books) {
        this.books = books;
    }
}

The Book Entity is
@Entity
@Table(name = "book")
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String bookName;
    private BigDecimal price;
    private BookStock bookStock;

    @Column(name = "id")
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Column(name = "book_name")
    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    @Column(name = "price")
    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    @ManyToOne
    public BookStock getBookStock() {
        return bookStock;
    }

    public void setBookStock(BookStock bookStock) {
        this.bookStock = bookStock;
    }
}

The Example class is
public class transactionsExample {

    public static void main(String[] args) {
        AnnotationConfiguration configuration = new AnnotationConfiguration();
        configuration.configure();
        configuration.addAnnotatedClass(Book.class);
        configuration.addAnnotatedClass(BookStock.class);
        configuration.setNamingStrategy(ImprovedNamingStrategy.INSTANCE);
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        Session session = sessionFactory.openSession();

        session.beginTransaction();
        Book book1 = EntityBuilder.book().withISBN("21234").withName("Anario").withPrice(25.90).purchase();
       session.save(book1);
        session.getTransaction().commit();
    }
}

What's going wrong in this relation?

A: It does not find all of your annotations, because you are annotating both fields and methods. You have to use only one strategy. In your case @Id annotation in id field is seen first and thats why annotations in get-methods does not have effect. As result hibernate assumes correctly that
List<Book> books;

is not mapped. If you move also annotations from id-field to the getId-method (for both entities), problem is solved.
About fixing other issues with mappings, please see comment below.


text:
Q: Ubuntu .bashrc custom PS1 behaving strange I am currently running Ubuntu 14.04 and this is my custom PS1:
PS1="\n\[\033[0;90m\]\t \[\033[01;32m\]\e[1m\u@\h\e[m:$ \[\033[0;33m\w\n\e[1m\[\033[1;31m\]➤\e[m "

I am getting this weird text wrapping effect, when I use the arrow up key to summon the last command I typed, it creates an overlap effect oO! Can anyone tell me what's wrong with it please?

A: You did not enclose all the non-printing characters in \[...\], and I think you want to leave things like \w unenclosed.
PS1="\n\[\033[0;90m\]\t \[\033[01;32m\]\e[1m\u@\h\e[m:$ \[\033[0;33m\w\n\e[1m\[\033[1;31m\]➤\e[m "
                                       ^^^^^                        ^^                      ^^^^

A: ok i had to do it on my own so here it is.
so i did do this custom PS1 for like 5 years back or so, and that's why it's all fucked up, by the help of this well elaborated tutorial i fixed it so here it is:
 PS1="\n\[\e[0;90m\]\t \[\e[01;32m\]\u@\h:$ \[\e[0;33m\]\w\n\[\e[1;31m\]➤ \[\e[0;37m\]"


text:
Q: WebView2 runtime silent install fails with error 0x80070057 I am trying to get the WebView2 runtime installed using the Evergreen installer MicrosoftEdgeWebview2Setup.exe which is embedded in my app.
This works fine:
Process.Start(Application.StartupPath + "\\MicrosoftEdgeWebview2Setup.exe");

but I want to install the runtime silently.
I tried this code
ProcessStartInfo startInfo = new ProcessStartInfo
            {
                FileName = Application.StartupPath +"\\MicrosoftEdgeWebview2Setup.exe",
                Arguments = " / silent / install",
                UseShellExecute = true,
                Verb ="runas"
            };
            Process p = Process.Start(startInfo);

but the install fails with error code 0x80070057.
Has anyone else hit this issue ?

A: My command line arguments had too many spaces. It should read
Arguments = " /silent /install"

After that the runtime install will install silently and also much quicker than just using Process.Start without startinfo


text:
Q: facebook share IE problems

i am using above code for implementing facebook share in my website its working fine in firefox and chrome but in IE when i am clicking on share button it is creating two instances of one as a popup and another instance opens in the same tab i just want the popup are there any methods to prevent this

A: It seems that facebook tries to solve some issues ( cross-domain, i believe ) by loading twice the page.
You can prevent this behavior by specifying a channel url on init. Check FB.init
Basically, instead of loading your page a second time, you specify an url to load instead.
FB.init({
     appId  : 'YOUR APP ID',
     channelUrl  : 'http://example.com/channel.html'  // custom channel
   });

The only content needed in that html file is:


text:
Q: laravel 5.2 eloquent order by on relationship result count I have two tables website_link and website_links_type. website_link is related website_links_type with hasmany relationship.
$this->website_links->where('id',1)->Paginate(10);

and relationship
public function broken()
{
    return $this->hasMany('App\Website_links_type')->where('status_code','!=',"200");
}

Now I want to get result from website_link table but Orderby that result on count of broken relationship result.

A: There are many ways to solve this problem. In my answer I'll use two I know.
You can eagerload your relationship and use the function sortBy(). However I don't think you can use the paginate() functionality with this solution.
Example:
$results = Website_link::with('website_links_type')->get()->sortBy(function ($website_link) {

    return $website_link->website_links_type->count();

});

See this answer
You can also use raw queries to solve this problem. With this solution you can still use the pagination functionality (I think).
Example:
$results = Website_link

    ::select([
        '*',
        '(
            SELECT COUNT(*)
            FROM website_links_type
            WHERE
                website_links_type.website_link_id = website_link.id
            AND
                status_code <> 200
        ) as broken_count'
    ])

    ->orderBy('broken_count')

    ->paginate(10);

You may have to change the column names to match your database.

A: You can not put WHERE condition in model file.
You just give relationship hasMany in model file.
And use where condition in controller side.
Refer this document.
Try this
Model file:
public function broken()
{
    return $this->hasMany('App\Website_links_type');
}

Controller file:
$model_name->website_links->where('id',1)
            ->where('status_code','!=',"200")
            ->orderBy('name', 'desc')
            ->Paginate(10);


text:
Q: Table of contents, how to change name I want to start with my first LaTeX project and I am using a couple of templates, but I've encountered a problem. The template seems to be using:

\tableofcontents

For the table of contents, it looks good however I want to change the header from 'Contents' to something else, like 'Inhoudsopgave', but I can't seem to do that.
What is the solution?

A: In some cases you can use the command \renewcommand{\contentsname}{Inhoudsopgave}.
In other cases (when you only want to change the language settings to Dutch) you should rather use a package for this cause (I recommend babel) like this.
\documentclass{book}

\usepackage[dutch]{babel}

\begin{document}

\tableofcontents

\end{document}