text:
Q: What am I missing in this access SQL query? I am trying to pull specific information from several tables using the INNER JOIN function and I think I have a problem with my syntax - thinking too many or too few (). What does the community think?
SELECT Employee.EmployeeID
    ,Service.HoursWorked
FROM (
    Equipment INNER JOIN (Equipment Repair)
        ON Equipment.EquipmentID = Equipment Repair.RepairID
    )
INNER JOIN (
    (
        (
            Service INNER JOIN EMPLOYEE
                ON Service.ProductID = EMPLOYEE.EmployeeID
            ) INNER JOIN (
            OWNER INNER JOIN Property
                ON OWNER.OwnerID = Property.OwnerID
            )
        INNER JOIN SubProperty
            ON Property.PropertyID = SubProperty.PropertyID
        )
    ON Service.PropertyID = Subproperty.PropertyID
    )
INNER JOIN TrainingCourse
    ON EMPLOYEE.EmployeeID = TrainingCourse.EmployeeID
        ON Equipment.EquipmentID = TrainingCourse.EquipmentID ORDER BY Employee.EmployeeID

A: Your query is attempting to join several tables together, but you are perhaps trying to use parentheses as well? Those don't have the effect you might be expecting here.
Without the (apparently?) spurious parentheses, I would understand that query as meaning this:
SELECT
    Employee.EmployeeID
    ,Service.HoursWorked
FROM Equipment
    INNER JOIN (Equipment Repair)
        ON Equipment.EquipmentID = Equipment Repair.RepairID
    INNER JOIN Service
    INNER JOIN EMPLOYEE
        ON Service.ProductID = EMPLOYEE.EmployeeID
    INNER JOIN OWNER
    INNER JOIN Property
        ON OWNER.OwnerID = Property.OwnerID
    INNER JOIN SubProperty
        ON Property.PropertyID = SubProperty.PropertyID
        ON Service.PropertyID = Subproperty.PropertyID
    INNER JOIN TrainingCourse
        ON EMPLOYEE.EmployeeID = TrainingCourse.EmployeeID
        ON Equipment.EquipmentID = TrainingCourse.EquipmentID
ORDER BY Employee.EmployeeID

But that still has errors, because many of the joins are lacking join conditions and some have multiple join conditions.
Instead, you need to think of the projection operation that you are trying to express. What columns, from what tables, should appear in the result set (this tells you which tables to join), and under what condition should a row from table Foo appear in the total result set (this tells you the join condition for that table).


text:
Q: Comparing gene expression overlap with hypergeometric distribution I got stuck with an issue in analyzing my RNA-seq data. I have three tratments (Control, D1 and D2), and within each tratment I calculate DE genes between two groups (G1 and G2). Then I identify genes that become DE in both D1 and D2 compared to the control. Summarizing, I have (see also Fig. 1):

*

*15,000 genes representing the entire transcriptome

*1,000 genes representing those that become DE as effect of treatment, filtering those that are DE in the control. This group is made as union of D1 and D2 DE genes, respectively 450 and 600 genes.

*Intersecting the DE genes, I found that 50 of them are common to both D1 and D2, 400 are specific to D1 and 550 are specific to D2.

Now I want to understand if this overlap is due by chance or not. So I'd like to have a feedback on my solution and, if wrong, a possible answer to my problem.
I have my oberservation: out of 1,000 DE genes common to both D1 and D2, 50 overlap. Then, I draw 100 genes from both D1 and D2, and I counted how many overlap (bootstrapped 1,000 times). Let's say that the result of bootstrapped drawing is 10. Finally, I tested if the overlap observed and the one got by random drawing is different through a hypergeometric distribution.
I've done everything with R, using the phyper (link) as follows:
Here I have to use 4 values:
x = 10 (overlapping genes from drawing)
m = 50 (overlapping observed)
n = 950 (total DE genes - m)
k = 100 (number of genes drawn from D1 and D2)
lower.tail=FALSE

I got 0.007 which, if I understood correctly and my procedure is correct as well, means that the overlap I observe between D1 and D2 is not due by chance.
Any opinion about my approach?
Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: script to upload a file without submit I have the below code to upload a photo.  I currently have the process set so it uploads upon click of a submit button.  How can I change this code to upload automatically without the submit button? Thanks
HTML:
<form data-ajax="false" id="imageform" action="imageup.php" method="POST" enctype="multipart/form-data" name="form">

            <img id="companyprofileimg" src="image/<?php echo $row['photo']?>"/>

        <?php echo $row['username']?>

        <input id="upfile" type="file" value="upload" name="file" onchange="readURL(this);"/>

    Upload Image
</form>

JAVASCRIPT:
 function getFile(){
   document.getElementById("upfile").click();
 }
 function sub(obj){
    var file = obj.value;
    var fileName = file.split("\\");
    document.getElementById("companyprofileimg").innerHTML = fileName[fileName.length-1];
    document.myForm.submit();
    event.preventDefault();
    document.getElementById('imageform').submit();
  }

A: JavaScript:
document.getElementById('imageForm').submit();

A: try this
function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#companyprofileimg')
                .attr('src', e.target.result)
                .width(50)
                .height(50)
        };

        reader.readAsDataURL(input.files[0]);
        $('#imageForm')[0].submit();
    }
}

A: I just figured it out, I just added the submit onchange to the input, thanks for the help folks


text:
Q: At the end of my rope - Virtualbox not booting my Windows 10 VHD I am interested in moving from Windows to Linux, but I have some applications on Windows that I still use (university requires it) and thus I would like to build a Windows 10 virtual machine.
I used disk2vhd to convert my current Windows 10 into a .vhd file, and then I ran it on Virtualbox and selected the existing hard disk. However, no matter what I tweaked, the system said

FATAL: No bootable medium found! System halted.

I've read the very instructional user manual for Virtualbox, but unfortunately it didn't provide answers. I followed all the instructions on this and other websites that solved the same problem on other machines, like simply configuring the Controller IDE (my controller IDE doesn't even show under Storage, and when I add it manually and want to choose a file, the .vhd is not available). So I am pretty confused.
Might there be something wrong with my laptop, or what am I missing?


text:
Q: can i send a flash sms from my android handset ? and q.2. how to send sms from mobile , without displaying sender's number? Can i send a flash sms from my android handset ?
 q.2. how to send sms from mobile , without displaying sender's number ?
Various sites in the net allow you to do this , can this be done using some script / programming in  android ??
Thanks in advance
Raj

A: It's not a programming issue. The SMSC (SMS server) must allow this. Under normal conditions (i.e. when connected to the commercial SMSC's, not private dev&test SMSCs) this is allowed for MT messages (mobile terminated) (subject to account terms), but not for MO (mobile originated) messages.


text:
Q: Create dendrogram on communities, not nodes in igraph I am trying to create a dendrogram of the communities only of a network. The example code below gives me a dendrogram of all the nodes, but as I work with a relatively large dataset, I would like to create a dendrogram of only the comunities,so that I would have a smaller dendrogram with only the communities, is this possible?
library(igraph)
set.seed(1)
g001 <- erdos.renyi.game(100, 1/10, directed = FALSE)

fc01 <- fastgreedy.community(g001)
colors <- rainbow(max(membership(fc01)))
plot(g001, vertex.size=2, vertex.label=NA, vertex.color=colors[membership(fc01)] )

dendPlot(fc01, mode="phylo", cex=1)

Thank you.

A: The dendrogram class has a cut function you can use to split up a dendrogram at a certain height. The community algorithm seems to use heights based on how many objects there are. Therefore, given your fc01 object above, you can split it into subgroups with
ss01 <- cut(as.dendrogram(fc01), h=length(membership(fc01))-length(fc01))$lower

That created 5 groups for me. We can plot the entire set and the 5 subsets with
layout(matrix(1:6, nrow=2))
dendPlot(fc01, mode="hclust")
lapply(ss01, plot, cex=1)

So each sub-graph is in ss01[[1]], ss02[[2]], etc...


text:
Q: Printing an integer value from an ASCII character I am trying to implement the function stoi() in c++. I have made an int array arr to store the integer ASCII of all elements of char_arr. This works fine if I print the values from my char_arr array because its a character array. But, how do I transfer my integer values from the char array to an int array and print only the numbers and not their ASCII?
Code:
int stoi(){
        int *arr = new int [strlen(char_arr)];
        for (int i=0; char_arr[i]!='\0'; ++i){
            arr[i] = char_arr[i];
        }
        for (int i=0; char_arr[i] != '\0'; ++i){
            if (arr[i] >= 48 && arr[i] <= 57){
                cout << char_arr[i];
            }
        }

    }

A: First of all, remove the first loop and use char_arr directly. You don't need to hold ints to make it work.
As for printing int values, you can use this:
for (int i = 0; char_arr[i] != '\0'; ++i) {
  if (char_arr[i] >= '0' && char_arr[i] <= '9') { //I would suggest you to use this syntax instead of raw ASCII codes.
    cout << (char_arr[i] - '0');
  }
}

A: int stoi(){
    /* if you do not use arr.
    int *arr = new int[strlen(char_arr)];
    for (int i = 0; char_arr[i] != '\0'; ++i){
        arr[i] = char_arr[i];
    }
    */
    int sign = 1, value = 0;
    if (*char_arr == '+') {
        ++char_arr;
    }
    else if (*char_arr == '-') {
        ++char_arr;
        sign = -1;
    }
    while (*char_arr) {
        if (*char_arr >= '0' && *char_arr <= '9') {
            value = value * 10 + *char_arr - '0';
            ++char_arr;
        } else {
            break;
        }
    }
    return sign * value;
}

A: Here's the one I came up with:
#include <cstdio>
#include <cstring>

#define _BASE_  10

int main(int argc, char **argv)
{
    char ascii[] = "474927";
    signed int value = 0;

    signed int ascii_len = strlen(ascii);

    int pos = 0;
    for(signed int i = ascii_len-1; i >= 0; i--)
    {
        if(i == 0 && ascii[i] == '-')
        {
            value *= -1;
            continue;
        }

        int base = 1;

        if(pos > 0)
        {
            base = _BASE_;

            for(int j = 1; j < pos; j++)
                base *= _BASE_;
        }

        value += base * (ascii[i] - 48);
        pos++;
    }

    printf("Value: %d\n", value);

    return 0;
}


text:
Q: Vscode not giving the option to open remote repository I created some Github repositories from my computer, but my computer became old and I got an iPad.
With my iPad, I started two new Github repositories, creating a README.md file for each one. Then, I started to develop some code in those with Codespaces.
Now, I want to continue developing, but using Vscode from Blink App instead Codespaces. The problem arises when I try to open my repositories. Vscode from Blink only give me the option to open the repositories that I created with my computer, not the last two ones (created with my iPad).
I have no idea about what's happening and why Vscode from Blink does not allow me to open all repositories.
Please, may I have your help?
I tried to make the repository public, just in case... but it doesn't work either. All my repositories are private and Vscode for Blink opens only those created with my computer.

A: In the repository, go to "Settings" -> "Collaborators and Teams" and there, include a member (include yourself if you are who want to access).
This member will have access to this repo from vscode (blink).


text:
Q: $p$-groups with trivial $H^3$ Let $Q_8$ be the group of quaternions of order $8$. It is a non-abelian $2$-group such that $H^3(Q_8,\mathbb{Z})=0$, where $\mathbb{Z}$ has the trivial action. For a proof, see the book "Homological Algebra" of Cartan and Eilenberg, Chapter XII, Section 7 (Examples), where the case of cyclic groups and generalized quaternions is also considered.
I am curious if more examples of this kind exist (for other primes). More precisely, let $p>2$ be an odd prime. Does there exists a finite (non-abelian) $p$-group $G$ such that $H^3(G,\mathbb{Z})=0$? I could not find anything even for groups of order $p^3$.

A: For $G$ a finite group, $H^3(G,\mathbb{Z})$ is isomorphic to the Schur multiplier, and you'll find lots of examples using that as a search term (also, "Schur-trivial" is sometimes used to mean "having trivial Schur multiplier").
For an example of order $p^3$, see The integral cohomology rings of groups of order $p^3$ by Gene Lewis (Trans AMS, 132(2), p. 501-529, (1968)). The semidirect product $C_{p^2}\rtimes C_p$, with a generator of $C_p$ acting on $C_{p^2}$ by $x\mapsto x^{p+1}$ is an example for every $p$.


text:
Q: Predict Coefficients with glmnet() ridge.fit1 <- glmnet(x,y, alpha = 0)

ridge.fitt <- coef(glmnet(x, y, alpha = 0, lambda = 3))
ridge.pred <- predict(ridge.fit1, s = 3, type = 'coefficients')

What's the difference between ridge.fitt and ridge.pred?

A: If you call
ridge.fit1 <- glmnet(x,y, alpha = 0)

the lasso is fit for a grid of 100 values of the regularization parameter lambda. If you call the predict function for a value of lambda that is not a grid point itself, the coefficients are extrapolated.
If you call
ridge.fitt <- coef(glmnet(x, y, alpha = 0, lambda = 3))

the lasso is fit only for a lambda value of 3, and the exact coefficients for this fit are returned. You can make the predict function refit the model using the given lambda value and return exact coefficients by adding the argument exact=TRUE.


text:
Q: Give Access to different visualforce pages for Customer Portal users I created customer portal with login enabled and assigned Customer Community Plus User to the portal with two users. I am able to login to the customer portal by using those two user's credentials.
Requirement : Now I have two users(Customer Community Plus Login User License) and I have two custom visualforce pages. I want to redirect to first visualforce page if the first user logged in and I want to redirect to second visualforce page if the second user logged in to the customer portal.
How to setup this retrictions for different users on visualforce page?
for example,
first person has access to --- first visualforce page

second person has access to --- second visualforce page

third person has access to --- all the visualforce pages

Thanks,
Azar.

A: When you enable communities , some classes are by default created in your org. One of the class is  "CommunitiesLandingController".
You can use this class to perform redirection.
**
 * An apex page controller that takes the user to the right start page based on credentials or lack thereof
 */
public with sharing class CommunitiesLandingController {

    // Code we will invoke on page load.
    public PageReference forwardToStartPage() {
        If(UserInfo.getUserName() == 'FirstuserName1'){
            PageReference pg = Page.FirstPage ; //your pagename1 here
            return pg;
        }
        else if(UserInfo.getUserName() == 'SeconduserName1')}
            PageReference pg = Page.FirstPage ; //your pagename2 here
            return pg;
        }
        else
             return Network.communitiesLanding();
    }

    public CommunitiesLandingController() {}
}

Check in the "forwardToStartPage()" method , the current user and redirect it to your desired page depending upon the condition, otherwise keep it default.


text:
Q: ScalaTest Matchers vs MustMatchers difference It seems for latest version of ScalaTest we have two matchers one isMatchers (ShouldMatchers before) andMustMatchers.
What's the real difference between this two? Is that kind of style the team can choose or?
Also, any difference betweenshouldBe and should be

A: The only difference is the word - quoting from the ScalaDocs for MustMatcher:

Trait MustMatchers is an alternative to Matchers that provides the exact same meaning, syntax, and behavior as Matchers, but uses the verb must instead of should. The two traits differ only in the English semantics of the verb: should is informal, making the code feel like conversation between the writer and the reader; must is more formal, making the code feel more like a written specification.

As for should be vs. shouldBe ... it depends on which instance of should[Be] you are invoking.  In all cases shouldBe does one less registration step (because it skips the work that be does).  Sometimes it looks like that means fewer objects are allocated - other times, the same steps are taken, but both "should" and "be" are registered in one pass.  As far as I can tell there is no difference in behavior (at least in the day-to-day of writing tests), it's just which one you prefer stylistically.


text:
Q: Is there a way that i can find numbers that are the nearest to each other in a array My logic in my code right now is this
Step1. Scan for 100 candlesstick or more from the past
Step2. Collect and store the date of all 100 to find out the high of each candlestick
Step3. Go through all the candlestick high data and find the one that are near each other (Still dont know how i would do that)
Step4. Plot HLine
Now the first problem im having is how would i code it where i would be able to find which candlestick numbers are close to each other in order to plot the HLine.

extern int candleCount = 100;
int totalHigh;
int FinishingTotalHigh;

int totalLow;
int FinishingTotalLow;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---

//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
  totalHigh = 0;
  totalLow = 0;

// Initializing the variables.
   double Highest = High[0];
   double Lowest = Low[0];
      Alert("");
      Alert("");
      Alert("");
      Alert("");
      Alert("");
   // Scan the 100 candles and update the values of the highest and lowest.
   for (int i = 0; i <= candleCount; i++)
   {

      //Alert(i+"Index Data: "+High[i]);
      totalHigh = High[i] + totalHigh;
       totalLow = Low[i] + totalLow;

      if (High[i] > Highest) Highest = High[i];
      if (Low[i] < Lowest) Lowest = Low[i];
   }
   FinishingTotalHigh = totalHigh/candleCount;
   FinishingTotalLow = totalLow/candleCount;
   // Print the result.

   Alert("Highest price found is "+Highest);
   Alert("Lowest price found is "+Lowest);
   Alert("TotalHigh: "+FinishingTotalHigh);
   Alert("TotalLow: "+FinishingTotalLow);

  }
//+------------------------------------------------------------------+


text:
Q: Convert SQL to Doctrine 2 Query Builder or DQL by using NOT IN? How would I convert the SQL bellow to Doctrine 2 Query Builder or DQL?
SELECT tags.*
FROM tags
WHERE tags.id NOT IN (
                     SELECT tag_id AS totalTags
                     FROM human_resource_tags
                     WHERE human_resource_id=1)

Tag entity is as follows:
Tag entity
HumanResource entity is as follows:
HumanResource entity
Basically what I want to do is to select all Tag entities for one HumanResource entity that that HumanResource entity does not have already.
I am really struggling here so any help is appreciated.
I am using Doctrine version 2.4.2.
==========================================================================
All hail to FuzzyTree for pointers :)
I have slightly modified it and it works like a charm :)
So this will get you all Tag entities for particular HumanResource entity that are not added to
HumanResource entity yet :)
SO THIS IS SOLUTION:
$q = $this->createQueryBuilder('t')
      ->where('t.name LIKE :name')
      ->andWhere('NOT EXISTS (
                    SELECT h
                    FROM HRAPIBundle:HumanResource h
                    WHERE h.id = ' . $humanResource->getId() .
                    'AND h MEMBER of t.human_resources
                )')
      ->setParameter('name', "%".$query."%")
      ->getQuery();

A: You can achieve this using NOT EXISTS and MEMBER OF
$qb->select("t")
    ->from('HardCoreMore\HRAPIBundle\Entity\Tag', 't')
    ->where('NOT EXISTS (
        SELECT 1
        FROM HardCoreMore\HRAPIBundle\Entity\HumanResource h
        WHERE h.id = 1
        AND h MEMBER of t.human_resources
      )');

A: Select your $hmEntitythat you don't want then use the follow code:
 $em = $this->getDoctrine()->getManager();
 $result= $em->getRepository('HRAPIBundle:Tag')->findByHumanResource(!$hmEntity);


text:
Q: Object name not found in R I have created following map for disaster by district as shown below.

The code I used is:-
install.packages("cartography")
install.packages("sf")
install.packages("tidyverse")
library(cartography)
library(sf)
library(tidyverse)
setwd("C:/Users/lenovo/Desktop/IEM")
Province2Disaster<-st_read("DisasterBagmatiProvince.shp")
View(Province2Disaster)
Province2Disaster$DeathClass<-cut(Province2Disaster$Deaths,
             breaks = c(0,500,1500,3000,4500, Inf),
             labels=c('<500','50-1500','1500-3000','3000-4500','>4500'))
ggplot()+geom_sf(aes(fill=DeathClass),data=Province2Disaster)+
ggtitle("Total Death by Disaster in Province 2")

But I want to label feature by district name (dist_name) as shown in attribute table.

But using the code (after the code above) :-
ggplot()+geom_sf(aes(fill=DeathClass),data=Province2Disaster)+
geom_text(aes(label = dist_name))+
ggtitle("Total Death by Disaster in Province 2")

The error display as:- Error in FUN(X[[i]], ...) : object 'dist_name' not found. Though the column name dist_name is present in table. Why is this occuring? How to fix it?

A: Your error is because here:
ggplot()+geom_sf(aes(fill=DeathClass),data=Province2Disaster)+
 geom_text(aes(label = dist_name))+
 ggtitle("Total Death by Disaster in Province 2")

you've specified data in the geom_sf function, and so column names are only valid in that function. If instead you started with ggplot(data=Province2Disaster) + ... then the data is applicable in the rest of the ggplot elements and so you can use all column names (unless there's another ggplot element with a data= argument)
For geom_text you also need to specify the x and y coordinates for the text. We don't have your data so we can't tell if you already have suitable point coordinates, otherwise you can do something like add the polygon centroids (example using GADM Nepal level 1 data):
> np = st_read("./gadm40_NPL_1.shp")
Reading layer `gadm40_NPL_1' from data source
  `/nobackup/rowlings/Downloads/nepal/gadm40_NPL_1.shp' using driver `ESRI Shapefile'
Simple feature collection with 5 features and 11 fields
Geometry type: POLYGON
Dimension:     XY
Bounding box:  xmin: 80.06014 ymin: 26.34752 xmax: 88.20401 ymax: 30.44702
Geodetic CRS:  WGS 84
> np = cbind(np, st_coordinates(st_centroid(np)))
Warning message:
In st_centroid.sf(np) :
  st_centroid assumes attributes are constant over geometries of x
> names(np)
 [1] "ID_0"      "COUNTRY"   "ID_1"      "NAME_1"    "VARNAME_1" "NL_NAME_1"
 [7] "TYPE_1"    "ENGTYPE_1" "CC_1"      "HASC_1"    "ISO_1"     "X"
[13] "Y"         "geometry"
> ggplot(np) + geom_sf(aes(fill=HASC_1)) + geom_text(aes(label=NAME_1, x=X, y=Y))

Also I think you can maybe use geom_sf_text instead of plain geom_text here - although I can't find documentation of how it exactly chooses X and Y coordinate, I imagine its probably centroid.


text:
Q: Как извлечь из массива все значения, кроме последних двух в php Всем привет.
Как извлечь из массива все значения (любое количество), кроме последних двух или трех в php?
Заранее спасибо!
A: Для обычных массивов
$arr=explode(" ", "1 2 3 4 5 6 7 8 9 0");
var_dump(array_slice($arr, 0, sizeof($arr)-2));

Для ассоциативных массивов
$arr=array("a"=>12, "b"=>13, "c"=>14, "d"=>15);
var_dump(array_slice($arr, 0, sizeof($arr)-2, true));

A: function get_all_exept($num,$arr,$begin=false){
  for($i=0;$i<$num,count($arr);$i++){//пока в массиве есть элементы вынимаем num элементов
    if($begin){//Вынимаем из начала или из конца
      array_shift($arr);
    }else{
      array_pop($arr);
    }
  }
  return $arr;
}

Работает даже для ассоциативных массивов.
Если массив с числовыми ключами, расположенными последовательно от 0, то все еще проще: по циклу вынимаем.

for($i=num;$i<count($arr);$i++)

для всех, кроме трех первых
for($i=0;$i<(count($arr))-$num;$i++)

для всех, кроме трех последних
A: В каком смысле извлечь? Если имелось ввиду извлечь в другой массив, то можно так:
 <?php
    $a = array(1, 2, 3, 4, 5, 6, 7);
    $b = array();
    if (count($a) >= 2) {
        for ($i = 0; $i < count($a) - 2; $i++) {
            $b[$i] = $a[$i];
        }
    } else {
        echo "В массиве меньше двух элементов!";
    }
    var_dump($a, $b);
    ?>

A: Думаю, примерно так...
<?php
$arr[] = 1; // элемент массива
$arr[] = 3; // элемент массива
$arr[] = 5; // элемент массива
$result = count($arr)-2; // длинна всего массива за минусом двух последних элементов
// $result == 3
echo $result; // на экран получим 1
?>


text:
Q: How can i draw on a canvas in mobile device? i have some canvases in my code. All of these are like a blackboard, this canvases let me draw on an image, but when i try to draw in a device nothing happens. This is all of my code:

let configureCanvas = canvas => {
  let ctx = canvas.getContext("2d");
  let painting = canvas.parentNode;
  let paintStyle = getComputedStyle(painting);

  if(canvas == document.getElementById("pizarra-musculos")) {
      var x = window.matchMedia("(max-width: 700px)")
      myFunction(x) // Call listener function at run time
      x.addListener(myFunction) // Attach listener function on state changes
      function myFunction(x) {
      if (x.matches) { // If media query matches
          canvas.width = "350";
          canvas.height = "350";
        } else {
          canvas.width = "500";
          canvas.height = "500";
        }
      }
  }else{
    canvas.width = "350";
    canvas.height = "350";
  }

  let mouse = {
    x: 0,
    y: 0
  };

  canvas.ontouchstart = function(e){
    var touches = e.touches || [];
    var touch = touches[0] || {};
  }

  canvas.addEventListener('mousemove', function(e) {
    mouse.x = e.pageX - this.offsetLeft;
    mouse.y = e.pageY - this.offsetTop
  }, false);

  if(canvas == document.getElementById("pizarra-musculos")) {
     //Rojo Claro
    ctx.lineWidth = 12;
    ctx.lineJoin = 'round';
    ctx.lineCap = 'round';
    ctx.strokeStyle = 'rgba(255, 8, 53, 0.02)';

    document.getElementById("btnRojoClaro").addEventListener("click", ()=>{
      //Rojo Claro
      ctx.lineWidth = 12;
      ctx.lineJoin = 'round';
      ctx.lineCap = 'round';
      ctx.strokeStyle = 'rgba(255, 8, 53, 0.02)';
    });
    document.getElementById("btnVerde").addEventListener("click", ()=>{
      //Rojo Claro
      ctx.lineWidth = 4;
      ctx.lineJoin = 'round';
      ctx.lineCap = 'round';
      ctx.strokeStyle = '#249120';
    });
    document.getElementById("btnRojo").addEventListener("click", ()=>{
      //Rojo Claro
      ctx.lineWidth = 4;
      ctx.lineJoin = 'round';
      ctx.lineCap = 'round';
      ctx.strokeStyle = '#ff0000';
    });
    document.getElementById("btnNegro").addEventListener("click", ()=>{
      //Negro
      ctx.lineWidth = 4;
      ctx.lineJoin = 'round';
      ctx.lineCap = 'round';
      ctx.strokeStyle = '#000000';
    });
    document.getElementById("btnAzul").addEventListener("click", ()=>{
      //Azul
      ctx.lineWidth = 4;
      ctx.lineJoin = 'round';
      ctx.lineCap = 'round';
      ctx.strokeStyle = '#1e5085';
    });

  }else{
    ctx.lineWidth = 3;
    ctx.lineJoin = 'round';
    ctx.lineCap = 'round';
   ctx.strokeStyle = '#e34f54';
  };

  canvas.addEventListener('mousedown', function(e) {
    ctx.beginPath();
    ctx.moveTo(mouse.x, mouse.y);
    canvas.addEventListener('mousemove', onPaint, false);
  }, false);

  canvas.addEventListener('mouseup', function() {
    canvas.removeEventListener('mousemove', onPaint, false)
  }, false);

  var onPaint = function() {
    ctx.lineTo(mouse.x, mouse.y);
    ctx.stroke();
  };

  canvas.nextElementSibling.addEventListener('click', function() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
  });

}

PD: i learned about the touchscreens on mozila developers but i can't do functionally this canvas on device... Thanks for learning my question.

A: In javascript, you can add listenner! That means that something will be listenned and a code will be executed when the listenner will be activated !
For instance, if you declare in html <button id="mybutton"></button> in js, you can retrieve this button with document.getElementById("mybutton"), thus, you can manipulate the element itself, value, return, action, etc...,
Let's store this element var button = document.getElementById("mybutton")
now console.log(button) will sort of display this element, cool right ?
On this button you can add listenner, onClick for example that will execute a function when the button is clicked
button.addEvenListenner("onClick", my_function)
So now when you will click on your button you will execute my_function (you need to create my_function of course)
But in your case your want to get the eventListenner of a mouse mouve or when someone use finger on their phone!
You already made it, with 'mousemove' for example ! or 'mouseup' etc...
The thing desktop is a phone and vice versa!
You don't have a mouse on your phone you have your finger, so need to have a listenner when someone touch de screen!
That's where 'touchstart' event listenner is here for, when you touch the screen, you can call a function to do whatever you want with this !
Those four listenner will be enough for your project, why you may ask ?
'touchstart' tells when you touch the screen
'touchend' tells when you remove your finger from the screen
'touchmove' tells when you drag your finger on the screen (touchstart and touchmove are not the same thing !)
'touchcancel' tells when you cancel (Honestly I don't know, you don't need it I guess)
now you need to add your listenner to your canvas
var canvas = document.getElementById("pizarra-musculos")

then you add your listenner
  canvas.addEventListener("touchstart", handleStart);
  canvas.addEventListener("touchend", handleEnd);
  canvas.addEventListener("touchmove", handleMove);

Now when one of those 3 listenner will be used, the function next to them will be called !
Thus, you can execute whatever you want in those function
 function handleMove(e) {
      // Cache the client X/Y coordinates
      var clientX = e.touches[0].clientX;
      var clientY = e.touches[0].clientY;
    }

With this bit of code you are able to keep track of the x and y of your finger of your screen, try every listenner to know when they are called etc.. put some console.log to print out value, you will do it it's not hard hope it helped you


text:
Q: Animations only affect first element of css-doodle I want to make random "blinking" effect when hovering over a doodle. For this i store animation name blink into a variable when user hovers over doodle container. For some reason animation applies only to the first element of the grid. Is there a way to apply the animation to all elements?
CodePen: https://codepen.io/entityinarray/pen/mdbRPRz

<html>
  <script src="https://unpkg.com/css-doodle@0.7.2/css-doodle.min.js"></script>

  <css-doodle>
    :doodle {
      @grid: 4/128px;
      --h: ;
    }

    :doodle(:hover) {--h: blink;}

    background: #200040;
    animation-delay: rand(500ms);
    animation: @var(--h) 1s infinite;

    @keyframes blink {
      0% {
        background: #200040;
      }
      100% {
        background: #8000c0;
      }
    }
  </css-doodle>
</html>

A: The issue is that the use of @var(--h) is generating code like var(--h)-x which is invalid and only the first item is having the good value var(--h).
Instead of doing this you can simply consider the animation state like below. Note that rand() should be used with @ and placed after the animation definition:

<html>
  <script src="https://unpkg.com/css-doodle@0.7.2/css-doodle.min.js"></script>

  <css-doodle>
    :doodle {
      @grid: 4/128px;
    }

    :doodle(:hover) {--h:running;}

    background: #200040;
    animation: blink 1s infinite;
    animation-play-state:var(--h,paused);
    animation-delay: @rand(500ms);

    @keyframes blink {
      0% {
        background: #200040;
      }
      100% {
        background: #8000c0;
      }
    }
  </css-doodle>
</html>


text:
Q: Java exception in openConnection method (fetching data from html) I have a problem getting the input stream using 'getInputStream' method for few URLs (most of the URLs works fine) although the URL seems to work via web browser.
I am using the following code:
public static String getContents(String uri, String encoding) {
    StringBuffer sb = new StringBuffer();
    URL url;

    try {
        url = new URL(uri);

        URLConnection con = url.openConnection();
        con.setReadTimeout(90000);

        System.out.println("--------2.1:");//////////////////////////////////////////////////////////////
        InputStream is = con.getInputStream();
        System.out.println("--------2.2:"+is);/////////////////////////////////////////////////////////
        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        // read lines from HTML
        String line = null;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

    } catch (Exception e) {
        System.out.println("--------2.6:");//////////////////////////////////////////////////////
        return null;
    }
    return sb.toString();
}

output:
--------2.1:http://infoscience.epfl.ch/oai2d?verb=ListIdentifiers&metadataPrefix=oai_dc
--------2.6:

Exception:
java.io.IOException: Server returned HTTP response code: 503 for URL: http://infoscience.epfl.ch/oai2d?verb=ListIdentifiers&metadataPrefix=oai_dc
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at com.irWizard.common.util.FileUtils.getContents(FileUtils.java:29)
at com.irWizard.web.controller.WizardController.getActualTotalOfRecords(WizardController.java:500)
at com.irWizard.web.controller.WizardController.validateSets(WizardController.java:419)
at com.irWizard.web.controller.WizardController.onSubmit(WizardController.java:242)
at com.irWizard.web.controller.BaseController.onSubmit(BaseController.java:127)
at org.springframework.web.servlet.mvc.SimpleFormController.processFormSubmission(SimpleFormController.java:258)
at org.springframework.web.servlet.mvc.AbstractFormController.handleInvalidSubmit(AbstractFormController.java:652)
at org.springframework.web.servlet.mvc.AbstractFormController.handleRequestInternal(AbstractFormController.java:257)
at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153)
at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:45)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:728)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:396)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:350)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

It seems that it's code 503.
Does anyone know how it can be solved? (it works fine via browser).
Mike


text:
Q: Update Mongodb Object in Mongoose I can't figure out why this doesn't work. I've seen many examples where it does. All I want to do is add to an existing object in Mongo.
Current object
{ _id: 53951f43f6000e954d29f8e3,
  username: 'upload1',
  __v: 0 }

I'd like to add to this object, so it looks like this:
{ _id: 53951f43f6000e954d29f8e3,
  username: 'upload1',
  images: ['path/to/img', 'path/to/img'],
  __v: 0 }

I'm using Express, and this is what my code looks like:
User.findOne({_id: req.params.id}, function (err, user) {
  // catch error
  user.images = ['path/to/img', 'path/to/img']
  user.save(function (err) {
    // catch error
  })
})

I've also attempted User.update(), User.findAndUpdate(), {upset: true}, and nothing works... :\
Any ideas on whats going on here? Any help is much appreciated.


text:
Q: What are other elegant counterexamples to the convergence of a Cauchy product? What is an elegant case of two convergent series $\sum a_n$ and $\sum b_n$ which Cauchy product
$$\sum_{n=0}^{\infty} c_n = \sum_{n=0}^\infty \sum_{k=0}^n a_kb_{n-k}$$
diverges?

The most common, I believe, is $a_n=b_n=\frac{(-1)^n}{\sqrt{n+1}}$, in which case
$$c_n=\sum_{k=0}^n(-1)^n\frac{1}{\sqrt{k+1}\sqrt{n+1-k}}$$
and from the inequalities $k+1\leq n+1$ and $n+1-k\leq n+1$ it follows that the denominator is smaller than $n+1$, and
$$|c_n|\geq \sum _{k=0}^n \frac{1}{n+1}=1$$
so the condition $c_n\rightarrow 0$, necessary for converge, does not hold.

A: *

*Here is a family of counter examples to the Cauchy product convergence. Consider the conditional convergent series
$\sum^\infty_{n=0}\tfrac{(-1)^{n+1}}{(n+1)^\alpha}$ and $\sum^\infty_{n=0}\frac{(-1)^{n+1}}{(n+1)^\beta}$
where $0<\alpha,\beta<1$.
$$c_n:=\sum^n_{k=0}\frac{(-1)^{k+1}}{(k+1)^{\alpha}}\frac{(-1)^{n-k+1}}{(n-k+1)^\beta}=(-1)^n\sum^n_{k=0}\frac{1}{(k+1)^{\alpha}}\frac{1}{(n-k+1)^\beta}$$
As $1\leq k+1,n-k+1\leq n+1$ whenever $0\leq k\leq n$,
$$1\leq (k+1)^\alpha(n-k+1)^\beta\leq (n+1)^{\alpha+\beta}$$
If $\alpha+\beta\leq1$
$$|c_n|\geq\sum^n_{k=0}\frac{1}{(n+1)^{\alpha+\beta}}=(n+1)^{1-\alpha-\beta}\geq1$$
Hence $\sum_nc_n$ is a divergent series.

*More examples like the one above (alternating series with monotone decreasing driver) can be obtained. Consider $\sum^\infty_{n=0}(-1)^na_n$ and $\sum^\infty_{n=0}(-1)^nb_n$ where $a_n$ and $b_n$ are decreasing sequences converging to $0$.
$$c_n:=\sum^n_{k=0}(-1)^ka_k(-1)^{n-k}b_{n-k}=(-1)^n\sum^n_{k=0}a_kb_{n-k}$$
$a_n\leq a_k\leq a_0$ and $b_n\leq b_k\leq b_0$ for all $0\leq k\leq n$. Thus
$$|c_n|\geq \sum^n_{k=0}a_nb_n=(n+1)a_nb_n$$
Choosing sequences $a_n$ and $b_n$ so that $na_nb_n$ does not converge to $0$ will give a plethora of counter examples.

*Here is an example of convergence of Cauchy product of two conditionally convergent series. Consider the series $\sum^\infty_{n=0}\frac{(-1)^{n+1}}{n+1}$. Then
$$\begin{align}
\sum^n_{k=0}\frac{(-1)^{k+1}}{k+1}\frac{(-1)^{n-k+1}}{n-k+1}&=(-1)^n\sum^n_{k=0}\frac{1}{k+1}\frac{1}{n-k+1}
\end{align}$$
Since
$$\frac{1}{k+1}\frac{1}{n-k+1}=\frac{1}{n+2}\Big(\frac{1}{k+1}+\frac{1}{n-k+1}\Big)$$
$$\begin{align}
\sum^n_{k=0}\frac{(-1)^{k+1}}{k+1}\frac{(-1)^{n-k+1}}{n-k+1}&=\frac{2(-1)^n}{n+2}\sum^n_{k=0}\frac{1}{k+1}
\end{align}$$
Hence, the Cauchy product of $\sum^{\infty}_{n=0}\frac{(-1)^n}{n+1}$ with itself is
$$
\sum^\infty_{n=1}\frac{(-1)^n}{n+1}H_n
$$
where $H_n=\sum^n_{k=1}\frac{1}{k}$ is the $n$-th harmonic sum. It is left to the OP to show that the latter series converges ($H_n\sim\log n$)

*There are situations where the Cauchy product of two divergent series converge


text:
Q: How to Calculate Precision and Recall Manually based on TP and FP I have looked at the questions already asked about how to calculate precision and recall. However, I am still confused. There are specific questions that I face during the interviews that I am not sure how to approach them.
Question-1:
A binary classifier correctly filters 90% of spam emails but misclassifies 5% of non-spam emails as spam. Give the classifier's:
   - recall
   - precision
   - accuracy,
or explain why there's not enough information to know.

For the above example, my solution would be:

TP = 90%
FP = 5%

Recall = TP / TP + FN => cannot be calculated without knowing FN
Precision = TP / TP + FP => 0.90/0.90 + 0.05 = 0.94
Accuracy = TP + TN / FN + FP + TP + TN => cannot be calculated without knowing TN & FN

Question-2:
1 percent of Uber transactions are fraud

We have a model that:

When a transaction is fraud, 99% classifies as fraud
When a transaction is not fraud, 99% classifies not fraud

What is the precision and recall of this model?

For the above example, my solution would be:

Let's say we have 1,000 daily transactions

number of positive classes (number of frauds): 10
number of negative classes (number of non-frauds): 990

TP = 10 * 99% = 9.9
TN = 990 * 99% = 980.1

FN = 990 * 1% = 9.9
FP = 10 * 1% = 0.1

Then use these in the below formula.

recall = TP / (TP + FN)
precision = TP / (FP + TP)

Can you please help me clarify an approach for these kinds of questions?
Thank you all!


text:
Q: SYSLINUX 4.04 2010-10-22 EDD Copyright (C) 1994-2011 H. Peter Anvin et al When I boot Ubuntu from my USB Live I get:
SYSLINUX 4.04 2011-04-18 EDD Copyright (C) 1994-2011 H. Peter Anvin et al

Burned with LiLo, When I burn with UNETbootin I get:
SYSLINUX 4.03 2010-10-22 EDD Copyright (C) 1994-2011 H. Peter Anvin et al

I have a 8GB SanDisk Cruzer Edge...

A: I have seen a fix for the SanDisk users. It lies with the U3 folder. That prevents startup. Try to delete it and start it up that way!


text:
Q: Customize location of .so file generated by Cython I have a Cython package with wrappers of a C library. This is the tree structure of the package
package/
       _api.pxd
       _wrap.pyx
       setup.py
       wrapper/
              __init__.py
              wrap.py

Doing
python setup.py build_ext --inplace

puts the _wrap.so file in the top-level package/ directory which is normally required in most cases. However, my wrap.py needs the _wrap.so in the package/wrapper/ directory. I was wondering if there's a way in which setup.py could create the .so file in the desired place by itself without manually copying and pasting it in the location.

A: The output folder for the produced .so files can be specified as the first argument of setuptools.Extension function.
Here is an example for Cython extensions,
from setuptools import setup, find_packages, Extension
from Cython.Distutils import build_ext

ext_modules=[
    Extension("package.wrapper.wrap",    # location of the resulting .so
             ["package/wrapper/wrap.pyx"],) ]

setup(name='package',
      packages=find_packages(),
      cmdclass = {'build_ext': build_ext},
      ext_modules = ext_modules,
     )


text:
Q: File displaying only one form of request and response I am generating a file where it should output 2 various requests and 2 various responses from different SOAP Request steps which are:
TestRegion
TestRules

However I noticed the file is just generating  TestRegion request and response 2 times each over. For each request it displays  TestRegion request and for each response it's displaying  TestRegion response. Why is it doing this and how can I get the correct request and responses to show? it does display the hard coded strings correct like TESTREGION REQUEST: and then later on TEST REGION RESPONSE, but the request and response is incorrect.
def testRegionRequest = context.expand( '${${TestRegion}#Request}'  )
def testRegionResponse = context.expand( '${${TestRegion}#Response}'  )
def testRulesRequest = context.expand( '${${TestRules}#Request}'  )
def testRulesResponse = context.expand( '${${TestRules}#Response}'  )

def fileName = "XXX.txt"
def logFile = new File(fileName)

//Draws a line
def drawLine(def letter = '=', def count = 70) { letter.multiply(count)}

def testResult = new StringBuffer()
testResult.append drawLine('-', 60) + "\n\n"
testResult.append "\n\nTEST REGION REQUEST:\n\n"
testResult.append(testRegionRequest.toString())
testResult.append "\n\n" + drawLine('-', 60) + "\n\n"
testResult.append "\n\nTEST REGION RESPONSE:\n\n"

testResult.append(testRegionResponse.toString())
testResult.append "\n\n" + drawLine('-', 60) + "\n\n"
testResult.append "\n\nTEST RULES REQUEST:\n\n"
testResult.append(testRulesRequest.toString())
testResult.append "\n\n" + drawLine('-', 60) + "\n\n"
testResult.append "\n\nTEST RULES RESPONSE:\n\n"
testResult.append(testRulesResponse.toString())

// Now create and record the result file
logFile.write(testResult.toString())

A: It appears that you have incorrect values used in the context.expand
Change from:
${${SearchRegion}#Request}

To:
${SearchRegion#Request}

And the same is applicable to other properties as well.


text:
Q: what type of data do *args accept? The function works with direct input, but errors if tuples/lists variables are entered (below: "numbers") def add_unlimited(*args):
    sum = 0
    for n in args:
        sum += n
    print(sum)

numbers = [23, 45, 23, 56]
add_unlimited(23, 45, 23, 56)

A: Please note that *args does not have any type restriction, unlike other static languages like Go. You can even mix tuples of lists of integers, and plain strings together. This is equivalent to type annotating it like *args: Any - signifying that each argument can be any type.
However, in this case, it looks like your function depends on each argument being a number. So I would type annotate it like *args: Number, to hint to the caller that each argument passed in should be a valid number.
Usage can be as below:
from numbers import Number

def add_unlimited(*args: Number):
    sum = 0
    for n in args:
        sum += n
    print(sum)

numbers = [23, 45, 23, 56]
add_unlimited(*numbers)

A: def add_unlimited(*args) accepts an arbitrary amount of arguments. Inside the function, the arguments are accessible in the form of a list, which is named args.
Note that add_unlimited([23, 45, 23, 56]) is calling the function with one argument. That argument happens to be a list, [23, 45, 23, 56]. Inside the function, this will result in args = [[23, 45, 23, 56]]. The rest of your code inside the function doesn't work if each argument is not an integer, which is why you get an error.
You can pass a single list as several arguments by using the unpacking operator *:
add_unlimited(*[23, 45, 23, 56]) is equivalent to add_unlimited(23, 45, 23, 56)

A: sum=0
for n in args:
    sum = 0 + [23, 45, 23, 56]

you can't add a list and zero.
you probably wanted something like
for x in args:
    for n in x:
        sum += n


text:
Q: Equivalent function for url.openStream() in Golang import java.net.*;
import java.io.*;

public class URLReader {
    public static void main(String[] args) throws Exception {

    URL oracle = new URL("http://www.oracle.com/");
    BufferedReader in = new BufferedReader(
    new InputStreamReader(oracle.openStream()));

    String inputLine;
    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);
    in.close();
}
}

I need to do the same in golang i.e read and print the html source code, but cannot find the relation between two, I am a beginner with Go language, thank you in advance

A: Hope this will help:
package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

func Error(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

func main() {
    response, err := http.Get("http://www.oracle.com/")
    Error(err)

    defer response.Body.Close()

    contents, err := ioutil.ReadAll(response.Body)
    Error(err)

    fmt.Printf("%s\n", contents)
}

For more details: https://golang.org/pkg/net/http/


text:
Q: Concatenate names of the columns in a dataframe which contain true I have a dataframe that looks like this:
|id|type|isBlack|isHigh|isLong|
|1 |A   |true   |false |null  |
|2 |B   |true   |true  |true  |
|3 |C   |false  |null  |null  |

I'm trying to concatenate names of columns which contain 'true' into another column to get this:
|id|type|isBlack|isHigh|isLong|Description          |
|1 |A   |true   |false |null  |isBlack              |
|2 |B   |true   |true  |true  |isBlack,isHigh,isLong|
|3 |C   |false  |null  |null  |null                 |

Now, I have a predefined list of column names that I need to check for (in this example it'd be Seq("isBlack", "isHigh", "isLong"), which are present in the dataframe (this list can be somewhat long).

A: val cols = Seq("isBlack", "isHigh", "isLong")

df.withColumn("description", concat_ws(",", cols.map(x => when(col(x), x)): _*)).show(false)
+---+----+-------+------+------+---------------------+
|id |type|isBlack|isHigh|isLong|description          |
+---+----+-------+------+------+---------------------+
|1  |A   |true   |false |null  |isBlack              |
|2  |B   |true   |true  |true  |isBlack,isHigh,isLong|
|3  |C   |false  |null  |null  |                     |
+---+----+-------+------+------+---------------------+

Firstly map columns to column names when the value is true with:
cols.map(x => when(col(x), x))

And then use concat_ws to combine the columns concat_ws(",", cols.map(x => when(col(x), x)): _*)


text:
Q: What is the difference between allocating a specific sized array vs declaring a specific sized array in function in cpp? Normally a scope of an array in a function ends with it. But if I allocate beforehand then it perfectly returns the array. So what's the difference between allocating array or declaring array?
I am writing the code and the place where I am confused. Is it because of dynamic memory allocation of the first declaration or something else. Can someone elaborate please?
#include <bits/stdc++.h>
#define N 10

using namespace std;

int * get_array() {
    int * p = new int[N];
    //|--- by declaring like this, the array was perfectly returned.

    int p[N];
    //|--- but is case of this declaration the array returned showed garbage value in the main function.
    for(int i = 0; i < N; ++i) p[i] = i;
    return p;
}

int main(int argc, char const *argv[])
{
    int * M = get_array();
    for (int i = 0; i < N; ++i) {
        cout << M[i] << endl;
    }
    return 0;
}

A: In the second case the array is created in the heap of the function, so when you exit the function, that array doesn't exists anymore.
In the first case, you're reserving memory space to put your array, so isn't local to the function per se, and you must handle its destruction


text:
Q: How many ways can a committee be set up of 5 men and 7 women if only one male or female from each club can be selected? Question: Executives from 25 student clubs, one male and one female each, are attending a workshop on student violence. How many ways can a committee be set up of 5 men and 7 women if only one male or female from each club can be selected?
I'm currently taking a Grade 12 Data Management course, and this is a question I have from an assignment. I'm supposed to answer it using permutations and combinations preferably.
I have tried answering it by doing $(12C5)(12C7)$ and got the answer of 627,264. However, I am not sure if this is the correct method, or if my answer is right. Thanks so much in advance for any help you can give!

A: I would say $${25\choose 5}\cdot{20\choose 7}$$
First you take 5 man from 25 clubs, and then from the rest of 20 clubs you take 7 woman.


text:
Q: Variational problems living in two different Sobolev spaces Is there a general reference concerning variational problems living in $W^{h,p}\times W^{k,p}$, with $h, k\in\mathbb{N}_0$ not coinciding? I'm thinking to problems of type:
$$\inf_{u,v}\int_{\Omega} f_1\left(\frac{\partial^{|\alpha|} u}{\partial x_1^{\alpha_1}\dots \partial x_n^{\alpha_n}}\right)+f_2\left(\frac{\partial^{|\beta|} v}{\partial x_1^{\beta_1}\dots \partial x_n^{\beta_n}}\right)+ f_3\left(u-v\right)+V(x,u,v),$$
where $\Omega$ is a compact domain in $\mathbb{R}^n$ ($n\ge 1$), $|\alpha|=h$ and $|\beta|=k<h$. You can take $f_{1,2,3}$ and $V$ as nice as you wish ($V$ can also be assumed to depend only on $v$). You can include terms depending on other partial derivatives. What's important for me is that there's a term depending on $u-v$.
In the simplest one-dimensional cases (e.g., $h=1$, $k=0$, $f_{1,2,3}$ and $V(x,v)$ smooth), the term $u-v$ can be usually exploited to gain $H^1$ regularity for $v$ if, for instance, $f_1$ and $f_3$ are convex. Is any generalization of this known?
A further question: I encountered problems of this kind while studying (nonlinear) deformations of homogenized microstructured  continua. Where else may variational problem of this kind arise?


text: Q: Factoring a quadratic residue modulo Do apologize, wasn't sure where to ask this, but I was wondering how an algorithm would factor and show the square roots in a quadratic residue modolo when you're given $N$ and $a$, which is a quadrtic residue modulo $N$.


text:
Q: How to sort such a complex list in python? x = [([('x', 2), ('m', 3)], 'a'), ([('y', 4), ('t',8), ('d', '100')], 'c'), ([('a', 1)], 'b')]

I want to sort by the inner tuple integer, i.e. 2, 4, 1. So the sorted list should be:
sorted_x = [(('a', 1), 'b'), (('x', 2), 'a'), (('y', 4), 'c')]

It should look like something like this:
x_sorted = sorted(x, key=lambda tup: tup[1])

But the tup[1] is for the first level of tuple, and I can write tup[tupe[1]].
I think I need to flatten the list first, and then sort it.
EDIT:
Thanks for the solution for the very complex list sorting. It turns out that I should actually sort this (sorry for the problem statement modification):
x = ([('x', 2), ('m', 3), ('n', 1)], 'a')

Result:
sorted_x = ([('n', 1), ('x', 2), ('m', 3)], 'a')

I tried this:
x_sorted = sorted(x, key=lambda tup: tup[0][1])

But get this error:
x_sorted = sorted(x, key=lambda tup: tup[0][1])
IndexError: string index out of range

A: Try this:
>>> x = [([('x', 2), ('m', 3)], 'a'), ([('y', 4), ('t',8), ('d', '100')], 'c'), ([('a', 1)], 'b')]

>>> sorted([(a[0],b) for [*a],b in x], key = lambda x:x[0][1])
# or, sorted([(a,c) for [a,*b],c in x], key = lambda x:x[0][1])

[(('a', 1), 'b'), (('x', 2), 'a'), (('y', 4), 'c')]

This works as:
>>> [(a[0],b) for [*a],b in x]
[(('x', 2), 'a'), (('y', 4), 'c'), (('a', 1), 'b')]

[*a] receives the list in each tuple, and b receives the other element, so for first element:
[*a] == [('x', 2), ('m', 3)]   # b = 'a'
a == (('x', 2), ('m', 3))
a[0] == ('x', 2)

A more explicit version would be:
>>> sorted([(inner_tup_1,other_elem)
             for [inner_tup_1,*other_inner_tups], other_elem in x
           ], key = lambda x:x[0][1])

EDIT:
>>> x = ([('x', 2), ('m', 3), ('n', 1)], 'a')
>>> a, b = ([('x', 2), ('m', 3), ('n', 1)], 'a')
>>> (sorted(a, key = lambda x:x[1]), b)
([('n', 1), ('x', 2), ('m', 3)], 'a')

The second line is called unpacking:
a, b = (1, 2) # implies a == 1, and b == 2
# similarly,
a, b = ([('x', 2), ('m', 3), ('n', 1)], 'a')
       -------------------------------  ---
                1st elem of tuple     2nd elem
# implies a == [('x', 2), ('m', 3), ('n', 1)] and b == 'a'
>>> sorted(a, key = lambda x:x[1])
[('n', 1), ('x', 2), ('m', 3)]
>>> sorted(a, key = lambda x:x[1]),  b
  ( [('n', 1), ('x', 2), ('m', 3)], 'a' )

For more on unpacking see PEP 3132 and PEP 448 .


text:
Q: ¿Como posicionar dos tablas en la misma linea con FPDF PHP? Estoy intentando crear dos tablas en la misma linea pero no logro conseguirlo, agradeceria alguna ayuda.
_________________________     _________________________
Lado Izquierdo | Cumple        Lado Derecho | Cumple
_________________________     _________________________
  Lado1        |  Si           Lado1        |  Si
  Lado2        |  No           Lado2        |  Si
  Lado3        |  Si           Lado3        |  Si
  Lado4        |  Si           Lado4        |  Si
_________________________     _________________________

 _________________________
Lado Frente    | Cumple
__________________________
  Lado1        |  Si
  Lado2        |  No
  Lado3        |  Si
  Lado4        |  Si
_________________________

Mi codigo es el siguiente, trato de posicionar la tabla
de lado derecho pasando la posicion en X y Y
   <?php
require('/../../_FPDF/fpdf.php');

class PDF extends FPDF
{
    function BasicTable($header, $data, $x = 0, $y = 0)
    {
        // Cabecera
        if ($x > 0 and $y > 0) {
            $this->SetXY($x , $y);
        }
        foreach ($header as $col)
            $this->Cell(40, 7, $col, 1);
        $this->Ln();

        // Datos
        foreach ($data as $row) {
            foreach ($row as $col) {
                if ($x > 0 and $y > 0) {
                    $this->SetXY($x + 10 , $y + 10);
                }
                $this->Cell(40, 6, $col, 1);
            }
            $this->Ln();
        }
    }
}

$pdf = new PDF();
$pdf->SetFont('Arial', '', 14);
$pdf->AddPage();

//TABLA 1
$header = array('Lado Izquierdo', 'Cumple');
$data = [];
for ($index = 0; $index < 13; $index++) {
    array_push($data, array("izquierdo" . $index, 'valor' . $index));
}
$pdf->BasicTable($header, $data);
$pdf->Ln(5);

//TABLA 2
$header = array('Lado Derecho', 'Cumple');
$data = [];
for ($index = 0; $index < 5; $index++) {
    array_push($data, array("derecho" . $index, 'valor' . $index));
}
$pdf->BasicTable($header, $data , 115 , 10 );
$pdf->Ln(5);

//TABLA 3
$header = array('Lado Frente', 'Cumple');
$data = [];
for ($index = 0; $index < 13; $index++) {
    array_push($data, array("frente" . $index, 'valor' . $index));
}
$pdf->BasicTable($header, $data);

$pdf->Output();
?>

A: Modificando el posiciones SetXY($x , $y) consegui el reporte que necesitas.

class PDF extends FPDF {
    function BasicTable($header, $data, $x = 0, $y = 0) {

  $this->SetXY($x , $y);

  // Header
  foreach($header as $col)
   $this->Cell(40 ,7,$col,1);
  $this->Ln();

  // Data
  $i = 7;
  $this->SetXY($x , $y + $i);
  foreach($data as $row){
   foreach($row as $col){
    //$this->SetXY($x , $y + $i);
    $this->Cell(40 ,6,$col,1);

   }
   $i= $i + 6 ;  // incremento el valor de la columna
   $this->SetXY($x , $y + $i);
    //$this->Ln();
  }
 }
}

$pdf = new PDF();
$pdf->SetFont('Arial', '', 14);
$pdf->AddPage();

//TABLA 1
$header = array('Lado Izquierdo', 'Cumple');
$data = [];
for ($index = 0; $index < 13; $index++) {
    array_push($data, array("izquierdo" . $index, 'valor' . $index));
}
$pdf->BasicTable($header, $data, 10, 10);
//pdf->Ln(5);

//TABLA 2
$header = array('Lado Derecho', 'Cumple');
$data1 = [];
for ($index = 0; $index < 5; $index++) {
    array_push($data1, array("derecho" . $index, 'valor' . $index));
}
$pdf->BasicTable($header, $data1 , 100,10  );
$pdf->Ln(5);

//TABLA 3
$header = array('Lado Frente', 'Cumple');
$data = [];
for ($index = 0; $index < 13; $index++) {
    array_push($data, array("frente" . $index, 'valor' . $index));
}

$pdf->BasicTable($header, $data, 10, 110);

$pdf->Output();


text:
Q: Gulp module in Ansible? Is there a module that is able to install gulp files, like is possible for npm:

description: Install "coffee-script" node.js package.
- npm: name=coffee-script path=/app/location

description: Install "coffee-script" node.js package on version 1.6.1.
- npm: name=coffee-script version=1.6.1 path=/app/location

description: Install "coffee-script" node.js package globally.
- npm: name=coffee-script global=yes

description: Remove the globally package "coffee-script".
- npm: name=coffee-script global=yes state=absent

description: Install "coffee-script" node.js package from custom registry.
- npm: name=coffee-script registry=http://registry.mysite.com

description: Install packages based on package.json.
- npm: path=/app/location

description: Update packages based on package.json to their latest version.
- npm: path=/app/location state=latest

description: Install packages based on package.json using the npm installed with nvm v0.10.1.
- npm: path=/app/location executable=/opt/nvm/v0.10.1/bin/npm state=present

At the moment the following snippet:
- command: /usr/local/lib/npm/bin/gulp
  args:
    chdir: "{{ project_dir }}"

is used to install gulp packages, but is it possible to do it as follows?
description: Install packages based on package.json.
- gulp: path=/app/location

A: Looking at the documentation and ansible modules, the answer now seems to be "no". You need to use the Ansible command module.
A similar, but unrelated question was asked here. Until someone writes a gulp module for Ansible, you need to interact with it via the command or shell modules.


text:
Q: Unexpected Output Running Semaphore I'm trying to write a program that forks another process and stays in sync so that the first process doesn't start its (i)th iteration until the second process has finished its (i-1)th iteration. Is this possible using only two semaphores? This is what I have so far:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <semaphore.h>

sem_t semA, semB,sem,m;

int main(void)
{
 int i;

   pid_t child_a, child_b,pid2,pid3;
    sem_init(&semA, 0, 1);
    sem_init(&semB, 0, 0);
sem_init(&m, 0, 0);

   child_a = fork();
//wait();

   if (child_a == 0) {

  //  int j;

      pid2 =getpid();
      for (i = 0; i < 5; )
      {
    sem_wait(&semA);
//sem_wait(&m);
         printf("child1: %d\n", i);
     i++;
     //printf("pid1: %d\n", pid2);
         //printf("--------------------------\n");
         sleep(3);
//sem_post(&m);

sem_post(&semB);
      }
}
   else {

   child_b = fork();
//wait();
    if (child_b == 0) {

      pid3 =getpid();
      for (i = 0; i < 5;)
      {
sem_wait(&semB);
//sem_wait(&m);
         printf("child2: %d\n", i);
 i++;
         //printf("pid2: %d\n", pid3);
         //printf("--------------------------\n");
         sleep(5);
//sem_post(&m);
sem_post(&semA);

      }

    }
    }

    exit(0);
   return 0;
}

The output I expect is:
child1: 0
child2: 0
child1: 1
child2: 1
child1: 2
child2: 2
child1: 3
child2: 3
child1: 4
child2: 4
child1: 5
child2: 5
child1: 6
child2: 6
child1: 7
child2: 7
child1: 8
child2: 8
child1: 9
child2: 9

but I get just one child:
child1: 0

A: You may need three semaphores.
sem1
sem2
sem3
Process1:
if(FirstRun){
    Initialize the semaphores
    wait for sem2
}

post sem1
wait for sem3

Process2:
if(FirstRun){
    Initialize the semaphores
    post sem2
}

wait for sem1
post sem3

Note: In Initialize the semaphores you have to map the semaphores to a shared memory so that it is accessible by both the processes. Also Do Initialize them to some default value say 0, 0, 0.


text:
Q: Memory leak shown in MAT as GC root: Native Stack I have some third library code that I run and after some time I run into OutOfMemoryError. So I fired up the Eclipse MAT and analyzed the memory. Now it seems the memory can't be disposed because there is an object that is a shown as GC root: Native Stack. Reading the documentation:

In or out parameters in native code, such as user defined JNI code or JVM internal code. This is often the case as many methods have native parts and the objects handled as method parameters become GC roots. For example, parameters used for file/network I/O methods or reflection.

Now my question is: How can I confirm that the object is used in JNI or elsewhere (i.e. how do I find the code where it is used)? Can I somehow dispose the object? What other options do I have?
Thanks for the help already!

A: Objects being shown as GC root: Native Stack turned out to be a problem of the Eclipse Debugger. When the application was started without the debugger (i.e. with 'run' instead of 'debug') the problem disappeared. This was also the reason that I couldn't find the code where the objects where used in JNI inside my project (cause they weren't).
Finding the real memory leak without debugging was a bit hard, but using Eclipse MAT and its 'find Leak suspects' feature helped a lot!

A: If you do not have an access to the source code you can try and decompile it with any available decompilation tools (provided the code is not obfuscated). And then you can analyze the source code.


text:
Q: ASP.NET Session becomes null after postback on local Here is my code that runs on page load:
protected void Page_Load(object sender, EventArgs e)
{
    DisableChaching();
    if (Request.Cookies["UserName"] == null)
    {
        if (Session["UserName"] == null)
        {
            Response.Redirect("~/Default.aspx");
        }
        else if (Session["AccessLevel"].ToString().Equals("2"))
        {
            Response.Redirect("~/Default.aspx");
        }
    }
    else if (Session["AccessLevel"].ToString().Equals("2"))
    {
        Response.Redirect("~/Default.aspx");
    }
    if (!IsPostBack)
    {
        LoadControls();
        BindGrid();
    }
}

Sometimes when I try to save some data to database and I get an error, I try to re-save the data by clicking my save button, and I get this error:

Object reference not set to an instance of an object

on the following line if code:
else if (Session["AccessLevel"].ToString().Equals("2"))

Why am I getting this error?
here is my code in Login user control where ChR is the checkbox to remember the user :
if (ChR.Checked == true)
            {
                Response.Cookies["UserName"].Value = txtUserName.Text.Trim();
                Response.Cookies["UserName"].Expires = DateTime.Now.AddMonths(2);
                Response.Cookies["AccessLevel"].Value = member.AccessLevel.ToString();
                Response.Cookies["AccessLevel"].Expires = DateTime.Now.AddMonths(2);
                Response.Cookies["FirstName"].Value = member.FirstName;
                Response.Cookies["FirstName"].Expires = DateTime.Now.AddMonths(2);
                Response.Cookies["LastName"].Value = member.LastName;
                Response.Cookies["LastName"].Expires = DateTime.Now.AddMonths(2);
                Session["UserName"] = txtUserName.Text.Trim();
                Session["AccessLevel"] = member.AccessLevel.ToString();
                Response.Redirect("~/Default.aspx");
            }
            else
            {
                Session["UserName"] = txtUserName.Text.Trim();
                Session["AccessLevel"] = member.AccessLevel.ToString();
                Session["FirstName"] = member.FirstName;
                Session["LastName"] = member.LastName;
                Response.Redirect("~/Default.aspx");
            }

and in my master page I assign values to sessions this way in the page_Load event:
DisableChaching();
    FillInfo();
    if (Request.Cookies["UserName"] != null)
    {
        Session["UserName"] = Request.Cookies["UserName"].Value;
        Session["AccessLevel"] = Request.Cookies["AccessLevel"].Value;
        Session["FirstName"] = Request.Cookies["FirstName"].Value;
        Session["LastName"] = Request.Cookies["LastName"].Value;
        WellCome();
        if (Session["AccessLevel"].ToString() == "1")
        {
            RenderMenu(AcccessLevel.SiteManager);
        }
        else if (Session["AccessLevel"].ToString() == "2")
        {
            RenderMenu(AcccessLevel.Client);
        }
    }
    else if (Session["UserName"] != null)
    {
        WellCome();
        if (Session["AccessLevel"].ToString() == "1")
        {
            RenderMenu(AcccessLevel.SiteManager);
        }
        else if (Session["AccessLevel"].ToString() == "2")
        {
            RenderMenu(AcccessLevel.Client);
        }

    }
    else
    {
        WellGo();
        RenderMenu(AcccessLevel.LogedOutUser);
    }
enter code here

A: I think I found out why my sessions become null ! when I want to save info about a book in db and save an image file of the book in an app folder , I don't have the permission to save the file and my application throws an error and all my sessions become null !!!

A: Replace your code like below.
string val = Convert.ToString(Session["AccessLevel"]);
if (val == "2")
{

}

I hope you understand the difference between == and Equals()
public static String AccessLevel {
    get
    {
        return Convert.ToString(HttpContext.Current.Session["AccessLevel"]);
    }
    set
    {
        HttpContext.Current.Session["AccessLevel"] = value;
    }
}

A:
Why am I getting this error?

Because Session["AccessLevel"] is Null and you're attempting to call a method on a Null object.

A: For other users, check your session timeout. may be it is the problem. you can change the default timeout using
<system.web>
   <authentication mode="Forms">
      <forms timeout="50"/>
   </authentication>

   <sessionState timeout="60"  />
</system.web>


text:
Q: Log-in Only Works When Submit button is clicked Twice Please I need your help with this log-in script. When a user registers, a column active in the database is set to zero (0), and an activation link is sent to the email they provided. When the activation link is clicked and if successful, their respective active column is set to 1.
But a correct combination of username and password only works when i click the submit button twice.
On the first click i get the following lines
Notice: Undefined index: remember in C:\wamp\www\church\login.php on line 37
Not Verified Yet
But when I click the second time the log-in works.
<?php
if (isset($_POST['submit'])) {
    $username = trim($_POST['username']);
    $username = strip_tags($_POST['username']);
    $username = htmlentities($_POST['username']);
    $username = stripslashes($_POST['username']);
    $username = mysql_real_escape_string($_POST['username']);
    $password = sha1($_POST['password']);

    if (isset($_POST['username']) && isset($_POST['password'])) {
        $query = mysql_query("SELECT username, password
                           FROM USERS
                           WHERE username = '$username'
                           AND password = '$password'") or die (mysql_error());

        $user = mysql_num_rows($query);
        if ($user == 1) {
            $row = mysql_fetch_assoc($query);
            if ($row['active'] == 1) {
                $_SESSION['logged_username'] = $username;
                if ($_POST['remember']) {
                    setcookie("CookieUser", $_SESSION['logged_username'], time() + 60 * 60 * 24 * 100, "/");
                    setcookie("CookiePass", $password, time() + 60 * 60 * 24 * 100, "/");

                    header('Location: http://127.0.0.1/church/index.php?id=1');
                }
            }
            if ($row['active'] !== 1) {
                echo "Not Verified Yet";
            }
        }
        else {
            echo "
";
            echo "
";
            echo "Username & Password Combination Is Wrong";
            echo "
";
            echo "
";

        }
    }
}
?>

A: Change if ($_POST['remember']) { to if (isset($_POST['remember']) && $_POST['remember']) {
Honestly, it should be very obvious from the error message, esp. seeing as you have the isset test code everywhere else in your script.

A: The issue isn't that you aren't being logged in. It's that your code does not die() after sending the redirect header and therefore continues executing the code on that page. Also, if the user does not select remember, nothing happens. To fix (the first issue), simply add die(); immediately after header("location: ...");.
Why do I need die(); after header("location: ...");?
The header() function sends a string (text) to the browser (or other program requesting the page). However, the server doesn't know the difference between header("location: ..."); and header("somerandomthing: ...");, so it continues executing code until it either reaches the end of the script, an error, or the client disconnects. So, to prevent code execution from continuing, simply add die(); after every header("location: ..."); call.
Update regarding not checking 'remember'
<?php
if ($user == 1) {
        $row = mysql_fetch_assoc($query);
        if ($row['active'] == 1) {
            $_SESSION['logged_username'] = $username;
            if ($_POST['remember']) {
                setcookie("CookieUser", $_SESSION['logged_username'], time() + 60 * 60 * 24 * 100, "/");
                setcookie("CookiePass", $password, time() + 60 * 60 * 24 * 100, "/");

            }
            // Redirect even if not 'remembered'
            header('Location: http://127.0.0.1/church/index.php?id=1');
            die;
        }
        if ($row['active'] !== 1) {
            echo "Not Verified Yet";
        }
    }


text:
Q: Recall, Recall rate@k and precision in top-k recommendation According to authors in 1, 2, and 3, Recall is the percentage of relevant items selected out of all the relevant items in the repository, while Precision is the percentage of relevant items out of those items selected by the query.
Therefore, assuming user U gets a top-k recommended list of items, they would be something like:
Recall= (Relevant_Items_Recommended in top-k) / (Relevant_Items)
Precision= (Relevant_Items_Recommended in top-k) / (k_Items_Recommended)
Until that part everything is clear but I do not understand the difference between them and Recall rate@k. How would be the formula to compute recall rate@k?

A: Finally, I received an explanation from Prof. Yuri Malheiros (paper 1). Althougth recall rate@k as cited in papers cited in the questions seemed to be the normal recall metrics but applied into a top-k, they are not the same. This metric is also used in paper 2, paper 3 and paper 3
The recall rate@k is a percentage that depends on the tests made, i.e., the number of recommendations and each recommendation is a list of items, some items will be correct and some not. If we made 50 different recommendations, let us call it R (regardless of the number of items for each recommendation), to calculate the recall rate is necessary to look at each of the 50 recommendations. If, for each recommendation, at least one recommended item is correct, you can increment a value, in this case, let us call it N. In order to calculate the recall rate@R, it is neccesary to make the N/R.


text:
Q: Issues with hreflang php function on a multilingual site I have been asked by one of my clients to troubleshoot why their Wordpress website is having issues loading.
Their site was build by a different developer and no longer does business with my client anymore so seeking help from them is an issue.
When I was investigating the cause I found the following PHP error:
[09-Jan-2017 04:09:52 UTC] PHP Fatal error:  Can't use function return value in write context in /home/*********/public_html/fr/wp-content/themes/********/functions.php on line 121
When looking at the functions.php file I found the below code:
function bs_get_hreflang_tags() {
    ob_start();
    if( !empty( get_field('australia', get_the_ID() ) ) ) : ?>
        <link rel="alternate" href="<?php echo esc_url( get_field('australia', get_the_ID() ) ); ?>" hreflang="en-au" />
    <?php endif;
    if( !empty( get_field('france', get_the_ID() ) ) ) : ?>
        <link rel="alternate" href="<?php echo esc_url( get_field('france', get_the_ID() ) ); ?>" hreflang="fr"/>
    <?php endif;
    if( !empty( get_field('spain', get_the_ID() ) ) ) : ?>
        <link rel="alternate" href="<?php echo esc_url( get_field('spain', get_the_ID() ) ); ?>" hreflang="es" />
    <?php endif;
    if( !empty( get_field('italy', get_the_ID() ) ) ) : ?>
        <link rel="alternate" href="<?php echo esc_url( get_field('italy', get_the_ID() ) ); ?>" hreflang="it" />
    <?php endif;

    $output = ob_get_contents();
    ob_end_clean();

    return $output;
}

EDIT: line 121 is if( !empty( get_field('australia', get_the_ID() ) ) ) : ?>
I don't fully understand what this code is doing however I believe it is mostly related to multilingual SEO support.
As I didn't write the code or the original website, I was hoping to get some support on how to either patch the code so that it works or find alternative code to create the same job without causing issues.
I have commented out the code for the time being to allow the site to run. I was just hoping that someone might know the answer to this.
Any help would be appreciated

A: The ob construction is needlessly complicated..
Try replacing it with this.
function bs_get_hreflang_tags() {
    $output= '';
    if( get_field('australia', get_the_ID() ) ) :
        $output = '<link rel="alternate" href="'.esc_url( get_field('australia', get_the_ID() ) ) . '" hreflang="en-au" />';
    elseif( get_field('france', get_the_ID() ) ) :
        $output = '<link rel="alternate" href="'.esc_url( get_field('france', get_the_ID() ) ) . '" hreflang="fr" />';
    elseif( get_field('spain', get_the_ID() ) ) :
        $output = '<link rel="alternate" href="'.esc_url( get_field('spain', get_the_ID() ) ) . '" hreflang="es" />';
    elseif( get_field('italy', get_the_ID() ) ) :
        $output = '<link rel="alternate" href="'.esc_url( get_field('italy', get_the_ID() ) ) . '" hreflang="it" />';
    endif;

    return $output;
}


text:
Q: TypeError: cannot convert the series to  ( need to take log) I an trying to take sum of a variable after taking log of it. Can you please guide me on below code?
data_size['Deal Size / Complexity Measure2']=pd.DataFrame.sum(math.log(data_size['Deal Size'])+data_size['Deal Complexity'])/100

I am not sure if i have entered correct as i am trying to covert excel code to Python--below is excel code which i am trying to convert.
=SUM(LOG(D2)+E2)/100

A: Try this:
sanc['Deal Size / Complexity Measure2'] = sum([(math.log(x)+y) for x,y in zip(sanc['Deal Size'],sanc['Deal Size'])])


text:
Q: FormLayout, FormData and controls can someone please explain to me how FormData on FormLayout works? I'm trying to understand the FormAttachment constructors and its parameters (numerator, offset, denominator). When do you need only one of them, two of them or all of the parameters... Also, if i have a group (or a composite) which will add widgets like buttons and labels which will need to be resized as per resolution using FormData, does the Group need to have a FormLayout also? I tried specifying a width of a group with form layout but no change

A: FormAttachment has several different constructors, I generally use two typically:
new FormAttachment (int numerator, int offset) - If there's only two integer parameters then the first parameter represents the percentage from the edge of the parent.  Which edge is determined by which slot in the FormData object you insert the FormAttachment into: FormData.top, data.bottom, data.left, and FormData.right.
new FormAttachment (Control control, int offset) - Instead of positioning the object against the parent, this positions the object next to another child object.  This works in conjunction with the previous constructor so that you effectively "anchor" one element against the parent, then build your layout by positioning other elements relative to the anchor.  This also allows you to easily move and insert elements into the overall layout without having to rebuild the entire layout.
The others are variations on the themes of these two.  FormAttachment (int numerator, int denominator, int offset) is the same as the FormAttachment with two integer parameters, but with two the denominator just becomes "100", i.e. it turns the numerator into a percentage.  But you could say something like (1, 2, 0) for 1/2 of the way across or (1, 3, 0) for 1/3 of the space.
I'm not sure what you mean about whether the Group will need to have a layout defined but in general every parent Composite must have a layout defined on it to display children elements.  If you want elements to resize as the parent resizes, one option is to attach the child to both the left and right sides of the element:
FormData formData = new FormData();
formData.left = new FormAttachment (0, 0); // Attach at the 0% left with 0 offset
formData.right = new FormAttachment (100, 0); // Attach at the 100% right with 0 offset

The Eclipse site has a lot of good snippets showing FormLayout, check out:
http://www.eclipse.org/swt/snippets/
Scroll down to the FormLayout section.


text:
Q: How to use HTTP Auth with resque web interface? I have a standalone resque worker queue und would like to monitor it using the included web interface without any rails applications involved.
I manage my processes via foreman, my Procfile looking like this:
worker: bundle exec rake resque:work
web: bundle exec resque-web --foreground --app-dir /home/xxxx --server thin --port 5678 --no-launch

The generated upstart script for web looks like this:
start on starting resque_cmd_runner-web
stop on stopping resque_cmd_runner-web
respawn

env PORT=5100
env PATH='/usr/local/rvm/gems/ruby-2.2.1/bin:/usr/local/rvm/gems/ruby-2.2.1@global/bin:/usr/local/rvm/rubies/ruby-2.2.1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/local/rvm/bin:/usr/local/rvm/gems/ruby-2.2.1/bin:/usr/local/rvm/gems/ruby-2.2.1@global/bin:/usr/local/rvm/rubies/ruby-2.2.1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/local/rvm/bin'
env GEM_PATH='/usr/local/rvm/gems/ruby-2.2.1:/usr/local/rvm/gems/ruby-2.2.1@global:/usr/local/rvm/gems/ruby-2.2.1:/usr/local/rvm/gems/ruby-2.2.1@global'
env QUEUE='*'
env RESQUE_WEB_HTTP_BASIC_AUTH_USER='xxxx'
env RESQUE_WEB_HTTP_BASIC_AUTH_PASSWORD='zzzz'

setuid xxxx

chdir /home/famulus/resque_cmd_runner

exec bundle exec resque-web --foreground --app-dir /home/famulus/resque_cmd_runner --server thin --port 5678 --no-launch

However, the environment variables for the HTTP BASIC AUTH are ignored. I figure they just work in the resque-web gem and not in the interface included with resque.
How can I get HTTP AUTH for the included app?


text:
Q: How to use multiple og:image, og:url, og:title, so that I can have different thumbnails on fb and twitter on every page on my website ** I made a website and I want to post on fb and twitter. I want to put a different thumbnails, title and description on each web page. But i can't figure out, so every time I post a web page on fb/twitter, I need to change the og:image,title,desc. I also encounter problems, my past post in fb ( mnyweb pages), changes the thumbnail to the new :(
eg. Animal page and Fruit page
I posted yesterday about my animal page, i put an animal thumbnail and title. Then today i have to post my fruit page, I have to change again my og tags (new thumbnails (image,title,desc)). Now the post I posted yesterdat has the same thumbnail even tho they have different content. This problem keeps recurring because I need to post my web pages weekly :(
Is it possible to have different og tags for every page? This is my code. Thank you in advance**
  <meta charset="utf-8">
  <!-- Primary Meta Tags -->
  <title>Title</title>
  <meta name="title" content="title thumbnail">
  <meta name="description" content="Desc thumbnail">

  <!-- Open Graph / Facebook -->
  <meta property="og:type" content="website">
  <meta property="og:url" content="https://website.com.ph/">
  <meta property="og:title" content="TITLE THUMBNAIL">
  <meta property="og:description" content="DESC THUMBNAIL">
  <meta property="og:image" content="https://image.jpg"/>

  <!-- Twitter -->
  <meta property="twitter:card" content="summary_large_image">
  <meta property="twitter:url" content="https://website.com.ph/">
  <meta property="twitter:title" content="TITLE THUMBNAIL">
  <meta property="twitter:description" content="DESC THUMBNAIL">
  <meta property="twitter:image" content="https://image.jpg"/>


text:
Q: PACT-JVM problems with closeArray So I'm only starting to use JVM-PACT.
I'm trying to crate this JSON
{
  "elements": [
    {
      "Location": {
        "id": "loc_id1",
        "Addr": {
          "Addr1": {
            "value": "545 Test Street"
          },
          "City": {
            "value": "New York City"
          },
          "StateProvCd": {
            "value": "NY"
          },
          "PostalCode": {
            "value": "11111"
          }
        }
      }
    }
  ]
}

Trying to do this: but it keeps on crashing when trying to call closeArray()
DslPart body = new PactDslJsonBody()
            .eachLike("elements")
                .object("Location")
                    .stringType("id","loc_id1")
                    .object("Addr")
                        .object("Addr1")
                            .stringType("value", "545 Test Street")
                        .closeObject()
                        .object("City")
                            .stringType("value", "New York City")
                        .closeObject()
                        .object("StateProvCd")
                            .stringType("value", "NY")
                        .closeObject()
                        .object("PostalCode")
                            .stringType("value", "11111")
                        .closeObject()
                    .closeObject()
                .closeObject()
            .closeArray();

I know it says " can't call closeArray on an Object" but it is definitely trying to close the "eachLike"
java.lang.RuntimeException: Failed to invoke pact method
    at au.com.dius.pact.consumer.PactProviderRule.getPacts(PactProviderRule.java:269)
    at au.com.dius.pact.consumer.PactProviderRule$1.evaluate(PactProviderRule.java:145)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at au.com.dius.pact.consumer.PactProviderRule.getPacts(PactProviderRule.java:267)
    ... 17 more
Caused by: java.lang.UnsupportedOperationException: can't call closeArray on an Object
    at au.com.dius.pact.consumer.dsl.PactDslJsonBody.closeArray(PactDslJsonBody.java:542)

    ... 22 more

Any suggestions would be very helpful

A: Don't you need to close the last object? The one within the array containing location?  You're closing the Location ibject, but forgetting that you're not closing the object containing the Location.  I know it's a tad confusing with the DSL because arrays opens up a new object, we might have to look into making that better.
DslPart body = new PactDslJsonBody()
            .eachLike("elements")
                // New Object in Array starts here
                .object("Location")
                    .stringType("id","loc_id1")
                    .object("Addr")
                        .object("Addr1")
                            .stringType("value", "545 Test Street")
                            .closeObject()
                        .object("City")
                            .stringType("value", "New York City")
                            .closeObject()
                        .object("StateProvCd")
                            .stringType("value", "NY")
                            .closeObject()
                        .object("PostalCode")
                            .stringType("value", "11111")
                            .closeObject()
                        .closeObject()
                    .closeObject()
                // Array object needs to close here
                .closeObject()
            .closeArray();


text:
Q: Property of the limit of function proof If $c≠0$ and $\lim_{x→c}〖f(x)〗=L$, prove that $\lim_{x→1/c}〖f(1/x)〗=L$
I know that meaning for all $ε>0$, there exist a $δ>0$ such that $0<|x-c|<δ$  implies $|f(x)-L|<ε$. How can I use these to prove the conclusion.

A: When you say |x-c| < $\delta$ you mean $\delta$ - c < x < $\delta$ + c.  Now restate that inequality in terms of 1/x.  Can you work from there to construct a new $\delta_{1/x}$ which works for your limit?


text:
Q: How to get lxml working under IronPython? I need to port some code that relies heavily on lxml from a CPython application to IronPython.
lxml is very Pythonic and I would like to keep using it under IronPython, but it depends on libxslt and libxml2, which are C extensions.
Does anyone know of a workaround to allow lxml under IronPython or a version of lxml that doesn't have those C-extension dependencies?

A: You might check out IronClad, which is an open source project intended to make C Extensions for Python available in IronPython.

A: Something which you might have already considered:
An alternative is to first port the lxml library to IPy and then your code (depending on the code size). You might have to write some C# wrappers for the native C calls to the C extensions -- I'm not sure what issues, if any, are involved in this with regards to IPy.
Or if the code which you are porting is small, as compared to lxml, then maybe you can just remove the lxml dependency and use the .NET XML libraries.


text:
Q: only return document _id on mongoose .find() I update 100's of documents every second by pushing new data to an array in its document. To get the document of which I am going to add data to, I use the mongoose .find().limit(1) function, and return the whole document. It works fine.
To help with some memory and cpu issues I have, I was wondering how I could get find() to only return the id of the document so I can use that to $push or $set new data.
Thanks.

A: You want to use Projection to tell your query exactly what you want off of your objects.
_id is always included unless you tell it not to.
readings = await collection
.find({
    name: "Some name you want"
})
.project({
    _id: 1 // By default
})
.toArray();

A: You could use the distinct method in order to get an array of _id for your query.
Follow this question

A: As mentioned by @alexmac, this works for me:
collection.find({}, '_id')


text:
Q: Can't get original message in telegram bot response So when a user sends a message to my bot, I send a message back asking for more information and set the reply_to_message field to the original message by the user (as described in the Telegram BOT API)
Once the user then replies back to my question, I try to check for the reply_to_messsage to extract the original message but it doesn't exist.
Am I doing something wrong?

A: What you're looking for is the ForceReply.
If you use that, you can find your original message in the reply_to_message

A: $message_reply=$update->message->reply_to_message; // if(message_reply) == true
$message_reply_message_text=$update->message->reply_to_message->text;
$message_reply_message_caption=$update->message->reply_to_message->caption; // text for picture


text:
Q: Creating a custom tag / field with Contact Form 7 I want to create a custom textrea field in Contact form 7. Were I can pre-populate it with data. I have the below which shows on the front end and creates a text area field. But when I submit the form the tag is always blank within the email so the data doesn't get emailed. The tag also does not show in the list of available tags in Contact form 7. Any ideas?
add_action( 'wpcf7_init', 'wpcf7_add_form_tag_pathtag' );

function wpcf7_add_form_tag_pathtag() {
  wpcf7_add_form_tag(
    array( 'pathtag', 'pathtag*'), 'pathtag_form_tag_handler',  array( 'name-attr' => true )
  );
}
function pathtag_form_tag_handler( $tag ) {

$tag = new WPCF7_FormTag( $tag );

if ( empty( $tag->name ) ) {
        return '';
    }

        $atts = array();

    $class = wpcf7_form_controls_class( $tag->type );
    $atts['class'] = $tag->get_class_option( $class );
    $atts['id'] = $tag->get_id_option();

    $atts['name'] = $tag->name;
    $atts = wpcf7_format_atts( $atts );

      $output = '';

      $output .= '<textarea cols="40" rows="10">';

          foreach ( $_SESSION['question-path'] as $path ) {

            $output .= $path ."\n\n";

          }

      $output .= '</textarea>';

       return $output;

}

A: You did not add the attributes to the textarea code.  Also, make sure you enter your shortcode in the contact form as
[pathtag field-name]
function pathtag_form_tag_handler($tag) {

    $tag = new WPCF7_FormTag($tag);

    if (empty($tag->name)) {
        return '';
    }

    $atts = array();

    $class = wpcf7_form_controls_class($tag->type);
    $atts['class'] = $tag->get_class_option($class);
    $atts['id'] = $tag->get_id_option();

    $atts['name'] = $tag->name;
    $atts = wpcf7_format_atts($atts);

    $output = '';

    // Make sure to add the $class and $atts to the form tag
    $output .= sprintf('<textarea cols="40" rows="10" %s %s>', $class, $atts);

    foreach ($_SESSION['question-path'] as $path) {

        $output .= $path . "\n\n";

    }

    $output .= '</textarea>';

    return $output;

}


text:
Q: Loading grunt tasks from a remote Gruntfile.js In the root directory of a project, I'm trying to load Grunt tasks, and all the content of the file as well, from a remote Gruntfile.js, accessible through a network (web or internal network).
I've already tried several things (see below), first hosting the Gruntfile.js on a local Apache server for the tests.
Using the --gruntfile option
> /project/path> grunt --gruntfile=http://localhost/Gruntfile.js build
Reading "Gruntfile.js" Gruntfile...ERROR
Fatal error: Unable to find "/project/path/http://localhost/Gruntfile.js" Gruntfile.

Using the --base option
> /project/path> grunt --base=http://localhost/Gruntfile.js build
    process.chdir(grunt.option('base') || path.dirname(gruntfile));
Error: ENOENT, no such file or directory

Creating a Gruntfile.js located at the root directory of my project, which contains only the following code :
module.exports = function (grunt) {

  grunt.loadTasks( 'http://localhost/Gruntfile.js' );

};

The result was :
> /project/path> grunt build
>> Tasks directory "http://localhost/Gruntfile.js" not found.
Warning: Task "build" not found. Use --force to continue.

Aborted due to warnings.

Another try with the Gruntfile.js
module.exports = function (grunt) {

  require( 'http://localhost/Gruntfile.js' )( grunt );

};

Gave me this :
> /project/path> grunt build
Loading "Gruntfile.js" tasks...ERROR
>> Error: Cannot find module 'http://localhost/Gruntfile.js'
Warning: Task "build" not found. Use --force to continue.

Aborted due to warnings.

Edit: It seems there is no way of loading tasks from a grunt file not located on the disk. I will find another solution.

A: I ran into the same problem and this is my solution. I hope it helps someone in the present/future:

*

*Create a npm package to host the Gruntfile.js and upload it to a repository (I´am currently using Bitbucket) This is how my package.json looks like:
{
  "name": "my-remote-gruntfile-package",
  "private": true,
  "version": "0.0.1"
}

*Configure it in the package.json of your current project and install it using npm install or just run
npm install git+ssh://git@bitbucket.org:user/my-remote-gruntfile-package.git#0.0.1

*Create a bash script (or windows bash equivalent) to cover the problem of changing Gruntfile.js location and setting current base path. This is to avoid passing --gruntfile and --base parameters on every execution (this step is not mandatory)
#!/bin/bash
grunt --base ./ --gruntfile ./node_modules/my-remote-gruntfile-package/GruntFile.js $1
Note: take care of relative paths used on your Gruntfile.js

A: Requiring a separate file should work, note that you shouldn't refer to it via localhost, but rather the location on disk, for example ./somedir/yourtask.js. Here's an example:
yourtask.js:
module.exports = {
    // your task config goes here
};

Your Gruntfile.js:
module.exports = function(grunt) {
    var externalFile = require('./somedir/yourtask.js');

    grunt.initConfig({
        // some random tasks go here
        yourtask: externalFile
    });
};

This should work but I'm not able to run it right now and you haven't posted what kind of info you have defined in your separate file. You can also have a function in there as well.