text:
Q: Compare Rows in DataTable I have 2 DataTables that looks like this:
YesterdaysTable
AAA
BBB
CCC
DDD
EEE
FFF
GGG
HHH
III
JJJ

TodaysTable
AAA
BBB
DDD
FFF
GGG
HHH
III
JJJ

As you can see, TodaysTable does not contain CCC & EEE. When I try to find the differences to let me know what's in YesterdaysTable that does not exist in TodaysTable using the following code, I get an error:

InvalidOperationException: the source contains no DataRows

but there are rows in my source:
DataTable dtSource = new DataTable();
dtSource = yesterdaysTable.AsEnumerable().Except(todaysTable.AsEnumerable()).CopyToDataTable();

var difference = yesterdaysTable.AsEnumerable().Select(r => r.Field<string>("Apps")).Except(todaysTable.AsEnumerable().Select(r => r.Field<string>("Apps")));

if (difference.Any())
{
    DataTable Table3 = (from row in todaysTable.AsEnumerable()
                        join app in difference on row.Field<string>("Apps") equals app
                        select row).CopyToDataTable();
}

I get the same error when I use similar code:
var appsNotInB = yesterdaysTable.AsEnumerable().Select(r => r.Field<string>("Apps"))
        .Except(todaysTable.AsEnumerable().Select(r => r.Field<string>("Apps")));

var TableC = (from row in yesterdaysTable.AsEnumerable()
              join id in appsNotInB on row.Field<string>("Apps") equals id
              select row).CopyToDataTable();

I went as far as trying to write a nested for-loop to try to put the differences into a List<string> object, to no avail:
for (int i = 0; i < yesterdaysTable.Rows.Count; i++)
{
    for (int j = 0; j < todaysTable.Rows.Count; j++)
    {
        if (yesterdaysTable.Rows[i]["Apps"].ToString() != todaysTable.Rows[j]["Apps"].ToString())
        {
            //lstNoMatch.Add(yesterdaysTable.Rows[i]["Apps"].ToString());
            lstNoMatch.Add(todaysTable.Rows[j]["Apps"].ToString());
        }
    }
}

I've tried a few different solutions but nothing is working and I don't want the post to be unnecessarily long. I've hit a dead-end :(
Any suggestions?

A: CopyToDataTable throws this exception if the query didnt return any rows. One reason why i avoid that method. You could avoid the exception with pre-checking with query.Any(). But that executes it twice. So a foreach to add the rows is to be preferred.

I try to find the differences to let me know what's in
  YesterdaysTable that does not exist in TodaysTable

Then this query does the job (you've done this correctly):
var onlyYesterdayApps = yesterdaysTable.AsEnumerable()
    .Select(r => r.Field<string>("Apps"))
    .Except(todaysTable.AsEnumerable().Select(r => r.Field<string>("Apps")));

If you want the rows in a third table you have to use YesterdaysTable as source:
DataTable result = yesterdaysTable.Clone(); // empty table with same columns
var yesterdayRows = from r in yesterdaysTable.AsEnumerable()
                    join app in onlyYesterdayApps
                    on r.Field<string>("Apps") equals app
                    select r;
foreach(DataRow row in yesterdayRows)
    result.ImportRow(row); // import rows if the query above yielded rows

Just the final foreach will execute the two queries(which are actually merged to one).


text:
Q: Stack using stack in java I have a problem with my homework. And I need all the help that you can give me.
i need to create a combination of a stack that can store any type of data and a Stack that works with elements of type Stack. I´m very confused.
The methods that I was supposed to implement were:

initializeStack()
  isEmpty()
  isFull()
  Push()
  Pop()
  showStack()
  countElements()

And this is what i have so far:
public class pilita {
    Object vectorPila[];
    int tope;
    public pilita(int tam){
        vectorPila=new Object[tam];
        tope=-1;
    }
    public void inicializarPila(){
        tope=-1;
    }
    public void push(Object dato){
        tope++;
        vectorPila[tope]=dato;
    }
    public Object pop(){
        Object fuera=vectorPila[tope];
        tope--;
        return fuera;
    }
    public boolean pilaVacia(){
        return tope==-1;
    }
    public boolean pilaLlena(){
        return vectorPila.length-1==tope;
    }
    public Object cima(){
        return vectorPila[tope];
    }
    public Object contar(){
        return tope+1;
    } }

All the methods are well implemented (Using my logic).
But how can i make an Stack using Stack data type using those methods?.
I would be very grateful if anyone could help me.
Also here is the original problem.

Stack of little Stacks: The elements of the Data Structure Little Stack are of any type of data. The elements of the Data Structure Stack are of Stack type.

A: // Java code for stack implementation

import java.io.*;
import java.util.*;

class Test
{
    // Pushing element on the top of the stack
    static void stack_push(Stack<Integer> stack)
    {
        for(int i = 0; i < 5; i++)
        {
            stack.push(i);
        }
    }

    // Popping element from the top of the stack
    static void stack_pop(Stack<Integer> stack)
    {
        System.out.println("Pop :");

        for(int i = 0; i < 5; i++)
        {
            Integer y = (Integer) stack.pop();
            System.out.println(y);
        }
    }

    // Displaying element on the top of the stack
    static void stack_peek(Stack<Integer> stack)
    {
        Integer element = (Integer) stack.peek();
        System.out.println("Element on stack top : " + element);
    }

    // Searching element in the stack
    static void stack_search(Stack<Integer> stack, int element)
    {
        Integer pos = (Integer) stack.search(element);

        if(pos == -1)
            System.out.println("Element not found");
        else
            System.out.println("Element is found at position " + pos);
    }

    public static void main (String[] args)
    {
        Stack<Integer> stack = new Stack<Integer>();

        stack_push(stack);
        stack_pop(stack);
        stack_push(stack);
        stack_peek(stack);
        stack_search(stack, 2);
        stack_search(stack, 6);
    }
}

In Java, they are called Collections and the are analogous to the standard template library(STL) of C++.Now, what you can do is define a void type stack and typecast it for various type of elements.
In c, stack.h has the following stack structure
    typedef struct{
        void *elems;
        int elemSize;
        int allocLength;
        int logLength;
        void (*freefnc)(void *);
    } Stack;

void stackNew(Stack *s, int elemSize, void (*freefnc)(void *));
void stackDispose(Stack *s);
void stackPush(Stack *s, void *elemAddr);
void stackPop(Stack *s, void *target);

You can study more about them here:-
http://www.geeksforgeeks.org/java/ (see collections in java)
http://www.geeksforgeeks.org/c-plus-plus/#STL (see standard template library(STL))
for defining void type generics in java refer:-
What's the difference between Void and no parameter?
https://coderanch.com/t/450693/java/pass-void-generic-parameter-type

redpajama_set_name: RedPajamaStackExchange


text:
Q: Recursively walk though complex object structure Hello stackoverflow community,
I have a fairly vexing issue that I'm trying to resolve, and would welcome some assistance or suggestions.  Basically, I need to recursively walk through a complex object, and once I find the property (no matter how nested down it is), pull the data from that property.
The existing code I have that works (found here on stackoverflow) at least for the object, properties, and sub object properties is as follows:
public static void GetPropertyValue(Type type, string propertyName)
{
    Console.WriteLine($"Describing type {type.Name}");

    var propertyInfos = type.GetProperties();

    foreach (var pi in propertyInfos)
    {
        Console.WriteLine($"Has property {pi.Name} of type {pi.PropertyType.Name}");

        if (pi.PropertyType.IsClass && !pi.PropertyType.FullName.StartsWith("System."))
        {
            GetPropertyValue(pi.PropertyType, propertyName);
        }
    }
}

The problem is that it falls apart when there is a collection (ICollection, List, etc.,), basically any Enumerable type. It's not a type of Class nor starts with System.  How do you tell the function the property type is a collection / enumerable type, and walk further into the object? Also, if nothing is found in that collection, do you have to walk backwards to the parent object? Lastly, are there any other complex types that should be accounted for as well?
NOTE, this code doesn't include checking the propertyName, JUST the recursive walking through of the object.
Thanks in advance for the help!


text:
Q: Storing the amount of factors as a variable in C I'm taking a beginner's programming course and have a question. I'm suppose to be able to enter a number, and have it print out something like this
Factors of 36 between 2 and 35: 2 3 4 6 9 12 18
36 has 7 factors
36 is not a prime number

My code so far allows the user to enter a number, and can print out the first line, but i'm having trouble getting the number of factors as a variable.
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int num, num2, factors;

    printf("Enter a number: ");
    scanf("%d", &num);
    num2 = num - 1;
    printf("Factors of %d between 2 and %d: ", num, num2);
    for(factors = 2; factors < num; factors++){
        if(num % factors == 0){
            printf("%d ",factors);
            }
        }
    if(num % factors == 0){
        printf("\n");
        printf("%d has factors\n", num);
        printf("%d is not a prime number\n", num);}
}

If I can figure out how to get number of factors as a variable, then I can get the third line by myself, but I'm having trouble.
Any help in the right direction would be appreciated.

A: I think what you're asking is how to store all factors?
However, based on your sample output, you wouldn't even need to cache the values, you should only need to keep a count of them.
Initialize a variable cnt to 0
int cnt = 0;

and increment it every time you see a factor:
  if(num % factors == 0){
      printf("%d ",factors);
      cnt++;
  }

Then your line 2 output would be:
printf("%d has %d factors", num, cnt);

And then you can check the cnt of factors to determine if it is prime:
bool isPrime = (cnt == 0);
if(isPrime) printf("%d is a prime number", num);
else printf("%d is not a prime number", num);

A: Algorithm error
The for() has no early break, so after the loop is done, factors == num if num is at least 2.
for(factors = 2; factors < num; factors++){
....
}
// This is really doing `num % num` which is 0, which equals 0, so always true
if(num % factors == 0){

Instead simply counts the factors.  2nd half similar to @James Wierzba
unsigned count = 0;
for(factors = 2; factors < num; factors++) {
  if(num % factors == 0){
    count++;
    printf("%d ",factors);
  }
}

if (count > 0) {
  printf("%d is not a prime number\n", num);}
}


text:
Q: How can I make a system to lock aim to different parts of body with IK? I just had this idea and would like to learn how to implement, what I wanna do is, when I press a button character's aim and also IK for aim, like arm position or how he holds the weapon are adjusted to head, legs or body of NPC and shoots it. Different buttons for different part. How would I go about implementing that, I just need a little nodge to the right approach, thanks in advance

A: I'm going to assume what you mean is that you want to press a button and it "auto" aims at a body part
Well the first step would be to find and aim at the desired npc. (Many ways of doing this but just getting the location and rotation, and shooting a ray on frame update. Then rotating the character towards the desired location.)
The second thing I can really think of is the IK but that should run really easy. Just get the transform of the NPC your aiming at and set that to the NPCs head hitbox.


text:
Q: Fatal error: Call to undefined function mcrypt_encrypt        $key = '6yOFZuQis%7$oF_[M89=EV!a}\mzb7=B';
       $iv = 'Fa)=zx"h^O8t.-s4nO-q#vTp,,ft;fCj';

       $data = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, serialize($data), MCRYPT_MODE_CBC, $iv);
       $data=base64_encode($data);

above code works in localhost without any errors with encrypted value.but while uploading   line number 3
($data=mcrypt) shows error as

Fatal error: Call to undefined function mcrypt_encrypt() in demo.php on line 3.....
  i cant understand what is the error.I googled about it but i didnt get answer.

A: Check this with your host if PHP mcrypt library is installed or not. If you have root access to your server, run the following command:
yum install php-mcrypt


text:
Q: Delaying the opening of a NSPopUpButton I've encountered the same problem as this one:
This one.
It has never been answered so far. In two words:
When you place a NSPopUpButtonCell in a NSTableView, the popUp opens before the selection in the tableView has changed.
If the menu of the popUp relies on the selection of a row of the tableView, it will be updated too late.
Solution 1: differ the opening of the popUp with a block which calls [super] a few nanoseconds later. But I don't know which method I must override.
Solution 2: use other bindings that I'm currently using (the popUp contains the NSSet of the entity selected in the table, I'm using a different controller, not the table's one, and I bind its content set to myTable.selection.theSet.
Is there something else I could do? Thanks !

A: Yes, if you use a view-based tableView, you can bind the popUp through the cellView it's inside (like the other table objects you bind in this mode), and so it's completely unambiguous and doesn't depend on the selection.
In view-based mode, each cell in each row have is assigned an 'objectValue' from your original data, so you can bind directly to it, like 'objectValue.popUpContents'.


text:
Q: javascript to check checkbox when input box is ticked - checkbox array [] I have a simple javascript issue. I have a checkbox and a input box.
when the user inputs text into an input box (onkeydown) I want it to check the corresponding checkbox in the row.
My checkbox's all share the same name for an array checkbox[].
my simplified syntax is:

<?php if(isset($records)) : foreach ($records as $row) : ?>

            <input type=checkbox name="editcustomer[]" id="editcustomer[]" value="<?php echo $row->id ?>">

            <input type="text" name="customer_name_<?php echo $row->id ?>" id="customer_name_<?php echo $row->id ?>" value="<?php echo $row->customer_name ; ?>" onclick="document.getElementById('editcustomer<?php echo $row->id ?>').checked = true;">

<?php endforeach ; ?>

As the name of the checkbox is not unique, only the value thereof how do I tell the javascript which checkbox to check?
<input type="text" name="customer_name_<?php echo $row->id ?>" id="customer_name_<?php echo $row->id ?>" value="<?php echo $row->customer_name ; ?>" onclick="document.getElementById('editcustomer<?php echo $row->id ?>').checked = true;">

Help appreciated as always.
Thanks

A: HTML
<input type="checkbox" name="checkbox[]"/>
<input type="text" name="name1" id="name1" />

 <input type="checkbox" name="checkbox[]"/>
<input type="text" name="name2" id="name2" />

 <input type="checkbox" name="checkbox[]" />
<input type="text" name="name3" id="name3" />

Jquery
$(':text').change(function(){
    $(this).prev(':checkbox').attr('checked','true');
});

Hope this helps.
Regards.


text:
Q: How I can read file with Array in spark scala? The interviewer asked me to read this file using spark-scala and select from this data, I don,t know which file contain this kind of data. I tried with csv but it shows error that csv does not support array type.
output required is -> 1,salman,p
file.csv data -
1,salman,[p, c, m]
2,srk,[p, c, b]
3,aamir, [p, c, g]

val schema1 = StructType(List(
    StructField("Id", IntegerType),
    StructField("Name", StringType),
    StructField("Subjects",ArrayType.apply(StringType))

val df1=spark.read
    .schema(schema1)
    .format("csv")
    .load("/home/sayyad/study_material/syllabus_ppt/file1.csv")

A: How about this?
df1.select("Id", "Name", $"Subjects".getItem(0))


text:
Q: General question about iPhone programming I have a question regarding nibs and how detail views are created in professional apps. I want to make an app that loads different uitextfields for each nib that is selected from a table. These textfields contain some logic that is different from each. I wanted to ask if it's possible to make one nib and change the data from thatto match all these scenarios. I'm unsure how this is done and how nib management can be done by arrays. Thanks and I hope I was clear enough :)

A: I can only speak myself but I've moved away from nibs. When you get complex layouts that have elements disappearing and reappearing your nib/s become unmanageable. You can do a better job of keeping elements tidy and manageable in code as well as a slightly faster App (not much but its a nice bonus).
EDIT: As a very basic example just remove any details of a nib and if you class is a UIViewController subclass do this:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50,50,150,30);
label.text = @"Hello World";
[self.view addSubview:label];
[label release];

Very basic but hopefully this will get you on your way to developing without nibs. Note: Nibs aren't bad and if its a basic view use them but if you are having complex views you will find nibs becoming unmanageable.

A: I found this article on Cocoa With Love to be really interesting in regardless to performance of nibs vs code.

A: IB / Nibs are useful for "getting started" and quick prototyping.  However like @Rudiger mentions it's useful only in simple, static layouts.  Usually it's only a matter of time before you'll run into limitations and find yourself having to write real code.


text:
Q: undefined reference to `sqrt', 'log', When I compile this code:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main() {

    char str[] = "3.6";

    double res = atof(str);

    printf("%f\n", sqrt(res));

    return 0;
}

I get this error:
    ====================[ Build | untitled12 | Debug ]==============================
/snap/clion/81/bin/cmake/linux/bin/cmake --build /home/abdo/CLionProjects/untitled12/cmake-build-debug --target untitled12 -- -j 4
[ 50%] Linking C executable untitled12
/usr/bin/ld: CMakeFiles/untitled12.dir/main.c.o: in function `main':
/home/abdo/CLionProjects/untitled12/main.c:11: undefined reference to `sqrt'
collect2: error: ld returned 1 exit status
make[3]: *** [CMakeFiles/untitled12.dir/build.make:84: untitled12] Error 1
make[2]: *** [CMakeFiles/Makefile2:73: CMakeFiles/untitled12.dir/all] Error 2
make[1]: *** [CMakeFiles/Makefile2:85: CMakeFiles/untitled12.dir/rule] Error 2
make: *** [Makefile:118: untitled12] Error 2

I get same error when I replace 'sqrt' with 'log' or 'ln' ...
compiler: cc (Ubuntu 8.3.0-6ubuntu1) 8.3.0

A: The math library must be linked in when compiling. Add the -lm flag to your gcc command, after the source or object file(s).


text:
Q: How is it possible get scroll coordinates of a RecycleView? Want to get scroll coordinates of a RecycleView like this:
int scrollX = recycleView.getScrollX();

But it always returns 0, even though view is already scrolled. Why it does not help? How is it possible get the shifted distance of the content?

A: Try with this
int scrollX = recycleView.computeHorizontalScrollOffset();

A: You can use OnScrollListener to achieve this:
private int xScroll = 0;
...
mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);

        xScroll += dx;
    }
 });


text:
Q: Find v3 so that v1 v2 v3 is a basis of R^3
Let $v_1=(2,3,4),v_2=(1,0,2)$.
  Find $v_3$ so that $\{v_1, v_2, v_3\}$ is a basis of $\mathbb{R}^3$?

I don't really know how to solve and it's a common question, I would really appreciate the help.
Thank you.

A: Note that $v_1$ and $v_2$ are linearly independent and in $\mathbb{R}^3$. You need a third vector which is linearly independent of the first two. The easiest way in $\mathbb{R}^3$ is to take
$$
v_1 \times v_2
$$
which is perpendicular to both $v_1$ and $v_2$ and hence linearly independent of both.


text:
Q: Can't call the outOfBound function I can't seem to call this no matter how I tried. It says Error: use of undeclared identifier "outOfBound". How do I call the outOfBound function to my hh function properly? Thanks
void hh(int var1, int var2, int var3, char char_a, char char_b, char array[10][10])
{
    if(outOfBound(var1, var2, var3))
    {
        cout << "Error: image access out of bounds (0, 0)";
        exit(0);
    }

    for(int i = 0; i < var3; i++)
    {
        array[var1 - 1][var2 - 1 + i] = char_b;
    }
}

bool outOfBound(int var1, int var2, int var3)
{
    if(var1 < 1 || var1 > 10 || var2 < 1 || var2 > 10 || var3 < 1 || var3 > 10)
    {
        return true;
    }
    else
    {
        return false;
    }
}

A: You declared the function after trying to use it, it has to be before:
bool outOfBound(int var1, int var2, int var3);

void hh(int var1, int var2, int var3, char char_a, char char_b, char array[10][10])
{
    if(outOfBound(var1, var2, var3))
    {
        cout << "Error: image access out of bounds (0, 0)";
        exit(0);
    }

    for(int i = 0; i < var3; i++)
    {
        array[var1 - 1][var2 - 1 + i] = char_b;
    }
}

bool outOfBound(int var1, int var2, int var3)
{
    if(var1 < 1 || var1 > 10 || var2 < 1 || var2 > 10 || var3 < 1 || var3 > 10)
    {
        return true;
    }
    else
    {
        return false;
    }
}


text:
Q: change text with css (less) animation rotate (Y) possible? I'm stuck here. Anyone knows where's the mistake in below code? Tried searching and tried all kinds of codes, I could think of. For some reason, the text does not alter but only shows "Original Text" and even without rotating (but with appearance change). I would like to rotate (Y) and while doing so, change appearance and text. Any help appreciated, thanks.
.test:before {
content: "Original Text";
font-size: 250%;
font-weight: bold;
padding-top: 25px;
color: #ffffff;
-webkit-animation: anim 4s infinite alternate ease-in-out;
animation: anim 4s infinite alternate ease-in-out;
}
@-webkit-keyframes anim {
from {text-shadow: 2.5px 2.5px 2.5px #333333; -webkit-transform: rotateY(0deg); transform: rotateY(0deg);}
to {-webkit-text-stroke: 0.5px #800000; -webkit-transform: rotateY(180deg); transform: rotateY(180deg);}
}
@keyframes anim {
from {text-shadow: 2.5px 2.5px 2.5px #333333; -webkit-transform: rotateY(0deg); transform: rotateY(0deg); content: "Original Text";}
to {-webkit-text-stroke: 0.5px #800000; -webkit-transform: rotateY(180deg); transform: rotateY(180deg); content: "Changed Text";}
}

A: The pseudo-element needs to have display:inline-block for the transform to take place.

.test:before {
  display: inline-block;
  content: "Original Text";
  font-size: 250%;
  font-weight: bold;
  padding-top: 25px;
  color: #ffffff;
  -webkit-animation: anim 4s infinite alternate ease-in-out;
  animation: anim 4s infinite alternate ease-in-out;
}

@-webkit-keyframes anim {
  from {
    text-shadow: 2.5px 2.5px 2.5px #333333;
    -webkit-transform: rotateY(0deg);
    transform: rotateY(0deg);
  }
  to {
    -webkit-text-stroke: 0.5px #800000;
    -webkit-transform: rotateY(180deg);
    transform: rotateY(180deg);
  }
}

@keyframes anim {
  from {
    text-shadow: 2.5px 2.5px 2.5px #333333;
    -webkit-transform: rotateY(0deg);
    transform: rotateY(0deg);
    content: "Original Text";
  }
  to {
    -webkit-text-stroke: 0.5px #800000;
    -webkit-transform: rotateY(180deg);
    transform: rotateY(180deg);
    content: "Changed Text";
  }
}


text:
Q: how do I stop my grid from going outside its container div? I have this interactive grid and when I hover over the cell it colors the inside divs background color but its is coloring  past the container its in, how do I get it to only color inside the container? it seems to stop at the containers top and sides but the bottom can be colored downwards the whole page. This is my code
***HTML**
<!DOCTYPE html>

         <title> Claudias Etch-A-Sketch</title>
         <link rel= "stylesheet"  href="style.css">

           Claudia Etch-A-Sketch!

          <button class="Black">Black</button>
          <button class="Pink">Pink</button>
          <button class="Clear">Eraser</button>

**JAVASCRIPT**

const container = document.getElementById("container");
const btn = document.querySelector('button');

let y = document.querySelectorAll('button');
y.forEach(button => {
  button.addEventListener('click', () => {
    let choice = button.innerHTML;
    switch (choice) {
      case "Pink":
        random();
        break;
      case "Black":
        blackchange();
        break;
      case "Eraser":
        reset();
        break;
    }
  });
});

var currentMouseoverFunction = function() {};

function blackchange() {
  container.removeEventListener('mouseover', currentMouseoverFunction);
  currentMouseoverFunction = function(e) {
    e.target.classList.remove('pink');
    e.target.classList.remove('reset');
    e.target.classList.add('black');
  };
  container.addEventListener('mouseover', currentMouseoverFunction);
};

function random() {
  container.removeEventListener('mouseover', currentMouseoverFunction);
  currentMouseoverFunction = function(e) {
    e.target.classList.remove('black');
    e.target.classList.remove('reset');
    e.target.classList.add('pink');
  };
  container.addEventListener('mouseover', currentMouseoverFunction);
};

function reset() {
  container.removeEventListener('mouseover', currentMouseoverFunction);
  currentMouseoverFunction = function(e) {
    e.target.classList.remove('black');
    e.target.classList.remove('pink');
    e.target.classList.add('reset');
  };
  container.addEventListener('mouseover', currentMouseoverFunction);
};

function makeRows(rows, cols) {
  container.style.setProperty('--grid-rows', rows);
  container.style.setProperty('--grid-cols', cols);
  for (c = 0; c < (rows * cols); c++) {
    let cell = document.createElement("div");
    container.appendChild(cell).className = "griditem";
  };
};

makeRows(24, 24);

**CSS**

#container{

  width:500px;
  height:500px;
 margin-top: 30px;
 margin-bottom: 300px;
  background:#eee;
}

#container div {
 position: center;
 float:left;
 height: 35px;
 width: 35px
}

.black {
  background: black;
}

.pink {
  background: pink;
}

.reset {
  background: transparent;
}

A: The divs in #container are floated left with float:left; in the CSS. Float takes elements out of the normal layout of the page, so the #container's height doesn't expand with its content. To fix this, remove the explicit height:500px; height definition of #container, and add a clear element after the .griditem divs inside #container.

const container = document.getElementById("container");
const btn = document.querySelector('button');

let y = document.querySelectorAll('button');
y.forEach(button => {
  button.addEventListener('click', () => {
    let choice = button.innerHTML;
    switch (choice) {
      case "Pink":
        random();
        break;
      case "Black":
        blackchange();
        break;
      case "Eraser":
        reset();
        break;
    }
  });
});

var currentMouseoverFunction = function() {};

function blackchange() {
  container.removeEventListener('mouseover', currentMouseoverFunction);
  currentMouseoverFunction = function(e) {
    e.target.classList.remove('pink');
    e.target.classList.remove('reset');
    e.target.classList.add('black');
  };
  container.addEventListener('mouseover', currentMouseoverFunction);
};

function random() {
  container.removeEventListener('mouseover', currentMouseoverFunction);
  currentMouseoverFunction = function(e) {
    e.target.classList.remove('black');
    e.target.classList.remove('reset');
    e.target.classList.add('pink');
  };
  container.addEventListener('mouseover', currentMouseoverFunction);
};

function reset() {
  container.removeEventListener('mouseover', currentMouseoverFunction);
  currentMouseoverFunction = function(e) {
    e.target.classList.remove('black');
    e.target.classList.remove('pink');
    e.target.classList.add('reset');
  };
  container.addEventListener('mouseover', currentMouseoverFunction);
};

function makeRows(rows, cols) {
  container.style.setProperty('--grid-rows', rows);
  container.style.setProperty('--grid-cols', cols);
  for (c = 0; c < (rows * cols); c++) {
    let cell = document.createElement("div");
    container.appendChild(cell).className = "griditem";
  };
  let cell = document.createElement("span");
  container.appendChild(cell).style.display = "block";
  cell.style.clear = "both";
};

makeRows(24, 24);
#container {
  width: 500px;
  margin-top: 30px;
  margin-bottom: 300px;
  background: #eee;
}

#container div {
  position: center;
  float: left;
  height: 35px;
  width: 35px
}

.black {
  background: black;
}

.pink {
  background: pink;
}

.reset {
  background: transparent;
}

     Claudia Etch-A-Sketch!

      <button class="Black">Black</button>
      <button class="Pink">Pink</button>
      <button class="Clear">Eraser</button>

As a side note, your .griditem divs are 35px wide each, so you should make the #container 840px wide if you want this to be a 24x24 square grid.

A: Your code seems a little strange in that it uses some outdated solutions.
First, don't use , it's obsolete. You should keep the appearance (including alignment) of your page inside the CSS.
Second, you don't have to use float (hardly ever). It is a common source of bugs like the one you're experiencing. Instead you could use flexbox, so your container would look like:
#container{
 display: flex; /* Puts all children inside a flexbox */
 flex-wrap: wrap; /* And allows the flexbox to span multiple lines */

 margin-top: 30px;
 margin-bottom: 300px;
 background:#eee;
}

Now, for the children, this solution allows them to distort slightly to adjust to the width of the parent:
.griditem {
 flex-basis: 35px; /* Set a base width */
 flex: 1; /* Allows it to stretch */

 height: 35px;
}

Flexbox will prove to be a very important tool in your toolset. Give it a go!
Edit: a simpler solution - sorry.
I'm usually so excited to tell people about flexbox that I sometimes overlook simpler solutions. As I see it, the reason you resorted to float is because you added a ton of divs and they stacked on top of each other - divs are "blocks" and blocks take up the hole line.
You could just have created them as spans, which as "inlines" concatenate one after the other (like letters) and do the line-break naturally. But then setting dimensions for them wouldn't work - they take their width from their content.
The simpler solution by far would be to give the divs the rule display: inline-block. Now they'd have the right size, would be inline and wrap nicely.
But then you'd find there's a mysterious space separating the lines, which is not margin nor padding. That's actually whitespace between the divs. Ugh!
The easiest way to fix that is giving the container font-size: 0 - the space is there, it just doesn't take up... space.
Anyway, the css would look like:
#container{
 font-size: 0;

 margin-top: 30px;
 margin-bottom: 300px;
 background:#eee;
}

.griditem {
 display: inline-block;

 height: 35px;
 width: 35px;
}


text:
Q: SystemVerilog: always_comb construct does not infer purely combinational logic I have this FSM that controls different events in a game I'm building (in Quartus Prime Lite Edition 17.0).
When I try to compile it, I get this error:
Error (10166): SystemVerilog RTL Coding error at GameFSM.sv(40): always_comb construct does not infer purely combinational logic.

I have all the outputs assigned as default values, so no latches should be inferred I believe (I don't totally understand how it works..).
    //Game FSM, controls the game events

module GameFSM (
    input logic clk, resetN, NPCCollisions, Dead_NPCs, start_game, pause_game, continue_game, delay_indicator,

    output logic Message_main_menu,
    output logic Message_pause,
    output logic Message_win,
    output logic Message_lose,
    output logic Display_Main_Menu,
    output logic MainMenu_Music,
    output logic BackGround_Music,
    output logic Paused,
    output logic Win_Music,
    output logic Lose_Music
   );

enum logic [2:0] {main_Menu, three_hearts, two_hearts, one_heart, delay_state, pause, win, lose} prState, nxtState;

logic [1:0] return_state;

always @(posedge clk or negedge resetN)
  begin

    if ( !resetN ) begin // Asynchronic reset
        prState <= main_Menu;
    end

    else    begin   // Synchronic logic FSM
        prState <= nxtState;
    end

end // always

always_comb // Update next state and outputs
    begin
        nxtState = prState; // default values
        Message_main_menu = 1'b0;
        Message_pause = 1'b0;
        Message_win = 1'b0;
        Message_lose = 1'b0;
        MainMenu_Music = 1'b0;
        BackGround_Music = 1'b0;
        Paused = 1'b0;
        Win_Music = 1'b0;
        Lose_Music = 1'b0;
        Display_Main_Menu = 1'b0;

        case (prState)

            main_Menu: begin
                Message_main_menu = 1'b1;
                MainMenu_Music = 1'b1;
                Display_Main_Menu = 1'b1;
                if(start_game)
                    nxtState = three_hearts;
            end

            three_hearts: begin
                BackGround_Music = 1'b1;
                return_state = 2'h3;
                if(NPCCollisions) //Corony hits an npc while he has 3 hearts left
                    nxtState = delay_state;
                else if(Dead_NPCs) //all npc's are dead
                    nxtState = win;
                else if(pause_game)
                    nxtState = pause;
            end

            two_hearts: begin
                BackGround_Music = 1'b1;
                return_state = 2'h2;
                if(NPCCollisions) //Corony hits an npc while he has 2 hearts left
                    nxtState = delay_state;
                else if(Dead_NPCs) //all npc's are dead
                    nxtState = win;
                else if(pause_game)
                    nxtState = pause;
            end

            one_heart: begin
                BackGround_Music = 1'b1;
                return_state = 2'h1;
                if(NPCCollisions) //Corony lost all his hearts
                    nxtState = lose;
                else if(Dead_NPCs) //all npc's are dead
                    nxtState = win;
                else if(pause_game)
                    nxtState = pause;
            end

            delay_state: begin
                if(delay_indicator) begin
                    if(return_state == 2'h3)
                        nxtState = two_hearts;
                    else if(return_state == 2'h2)
                        nxtState = one_heart;
                end
            end

            pause: begin
                Paused = 1'b1;
                Message_pause = 1'b1;
                if(continue_game) begin
                    if(return_state == 2'h3)
                        nxtState = three_hearts;
                    else if(return_state == 2'h2)
                        nxtState = two_hearts;
                    else
                        nxtState = one_heart;
                end
            end

            win: begin
                Win_Music = 1'b1;
                Message_win = 1'b1;
            end

            lose: begin
                Lose_Music = 1'b1;
                Message_lose = 1'b1;
                end

            endcase
    end // always comb

endmodule

return_state is used so I can know which state delivered me to the pause state, so when I want to leave the pause state, I'd know where I should return to.

A: The problem is that you read and assign to the counter signal in side the always_comb block:
                counter = counter - 1;

This can create a combinational feedback loop.
Similarly for:
                counter = DELAY_TIME;

Perhaps you should use sequential logic for counter: always @(posedge clk ...)
Another problem signal might be return_state.  I'm not sure why my simulator doesn't complain about this one.  I think return_state should be assigned in its own sequential logic block as well.


text:
Q: Change language of all slides in LibreOffice Impress I am running LibreOffice (Version 3.6.2.2) on Mac OSX and would like to change the spellcheck language for all slides. How can I set this for the whole document.
The common advice that I found online suggests to go to Tools->Options->language settings. This dialog does not seem to exist though ...

A: Seems like it is a bug see https://bugs.launchpad.net/ubuntu/+source/libreoffice/+bug/980467. I think the only workaround is to mark the text on the slides individually and select "format" -> character and there select the language you want.
Hope this is fixed soon.

A: Since the paragraph setting for language overrides the default which you set via preferences or on the tool menu, or even for an individual slide, you're forced to change the language for each paragraph.
There is a quick way which seems to work:

*

*Switch to the outline view (menu View/Outline)

*ctrl-A to select all text

*right click for the popup/context menu (but don't have the mouse over the selected text!)

*choose "Character..."

*select the language from the ComboBox.

It seems to me (I hope a developer is reading...) that the paragraph language should only be needed if the paragraph has a different language from the rest of the presentation, but currently the paragraph language is set for each paragraph as it is created.

A: The feature
(available in 5.3 at least)

Making the language visible
For all text → More... and set Locale setting to French (France).
Not sure I had to, but before that I also downloaded the french dictionary via More Dictionaries Online..., then import it as described here: Tools → Extension Manager → Add...


text:
Q: How to add a string in a certain position? Is there any function in Python that I can use to insert a value in a certain position of a string?
Something like this:
"3655879ACB6" then in position 4 add "-" to become "3655-879ACB6"

A: This seems very easy:
>>> hash = "355879ACB6"
>>> hash = hash[:4] + '-' + hash[4:]
>>> print hash
3558-79ACB6

However if you like something like a function do as this:
def insert_dash(string, index):
    return string[:index] + '-' + string[index:]

print insert_dash("355879ACB6", 5)

A: I have made a very useful method to add a string in a certain position in Python:
def insertChar(mystring, position, chartoinsert ):
    mystring   =  mystring[:position] + chartoinsert + mystring[position:]
    return mystring

for example:
a = "Jorgesys was here!"

def insertChar(mystring, position, chartoinsert ):
    mystring   =  mystring[:position] + chartoinsert + mystring[position:]
    return mystring

#Inserting some characters with a defined position:
print(insertChar(a,0, '-'))
print(insertChar(a,9, '@'))
print(insertChar(a,14, '%'))

we will have as an output:
-Jorgesys was here!
Jorgesys @was here!
Jorgesys was h%ere!

A: Python 3.6+ using f-string:
mys = '1362511338314'
f"{mys[:10]}_{mys[10:]}"

gives
'1362511338_314'

A: No. Python Strings are immutable.
>>> s='355879ACB6'
>>> s[4:4] = '-'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

It is, however, possible to create a new string that has the inserted character:
>>> s[:4] + '-' + s[4:]
'3558-79ACB6'

A: As strings are immutable another way to do this would be to turn the string into a list, which can then be indexed and modified without any slicing trickery.  However, to get the list back to a string you'd have to use .join() using an empty string.
>>> hash = '355879ACB6'
>>> hashlist = list(hash)
>>> hashlist.insert(4, '-')
>>> ''.join(hashlist)
'3558-79ACB6'

I am not sure how this compares as far as performance, but I do feel it's easier on the eyes than the other solutions. ;-)

A: I think the above answers are fine, but I would explain that there are some unexpected-but-good side effects to them...
def insert(string_s, insert_s, pos_i=0):
    return string_s[:pos_i] + insert_s + string_s[pos_i:]

If the index pos_i is very small (too negative), the insert string gets prepended. If too long, the insert string gets appended. If pos_i is between -len(string_s) and +len(string_s) - 1, the insert string gets inserted into the correct place.

A: Simple function to accomplish this:
def insert_str(string, str_to_insert, index):
    return string[:index] + str_to_insert + string[index:]

A: If you need to insert a given char at multiple locations, always consider creating a list of substrings and then use .join() instead of + for string concatenation. This is because, since Python str are mutable, + string concatenation always adds an aditional overhead. More info can be found here.

A: I'd like to add another simple one-liner-solution ;)
'-'.join([_string[:4], _string[4:]]

A: If you want many inserts
from rope.base.codeanalyze import ChangeCollector

c = ChangeCollector(code)
c.add_change(5, 5, '')
c.add_change(10, 10, '')
rend_code = c.get_changed()


text:
Q: get the text value in the dropdown with class how to get the selected text of the option.
<select class="float-left groupNames" name="Group">
       <option value="preview[object Object]0">test</option>
        <option value="preview[object Object]1">test1</option>
        <option value="preview[object Object]2">test2</option>
    </select>

I tried $(".groupNames option:selected").text();
but its not the right value. so I am getting testtest2 if I am selecting the third option.

A: $(".groupNames").val() is all you need.
jsFiddle example
However if you have multiple .groupNames elements, you'll need to be more specific with the selector.
$(".groupNames option:selected").text(); as you probably saw, will get the selected option's text, not the select's value.

A: hi please add an id to easily access the select here is an tested fiddle  http://jsfiddle.net/elviz/259m3qkb/1/
    $("#newSkill").change(function(){
         var kamote = document.getElementById("newSkill").options[document.getElementById('newSkill').selectedIndex].text;
       alert(kamote);
     });


text:
Q: R message "Can't subset columns that don't exist. x Locations 2, 3, 4, 5, 6, etc. don't exist. i There are only 1 column" MBCB packge I am trying to do a background correction on my data sets that has only 3 columns, when submitting my code I get the error "Can't subset columns that don't exist. x Locations 2, 3, 4, 5, 6, etc. don't exist. i There are only 1 column". Actually my data has only 3 columns so I dont get the error.
This is the code:
MBCB::mbcb.main(GSE150738_Dataraw,GSE150738_Dataraw_ctrol,
    npBool=TRUE,
    rmaBool=FALSE,
    mleBool=FALSE,
    bayesBool=FALSE,
    gmleBool=FALSE,
    paramEstFile="/Users/juanitadussan/Dropbox/ESTUDIO/BIOMEDICA/TESIS/TESIS 1/Análisis de datos GSE/Datasets/Background correction_parameters.xlsx",
    bgCorrectedFile="/Users/juanitadussan/Dropbox/ESTUDIO/BIOMEDICA/TESIS/TESIS 1/Análisis de datos GSE/Datasets/Background correction_corrected.xlsx",
    iter=500,
    burn=200,
    normMethod="none",
    isRawBead=FALSE)

Error in stop_subscript():
! Can't subset columns that don't exist.
x Locations 2, 3, 4, 5, 6, etc. don't exist.
i There are only 1 column.

Can anyone tell me what I am doing wrong?
Thanks!
A subset of the data is here:
Data 1:
dput(mydatasubset1)
structure(list(ID_REF = c("TC0100006437.hg.1", "TC0100006476.hg.1",
"TC0100006479.hg.1", "TC0100006480.hg.1", "TC0100006483.hg.1"
), GSM4557962 = c("44.944035", "100.85072", "157.17555","89.425964", "68.77652"), GSM4557965 = c("42.962048", "126.33466", "139.22046", "139.04102", "79.80324")), row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"))

Control:
dput(mydatasubset2)
structure(list(ID_REF = c("TC0100006437.hg.1", "TC0100006476.hg.1",
"TC0100006479.hg.1", "TC0100006480.hg.1", "TC0100006483.hg.1"
), GSM4557961 = c("46.799675", "127.531555", "212.54181","121.27715", "70.95126"), GSM4557964 = c("49.06907", "147.042", "206.33817", "126.067024", "60.933674")), row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"))

A: You need to make the numbers numeric fields and make the ids row names. Currently, these datasets are tibbles. You'll have to change them to data frames first. Since you're not using normalization, you could use mbcb.correct, as well.
This is how I prepared the data.
library(MBCB)

mydatasubset1 <- structure(list(
  ID_REF = c("TC0100006437.hg.1", "TC0100006476.hg.1",
             "TC0100006479.hg.1", "TC0100006480.hg.1", "TC0100006483.hg.1"),
  GSM4557962 = c("44.944035", "100.85072", "157.17555", "89.425964", "68.77652"),
  GSM4557965 = c("42.962048", "126.33466","139.22046", "139.04102", "79.80324")),
  row.names = c(NA, -5L), class = c("tbl_df","tbl","data.frame"))

mydatasubset2 <- structure(list(
  ID_REF = c("TC0100006437.hg.1", "TC0100006476.hg.1","TC0100006479.hg.1",
             "TC0100006480.hg.1", "TC0100006483.hg.1"),
  GSM4557961 = c("46.799675", "127.531555", "212.54181","121.27715", "70.95126"),
  GSM4557964 = c("49.06907", "147.042", "206.33817", "126.067024", "60.933674")),
  row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"))

mydatasubset1$GSM4557962 <- as.numeric(mydatasubset1$GSM4557962)
mydatasubset1$GSM4557965 <- as.numeric(mydatasubset1$GSM4557965)
mydatasubset2$GSM4557961 <- as.numeric(mydatasubset2$GSM4557961)
mydatasubset2$GSM4557964 <- as.numeric(mydatasubset2$GSM4557964)

str(mydatasubset1)
str(mydatasubset2)

md1 <- as.data.frame(mydatasubset1)
md2 <- as.data.frame(mydatasubset2)

row.names(md1) <- md1$ID_REF
row.names(md2) <- md2$ID_REF

(md1 <- md1[, 2:3])
(md2 <- md2[, 2:3])

I used temp files for the output.
t1 <- tempfile()
t2 <- tempfile()

MBCB::mbcb.main(md1,
                md2,
                npBool = TRUE,
                rmaBool = FALSE,
                mleBool = FALSE,
                bayesBool = FALSE,
                gmleBool = FALSE,
                paramEstFile = t1,
                bgCorrectedFile = t2,
                iter = 500,
                burn = 200,
                normMethod = "none",
                isRawBead = FALSE)
# 1 / 2  complete.
# 2 / 2  complete.

This is the setup for mbcb.correct.
tellMe <- mbcb.correct(md1,
                       md2,
                       npBool = TRUE,
                       rmaBool = FALSE,
                       mleBool = FALSE,
                       bayesBool = FALSE,
                       gmleBool = FALSE,
                       # paramEstFile = t1,
                       # bgCorrectedFile = t2,
                       iter = 500,
                       burn = 200,
                       # normMethod = "none",
                       isRawBead = FALSE)
# 1 / 2  complete.
# 2 / 2  complete.

A: I also had the same problem. After grouping the original database by airline, I could not sort the result by total count of airlines.
The solution for me was very simple
The problematic code is below:
top_5_airLines <- (grouped[order(grouped$Total, decreasing = TRUE)]

The right code can be found here:
top_5_airLines <- (grouped[order(grouped$Total, decreasing = TRUE),])


text:
Q: Under what conditions is this system uniquely satisfied? I have a system of two nonlinear equations:
$$\theta_{LB}=\frac{1}{k_{LB}} \left[\frac{k_{LG}}{(1-\delta_L)\Delta q(\theta_{LG})} -(1-\beta_L)(y_{LG}-z_L)-(1-\beta_L)k_{LG}\theta_{LG} \right]$$
$$\theta_{LG}=\frac{1}{k_{LG}} \left[ \frac{k_{LB}}{(1-\delta_L)\Delta q(\theta_{LB})} -(1-\beta_L)(y_{LB}-z_L)-(1-\beta_L)k_{LB}\theta_{LB} \right]$$
where $q(\theta_{Li})=\frac{\theta_{Li}}{(\theta_{Li}^\eta+1)^{\frac{1}{\eta}}}$ with $\eta>0$. The two unknowns are $\theta_{LB}$, $\theta_{LG}$ which are restricted to be greater than $0.$ All other names denote parameters. Some properties: $\Delta \in (0,1)$; $\delta_L \in (0,1)$; $\beta_L \in (0,1)$; $0 < kLB<kLG$; $zL<yLB<yLG.$  I can show that $\theta_{LB}$ is strictly decreasing in $\theta_{LG}$ and is concave up (i.e. the second derivative of $\theta_{LB}$ w.r.t. $\theta_{LG}$ is positive) and $\theta_{LG}$ is decreasing in $\theta_{LB}$ and is concave up.
I know there can be at most two solutions. But it would be great to find parameters values for which there is 1, 0, or 2. I have found numerical examples, but I am looking for a more general solution. Basically wondering if there is a theorem I am unaware of that will help me out here.
Any guidance will be great!


text:
Q: Can homebrew update a formula and can it manage multiple versions? I currently have Scala 2.9.0.1 installed and see that Scala 2.9.1 was released fairly recently. I want to upgrade. However, from what I'm seeing, I don't think homebrew supports upgrading formulae.
I see that "Multiple Version Support" is on the homebrew wishlist, but I wonder if this is up-to-date and/or much of an indication of future priorities for the project. I did a quick look at tickets in the ticket tracker but didn't see anything that jumped out at me.
In my case, I'm going to just install the new version and update my environment variables. That will work I suppose. But I feel like a package manager should help me clean up old versions if I want it to.
Related links from the mailing list archives:

*

*I missed how to "brew upgrade outdated" or similar

*Making upgrades work properly

A: No to both (automatic updating and multiple version management) per https://github.com/mxcl/homebrew/wiki/Wishlist


text:
Q: Is "us" a valid language for the lang attribute in HTML? In the example HTML file that comes with jQuery UI, the html element looks like this:
<html lang="us">

Is this even a valid language to use in the lang field? I thought it had to be en or similar? What kinds of things are valid? Would en-US or similar be valid if you wanted to specify US English? Are some values only compatible with some browsers or systems?

A:
Is this even a valid language to use in the lang field?

No, it is not an ISO language code.

Would en-US or similar be valid if you wanted to specify US English?

Yes

Are some values only compatible with some browsers or systems?

Yes. For example, a screen reader might not have a pronunciation guide for zu available (so would revert to a default).


text:
Q: Select Distinct Field on Join I am joining two large tables in MySQL based on a unique identifier they both share. Because there are a large number of fields, I do not want to list out all fields after SELECT. Instead I want to select all fields, but I do not want recurring fields (the shared unique identifier in this case) to be repeated.
With this example query:
SELECT *
FROM Gr3_PracMath_Jan11_D1 as a, student_list_011811 as b
WHERE a.StudentID = b.StudentID

The field StudentID is repeated. Is there a way to prevent this?

A: I don't think there is. You might cut your work by listing only half the fields:
SELECT a.*, b.Field1, b.Field2...

A: I believe that if you do an explicit join with the USING keyword, you won't get a duplicate.
SELECT *
FROM Gr3_PracMath_Jan11_D1
LEFT JOIN student_list_011811
USING (StudentID)

A: It is bad practice to not list out all of the columns, even if there are a lot of them. Just bite the bullet and write them out.


text:
Q: Hibernate : classpath resource cannot be opened because it does not exist I have a Maven project using Spring and Hibernate. When I launch it in Eclipse using Debug As > Java Application, it works great. But once I exported it as a runnable .jar file, it gives me this error :
class path resource [com/xxx/file.hbm.xml] cannot be opened because it does not exist

But when I open the .jar file, the file is located under /resources/com/xxx.file.hbm.xml. What did I do wrong ?
Thank you.

A: I finally found a way to get it to work by specifying an absolute path instead of a relative path in my applicationcontext.xml file. In concrete terms, I changed "com/xxx/file.hbm.xml" to "/resources/com/xxx/file.hbm/xml". Thanks to duffymo for leading me to the right way.


text:
Q: Update RecyclerView When Adding Comment I'm making a CommentFragment. I have a RecyclerView to list comments and a Edittext to write comment. However when I add a comment it's sent to server but RecyclerView isn't updated. I use notifydatasetchanged to update. Code:
 private void getComments(){

    Call<List<CommentsModel>> call=restApiClass.getComments(post_id);
    call.enqueue(new Callback<List<CommentsModel>>() {
        @Override
        public void onResponse(Call<List<CommentsModel>> call, Response<List<CommentsModel>> response) {

            if(response.isSuccessful()){

                list=response.body();
                if(commentsAdapter==null) {
                    commentsAdapter = new CommentsAdapter(list, getContext());
                }
                else{
                    commentsAdapter.notifyDataSetChanged();
                }
                recyclerView.setAdapter(commentsAdapter);
            }

        }
        @Override
        public void onFailure(Call<List<CommentsModel>> call, Throwable t) {
        }
    });
}

I call this method when I click to sendCommentTextView:
  sendCommentTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

              //............send comment codes.........
               getComments();

        }
    });

A: check this correct answer: notifyDataSetChanged example.
I think you should follow there the answer to make the adapter work as expected with notifyDataSetChanged(). Shortly: you have to update the list inside the adapter and then notify to it that the list has been updated, so it will render again on ui (recyclerview).
PS: after notifyDataSetChanged function, you don't have to set the adapter again on the recyclerview if already assigned.

A: Here you updated the list when Retrofit brings new data back, but actually you didn't feed your adapter with this data; you just called commentsAdapter.notifyDataSetChanged();, but you need first to add a method like updateList(List<CommentsModel> list) in your adapter, and call it with updateList(list); before using commentsAdapter.notifyDataSetChanged();
So, add updateList(List<CommentsModel> list) into your adapter to update its list internally like Below:
class CommentsAdapter extends RecyclerView.Adapter<CommentsAdapter.ViewHolder> {
    ...

    List<CommentsModel> mList;

    updateList(List<CommentsModel> list) {
        this.mList.clear();
        this.mList.addAll(list);
    }

}

And then the change in your code could be something like:
call.enqueue(new Callback<List<CommentsModel>>() {
    @Override
    public void onResponse(Call<List<CommentsModel>> call, Response<List<CommentsModel>> response) {

        if(response.isSuccessful()){

            list=response.body();
            if(commentsAdapter==null) {
                commentsAdapter = new CommentsAdapter(list, getContext());
            }
            else{
                commentsAdapter.updateList(list);
                commentsAdapter.notifyDataSetChanged();
            }
            recyclerView.setAdapter(commentsAdapter);
        }

    }
    @Override
    public void onFailure(Call<List<CommentsModel>> call, Throwable t) {
    }
});

Update
Yes it's working but recylerview return to first position and list
  reload. But I want to load only last comment. Other comments must stay
  same. So how can I do that ?

To just update the last comment in your list, then add a new method into your adapter that takes only that comment, and add it to the list like:
class CommentsAdapter extends RecyclerView.Adapter<CommentsAdapter.ViewHolder> {
    ...

    List<CommentsModel> mList;

    addComment(CommentsModel comment) {
        this.mList.add(comment);
        notifyItemInserted(mList.size()-1);
    }

}

Then when the data comes in back by Retrofit:
call.enqueue(new Callback<List<CommentsModel>>() {
    @Override
    public void onResponse(Call<List<CommentsModel>> call, Response<List<CommentsModel>> response) {

        if(response.isSuccessful()){

            list = response.body();
            if(commentsAdapter == null) {
                commentsAdapter = new CommentsAdapter(list, getContext());
            }
            else{
                // updating the adapter list with the last comment
                commentsAdapter.addComment((CommentsModel) list.get(list.size()-1));

            }
            recyclerView.setAdapter(commentsAdapter);
        }

    }
    @Override
    public void onFailure(Call<List<CommentsModel>> call, Throwable t) {
    }
});


text:
Q: Aligning datetime formats for comparrison I'm having trouble align two different dates. I have an excel import which I turn into a DateTime in pandas and I would like to compare this DateTime with the current DateTime. The troubles are in the formatting of the imported DateTime.
Excel format of the date:
2020-07-06 16:06:00 (which is yyyy-dd-mm hh:mm:ss)

When I add the DateTime to my DataFrame it creates the datatype Object. After I convert it with pd.to_datetime it creates the format yyyy-mm-dd hh:mm:ss. It seems that the month and the day are getting mixed up.
Example code:
df = pd.read_excel('my path')
df['Arrival'] = pd.to_datetime(df['Arrival'], format='%Y-%d-%m %H:%M:%S')
print(df.dtypes)

Expected result:
2020-06-07 16:06:00
Actual result:
2020-07-06 16:06:00
How do I resolve this?
Gr,
Sempah

A: An ISO-8601 date/time is always yyyy-MM-dd, not yyyy-dd-MM. You've got the month and date positions switched around.
While localized date/time strings are inconsistent about the order of month and date, this particular format where the year comes first always starts with the biggest units (years) and decreases in unit size going right (month, date, hour, etc.)

A: It's solved. I think that I misunderstood the results. It already was working without me knowledge. Thanks for the help anyway.


text:
Q: how can we call details from database based on id and it should call for every ID without repeating same details of previous ID <?php
$get_cats = "select * from form";
$run_cats = mysqli_query($conn, $get_cats);
if (!$run_cats) {
  printf("Error: %s\n", mysqli_error($conn));
  exit();
}
while($cats_row = mysqli_fetch_array($run_cats)){
 $cat_id = $cats_row['phone_number'];
 $cat_title = $cats_row['full_name'];
 $user_id = $cats_row['user_id'];

//   $post_image = $row_posts['course_choose'];
                        echo "

                            //This is ICON in home and when I click this I will get slider with the ID details but when I create next ID using PHP from FORM but still am able to see the same details of previous ID

$cat_id

$cat_title

";
                }
                ?>


text:
Q: Prime Factors displayed in multiplication format This is for an assignment so I'll just post the question details with my code right below it so you guys can follow easier than if I were to explain the problem myself.
Q) Any integer above 1 is either a prime number, or can be made by multiplying prime numbers together. For example: 16 = 2 x 2 x 2 x 2 = (2^4) 17 = (17^1) 18 = 2 x 3 x 3 = (2^1) x (3^2) Write a C program, primeFactor.c, that asks the user for an integer number greater than 1 and displays the product of its prime factors.
A Sample interaction is as follow:
Enter a valid number (>1): 18
18 = 1 x (2^1) x (3^3)
Enter a valid number (>1): 0
Invalid number.
Enter a valid number (>1): 19
19 = 1 x (19^1)
int readNum(int num)
{
    if (num <= 1)
    {
        return printf("Invalid Number.");
    }
    else
    {
        return printf("%i = ", num);
    }
}

int pcount = 0;
bool isPrime(int prime)
{
    bool p_flag = false;

    for(int i = 2; i < prime; i++)
    {
        if(prime % i == 0)
        {
            pcount += 1;
        }
    }
    if (pcount > 0)
    {
        p_flag = false;
    }
    else if (pcount == 0)
    {
        p_flag = true;
    }

    return p_flag;
}

int findPrimeCount(int num, int prime)
{
    int freq = 1;

    printf("1 ");
    for(prime = 2; prime < num; prime++)
    {
        freq = 1;
        while((num % prime) == 0)
        {
            printf(" * (%i ^ %i)", prime, freq);
            num = num / prime;
            freq++;
        }
    }

    if(num != 1)
    {
        printf(" * (%i ^ 1)", num);
    }

    return num;
}

int main(void)
{
    int number = 0;

    printf("Enter a valid number (>1): ");
    scanf("%i", &number);

    readNum(number);

    if(isPrime(number) == 1)
    {
        printf("1 * (%i ^ 1)", number);
    }
    else if (isPrime(number) == 0)
    {
        findPrimeCount(number, 2);
    }

    return 0;
}

Right now I guess I'm stuck in that if I input the number 64 the output will be:
64 = 1 * (2^1) * (2^2) * (2^3) * (2^4) * (2^5) * (2^6)
where I want the output to be just:
64 = 1 * (2^6)
I'm not sure how  I would go about truncating the string outputs before that or possibly even avoiding printing that whole thing out altogether. Any help is much appreciated!

A: In your findPrimeCount function, just put the print statement outside of your while loop so it only prints the factor^highestFreq:
int findPrimeCount(int num, int prime)
{
    int freq = 1;

    printf("1 ");
    for(prime = 2; prime < num; prime++)
    {
        freq = 1;
        while((num % prime) == 0)
        {

            num = num / prime;
            freq++;
        }
        // only print the last iteration
        // subtract 1 to frequency to equalize
        // the last freq++.
        freq--;
        // filter out num^0
        if(freq > 0)
        {
            printf(" * (%i ^ %i)", prime, freq);
        }
    }

    if(num != 1)
    {
        printf(" * (%i ^ 1)", num);
    }

    return num;
}

For input = 64 outputs:
64 = 1  * (2 ^ 6)

input = 46 outputs:
46 = 1  * (2 ^ 1) * (23 ^ 1)


text:
Q: Return from method, in the "try" block or after "catch" block? Is there any difference between following two methods?
Which one is preferable and why?
Prg1:
public static boolean test() throws Exception {
    try {
        doSomething();
        return true;
    } catch (Exception e) {
        throw new Exception("No!");
    }
}

Prg2:
public static boolean test() throws Exception {
    try {
        doSomething();
    } catch (Exception e) {
        throw new Exception("No!");
    }
    return true;
}

A: Nope there is no difference between both the methods.
It will return true value in both the cases effectively by resuming the flow of the program as soon an and exception is handled.
Catch will be accessed only when an exception occurs.

A: Consider these cases where you're not returning a constant expression:
Case 1:
public static Val test() throws Exception {
    try {
        return doSomething();
    } catch (Exception e) {
        throw new Exception("No!");
    }
    // Unreachable code goes here
}

Case 2:
public static Val test() throws Exception {
    Val toReturn = null;
    try {
        toReturn = doSomething();
    } catch (Exception e) {
        throw new Exception("No!");
    }
    return toReturn;
}

I would prefer the first one. The second is more verbose and might cause some confusion when debugging.
If test() incorrectly returns null, and you see toReturn being initialized to null, you might think the problem is in test() (especially when test() is not just a simple example like this).
Even though it can only return null if doSomething returns null. But that might be hard to see at a glance.

You could then argue that, for consistency's sake, it's better to always use the first form.

A: I'm assuming this is a general question. Otherwise I might comment on other aspects of your method(s).
I think in the case or small methods like these it doesn't really matter. The method is short enough to understand immediately what's going on, what's related to what etc.
However, in the case of longer methods the flow is much easier to follow in the first example. In my opinion. It keeps together related code and related scenarios. When you're reading the method, the normal execution flow is not broken by the catch block, making it more obvious and "fluent".
public static boolean test() throws Exception {
    try {
        doSomething();
        return true;
    } catch (Exception e) {
        throw new Exception("No!");
    }
}

But I won't generalize this for all methods; it's all about the context.

A: There is no difference, but the first Prg1 is faster than the Prg2.


text:
Q: Assertions are not failing in onErrorReturn rx java I am having following code:
public Single<Post> doSomething(Post post) {
    String endPoint = "some-url";
    JsonObject payload = new JsonObject().put("message", post.getPost());
    return oAuth.rxApi(HttpMethod.POST, endPoint, payload)
            .map(r -> {
                post.setPostId(r.getString("id"));
                post.setStatus(PostStatus.PROCESSED);
                return post;
            }).onErrorReturn(e -> {
                post.setStatus(PostStatus.FAILED);
                post.setError(e.getMessage());
                return post;
            });
}

And I have written following test case for it.
@Test
public void shouldHandleFailureWhilePosting() {
    Post post = new Post();
    post.setSocialAccountID("1234");
    post.setAccessToken("ABC");
    post.setPost("Some post to share!!!");

    String shareEndPoint = "some-url";
    JsonObject sharePayload = new JsonObject().put("message", post.getPost());
    when(oAuth2Auth.rxApi(HttpMethod.POST, shareEndPoint, sharePayload)).thenReturn(Single.error(new NoStackTraceThrowable("Error")));

    service.doSomething(post)
            .subscribe(postResponse -> {
                assert postResponse.getError().equals("Errorssss");
                assert postResponse.getAttachedMedia() == null;
                assert postResponse.getPostId() == null;
                assert postResponse.getStatus().equals(PostStatus.FAILED);
            });
}

Now my assertions in this case always pass. Even if I make a wrong assertion, it is always green.

A: Assertions are executed in the context of the observable chain, and won't be directly accessible from your tests.
Instead use a TestSubscriber to subscribe to the observable chain. It has a number of assertions on it.

A: Have you enabled assertion checks with the -ea option?
Assertion, by default, are disabled ... Also, testing framework usually expose own "asserts" methods. For instance, on jUnit (org.junit.Assert), you may find static assertTrue(), assertArrayEquals(), assertNull() and so on


text:
Q: IE CSS issue when hitting the browsers back button I am having an issue with IE (9 in this case) where I have uploaded a new CSS file for a page and it works just fine when I go to the page.  The problem I am having is when I browse to any another page, if I then hit the back button it renders my page using a previous version of the CSS file.  I verified this using the F12 tool to see that the css file only had the entries from the previous version.  In this case, i was styling 'ol' and 'li' elements if that matters.
Is there anything I can do to make IE load the most current version of a css file when the browsers back button is used?
Again, the page loads perfectly if I browse to it in any "forward" manner, I also have my browser set to check for new versions every visit.  Its when I hit the back button it has problems. Also every other browser ive tested has no problem using the back button.

A: you could add a parameter when calling the stylsheet...
?version=2

...after you .css extension

A: If you are clicking back to return to a page that you have previously visited with the old stylesheet, then yes, it will load the old stylesheet. A simple refresh should fix this.
The reason is that the back button is not meant to reload old pages, but to preserve the pages exact state and return the user back to that page.
If indeed you have loaded the new stylesheet on page A and then move forward to page B, then click back to go to page A and an old version of the style has been loaded, there might be something going seriously wrong with IE's cache. It might be a bug. Maybe changing the filename or adding something to the query string will force it to recognise your stylesheet as a newer version eg:
style.css?v2

will make sure the browser treats your style as a completely new file and disregard any old cached versions.


text:
Q: Python Column / Fieldnames combine I want to create a table with 2 headings but 5 entries / columns and get this problem:
Exception("Row has incorrect number of values, (actual) %d!=%d (expected)" %(len(row),len(self._field_names)))
Exception: Row has incorrect number of values, (actual) 5!=2 (expected)

How can I combine column 1 and column 2 in the title
Input:
+----------+----------+---------+---------+---------+
| Field 1  | Field 2  | Field 3 | Field 4 | Field 5 |
+----------+----------+---------+---------+---------+
| Adelaide | Brisbane |  Darwin |  Martin | Summary |
+----------+----------+---------+---------+---------+
|  Test1   |  Test2   |  Test3  |  Test4  |  Result |
+----------+----------+---------+---------+---------+

from prettytable import PrettyTable
x = PrettyTable()
x.hrules = 1
x.vrules = 1
x.header = True
x.add_row(["Adelaide","Brisbane","Darwin","Martin","Summary"])
x.add_row(["Test1","Test2","Test3","Test4","Result"])
print(x)

Output:
+----------+----------+---------+---------+---------+
|                    Names                | End     |
+----------+----------+---------+---------+---------+
| Adelaide | Brisbane |  Darwin |  Martin | Summary |
+----------+----------+---------+---------+---------+
|  Test1   |  Test2   |  Test3  |  Test4  |  Result |
+----------+----------+---------+---------+---------+

A: If you are willing to use Pandas here is a snippet that should work. Not sure how your headers and data would be read in so I am confident that you could make this more flexible, but just showing you how Pandas and MultiIndex can be used.
Pandas is really good when working with data and gives you loads of built in features so if this is something you will do regularly I would suggest having a look at a demo and seeing what you think.
    import pandas as pd
    header_row_1 = ["Names", "Names", "Names", "Names", "End"]
    header_row_2 = ["Adelaide","Brisbane","Darwin","Martin","Summary"]
    data = ["Test1","Test2","Test3","Test4", "Result"]
    tuples = list(zip(header_row_1, header_row_2))
    cols = pd.MultiIndex.from_tuples(tuples)
    df = pd.DataFrame([data], columns = cols)


text:
Q: In the proof that in a PID, every non-zero non-unit is the product of irreducibles... In proving that all non-zero non-units of a PID are a product of irreducibles, theres:

"We now show that $a$ is a product of irreducibles. If $a$ is irreducible,
  we are done. Otherwise let $p_1$ be an irreducible such that $p_1|a$. Then
  $a=p_1c_1$. If $c_1$ is a unit, we are done. "

How did they get that they're done?
I've got $aR = p_1 c_1 R = p_1 R$ if $c_1$ is a unit.
Thanks.

A: If $c_1$ is a unit, then $a=p_1c_1$ is in fact irreducible. Since we assumed that was not the case, then $c_1$ is not a unit.
I suspect that what they meant to say is "If $c_1$ is irreducible, we are done."


text:
Q: Dynamic redirect .htaccess not work I don't know much about .htaccess and redirects, what am I not doing right?
RewriteCond %{QUERY_STRING} ^id_pais=(.*)&id_provincia=(.*)&id_comunidad=([^&]+)
RewriteRule ^ https://example.com/comunidades/$1/slug? [R=301,L]

I want that $1 = id_comunidad but the result of this redirect is: https://example.com/comunidades//slug
I used %1 too instead $1 and the result always is: https://example.com/comunidades/1/slug

A: I have solved this, I had to pass it as third parameter %3, not as first %1
RewriteCond %{QUERY_STRING} ^id_pais=(.*)&id_provincia=(.*)&id_comunidad=([^&]+)
RewriteRule ^ https://example.com/comunidades/%3/slug? [R=301,L]


text:
Q: How to select all from one table order by the last created timestamp of values from another table I have 2 tables called conversation and message.
I would like to select all conversations sorted by order of the last updated message related to the conversation. The conversation table doesn't have the updated_at and to be able to get all conversations ordered by the last updated_at, that should be deducted from the last created message in the conversation from the table message.
The result should be based on what is the last message of the conversation.
The SQL I tried is not giving me the right result and I believe I should use a join but as I'm new to SQL cannot really get it how
select
    *
from
    conversation
inner join message on
    conversation.id = message.conversation_id
order by
    message.updated_at desc;

Tables looks as follow
The conversation

id
topic
origin_type
origin_id
created_at

1
t1
doc1
xx1
2021-04-07 13:23:40

2
t2
doc2
xx2
2021-04-07 14:23:40

3
t3
doc3
xx3
2021-04-07 15:23:40

Message table

id
conversation_id
message
created_at
updated_at

1
1
xxx
2021-04-07 13:23:40
2021-04-07 13:23:40

2
2
xxx
2021-04-07 14:23:40
2021-04-07 14:23:40

3
3
xxx
2021-04-07 15:23:40
2021-04-07 15:23:40

Seeing the tables I should get a result of the select as follow I believe as the
conversation.id = 3 has the last created and most recent message.

id
conversation_id

1
3

2
2

3
1

In SQL/PSQL I don't know how to do this kind of selection

A: Your data is not particularly illustrative, because the conversations only have a single message.  However, I think you want to keep all rows for a conversation together.  That would use a window function to get the maximum updated time for each conversation:
order by max(message.updated_at) over (partition by conversation.id) desc,
         conversation.id,
         message.updated_at desc

EDIT:
If you just want the conversations with no message information, you can use a subquery:
select c.*
from conversations c
order by (select max(m.updated_at) from messages m where m.conversation_id = c.id) desc;

A: You can just use a scalar subquery:
select *,
    (
        select max(m.updated_at) from message m
        where m.conversation_id = c.conversation_id
    ) as last_updated_at
from conversation c
order by last_updated_at desc;


text:
Q: Passing parameters to a url I'm calling a jsp page through an jax-rs endpoint as below.
 public String logout(@Context HttpServletRequest request,@DefaultValue("Empty Details") @QueryParam("logoutNotification") String logoutNotification,
                     @QueryParam("id_token_hint") String id_token_hint) {
     Response response=    Response.status(200).entity(logoutNotification).build();
    if(response.getEntity().toString().equals("True")){
       return "";
    }
   else {
       return null;
    }

The thing is I need to pass some parameters to the 'https://localhost:9443/carbon/authenticationendpoint/test.jsp' from this endpoint. How can I do it?
Can I pass it as a queryparam from the endpoint? Please advice me.
Thanks

A: I dont have much knowledge on RESTful webservices. But in an url if you want to pass paramters it can done as <url URL>?par1=val1&par2=val2 If your code opens a new window then this will work.
I hope so this would help you.
Example:    https://localhost:9443/carbon/authenticationendpoint/test.jsp?name=Joe&age=24


text:
Q: Syntax issue with then method on Navigator I have the following code snippet:
_openEditListingDialog(Listing listing,
    Function(Listing) onSubmittedCallback) async {
      Navigator
      .of(context)
      .push(
        new MaterialPageRoute<Listing>(
          builder: (BuildContext context) {
            return new ListingDialog.edit(listing);
          },
          fullscreenDialog: true,
        ),
      )
      .then((Listing newEntry) {
        if (newEntry != null) {
          newEntry.id = listing.id;
          onSubmittedCallback(newEntry);
        }
      });
  }

VSCode complains on the .then line with the following error:
[dart] The argument type '(Listing) -> Null' can't be assigned to the parameter type '(Object) -> FutureOr<Null>'.

What does this mean and how do I correct this?  I am new to dart and flutter and error messages like this are cryptic for me.  My code is based on this example: https://github.com/MSzalek-Mobile/weight_tracker/blob/v0.4.1/lib/home_page.dart.

A: TBH I'm not sure why VS Code is flagging that as an error for you - I see nothing substantially wrong with it and neither does my VS Code or IntelliJ. I pasted your code in and after adding a Listing class, I had no problem at all (for the record, if you paste enough code that someone can actually run things when you have a problem it makes it a lot easier for them to help you).
And in this particular case, the line number for the error might be quite helpful.
Maybe make sure your VS Code and Flutter are up to date (I'm using the Master channel/branch which has been updated to dart 2.0 so that might be part of it maybe...).
There are a couple of things you could try. First, it seems as though your push method isn't picking up the right type - I'm fairly sure the error you're seeing is at the .then(... where it expects and Object and you're telling it to be a Listing. You can change your .push to .push<Listing> to force it to return a Listing.
Next, I'm not actually familiar with what you're doing with Function(Listing). I don't think that's proper dart, or at least any more. I think the recommended way of doing that is typedef-ing a method with the right parameter type i.e. typedef void ListingCallback(Listing listing); and then using that as the argument, if you're going to use a callback (see later on in the answer for an arguably better alternative).
The other thing you're doing wrong, which many people seem to do at first in dart/flutter, is mis-using async. If you use async in a method signature, you should not be using .then for futures, but rather using await. See here and this part of effective dart. I've re-written your code to do that properly:
//outside class somewhere
typedef void ListingCallback(Listing listing);

...

  _openEditListingDialog(
      Listing listing, ListingCallback onSubmittedCallback) async {
    Listing newEntry = await Navigator.of(context).push<Listing>(
          new MaterialPageRoute<Listing>(
            builder: (BuildContext context) {
              return new ListingDialog.edit(listing);
            },
            fullscreenDialog: true,
          ),
        );

    if (newEntry != null) {
      newEntry.id = listing.id;
      onSubmittedCallback(newEntry);
    }
  }

Note that this also gets rid of that whole function that was causing you problems.
Also, you could just use futures and remove the async in the method signature, but then you're going to have to make sure to actually return a future.
And lastly, you could (should) probably be returning a Future rather than passing in a callback.
  Future<Listing> _openEditListingDialog(Listing listing) async {
    Listing newEntry = await Navigator.of(context).push<Listing>(
          new MaterialPageRoute<Listing>(
            builder: (BuildContext context) {
              return new ListingDialog.edit(listing);
            },
            fullscreenDialog: true,
          ),
        );

    if (newEntry != null) {
      newEntry.id = listing.id;
    }

    return newEntry;
  }

A: You pass a function
Function(Listing) onSubmittedCallback) async {
  // no return here
});

This means Dart infers return type Null
I think changing it to
FutureOr<Null> Function(Listing) onSubmittedCallback) async =>

and removing } at the end (last line of your code) should fix it.
If you want to keep the function body {...} use
    FutureOr<Null> Function(Listing) onSubmittedCallback) async {
      await Navigator
      .of(context)
      ...


text:
Q: Cant make a view show above another one in StackLayout-XamarinForms I am having a problem on my XAML page, I want to show an Image above a custom view and no matter what I try it is always shown behind. I have already shown a view above this specific custom view, but in this section, I cant make it work, and I don't see the difference between this part and the one that actually works.
My code:
<ContentPage Title="title">
            <renderers:GradientLayout
                x:Name="page"
                ColorsList="#D81BDE,#4847FF"
                Mode="ToBottomLeft">

                <Button
                    BackgroundColor="Yellow"
                    HeightRequest="45"
                    WidthRequest="45"

                    Margin="0,25,25,0"
                    VerticalOptions="Start"
                    HorizontalOptions="End"

                    Command="{Binding button}">

                </Button>

                <CarouselView
                    x:Name="carousel"

                    VerticalOptions="StartAndExpand"
                    HorizontalOptions="StartAndExpand"

                    BackgroundColor="Transparent">
                    <CarouselView.ItemTemplate>
                        <DataTemplate>
                            <StackLayout>

**This is the custom view I am trying to show below**
                                <custom:PancakeView
                                    CornerRadius="25"
                                    HasShadow="True"
                                    BackgroundColor="Pink"

                                    Margin="35,0,65,15"
                                    HeightRequest="600"
                                    WidthRequest="300"
                                    VerticalOptions="End"
                                    HorizontalOptions="StartAndExpand"
                                    Padding="15">
                                    <StackLayout>

                                        <Label
                                            Text="Este es un ejemplo de una descripcion, hace falta, por supuesto, hacer un binding con la descripcion real"
                                            TextColor="White"
                                            FontSize="20"
                                            HorizontalTextAlignment="Start"

                                            VerticalOptions="EndAndExpand"
                                            HorizontalOptions="Center"
                                            Margin="0,0,0,25">

**This is the custom view that is actually showing below**
                                        <custom:PancakeView
                                            BackgroundGradientStartColor="White"
                                            BackgroundGradientEndColor="Black"
                                            CornerRadius="25"
                                            Opacity="0.25"

                                            HeightRequest="60"
                                            WidthRequest="800"
                                            VerticalOptions="End"
                                            HorizontalOptions="CenterAndExpand"
                                            Padding="3"
                                            Margin="0,0,0,35">
                                            <Frame
                                                BackgroundColor="Pink"
                                                CornerRadius="25"

                                                VerticalOptions="FillAndExpand"
                                                HorizontalOptions="FillAndExpand"
                                                Padding="0"></Frame>
                                        </custom:PancakeView>

**This is the view that it is actually showing above**
                                        <Label
                                            Text="Buy now"
                                            TextColor="White"
                                            FontSize="30"
                                            FontAttributes="Bold"
                                            HorizontalTextAlignment="Start"

                                            Margin="10,-96,10,15"
                                            VerticalOptions="End"
                                            HorizontalOptions="Center">
                                    </StackLayout>
                                </custom:PancakeView>

**This is the image I am trying to show on top of the first custom view**
                                <Image
                                    Source="Burguer.png"
                                    BackgroundColor="Transparent"

                                    VerticalOptions="End"
                                    HorizontalOptions="Center"
                                    Margin="0,-500,0,0"></Image>
                            </StackLayout>
                        </DataTemplate>
                    </CarouselView.ItemTemplate>
                </CarouselView>

            </renderers:GradientLayout>
        </ContentPage>

And that is all, if you need more info I will provide it as soon as I see your request, thank you for your time, have a nice day.
EDIT:
Here are two pictures, the first one is what I am trying to achieve, the second one is what is happening with this code:

A: There is a simple way to overlap layouts using Grid, and it's like this:
<Grid>
    <Grid x:Name="ContentBehind">
        //This Content will stay below
    </Grid>
    <Grid x:Name="ContentAbove">
        //This Content will stay on front
    </Grid>
</Grid>

So if you want a StackLayout to be above another StackLayout, you shoul try this:
<Grid>
    <StackLayout BackgroundColor="Green"></StackLayout>
    <StackLayout BackgroundColor="Transparent"></StackLayout>
</Grid>

Or like this (it's the same thing but you define how you want your rows height to act):
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>

    <StackLayout Grid.Row="0" BackgroundColor="Green"></StackLayout>
    <StackLayout Grid.Row="0" BackgroundColor="Transparent"></StackLayout>
</Grid>


text:
Q: How to verify account termination with user's password in Rails app? I built the authentication system for my Rails application from scratch following this tutorial (among others).
Everything works as intended but it is still too easy for a user to destroy his own account (and thus all the data it contains):
class UsersController < ApplicationController

  def destroy
    @user.destroy
    flash[:success] = "Your account has been deleted."
    redirect_to root_path
  end

end

Right now, I have this in my edit view:
<%= link_to "Delete own account", @user, :confirm => "Are you REALLY sure?", :method => :delete %>

What is the Rails way to extend this and require the user's password as well before s/he can destroy their own account?
Thanks for any help.

A: You will have to add some logic for that.
Follow this:

*

*Create a form *using form_for) on destroy/(whichever page you want to), asking the password of the signed in user. Route the form to some action.

*In the sent action, authenticate the user against the password supplied; if it matches, call @user.destroy, otherwise, flash the error and warning etc.


text:
Q: Router-outlet creates a gap or space in my Angular app with Bootstrap I use Bootstrap 4 in my Angular 2 app and I'm facing a problem with the directive router-outlet.
Here a screen :

And my code :
AppComponent

Home

Sign in

Sign up

Chat

Logout

    <router-outlet ></router-outlet>

the component nested in the router-outlet above
ChildComponent

This code creates the red gap in the screen capture and if I uncomment the class attribute "class="d-none"" and I put it in the router-outlet attribute the red gap disappears.
So is it normal or there is an alternative to this ?


text:
Q: SIGFAULT with one thread - does it affect other existing threads? If my application runs 'x' number of threads, and if there are any one of them does the nasty memory corruption, and hence SIGFAULT occurs!!!. Does it affect other threads also ?

A: Unless you handle it, then yes, it kills the entire application.

A: offcorse it will effect all other threads.
see you are running x number of threads with your application it means you have created one process having x number of threads now when anyoone threads gets segmention faults & you cant able to handle that then it will kill your main process ...indirectly all ur threads will also close....!!!


text:
Q: JDBI SQL Annotations how to query CLOB with LIKE I'm trying to fetch data from our database using a CLOB column.
Hardcoded strings work:
@SqlQuery("SELECT * FROM users WHERE roles LIKE '%ADMIN%'")
fun findAllByRole(@Bind("role") role: String): List<UserRecord>

But when trying using the binder parameter role it doesn't:
@SqlQuery("SELECT * FROM users WHERE roles LIKE %:role%")
@SqlQuery("SELECT * FROM users WHERE roles LIKE '%:role%'")
@SqlQuery("SELECT * FROM users WHERE roles LIKE :role")

The role parameter contains the string "ADMIN".
What's the correct way to use LIKE on a CLOB with jdbi sql annotations?

A: From a colleague:
@SqlQuery("SELECT * FROM users WHERE roles LIKE CONCAT('%', :role, '%')")
fun findAllByRole(@Bind("role") role: String): List<UserRecord>

A: You can achieve this by:
@SqlQuery("SELECT * FROM users WHERE roles LIKE :role ")

or
@SqlQuery("SELECT * FROM users WHERE roles LIKE CONCAT('%', :role, '%')")


text:
Q: Slick2D - isometric map render bug I made an isometric map with the program "Tiled" and loaded it in my code.
I have two layers of tiles:
1. The background layer (grass)
2. The objects layer (a fridge in this case)
The fridge does not get rendered correctly. As you can see here (left how it should be, right how it is atm)
http://i.stack.imgur.com/UBTDf.png
The firdge consists of two parts, upper and lower part, as seen here:
http://i.stack.imgur.com/iuS47.png
So my first thought was, that I can't display a tile over a tile. That would explain why the grass tiles to the left and the right of the fridge is in front of the fridge. But that does only apply for the upper part. The lower part gets displayed correctly and also "goes over" the grass tile. So why is that happening?

A: Alright I figured it out.
You can render the layers of the map on by one.
map.render(x, y);

Renders all the layer at once. Then what happens is what @Marco13 commented under my question.
To avoid that use this instead.
map.render(x, y, layer);

And if you have two layers like me, for example you just go:
map.render(x, y, 1);
map.render(x, y, 2);

Then everything looks just fine :)


text:
Q: nuget "Unable to resolve dependency" after fixing typo in nuspec file I have two Visual Studio (2010) solutions.  One solution, SolutionAlpha, has two projects, ProjA and ProjB, both of which have nuspec files, both of which have package build enabled, and for both of which a nupkg file is generated.  I added a dependency in the nuspec file for ProjB pointing to ProjA, but I accidentally had a bunch of spaces in the name, so it looked like:
<depedencies>
    <dependency>Pro      jA</depedency>
</dependencies>

I put both of the nupkg files for ProjA and ProjB in a directory, which Visual Studio is set up to use as a nuget repository.  In SolutionNumeric's Proj1, I tried to add a Nuget reference to ProjA and to ProjB, but I kept getting Unable to resolve dependency 'Pro      jA.
I corrected the nuspec file in ProjA, copied it to the directory, confirmed that it was correct using NuGet Package Explorer, and cleared the recent packages and package cache through Visual Studio, yet I still get the error.
How can I resolve this?
Thanks!
edit:
This works from a solution for which nuget has never been used.
When I start the package manager console, I get Package Manager Console Host Version 2.0.30619.9119.

A: Of course, after way too much time trying to figure this one out, and immediately after asking the question here, I figure out that the answer is to remove the related folders from the packages directory in my solution.  I had tried doing full-text searches of the solution directory for the bad name, or even just the part of the name after the spaces, but got nothing that I was able to make sense of.  It must have been in some binary file somewhere in packages.


text:
Q: Audio player work on iOS simulator in Background but does not on iOS device (same version) I am trying to play an audio streaming until application is in background.
Here is the code :
var service;

if(isiOS4Plus()){
    Ti.App.addEventListener('resumed',function(e){
        if(service!=null){
                    if(winPlayer.controlStreamer)// if my controller (containing the audio player object) exists
                    {
                            //function that redeclare intervals and event listeners
                            winPlayer.controlStreamer.foregroundStreamer();
                    }
                    service.stop();
                    service.unregister();
            }
     });

    Ti.App.addEventListener('pause',function(e){
        if(winPlayer.controlStreamer)// if my controller (containing the audio player object) exists
            {
                    //function that stop and remove intervals and event listeners
                    winPlayer.controlStreamer.backgroundStreamer();
            }
            service = Titanium.App.iOS.registerBackgroundService({url:'/player/sound.js'});
            Ti.API.info("registered background service = "+service);
    });

}

Audio player object is intitialized before in this method :
this.streamer=Titanium.Media.createAudioPlayer({url:this.url_stream_stetienne,bufferSize:1000000});

Here is my problem : when i running app on iOS Simulator (iOS 5.0), stream player continue playing (what I want it does), but when I test it on iOS Device (iOS 5.0) sound volume decrease and player stop.
Note : the file info.plist contains the following lines :
<key>UIBackgroundModes</key>
    <array>
        <string>audio</string>
    </array>

And I now with alert boxes that events are correctly triggered and handled.

A: Ok, it is not a bug :
If you want to play an audio streaming (like a webradio stream) on iOS, you have to set the "audioSessionMode" parameter to "Titanium.Media.AUDIO_SESSION_MODE_PLAYBACK" (maybe others values are correct ?) in your audioPlayer instance.
If you don't, streamer will work fine in background mode, but only if tested with iPhone simulator, not with device.
Hope this helps somebody else.


text:
Q: Keep mobile browser from showing elements outside content bounds? In order to illustrate my problem, take a look at the following fiddle: http://jsfiddle.net/ECaD6/
Pretend that I have made this webpage where the center (dark grey) area is the main content of the page. The background of this content area is purposely a different color than the sides of the container that do not contain any content.
I have placed an image absolutely, so that it lies outside the bounds of the intended content area. This works and looks good on a desktop browser.
However, when viewed in a mobile browser, the user can zoom out on the page so that they see this:

I would like it if the browser could only zoom out only as wide as the content container. Is this possible? I could obviously put a overflow-x:hidden on the div but then it would actually cut off the soccer ball altogether.
Would be nice if the mobile browser could only zoom out this far:

I know that technically the image (in this case) is part of the 'content' since it's in the content div. I'm wondering if there are any layout or css tricks that could be used to achieve what I'm looking for.

A: Have you added a meta device-width tab to your header?

A: Add this meta tag in the <head> of your page.
<meta name="viewport" content="initial-scale=1, maximum-scale=1.0, user-scalable=no" />


text:
Q: Why project is not showing when import a android project from Github? When I  "Checkout project from Version Control" a project from Github then project is not showing or loading but project downloaded in desire folder. Android studio is showing a error which is:

Now what can I do to fix this error?

A: Did you check version Control ???
i suggest see this link it can help you.
Import Github project in AS


text:
Q: Malloc of pointer to an array- C++ I have a function which gets as a parameter a pointer to array,
e.g. int** segs.
I need to allocate (in the function-body) memory for the array, which has size 100 for example.
My attempt was:
*segs=(int*)(malloc(100));

So far so good.
I put a value into *segs[0], and still everything is great.
But... when I try to reach *segs[1], I get an "invalid write of size 4" error from valgrind, which leads to seg-fault.
I have no idea why does that happen.
I tried to reach to *segs[2], but then I get even something weirder-

Error of uninitialised value of size 8.

A: Due to operator precedence, *segs[N] is treated as *(segs[N]), which is ok when N is equal to 0. However, when you do the same thing using the index 1, things break since nothing has been allocated for segs[1]
For any index other than zero, you need to use (*segs)[N].
It will be easier to use a temporary pointer in the function.
int* ptr = (int*)(malloc(100));
*segs = ptr;

// and then

ptr[0] = ...;  // Good
ptr[1] = ...;  // Good

...

ptr[99] = ...; // Still good

Upgrading to C++ Way

*

*Pass the pointer by reference.
void foo(int*& segs) { ... }

*Use new instead of malloc to allocate memory.
segs = new int[100];

*Better yet, use std::vector insteady raw arrays.
void foo(std::vector<int>& segs) { ... }


text:
Q: How to include SQL Compact and .NET Framework in my Installer I need to have my installer include the .NET Framework 3.5 SP1 as well as SQL Compact 3.5.  I remember seeing a place somewhere in the Visual Studio IDE where these could be included in the install, but I can't find them.  Does anyone know how to do this?  Thanks!

A: Found it!  It looks like you can go to the "Properties" window of the Installer project and click on the "Prerequisites" button to see a list of prerequisite installers to include in your installer like SQL Server, SQL Compact, .NET Framework versions, etc.
It appears that the list is driven off of things that you have installed on the development computer.

A: You might also want to register for redistribution rights:
http://www.microsoft.com/sqlserver/2005/en/us/compact-redistribute.aspx