Extract values from a column in a Dataframe based in starting letters

Question: Hope everyone is doing well. I am using pandas and numpy and I would like to extract column values based on the first 3 letters (ap.) from a Dataframe. Below is an example of my Dataframe.

Name
Number

Orange
2

APple
6

Ap.ricot
1

AP.19
1

Juap.rte
3

I've tried df[df['Name'].str.lower().str.contains('ap.', na=False)].Name.unique() but it does not fully do the trick.
Output:
['AP.19','Ap.ricot']

The output should ideally be a list that I can then save onto a variable. Additionally, the 3 letters need to be at the start and in this order.
I am very new to Python so please explain as clearly as possible. Thank you.
Comment: Do you want to take out values where your code finds 'Ap' only?
Comment: No, I would like to extract the values in a list form, which start with 'ap.'

Of course, would also need to convert everything to lower case, but the output so be in its original form.

So exactly the output I have, otherwise have 'Ap' would also include 'APple'.
Comment: please check my answer once.
Comment: You can also try using `Match`.
Answer: Given the comments in the post, I believe you can get it done with:
ap = [x for x in df['Name'] if x.lower().startswith('ap.')]

And if you wish to not have duplicates, then you can use:
ap = [x for x in df['Name'].unique() if x.lower().startswith('ap.')]

Comment: Thank you @Celius Stingher

That is exactly what I was looking for. Wish you a nice day.
Comment: Have a great day and Merry Christmas! Feel free to mark my answer as accepted so we know the problem has been solved!
Answer: This may help you:
final = []

df['NameCopy'] = df['Name'].str.lower()

for index,row in df.iterrows():
   if row['NameCopy'].find('ap.') != -1:
      final += [row['Name']]
   else:
      pass

print(final)

Comment: This is very inefficient as it is looping over a dataframe and should be discouraged.
Comment: There is no conditions which you need to meet, and it has been proven many times there are vectorized ways of dealing with conditions such as `np.where()`. Using for loops should be avoided and discouraged when dealing with pandas dfs
Comment: Yes agree to @CeliusStingher: One should avoid iterating. https://stackoverflow.com/a/55557758/6660373 btw merry Christmas to all of you in advance :)
Comment: Thank you!

This also works. I will accept and approve the answer as soon as StackOverflow allows me.
Comment: @CeliusStingher: Good point, but such loops are better where there are more conditions you need to loop through within the same iteration. Which is why I prefer using these in my datasets.
Comment: You should avoid that. Visit the link that I have mentioned. It will help you in future :)
Answer: try:
df[df['Name'].str.match('^(ap[.])', case=False)].Name.unique()

array(['Ap.ricot', 'AP.19'], dtype=object)

Comment: I like the use of regex here :) Merry Xmas :D +5


How do I get aggregated data for selected attributes from shiny app?

Question: It would be great someone can help to solve below criteria.
Requirement details:-
How to pass multiple attributes dynamically to group_by/summaries clause to get  aggregated data for selected attributes? in my case I am able to achieve the same by using below code, but it was restricted to 1 group by attribute and summary attribute. If I select multiple group by or summary attributes, it's throwing error.
library(dplyr)
library(data.table)
library(shiny)
library(DT)

df1 <- data.frame("name"=c("AAA","BBB","CCC"),"dept"=c("HR","HR","FIN"),"Salary"=c(1000,1345,5678),"Salary2"=c(4567,7896,5678))

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
  pickerInput("Id0001","group by attributes",choices = unique(names(df1)),multiple = TRUE,options = list(`live-search` = TRUE)),
  pickerInput("Id0002","summary attributes",choices = unique(names(df1)),multiple = TRUE,options = list(`live-search` = TRUE)),
  actionButton("Id0003", "show data")
  ),
  mainPanel( DT::DTOutput("data_tbl") )
  )
)

server <- function(input,output,session){

  reactive_string  <- eventReactive(input$Id0003, {
    if (input$Id0003 > 0) {
      dt_agg_ui <<- df1  %>%
        group_by(!!rlang::sym(input$Id0001)) %>%
        summarise_at(vars(!!rlang::sym(input$Id0002)),funs(sum,n()))
    }
    dt_agg_ui
  })

  output$data_tbl <- DT::renderDT( {reactive_string()})
  }
shinyApp(ui = ui, server = server)

Answer: Using dplyr::across and tidyselect::all_of this could be achieved like so:
library(dplyr)
library(data.table)
library(shiny)
library(shinyWidgets)
library(DT)

df1 <- data.frame("name"=c("AAA","BBB","CCC"),"dept"=c("HR","HR","FIN"),"Salary"=c(1000,1345,5678),"Salary2"=c(4567,7896,5678))

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      pickerInput("Id0001","group by attributes",choices = unique(names(df1)),multiple = TRUE,options = list(`live-search` = TRUE)),
      pickerInput("Id0002","summary attributes",choices = unique(names(df1)),multiple = TRUE,options = list(`live-search` = TRUE)),
      actionButton("Id0003", "show data")
    ),
    mainPanel( DT::DTOutput("data_tbl") )
  )
)

server <- function(input,output,session){

  reactive_string  <- eventReactive(input$Id0003, {
    if (input$Id0003 > 0) {
      dt_agg_ui <<- df1  %>%
        group_by(across(all_of(input$Id0001))) %>%
        summarise(across(all_of(input$Id0002), .fns = list(sum = sum, n = ~ n())))
    }
    dt_agg_ui
  })

  output$data_tbl <- DT::renderDT( {reactive_string()})
}
shinyApp(ui = ui, server = server)

Comment: It seems there is package versioning issue as i am getting "Evaluation error: 'across' is not an exported object from 'namespace:dplyr'.". Could you please let me know which version of packages installed in your system. Below are the versioning details of mine.

platform       x86_64-w64-mingw32
version.string R version 3.4.3 (2017-11-30)

> packageVersion('dplyr')
[1] '0.8.0.1'
> packageVersion('tidyselect')
[1] '0.2.5'
Comment: @Koppula. Oh. I see. So you are running on quite old versions of R and dplyr. I'm using R version 4.0.2 and dplyr 1.0.2. In that case stick with your original code and try replacing `!!rlang::sym` by the "vectorized" version `!!!rlang::syms`. Checked it and worked on my machine. And just in case: my version of `rlang` is 0.4.7.
Comment: I have upgraded my version to 4.0.2 and now everything working well. I will keep both versions my local. Once again thanks for your help Stefan.


ELECTRICIAN BORED 4" HOLE through top & bottom chords in attic -- how to fix?

Question: I'm extremely concerned; hopefully unnecessarily so. We recently upgraded our electrical panel and I just noticed (about a month and a half later) that the electrician bored a 3.5" hole through what I think is the top chord and TWO 3.5" holes through what I think is the bottom chord.  There's nothing above it but the roof and it's not inhabitable space, but I'm still concerned that it might collapse over time, since there's nothing left of what (I think) is the bottom chord for approx 8" -- there was a previous 1" hole for electrical that they decided to bore next to... twice.  Is this going to be a problem over time, or is it okay because, presumably, this beam is supported by several studs along its length underneath? If we need to, how should we fix it?  We do not have the money right now to consult an engineer or tear open the outer wall/ceiling beneath the beam, etc.  The photos are of the top and bottom holes he drilled, which are 8" to the right of the dead center of our rear wall (where the attic peaks at the middle.)
Comment: Chords are members of a truss - https://books.google.com/books?id=KKeipCXitkMC&pg=PA132&lpg=PA132&dq=chord+carpentry&source=bl&ots=4kEgmNAvIs&sig=YZOvjb-_f-kEzm-YZuxgQW6VC0Q&hl=en&sa=X&ved=0ahUKEwj6x_Ov9eTYAhWf0YMKHZ70CEkQ6AEILjAB#v=onepage&q=chord%20carpentry&f=false - which sort of makes sense in context, I guess.
Comment: It appears to be passing through the roof at the gable end. That is not a load bearing wall. Don't sweat it.
Comment: What are you referring to when you say bottom and top 'chord'?
Comment: But I can't quite seem to interpret these images.
Comment: I'm so sorry if I'm using the wrong terminology.  I looked up the structure of a truss, and pulled terminology from there.  Maybe this image helps?   https://imgur.com/a/5plbQ  The red dots are where the holes are.  This is in the attic of the rear wall of my home.
Comment: Trusses and walls are different, as noted by @ArchonOSX . (Doing that to a truss would be **really** bad.)  If this was my house, I wouldn't be delighted, but (as a working carpenter), I really wouldn't worry about it.
Answer: For those that say, "It's no big deal," THEY DO NOT UNDERSTAND THE PURPOSE of the double top plate...especially at the perimeter of the house.
If this occurs at the perimeter of your house, you have a problem, especially if you live in 1) high wind area, or 2) seismically active area.
Everyone has mentioned why it's not a problem because it's not a "truss". True, but that is for VERTICAL loads. A double top plate is used for many purposes. In your case, the double top plate is used to "tie" the perimeter of all the walls together at the top of the wall for LATERAL loads.
When a wind load or seismic load is placed on your house, the house wants to "bend" to withstand the force. By cutting through  the double top plate, they have eliminated the chord that resists this bending...we call this "the extreme fiber in bending" in a normal beam supporting a vertical load. That is why it's important to lap the double top plates a minimum of 4' and nail the crap out of the lap.
If your House is 1) one story, or 2)is not located in a high wind area, or 3) small and square and not rectangular, you have less to worry about. Otherwise, I'd have the clown return and fix it. Fixing it can be determined, calculated and detailed by a structural engineer (not a civil engineer) or by an architect with a structural background.
Btw, get a Building Permit.
Comment: The house is two stories and in Southern California -- very seismically active.  However, the area where they drilled is only one story -- i.e. they drilled in the attic above the one story portion of the home.  It's not square - there's a roughly 10' differential between the length and width of the house.  Unfortunately, I can't get these guys to come back to fix the issue.  They've said everything from 'the hole was already there' to 'we'll fill the hole with foam,' but I doubt I will be able to get anything out of them without a lawsuit.  There's nothing I can do DIY, it sounds like?
Comment: So, now it's a "DIY repair", right. Without doing a ton of calculations and knowing a lot more about your home, you'll need a "standard" splice repair....and all from the attic, right? (You don't want to do anything through the siding.)
Comment: Unfortunately, yes.  Because tearing open the stucco is another expense that, you guessed it, the electrician will not incur sans lawsuit.  Thing is, I don't even know how we'd go about a splice repair because the beam is totally inaccessible with that humongous conduit in the way.  Guess we could cut out a portion of the ceiling and sister it on the only accessible neutral face, but doesn't seem like it'd offer a lot of structural integrity. In your opinion, is this severe or potentially dangerous enough in the event of an earthquake to warrant a lawsuit?
Comment: I wouldn't go to court over this...it's too difficult to prove "damages". And the fix isn't that expensive. (Less than $500, I'd guess.) Can you get to about 48" on each side of both holes?
Comment: The top hole - yes, no problem.  The bottom hole... Not without cutting away the plywood and ceiling beneath the attic.  I'm not sure if you can tell from the top photograph, but the beam they cut through is completely flush with the plywood that holds up the ceiling and butts up against the insulation/exterior stucco.  I wonder... is there some kind of thin metal repair piece that will fit around the conduit and attach to the top face (the one they drilled through)? Or will we just have to cut through the ceiling to sister it?
Answer: Laura,  That does not look like a truss to me.  That looks like stick framing.  However I do tend to agree with you, the electrician would have done well to avoid the structural members.  On the other hand because this is stick framing and not a truss, it is not so critical.  The holes in the lower plate is no problem at all except for maybe the mice getting through.  I don't expect the upper roof rafter is in any danger.  It is well reinforced. The stresses on a rafter are not like the stresses on a truss.  You could sister the rafter if it made you feel better.
Comment: Agreed, the conduit should have been on the other side of the strut. Not only avoiding the framing but moving the roof penetration further into the roof thereby making it easier to seal. A small offset here would have been very judicious.


How to get hover effect to reset when cursor is outside canvas area?

Question: I'm trying to set up a hover effect where the image will follow the cursor inside the canvas, but when the mouse goes outside of the canvas area I would like the image to move back to its center position.
My canvas and image are fine:

 <canvas id="canvas" width="550px" height="550px" style="border: 2px solid red" class="paddingleft">

But I need to fix something in with the javascript/jquery so that it will do what I like:
var AN = AN || {};

var pic = new Image();
var canvas;
var context;

var x = 0;
var y = 0;

AN.initialize = function() {
  //load canvas
  canvas = $('#canvas');
  canvas.mousemove(AN.moveMouse);
  context = canvas[0].getContext('2d');
  //load image
  pic.src = "https://cdn.shopify.com/s/files/1/0539/9904/2739/files/smiley.png?v=1614313440";
};
pic.height = 400;
pic.width = 400;

AN.moveMouse = function (e) {
  var element = $(pic);
  var t = 0; //0-1, this is what you change in animation loop
  var position = getMousePosition(e);
  function myLoop() {
    context.clearRect(0, 0, canvas.width(), canvas.height());

    x += EasingFunctions.easeInOutQuad(t) * (position.x - x);
    y += EasingFunctions.easeInOutQuad(t) * (position.y - y);

    // set element by tx
    context.drawImage(pic, x, y, pic.width, pic.height);

    if (t < 1) {
      t += 0.01; //determines speed
      requestAnimationFrame(myLoop);
      //setTimeout(myLoop, 16); //option to above
    }
  }
  myLoop();
};

EasingFunctions = {
  linear: function(t) {
    return t;
  },
  easeInQuad: function(t) {
    return t * t;
  },
  easeOutQuad: function(t) {
    return t * (2 - t);
  },
  easeInOutQuad: function(t) {
    return t < .5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
  },
  easeInCubic: function(t) {
    return t * t * t;
  },
  easeOutCubic: function(t) {
    return (--t) * t * t + 1;
  },
  easeInOutCubic: function(t) {
    return t < .5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
  },
  easeInQuart: function(t) {
    return t * t * t * t;
  },
  easeOutQuart: function(t) {
    return 1 - (--t) * t * t * t;
  },
  easeInOutQuart: function(t) {
    return t < .5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t;
  },
  easeInQuint: function(t) {
    return t * t * t * t * t;
  },
  easeOutQuint: function(t) {
    return 1 + (--t) * t * t * t * t;
  },
  easeInOutQuint: function(t) {
    return t < .5 ? 16 * t * t * t * t * t : 1 + 16 * (--t) * t * t * t * t;
  }
}

function getMousePosition(e) {
    return {
        x: e.clientX - pic.width * 0.5,
        y: e.clientY - pic.height * 0.5
    }
}

$(document).ready(function() {
  //initialize funtion
  AN.initialize();
});

</canvas>

I'm not sure if anyone will be able to help me but if someone can I would appreciate it.
Here is my code pen for convience:
https://codepen.io/kyannashanice/pen/gOLymYe
Answer: Not sure if this is what you are looking for. As solution I just added a mouseOut function and recalculated the smiley position. You can optimize the code further

var AN = AN || {};
var pic = new Image();
var canvas;
var context;

var x = 0;
var y = 0;

AN.initialize = function() {
  //load canvas
  canvas = $('#canvas');
  canvas.mousemove(AN.moveMouse);
  canvas.mouseout(AN.mouseOut);
  context = canvas[0].getContext('2d');
  //load image
  pic.src = "https://cdn.shopify.com/s/files/1/0539/9904/2739/files/smiley.png?v=1614313440";
};
pic.height = 400;
pic.width = 400;

function calculatePosition(position) {
  var element = $(pic);
   var t = 0; //0-1, this is what you change in animation loop
  function myLoop() {
    context.clearRect(0, 0, canvas.width(), canvas.height());

    x += EasingFunctions.easeInOutQuad(t) * (position.x - x);
    y += EasingFunctions.easeInOutQuad(t) * (position.y - y);

    // set element by tx
    context.drawImage(pic, x, y, pic.width, pic.height);

    if (t < 1) {
      t += 0.01; //determines speed
      requestAnimationFrame(myLoop);
      //setTimeout(myLoop, 16); //option to above
    }
  }
  myLoop();
}

AN.mouseOut = function () {
   calculatePosition({x:80, y:80});
}

AN.moveMouse = function (e) {
  var position = getMousePosition(e);
  calculatePosition(position);
};

EasingFunctions = {
  linear: function(t) {
    return t;
  },
  easeInQuad: function(t) {
    return t * t;
  },
  easeOutQuad: function(t) {
    return t * (2 - t);
  },
  easeInOutQuad: function(t) {
    return t < .5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
  },
  easeInCubic: function(t) {
    return t * t * t;
  },
  easeOutCubic: function(t) {
    return (--t) * t * t + 1;
  },
  easeInOutCubic: function(t) {
    return t < .5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
  },
  easeInQuart: function(t) {
    return t * t * t * t;
  },
  easeOutQuart: function(t) {
    return 1 - (--t) * t * t * t;
  },
  easeInOutQuart: function(t) {
    return t < .5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t;
  },
  easeInQuint: function(t) {
    return t * t * t * t * t;
  },
  easeOutQuint: function(t) {
    return 1 + (--t) * t * t * t * t;
  },
  easeInOutQuint: function(t) {
    return t < .5 ? 16 * t * t * t * t * t : 1 + 16 * (--t) * t * t * t * t;
  }
}

function getMousePosition(e) {
    return {
        x: e.clientX - pic.width * 0.5,
        y: e.clientY - pic.height * 0.5
    }
}

$(document).ready(function() {
  //initialize funtion
  AN.initialize();
});

 <canvas id="canvas" width="550px" height="550px" style="border: 2px solid red" class="paddingleft">

</canvas>
Comment: @KyannaShanice I will check that out and let you know soon. Meanwhile, as we have an accepted answer, I'm not sure if you will get sufficient reach for your second question in case I couldn't do it. You can create it as a new question.
Comment: thank you for coming back and helping me! I figured it out actually with some help from reddit. I will link the completed codepen later today!
Comment: @KyannaShanice I have hardcoded the value of x and y as 80 as of now. you might need to recalculate(to bring it to the exact center) according to your requirement. Please do accept the answer if this helps
Comment: sorry about that - I have accepted the answer. Thank you for the heads up, I have another question, how would I make it so that the image is visible outside of the canvas? Like when it goes over the edge I would like to be able to see that. I'm trying to create an effect similar to the images that follow your cursor on this site (https://www.readthissummer.com/)
Comment: unfortunately i'm unable to ask questions for the next 4 days so I will have to try and post elsewhere, thank you for the advice though!
Comment: @KyannaShanice. I'm not that great at HTML canvas. But I was wondering why u need to move the image out of the canvas. I have referenced few articles and created a pen on this. https://codepen.io/vinu_pen/pen/wvoZOvg Hope this is what you are looking for.
Credit: https://www.digimantra.com/tutorials/drag-an-element-image-etc-using-javascript-html-css/


JSP compilation error with custom classloader

Question: I have a custom WebappClassLoader in tomcat (7.0.55) which is configured in the server.xml as
<Context allowCasualMultipartParsing="true">
    <Loader loaderClass="org.project.system.core.classloader.DynamicClassLoader" />
</Context>

It's is loaded and everything is fine, but when I open a JSP which loads a class org.test.User which isn't under WEB-INF/classes, but loadable via my DynamicClassLoader I get this error:
org.apache.jasper.JasperException: Unable to compile class for JSP:

An error occurred at line: 7 in the generated java file
Only a type can be imported. org.test.User resolves to a package

So, I did some debugging and was checking in each loadClass call if my class is loaded and yes: right before this error message I see my debug message:
Trying to load org.test.User found!
Trying to load org.test NOT FOUND!!
Trying to load org.test NOT FOUND!!
Trying to load org.apache.el.ExpressionFactoryImpl found!
Trying to load com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl found!
Trying to load com.sun.org.apache.xerces.internal.impl.dv.dtd.DTDDVFactoryImpl found!
Trying to load org.apache.el.ExpressionFactoryImpl found!
org.apache.jasper.JasperException: Unable to compile class for JSP:

An error occurred at line: 7 in the generated java file
Only a type can be imported. org.test.User resolves to a package

So it seems, that the jsp compiler asks for the User class. But the real weird thing is that if I execute it out of eclipse, everything is working! The output looks the same except for the error message, of course. I double checked the configuration files which are generated by eclipse and my ones but I saw no difference.
Do you have an idea what could be wrong? Why is it working without any error in eclipse but not in a "normal" tomcat installation? Please let me know if you need any further information! Thanks in advance!
Answer: The JSP compiler sometimes has a tough time dealing with items in the classpath that can be resolved to both a package (directory) and a class (.class file). If your classes are being loaded from a JAR file, try to remove the directory entry from the JAR file (but leave the .class file, of course).
If the directories and classes are on the disk, you might have to suck it up and re-name either the package or the directory.
The difference in Eclipse versus standalone might have to do with the different deployment descriptor that Eclipse uses. You might want to check out what Eclipse is doing... there might be a slightly different configuration or packaging strategy in play.
Comment: The names are like in the example "org.test.User", so there shouldn't be a problem with the naming, should it?
Comment: Do you also have `org.test.user.OtherClass`?
Comment: Yep, there are multiple classes in this package.
Comment: Think about a ZIP (JAR) archive: it's made up of directories and files, but the directories are optional. If you leave-out the directories, the entry `org.test.User` can only refer to a single thing: the class. If the directory (aka package in Java nomenclature) also exists then `org.test.User` (especially on case-insensitive filesystems) can refer to *either* the directory *or* the class. This ambiguity makes the compiler complain.


What happens if I downgrade libpython in 18.04?

Question: I just upgraded to ubuntu 18.04, and I'm not sure what happened, but vim doesn't work anymore. I tried sudo aptitude install vim and i get this:
$ sudo aptitude install vim
The following NEW packages will be installed:
  libpython3.6{ab} vim vim-runtime{a}
0 packages upgraded, 3 newly installed, 0 to remove and 4 not upgraded.
Need to get 8009 kB of archives. After unpacking 36,8 MB will be used.
The following packages have unmet dependencies:
 libpython3.6 : Depends: libpython3.6-stdlib (= 3.6.6-1~18.04) but 3.6.7-1+xenial1 is installed
open: 17; closed: 390; defer: 5; conflict: 7                                                                                .The following actions will resolve these dependencies:
 Keep the following packages at their current version:

1)     libpython3.6 [Not Installed]
2)     vim [Not Installed]
Does anyone know what to do without ruining my stuff?
Comment: You have added non-Canonical/non-Ubuntu sources to your system, and they used a versioning system that is now getting in the way.  The 'depends' shows 16.04 was using 3.6.5-3 meaning [bionic's] 3.6.6-1 is an upgrade, but because you installed a xenial intended version 3.6.7-1 via PPA or other which has a higher [numbered] version, your problem exists now due to it's version number (https://askubuntu.com/questions/1089620/what-happens-if-i-downgrade-libpython-in-18-04)   I'd suggest removing the problem libs/packages, and then installing the Ubuntu official release versions
Answer: This happens when you forget to use ppa-purge before upgrading.  It's annoying, but not a serious problem.  You have to identify all the Python 3.6 packages that did not come from the primary Ubuntu archive and reinstall the right versions.
One way of doing that is to use apt-show-versions:
sudo apt install apt-show-versions
sudo apt-show-versions -i    # rebuild index; only needed once

apt-show-versions|grep -v uptodate|grep -v not.installed

Then look for packages having python3.6 in the name.
Now the simpler option is to uninstall them all:
sudo apt remove --auto-remove libpython3.6-stdlib ...

Now you can proceed with sudo apt install vim (and reinstall any other packages you need that got removed when you removed the old PPA Python 3.6).
Comment: be VERY VERY careful when executing `sudo apt remove --auto-remove libpython3.6-stdlib` it locked me out of desktop and 600mb of packages were removed, mine was 3.8 instead of 3.6 and ubuntu 20


Laravel Get 'belongsTo' relation from 'hasMany' relation

Question: <code>class Post {
    function category() {
        $this->belongsTo('Category');
    }
}
class User {
    function posts() {
        $this->hasMany('Post');
    }

    function categories() {
        //???
        $this->posts->category;
    }
}
</code>
I have code that looks like this, and I'm wondering how I can access "categories" on the user object and have it return a Laravel relation.
None of the existing relation methods "hasManyThrough", etc seem to fit this use case.
Answer: Perhaps you can look at it the other way? Starting at the categories and filtering by user:
<code>$userCategories = Category::whereHas('posts' function($query){
    $query->where('user_id', $userId);
})->get();
</code>
This will grab all categories where a user has made a post to.
Answer: An other solution :
<code>//user model
public function getCategoriesAttribute()
{
    return $this->posts->lists('category')->unique();
}
</code>
To limit queries you can change posts relationship
<code>//user model
function posts() {
    $this->hasMany('Post')->with('category');
}
</code>
source : http://softonsofa.com/laravel-querying-any-level-far-relations-with-simple-trick/


Spring MVC + FreeMarker: How to render option tag?

Question: The Spring 3 MVC docs state that option tags can be rendered like this:

      Country:

          <form:select path="country">
              <form:options items="${countryList}" itemValue="code" itemLabel="name"/>
          </form:select>

I am using FreeMarker with Spring MVC, so I interpret this as:

    Place:

        <@form.select path="place">
            <@form.options items="${places}" itemValue="id" itemLabel="name"/>

        </@form.select>

When I hit the page I get the following exception:
freemarker.core.NonStringException: Error on line 40, column 73 in event.ftl
Expecting a string, date or number here, Expression places is instead a freemarker.template.SimpleSequence

What should I use instead of ${places} in my FreeMarker template so that the above works?
Thanks.
Answer: I was looking for exactly the same thing. I've no idea why this isn't included in Spring's Freemarker macro library, but fortunately enough it's quite easy to implement: Best practice would be to start your own macro library (say mylib.ftl for example) and put the macro there:
<#macro selectOptions path options key value>
  <@spring.bind path/>
  <select id="${spring.status.expression}" name="${spring.status.expression}">
    <#list options as option>
      <option value="${option[key]?html}"<@spring.checkSelected option[key]/>>${option[value]?html}</option>
    </#list>
  </select>
</#macro>

You can then use your new macro in your Freemarker template like so:
<#import "/mylib.ftl" as mylib />
...
<@mylib.selectOptions "country" countryList "code" "name" />

HTH
Answer: You could try the following (not tested personally)
<@form.select path="place">
    <#list Request.places as place>
       <@form.option value="${place}" label="name" />
    </#list>
</@form.select>

Hope this helps!
Answer: a little bit weird but it works.

remove ${"places"} and use it straigh as places
remove the itemid and let spring handle it for you

so you will have
<@form.select path="place">
   <@form.options items=places itemLabel="name"/>

</@form.select>


Breaker being tripped - Oven or wiring?

Question: Recently, our oven was left on all day, and sometime during the day it tripped the breaker.
Now, whenever the oven is used (only for heating pizza, so 10-15 minute timeframe), the breaker trips during the preheat phase. If I reset the breaker, the oven functions normally.
Is this more likely to be a wiring problem, or an oven problem? Is there any danger in using the oven after resetting the breaker?
Clarification - The stove top (ceramic elementless) works fine. It also functioned normally previous to it being left on for an extended period. The home was built in the late 90's, and while the stove is a newer model, it was there when we purchased the home in 2010, so I do not know the provenance.
It is only when the oven is used that the breaker trips. I will have it checked, however.
Answer: Stop and get things checked out!!!
The breaker is there as a safety protection device - not as a minor inconvenience. If the breaker is tripping there is an overload or short circuit some place that needs to be addressed. Electrical safety issues are nothing to mess around with. You could get severely shocked or killed as a result of an electrical fault. Call in a qualified electrician today to evaluate the situation and help with the proper fix.
The problem could be any one of the following:

oven
oven power plug
wiring feeding power to the oven
circuit breaker in the main junction box
Answer: The problem could be either the oven or the wiring. The oven could be using more amperage than the circuit breaker is rated for, and thus tripping the breaker. Or, the problem could be with the wiring (for example, damaged insulation causing unwanted current in the wire), or the circuit breaker could be failing.
Standard circuit breakers are designed with a certain amerage-time trip-curve. For example, a 30 A breaker should never trip while it flows 30 A, and at twice the rated current (60 A), could trip after as long as a minute. It may trip within a second only for ten times the rated current.... This is the expected behavior, and does not indicate a malfunction. For an example curve, see this Siemens document. Your oven could be using more than the rated current when on, but since it is only continuously on during warmup, it would only trip the breaker during the preheat stage.
Newer installations could have special types of breakers, such as GFCI or AFCI. But, this would be unlikely for a dedicated appliance circuit.  Loose connection could cause series-arcing, but this shouldn't trip a standard circuit breaker (it would reduce the average power being used). If the appliance was connected to an AFCI breaker, the breaker could be detecting the arc and tripping.
In any case, correct the problem soon. The circuit breaker is likely not designed to be used as a switch, it has a limited number of trips during its lifetime. Also, the fact that it is tripping signals that something is wrong (and probably overheating), and likely unsafe (possibly causing a fire).
Electricity is dangerous, and you should only attempt repair if you are comfortable around electricity and know the proper safety precautions. working in the circuit breaker panel is especially dangerous, and you should wear a face shield and other protective equipment, in case there is an arc, or a circuit breaker explodes.
My gut feeling is that the breaker is likely failing, and should be replaced. I think this because ovens will usually "fail open" causing their current to go to zero, not increase their power used. Also, running the oven all day would put additional stress on the breaker. The oven is likely powered with 240 V split phase electricity (common in the United States). In this case, it would have two "hot" wires, one "neutral", and one ground.
I would go about troubleshooting with the following steps:

Verify the breaker is of the correct rating. Examine the information plate on the back of the oven for the maximum current that it requires. Ensure that the circuit breaker is rated for that same amount of current, or the next higher standard amperage. The standard breaker sizes include 15, 20, 25, 30, 35, 40, 45, 50, 60, 70, 80, 90, 100, 110 A, et al. Read the NEC codebook for details on which breakers you are allowed to use. If your circuit breaker is undersized, then verify that the wiring and plug is sufficiently large to support the needed current, and make the necessary corrections to the setup.
Measure the actual current going to the oven. In the circuit breaker panel, attach a clamp-type ampmeter to one of the hot wires going to the oven, and measure its current while the oven is turned off and also during the preheat. The current while it is off should be near zero, and the current when it is on should be less than the oven's maximum current. Repeat this with the other hot wire.
If the preheat current is less than the rating of the circuit breaker, the circuit breaker is faulty.
If the current while the oven is off is significant (>0.3 A), then either the wire to the oven is bad, or the oven is damaged. Unplug the oven, and check if the current goes to zero. If it doesn't then you have wiring issues in your home.
If the off-current is near zero, and the preheat current is more than your oven is supposed to use, then your oven needs repairs.
Comment: Thank you for the detailed answer. I would add that the oven worked completely normally before this point, it is only since the oven was left on for an extended period that it has evidenced this problem.
Comment: Yes, I saw that you mentioned that. Leaving it on for a long time can certainly stress a circuit breaker and cause it to fail. In my experience failing heating elements use less and less power (and soon after fail quite catastrophically), which wouldn't cause the breaker to trip.
Answer: Final resolution:
Father in law came over and we did all the measurements above, starting from the oven outward. As it turns out, we could have saved time by starting at the panel first. However.
At the panel, the oven and the air conditioning unit are both being run off of aluminum wiring instead of copper. As was explained to me, the disadvantage is that aluminum expands and contracts, and can eventually loosen the fastening screws. He also told me that the breaker is heat related, i.e., if the breaker gets too hot, it trips.
The screws on the wiring had loosened, and had a reduced contact point. This caused more current to go through a smaller area, which increased the heat, which caused the breaker to trip. Tightened up all the screws, and fixed the problem.
I won't accept my own answer, as all the others contributed, I just wanted the answer here for archive/future research purposes.
Comment: Aluminum wiring is tricky stuff. You have got make sure that everything connected to it is specifically rated to use it (most large breakers are, but not all) and it's generally also a good idea to use anti-oxidant paste (made for the purpose, found in the electrical section as you'd expect) on the connections as well.
Comment: @Ecnerwal - Yeah, he explained about the paste, and seemed to feel that what was on there was enough, and didn't need to augment. Thanks, forgot to add that in.
Answer: A simple test will determine whether the source of the problem is the oven or the wiring.  If it is wiring, the most likely cause is the circuit breaker itself.
A clamp on ammeter like this placed around one of the wires in the breaker box will instantly read how much current is flowing through the wire.  (It works by magnetic coupling, so it is safe to touch and does not harm the wire.)  Note that clamping around a wire pair (such as a cord) will normally read zero.  That is, the power source wire must be separate from the return (neutral) wire for the ammeter to work.  The easiest access to this for an oven or any other household circuit is inside the breaker panel—easily opened by undoing 6 or so screws.
Clamp on the ammeter to one oven "hot" wire and turn on the oven.  Observe it for a minute or so—as the oven element heats up, it should change resistance and therefore the current, starting out high and decreasing as it heats.  If the current is well over the breaker value (that is, for a 40 amp breaker, 50 amps would be "well over"), the oven is defective—or maybe a mismatch for the circuit.  Check the oven rating tag (probably on the back) or the manufacturer's website.  The other over wire should read almost exactly the same current.
If the current is well within range (for example, 25 actual out of 40 rated) and the circuit breaker trips, replace the circuit breaker:  it is fatigued and ready for the great circuit breaker yard in the sky.

Breaker being tripped - Oven or wiring?


Kubernetes error syncing pod

Question: I installed Kubernetes, but in the creation of pod reported a mistake, I do not know where the problem is, I hope you can help me
I use centos7, use yum to install Kubernetes.
[root@k8s-master ~]# rpm -qa |grep -i kube
kubernetes-master-1.2.0-0.11.git738b760.el7.x86_64
kubernetes-client-1.2.0-0.11.git738b760.el7.x86_64

[root@k8s-master ~]# kubectl run   my-nginx01 --image=192.168.10.58:5002/test111/nginx  --port=80
deployment "my-nginx01" created

[root@k8s-master ~]# kubectl get pods
NAME                          READY     STATUS              RESTARTS   AGE
my-nginx01-3752101197-v34jm   0/1       ContainerCreating   0          3s

[root@k8s-master ~]# kubectl describe pod my-nginx01-3752101197-v34jm

Events:
  FirstSeen LastSeen    Count   From            SubobjectPath           Type        Reason          Message
  --------- --------    -----   ----            -------------           --------    ------          -------
  22s       22s     1   {default-scheduler }                    Normal      Scheduled       Successfully assigned my-nginx01-3752101197-v34jm to 192.168.6.133
  20s       20s     1   {kubelet 192.168.6.133} spec.containers{my-nginx01} Normal      Started         Started container with docker id 3e18486078c2
  20s       20s     1   {kubelet 192.168.6.133} spec.containers{my-nginx01} Normal      Created         Created container with docker id 3e18486078c2
  21s       17s     2   {kubelet 192.168.6.133} spec.containers{my-nginx01} Normal      Pulling         pulling image "192.168.10.58:5002/test111/nginx"
  20s       16s     2   {kubelet 192.168.6.133} spec.containers{my-nginx01} Normal      Pulled          Successfully pulled image "192.168.10.58:5002/test111/nginx"
  22s       16s     3   {kubelet 192.168.6.133}                 Warning     MissingClusterDNS   kubelet does not have ClusterDNS IP configured and cannot create Pod using "ClusterFirst" policy. Falling back to DNSDefault policy.
  16s       16s     1   {kubelet 192.168.6.133} spec.containers{my-nginx01} Normal      Created         Created container with docker id 0c5c9fdd19ca
  15s       15s     1   {kubelet 192.168.6.133} spec.containers{my-nginx01} Normal      Started         Started container with docker id 0c5c9fdd19ca
  11s       11s     1   {kubelet 192.168.6.133}                 Warning     FailedSync      **Error syncing pod, skipping: failed to "StartContainer" for "my-nginx01" with CrashLoopBackOff: "Back-off 10s restarting failed container=my-nginx01 pod=my-nginx01-3752101197-v34jm_default(b4f373b3-20c3-11e6-81d6-000c294bd99a)"**

  11s   11s 1   {kubelet 192.168.6.133} spec.containers{my-nginx01} Warning BackOff Back-off restarting failed docker container

Comment: Do the logs say anything? `kubectl logs -f my-nginx01-3752101197-v34jm`
Comment: `CrashLoopBackoff` is usually indicative of an application error, so your answer lies in the logs of that container.
Comment: > Possible duplicated with [https://stackoverflow.com/questions/49974003/i-got-pod-errors-crashloopbackoff-from-kubernetes/50389881#50389881]
Answer: The issue caused by the docker container which exits as soon as the "start" process finishes. Add a command that runs forever and probably it'll work. For example, recreating docker image:
#Dockerfile
[...]
CMD exec /bin/bash -c "trap : TERM INT; sleep infinity & wait"

Kubernetes error syncing pod


Converting JSON array into java List with Spring MVC

Question: I have a list of string in my javascript code which I send via JQuery to a REST based service as follows:
var ids = [];
$("input:checked").each(function() {
    ids.push(this.id);
});
var selectedIds = JSON.stringify(ids);
$.post("/todonotes/tasks/removeTask", selectedIds,function(e) {
}, "json");

As you can see, I convert a javascript array into a JSON array.
Now, in the server side, I use Spring MVC and Jackson to receive and parse the input JSON:
@RequestMapping(value="/tasks/removeTask", method = RequestMethod.POST)
public @ResponseBody String removeTask(@RequestBody List<String> selectedIds) {
    ...
}

But I always get:
HTTP Status 415 -

--------------------------------------------------------------------------------

type Status report message

description The server refused this request because the request entity is in a format     not supported by the requested resource for the requested method.

I tried to remove the quotes from the JSON object, and also tried using @RequestParam without success.
Update as per OQJF suggestion:
I modified my post request as follows:
$.post("/todonotes/tasks/removeTask", {selectedIds: selectedIds},function(e) {
}, "json");

Now my controller method gets called, but each List element is populated with the double quotes and brackets. This the List argument:
[["15", "21"]]

So e.g. the first element looks like:
["15"

I would prefer not to parse each String element of the List.
I also tried removing the JSON.stringify conversion but my controller didn't even get called. With this I got:
HTTP Status 400 - Required List parameter 'selectedIds' is not present

--------------------------------------------------------------------------------

type Status report

message Required List parameter 'selectedIds' is not present

description The request sent by the client was syntactically incorrect.

Update
I tried to create an object to hold my ids, as follows:
public class TaskIdHolder {

    private String[] selectedIds;

    public String[] getSelectedIds() {
        return selectedIds;
    }

    public void setSelectedIds(String[] selectedIds) {
        this.selectedIds = selectedIds;
    }
}

Then I modified my controller method signature:
public @ResponseBody String removeTask(@RequestBody TaskIdHolder selectedIds) {

And my JSON request looks like this:
{"selectedIds":["15"]}

I also modified my Jquery code as per Andrei's suggestion:
var data = JSON.stringify({selectedIds:selectedIds});
$.post("/todonotes/tasks/removeTask", data, function(e) {

Where selectedIds is a JavaScript array.
But now I get:
POST http://localhost:8080/todonotes/tasks/removeTask 415 (Unsupported Media Type)

Comment: may be http://stackoverflow.com/questions/11492325/post-json-fails-with-415-unsupported-media-type-spring-3-mvc can help you with updated question.
Comment: One of the solutions in this post has worked for me. Thanks.
Answer: As I know that you don't need to use JSON.stringify(), your code can be like this:
var ids = [];
$("input:checked").each(function() {
    ids.push(this.id);
});

$.post("/todonotes/tasks/removeTask", $.param({'id': ids}, true),function(e) {
}, "json");

And on the server side, you should specify the value of:
public methodName(@RequestParam("id") List<String> selectedIds)

Answer: Try the following, no need to change your controller's method signature or create an object to hold your ids.
$.post("/todonotes/tasks/removeTask", {selectedIds: selectedIds.join(',')},function(e) {
}, "json");

That way you'll be sending your ids like selectedIds: id1,id2,id3 which is how the Controller is expecting them to be if you declare your request param to be String[] or List<String> (works for both scenarios).
Answer: Try giving the the request parameter an explicit name:
$.post("/todonotes/tasks/removeTask", {selectedIds: selectedIds},...

Update. You can also try to stringify the whole request data object to JSON:
var data = {selectedIds: selectedIds};
$.post("/todonotes/tasks/removeTask", JSON.stringify(data),...

Comment: Thanks. Got some progress. I still have some issues with the List argument. Please see my question updated.
Comment: @GonzaloGarciaLasurtegui, please have a look at the updated answer - this should help.
Comment: I tried this with @RequestBody annotation. Please see a new update in my question.


Is there a good way how to combine two contact forms in one?

Question: So insurance company customers have an access to their services through log in. One of the services is ability to ask questions to doctors/nurses and receive support from them.
Currently there are 2 forms actually: one is e-mail query, second is request a call back. Two types of how to get support from the service.
So the question is: what do you guys advise to do - to have 2 separate forms one after another or to combine it in one form? If you advise me to combine them, what is the smart way to do it?
Answer: I think this starts with: what is your intended support path for customers?
There are several different possible rationales that I can think of for having two contact methods:

Catering to customer preference - the two are basically equivalent, and the customer can choose whichever they like (and once choosing one they are unlikely to switch to the other contact mode).
Different methods based on urgency - phone calls are for more urgent query
Email as preferred mode, with phone calls as a fall-back. - If the email is not able to answer a customer's question, speaking on the phone can solve the issue.

Another issue here is: Do you need to capture the same information in each case?
For an email enquiry, you need to get all of the information up front to answer the question, but a phone conversation allows more information to be obtained on the phone.  So it may imply different forms are needed.
I think if you clarify the support path and the information requirements, what to do about the forms should become clear.
Ultimately, whether one form or two exists on the website is irrelevant to the user, but the user should be presented with a clear path and options to get needed support; there shouldn't be multiple paths that make it unclear which one should be selected.
Answer: I think it would be a better experience to have one form but ask the customer to choose their preferred method of contact, like so:

Allow the customer to provide a description of their issue and below it, ask them to pick their preferred method of contact.


How to compute quotient rings?

Question: I am discovering class numbers and ideal class groups. Going through Wikipedia, the example $\mathbb{Z}[\sqrt{-5}]$ is considered along with the ideal $J=(1+\sqrt{-5}, 2)$. Two facts are troubling me (I might haven't understood that well ideals and quotients):

$\mathbb{Z}[\sqrt{-5}]/(1+\sqrt{-5}) \simeq \mathbb{Z}/6\mathbb{Z}$
$\mathbb{Z}[\sqrt{-5}]/J \simeq \mathbb{Z}/2\mathbb{Z}$

For the first one, I have no idea of how such computations are handled. For the second, I would say that the quotient of $Z/6$ by $Z/2$ is $Z/3$, isn't it?
This is an instance of the more general question I have in mind: how do one generally compute a quotient ring? Is there any standard manner to do so? (at least for well presented rings or groups)
Thanks for any comment and help.
Comment: "Is there any standard manner to do so?" Not really. You try a bunch of different simplifications until you can make one work.
Answer: For the first question: $(1 + \sqrt{-5}) (1-\sqrt{-5}) = 6$ and $(1 + \sqrt{-5})\sqrt{-5} = \sqrt{-5}-5$. In particular, in the quotient all the classes are represented by integers (because $[\sqrt{-5}]=[5]$) included between $0$ and $5$ (because $[6]=[0]$). Your ring could still be isomorphic to a proper quotient of $\mathbb{Z}/6\mathbb{Z}$, but somehow you can check that the positive integers smaller than $6$ are not sent to $0$ (because they are not multiples of $1+\sqrt{-5}$). The second case is similar, but also $2$ is sent to $0$, hence you get a quotient of $\mathbb{Z} / 2 \mathbb{Z}$ and again you can somehow check that at least $1$ is not sent to $0$ (i.e., it is not a linear combination of $1+\sqrt{-5}$ and $2$) (Wikipedia proves that $J$ is not principal, so in particular it is not $(1)$).
The intuition you mentioned is wrong. We are applying the Third isomorphism theorem for rings, which says that
$$ (\mathbb{Z} / 6\mathbb{Z}) / ( 2\mathbb{Z} / 6\mathbb{Z} ) \cong \mathbb{Z} / 2\mathbb{Z}.$$
Answer: First of all,
Claim: $\;a+b\sqrt{-5}\in\langle 1+\sqrt{-5}\rangle\iff 6\,\mid\,(a-b)\;$ in $\;\Bbb Z\;$
Proof: We have that $\;a+b\sqrt{-5}\in\langle1+\sqrt{-5}\rangle\;$ iff
$$a+b\sqrt{-5}=(r+s\sqrt{-5})(1+\sqrt{-5})=r-5s+(r+s)\sqrt{-4}\iff$$
$$\begin{cases}a=r-5s\\{}\\b=r+s\end{cases}\iff6s=b-a\;$$
since this already gives $\;6\,\mid\,b-a\;$ , but then also $\;5b+a=6b-(b-a)=0\pmod6\;$ , thus
$$a+5b=r-5s+5r+5s=6r\implies 6\,\mid\,(a+5b)\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\square$$$${}$$
For example, $\;-5+7\sqrt{-5}\in\langle 1+\sqrt{5}\rangle\;$ because $\;7-(-5)=12=0\pmod6\;$ , and indeed:
$$-5+7\sqrt{-5}=(5+2\sqrt{-5})(1+\sqrt{-5})$$
or
$$2+8\sqrt{-5}=(7+\sqrt{-5})(1+\sqrt{-5})$$
Then, we can define
$$\phi:\Bbb Z[\sqrt{-5}]\to\Bbb Z/6\Bbb Z\;,\;\;\phi(a+b\sqrt{-5}):=(a-b)\pmod6$$
Prove this is a ring epimorphism (the multiplicative part is easy but not trivial. One has to be careful there) whose kernel is precisely $\;\langle 1+\sqrt{-5}\rangle\;$ , and now apply the first isomorphism theorem.
The second part follows, as already mentioned in the other answer, from the third (or second or something) isomorphism theorem, since
$$\Bbb Z[\sqrt{-5}]/J=\Bbb Z[\sqrt{-5}]/\langle\,1+\sqrt{-5},\,2\,\rangle \cong$$
$$\cong\left[\Bbb Z[\sqrt{-5}]/\langle1+\sqrt{-5}\rangle\right]\big/\left[\langle1+\sqrt{-5},\,2\rangle/\langle1+\sqrt{-5}\rangle\right]\cong\left(\Bbb Z/6\Bbb Z\right)\big/\left(2\Bbb Z/6\Bbb Z\right)\cong\Bbb Z/2\Bbb Z$$
because we in fact have (by the second isomorphism theorem:$\;\left(M+N\right)/M\cong N/(M\cap N)\;$
$$\langle1+\sqrt{-5},\,2\rangle/\langle1+\sqrt{-5}\rangle\cong\langle2\rangle/\left(\langle 2\rangle\cap\langle1+\sqrt{-5}\rangle\right)$$
But $\;\langle 2\rangle\cap\langle1+\sqrt{-5}\rangle=\left\{\,a+b\sqrt{-5}\;/\;a-b=0\pmod 3\,\right\}\cong\Bbb Z/3\Bbb Z\;$ and etc.

How to compute quotient rings?


why it is throw error as NullPointerException when I using Parcelable for my project in Kotlin?

Question: I have small chat app and I try to use the Parcelable for my project, there is not any error until debug the project. When I debug the project it is throw an error for

setInfo(chat)
return participants.find { it.id != userId }!!.profilePicture

as NullPointerException, I do not know why? Any idea?
ChatActivity:
   val chat = intent.extras!!.getParcelable<Chat>("chat")!!

        setInfo(chat)
        configureRecycler(chat.messages)

    private fun configureRecycler(messages: ArrayList<Message>) {
        val user = userPresenter.getUser()
        val messagesAdapter = MessagesAdapter(user.id, messages)

        recycler_chat.apply {
            setHasFixedSize(true)
            layoutManager = LinearLayoutManager(context)
            adapter = messagesAdapter
        }
    }

User:
import android.os.Parcelable;
import kotlinx.android.parcel.Parcelize

  @Parcelize
  class User(
    val username: String?,
    val profilePicture: String?
): BaseModel(), Parcelable {
    constructor() : this("", "",)
}

Chat:
import android.os.Parcelable;
import kotlinx.android.parcel.Parcelize
@Parcelize
class Chat(

    val participantsId: ArrayList<String>,

): BaseModel(), Parcelable {

    var participants = ArrayList<User>()
    val messages = ArrayList<Message>()

    fun getProfilePicture(userId: String): String? {
        return participants.find { it.id != userId }!!.profilePicture
    }

    fun getChatName(userId: String): String? {
        return participants.find { it.id != userId }!!.username

    }

  }

Message:
import android.os.Parcelable;
import kotlinx.android.parcel.Parcelize
@Parcelize
class Message(
    val ownerId: String,
    val owner: User?
): BaseModel(), Parcelable {
    val status: MessageStatus = MessageStatus.CREATED

}

Comment: `participants.find { it.id != userId }` can be null if `participants` size is only 1 and that one item is that userId.  How are you so sure that `participants.size>1` always ? you need to check for these edge cases . Log the `participants` list data when you get the exception . Even during debugging you can evaluate the expression and find out why its null .
Comment: @ADM, understand , tnx so much
Answer: The issue is not in Parcelable. Check twice if you are passing the chat parcelable object correctly or not. For some reason, chat is not being passed from the previous activity. You can avoid the error by using safe call operator.
val chat: Chat? = intent.extras?.getParcelable<Chat>("chat")

chat?.let{ it->
    setInfo(it)
    configureRecycler(it.messages)
}

private fun configureRecycler(messages: ArrayList<Message>) {
val user = userPresenter.getUser()
val messagesAdapter = MessagesAdapter(user.id, messages)

recycler_chat.apply {
        setHasFixedSize(true)
        layoutManager = LinearLayoutManager(context)
        adapter = messagesAdapter
    }
}

Comment: I understand now tnx :)


PVC conduit, service line with siding offset

Question: I am updating our service line and moving it to another part of our home, as per request of the energy supplier.  I have installed the new panel and meter socket. However I am unsure how to run the pvc conduit up the side of our home.
The house has an offset line in the siding of three inches in between the first and second story.  Should I cu a groove in the siding on the second story, or use offset fittings?  Or is there another solution?
Comment: Hello, and welcome to Stack Exchange. Where in the world are you located?
Answer: My first choice: Use standoffs to keep the line clear of the house by enough distance to clear the bump, with straight conduit.
Second choice: Given it's PVC either rent a blanket heater or get creative with boiling water and bend yourself a section (rather like an inchworm) that fits around the bump. Make it rather gentle/sweeping so that it's not too much trouble to get wires through it. You could cobble something with 15 or 22 degree bends and couplings, but PVC is easy enough to bend with heat, and a straight stick that you bend is a lot cheaper than a bunch of pre-bent sweeps and couplings - it's also smoother inside.
Answer: I would recommend EMT. It will look nicer longer.  I wouldn't cut the house; bad on many fronts.  I would use EMT 22.5* factory bends. Three should work.  You may need to lay it over a bit. This will keep the pipe close to the building; the best look.


How to check array values using IN operator?

Question: I have a table where each cell in columns has an array list.
          COL1              COL2
row1: ('hi','hello')    ('hi','hello')
row2: ('hihi','below')    ('pi','by')

I am trying to use an in operator on such data but my query is not returning anything.
Query: select * from table where col1 in ('hi')

Also, if I have another table (table2) that looks like this:
col3
____
'hi'
'bye'
'guy'

and I want to use the same concept where I'll be checking if 'hi','bye','guy' from col3 exists in col1 row1
My Query: select * from table2 where col3 in (select col1 from table1);

Comment: There is no such thing as "an array within a cell" in databases. Each cell contains a single piece of data.
Comment: If you are using a database that has a concept of arrays, it's non-standard. So please do as the [tag:sql] tag already asked you to do and add a tag identifying which database product you're actually working with.
Comment: `in` works on a *relational set of rows* - it does not parse strings. You should tag the RDBMS you are using.
Comment: If this is postgresql have a look at [array functions and operators](https://www.postgresql.org/docs/current/functions-array.html).
Answer: The first argument is the "inside" one, the second one is the group of values.
You are comparing col1 (a tuple of 2 values) to a unique value:
I think that could help you: col1[0] -> gets the first value
select * from table where col1[0] in ('hi')

Whether you want to compare both, you can use:
select * from table where col1[0] in ('hi') or col1[1] in ('hi')

Comment: Can you please look at my updated question? is my 2nd query valid?
Comment: @LalaLand Yes, I suppose so! Col3 has unique values and 'select col1 from table1' will return a list of tuples.


The kernel of the localization map

Question: Let $A$ be a commutative ring with $1$ and let $S\subset A$ be a multiplicative set such that $1\in A$.
In the usual construction of the localization $S^{-1}A$, we have
$$\ker{l}=\{a\in A:\exists s\in S(sa=0)\},$$
where $l\colon A\to S^{-1}A$ maps $a\in A$ to $\frac{a}{1}\in S^{-1}A$, essentially because $S^{-1}A=A\times S/\sim$, where $(a,s)\sim (b,t)$ iff there exists $u\in S$ such that $u(at-bs)=0$.
Is it possible to prove the above equality just from the universal property of $l\colon A\to S^{-1}A$ without recurring to any particular construction of $S^{-1}A$?
The fact that $l(s)\in S^{-1}A$ is invertible for all $s\in S$ implies $\{a\in A:\exists s\in S(sa=0)\}\subset\ker{l}$. The problem is the reverse inclusion.
Answer: You can't really prove a negative like this, but I feel like the answer has to be basically no.  In order to use the universal property, you have to actually have an example of a ring-homomorphism $f:A\to B$ that sends every element of $S$ to a unit.  In particular, if you want to restrict the kernel of $l$, you would need to give, for each $a\in A$ that does not annihilate any element of $S$, some particular ring-homomorphism $f:A\to B$ such that $f(a)\neq 0$ and $f(s)$ is a unit for each $s\in S$.
So no matter what, in order to use the universal property, you need to construct some particular rings $B$.  You technically don't have to choose $B$ to be the localization itself, but it is hard for me to imagine any choice of $B$ that would be more natural, or how you could construct such a $B$ in full generality without doing basically the same work you have to do to construct the localization.

The kernel of the localization map


Check to see if a MongoDB collection is capped with the .NET 2.0 driver

Question: With the now legacy .NET MongoDB driver I used to use the following to create a capped collection if it didn't already exist (not bulletproof, but it stopped us accidentally using uncapped collections on several occasions):
private MongoCollection GetCappedCollection(string collectionName, long maxSize)
{
    if (!this.database.CollectionExists(collectionName))
        CreateCollection(collectionName, maxSize);

    MongoCollection<BsonDocument> cappedCollection = this.database.GetCollection(collectionName);
    if (!cappedCollection.IsCapped())
        throw new MongoException(
            string.Format("A capped collection is required but the \"{0}\" collection is not capped.", collectionName));

    return cappedCollection;
}

private void CreateCappedCollection(string collectionName, long maxSize)
{
    this.database.CreateCollection(collectionName,
                                   CollectionOptions
                                      .SetCapped(true)
                                      .SetMaxSize(maxSize));
}

How can I do the same with the new 2.0 version of the .NET MongoDB driver? Ideally I'd like to keep the same behavior as above but it would be good enough to throw the exception. While it's possible to create a capped collection using CreateCollectionAsync it doesn't seem possible to check to see if an existing collection is capped.
The shell has db.collection.isCapped() but there is no equivalent that I can find in the .NET API. Another approach would be to get the stats for a collection and check for the capped flag, but I can't see how to do that either.
Comment: The shell should give you pointers here. Run `db.collection.stats` without the closing brackets `()` and you will see how this "JavaScript" function is implemented there. Basically you a are calling `db.runCommand({ "colStats": "collectionName" })` which returns an object of which has a property `capped` as a Boolean value for you to inspect. All drivers support a "dbcommand" method somewhere, as this is the basis of all operations sent to the MongoDB server.
Answer: Yes, There isn't isCapped in MongoDB.Driver 2.0. But you can get it from collection stats
public async Task<bool> IsCollectionCapped(string collectionName)
{
    var command = new BsonDocumentCommand<BsonDocument>(new BsonDocument
    {
        {"collstats", collectionName}
    });

    var stats = await GetDatabase().RunCommandAsync(command);
    return stats["capped"].AsBoolean;
}


"Incompatible pointer to integer conversion" when using blocks

Question: i´m getting these warnings for my code below.
Any ideas how to fix that?
Thanks for any help.

Type specifier missing, defaults to 'int'
Incompatible pointer to integer conversion initializing 'int' with an expression of type 'void *';
Unused variable 'mymoviePlayerController'

The important line is the "__block mymoviePlayerController = nil;
- (void) moviePlaybackCompleteLightBox:(NSNotification*) notification {

        MPMoviePlayerController *mymoviePlayerController = [notification object];
        [[NSNotificationCenter defaultCenter] removeObserver:self
                                                        name:MPMoviePlayerPlaybackDidFinishNotification
                                                      object:mymoviePlayerController];

        // movie fadein transition ====================
        self.moviePlayerController.view.alpha = 1;

        [UIView animateWithDuration:0.3f delay:0.0 options:UIViewAnimationCurveEaseOut
                         animations:^{
                             self.moviePlayerController.view.alpha = 0;
                         }
                         completion:^(BOOL finished) {
                             [mymoviePlayerController stop];
                             [mymoviePlayerController.view removeFromSuperview];
                             __block mymoviePlayerController = nil;

                         }];

    }

Comment: If you are using ARC then you do not need to write this line. [removefromSuperview] does that.
Comment: have you declared "mymoviePlayerController" in your .h file also?? i mean both locally and globally??
Comment: Also specify the line where you are getting the first and second warning
Comment: "The important line is the "__block mymoviePlayerController = nil;" This throws the warning.
Answer: __block is used when you declare variable, not when you assign value to it. So compiler treats the following line as variable declaration, which is wrong:
 __block mymoviePlayerController = nil;

You should use __block attribute when declare variable:
__block MPMoviePlayerController *mymoviePlayerController = [notification object];

P.S. Why do you use __block here anyway? It looks you don't need it in this situation
Answer: First, you don't have to set the mymoviePlayerController variable to nil, if you don' use it afterwards. Just don't worry about it, removing the controller's view from its superview is enough.
Second, you can't make a variable writable using the __block qualifier inside of a block. You'll have to modify your code to make the variable writable outside of the block:
__block MPMoviePlayerController *blockMoviePlayerController = mymoviePlayerController;
[UIView animate...animations:...complection:^(BOOL finished) {
    blockMoviePlayerController = nil; // or something else
}];

Comment: Thanks to Vladimir and Fabian for their help. Good to know. It fixes the problem. Thanks for your fast reply. Have a nice day.


{Firebase-javascript} How to query data from two path of realtime database

Question: I want to query data from two path reference. Here is my database structure

The data that I want are sum_powder from date of 2-3 (reference are "History/Sum/2021/6/2" and "History/Sum/2021/6/3") and included data in one array but I try this code my data is null. What should I do? Thank you for your help.
var path1 = firebase.database().ref().child("History/Sum/2021/6/2")
var path2 = firebase.database().ref().child("History/Sum/2021/6/3")

path1.on('child_added', snap => {
    path2.child(snap.val().timestamp).once('value', data => {
        console.log("join : ",data.val())
    })
})

Answer: Try running both the promises in a Promise.all():
var path1 = firebase.database().ref().child("History/Sum/2021/6/1").once("value")
var path2 = firebase.database().ref().child("History/Sum/2021/6/2").once("value")

Promise.all([path1, path2]).then((response) => {
  const [path1Snap, path2Snap] = response

  //Logging the values
  console.log("Value of path 1", path1Snap.val())
  console.log("Value of path 2", path2Snap.val())
})

The response is an array of snapshots received from Firebase.


Why does inline void foo() { ... } in a common header just work?

Question: Consider the use of inline in C99, with various options (extern'ing, static inline etc), as described here, for example.
I don't understand why the C standard does not allow for just using
void inline foo() { do_stuff(); }

in a common header file, and for that to work everywhere. Why do I have to add static? Isn't what I want clear enough already?
Comment: Show a minimal working compilable sample where your problem happens. It seems that your problem is not related to your question
Comment: Generally you *don't* need `static`, except in old versions of gcc.
Comment: @PaulR: I don't think version 4.8.3 is old, and I just got burned slightly for trying a non-static inline....
Comment: That's odd - I thought this only happened with gcc 2.x and maybe 3.x, and even then only with debug builds (`-O0`). Are you compiling with `-std=c99` or `-std=gnu99` or something else ? What error are you getting ?
Comment: OK - does it also happen with optimisation enabled (`-O3`) ? And what about if you add `-std=c99` (or is that the default now anyway ?) ? Also what is the error message ?
Comment: @PaulR correction... it's actually `gcc -shared  -fPIC -DPIC  a.o b.o c.o  -lpthread  -m64 -Wl,--rpath=\$ORIGIN/../lib   -Wl,-soname -Wl,d.so.0 -o d.so.0.1.0`
Comment: And I get `a.o: In function 'log_2': /some/where.h:470: multiple definition of 'log_2' \n b.o:/some/where.h:470: first defined here`
Comment: OK - yes - that's the old gcc behaviour - you get link errors for multiple definitions without `static`. I thought his had been fixed but evidently not. I don't know any other compiler that has this quirk.
Comment: Exactly. No `static` is required for inline functions in header files in C99. If your implementation produces linker errors, it means that the implementation is broken.
Comment: Please have a look at your code you have the function declared extern in more than one source file. This is why you get the multiple definition errors. You should declare the function extern in just one source file
Comment: @SebastianCabot: I don't have the function declared extern anywhere. Why should I? I mean, I "told" the compiler to inline it; so I don't want it to exist as object code anywhere; why do I have to do anything else? That's the point of my question.
Comment: Did you actually read my answer? You should declare it extern just once if you don't want it to be static inline
Answer: From the gcc site:

When an inline function is not static, then the compiler must assume
  that there may be calls from other source files; since a global symbol
  can be defined only once in any program, the function must not be
  defined in the other source files, so the calls therein cannot be
  integrated. Therefore, a non-static inline function is always compiled
  on its own in the usual fashion.

What does it mean for you. You cannot define the inline function in the header since it will mean that it will be defined from different translation units (.c files that include it).
Once it is defined static inline then each c file that includes the header will have its own copy of the function.
EDIT
gcc behaves correctly. Inline functions were added to the standard with the introduction of C99. The standard is somewhat ambiguous and states:

Any function with internal linkage can be an inline function.  For a
  function with external linkage, the following restrictions apply: If a
  function is declared with an inline function specifier, then it shall
  also be defined in the same translation unit.  If all of the file
  scope declarations for a function in a translation unit include the
  inline function specifier without extern,  then the definition in that
  translation unit is an inline definition.  An inline definition does
  not provide an external definition for the function, and does not
  forbid an external definition in another translation unit.  An inline
  definition provides an alternative to an external definition, which a
  translator may use to implement any call to the function in the same
  translation unit.  It is unspecified whether a call to the function
  uses the inline definition or the external definition.

What it actually means is that when the compiler sees the inline keyword cannot know if the function was already defined in another translation unit (This will be known only during linking). Now most compilers gcc included will not inline a function without optimizations turned on. So if you try to use an inline function when compiling with -O0 the compiler issues a real call to the function (It assumes it is defined in a another file then the one it is currently compiling). Now when the linker encounters the call it tries to find the function in all compiled objects but fails (because the compiler didn't create a body for the function neither did it inline it - the standard says it doesn't have to create a body for the function and that it can assume there is a definition some where). This is why you get the error: undefined reference to f when you link your project. This is the correct behavior when compiling with -std=c99 onward. It also means that if you want an inline function to have abody you must declare it external only once BUT you must also provide the definition within the same translation unit you declared the function with extrnal linkage.
So in order to get your code to work correctly according to the standard you should do the following:
in the h file just do as you would expect.
inline void f(){ /*DO SOMETHING*/}

And in just one of your code files (.c files) you do:
extern inline void f();

What happens is that now the compiler encounters in just one translation unit both body definition (taken from the header) and a declaration that says it should exist an external definition somewhere and in accordance with the standard creates one for the function.
So the standard says that any function with internal linkage can be declared inline and that the compiler should generate a body for it. In C a function is considered to have internal linkage only when adding the static keyword.
This is why static inline void f() works. Without the static keyword the compiler assumes that the function has external linkage and that is why just specifying inline void f() without also adding extern inline void f() in just one source file will not work.
Comment: So, is this gcc-specific? Because, if I inlined the function, I would think different compilers should assume "oh, ok, there's no real duplicate object code anyway". Also, you've just explained that gcc behaves that way, but the question remains - why?
Comment: I will edit my answer with explenation and show you how to do it correctly
Comment: @einpoklum I saw you wrote some more in the comments. Look there are two separate questions. The first is how to correctly use inline functions in C. The second is about gcc and how to compile correctly. In the comments you showed only the call to the linker and not the call to the compiler so I don't really know why you have multiple definitions. The reason static is taking them away is that when you add static every source gets its own copy of the function
Comment: @einpoklum In order to verify I have created a test project containing two source files and one h with an inline function. with the guidelines given above - gcc works as expected
Answer:
...C standard does not allow for just using...

That's completely wrong. Your question is based on some incorrect/outdated/compiler specific premise, which has nothing to do with C standard. In C language you don't need static when putting inline function in header file. An inline definition without an explicitly specified extern keyword does not form an external definition for that function. For that reason inline definition without static cannot trigger any multiple-definition-related errors (if that's what you are afraid of).
Moreover, the link that you posted clearly says that C standard does not say anything implied in your question. It says that GCC compiler implements inline differently from what's required by C standard (probably referring to an older version of GCC).
In other words, from C language point of view you can (and should) put
inline void foo() { do_stuff(); }

in the header file. No static required.
Comment: static is actually required since gcc actually corrected it's behavior. The document he quotes is old. (Or adding an external linkage specifier in one translation unit)
Comment: @Sebastian Cabot: It is nice to know that GCC has corrected its behavior, but I still don't see what makes you think that `static` is somehow required here. `static` would give that function internal linkage. If you want internal linkage, you specify `static`. However, it is in no way "required". C language does include the concept of inline function with external linkage. And yes, you define such function in header files without `static`.
Comment: Look at my answer. The standard clearly specifies that every internal linkage function can be made inline and that the compilers should generate  a body for it. As you know the header once included becomes part of the .c file. So if you declare it static inline the compiler will correctly generate the body in each source file that includes the header and no errors will occur during linkage
Comment: @Sebastian Cabot: That's great, but "...every internal linkage function..."? Why do you keep insisting on internal linkage? Nobody said so far that they want a function with internal linkage. You are basically saying that "it will work with `static`". That's nice. But what I'm saying is that it will work without `static` as well. Again, it is a question of linkage: what linkage do you want your function to have? No error will occur during linkage if you use it without `static`. If your implementation produces linkage errors without `static`, the implementation is broken.
Comment: You are partially right. It will work without static in one of two cases: One, you compile with aggressive optimizations turned on and your function can actually be inlined. Two, you specify inline extern void f(); in exactly one source file that includes the header. You should really read my answer, it's very thorough
Comment: @Sebastian Cabot: Well, that is true that an external definition for the function (with explicit `extern inline`) should be present somewhere as well. But that does not justify blatantly asserting that "`static` is required" in this case.
Comment: In the case that the OP asked about. Just putting an inline function in a header will not work. That is why he asked the question in the first place. You need to add certain things to your code for it to link. So although you can have a header with an inline function without static you should add static unless you make sure there is an actual definition somewhere
Comment: @AnT: Why? Why should it? My intentions are perfectly clear with the line of code I put in the common .h file. I don't want to have to say "Expect something extern" anywhere (not to mention the issue of needing to arbitrarily create asymmetry).
Comment: @einpoklum: I'm a bit confused about this, in the very same way as the page you linked. The page says "The standard is vague on this point. [...] Unfortunately this doesn't really make clear whether this external definition must actually exist." I also don't see a definitive answer anywhere on whether the *external definition* is required (as Sebastian Cabot claims). I tend to believe it is not supposed to required as long as plain `inline` definition is visible at the point of the call.
Comment: People like saying the standard is ambiguous. But in reality it is not. If you are really interested look it up and read it for yourself. Inline doesn't even mean that the compiler should inline anything just that it should try to call the function as fast as possible.
Comment: @Sebastian Cabot: My knowledge of the standard goes far beyond that of people who simply "like saying the standard is ambiguous". No, I don't like saying that the standard is ambiguous. Which means that when I do, it means that there's a very good chance that it is really ambiguous. And indeed, if you really "look it up and read it for yourself", you will certainly discover that there quite a few well-known defects in the standard (including ambiguities).


How I setup a background limit in CSS?

Question: I have a page with a searchable table, when someone use the text box to search for data the jQuery code will give live results "like google search suggestion" but inside the table itself.
When there is no text inside the search text box, the table show all data inside it. and the background work great on that, no matter how long the page is.
My problem is when someone search on specific thing and the table only show a few data like "1 or two" the background crop and a blank white background appear in the footer.
What am I doing wrong?
Here is my CSS:
body {
    margin: 30px 0 0 0;
    background: url(https://example.com/how/900.jpg) no-repeat center center fixed;
    background-size: cover;
    color: #000000;
    height: auto;
}

Comment: It's because you have given height auto, and it will adjust to the content.
Answer: Add this as the first rule in your stylesheet
{
    html, body{ height:100%; }
}

Remove height: auto; from you body selector.

Since you did not "reset" your styles, the browser is using the default one, and sadly the default style for the body does not render it as at least the full height as the viewport allows
Comment: It's still the same problem! I change it, It works if I setup the hehight to 150% , but the page become so long!
Comment: Now it works for some reson after a cleared the bouwser history it works, thanks :)
Answer: Change height: auto to height: 100vh will resolve your issue. Thanks
Comment: can you share link for more clarification. Thanks
Comment: Working fine not facing any issue.
Comment: write four "ffff" only on firefox, I just noticed that
Comment: Can you share the link?

How I setup a background limit in CSS?


Cannot update identity column 'Unique ID', Entity Framework Error

Question: I am trying to update my entity using Entity Framework 4.1 code First approach like this(In my Repository Class):
internal void SaveAccount(Account account) {

            context.Entry(account).State = EntityState.Modified;
            context.SaveChanges();
        }

but I am getting an error which is:
Cannot update identity column 'Unique ID'.

I am not updating Unique ID Column. How can I avoid this error ?
Answer: I added this attribute to my Model property and error gone:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
Answer: If the property is the primary key, the following attribute should be added instead:
[Key]


How to disable backlit keyboard in Ubuntu 20.04 (Dell Latitude)

Question: I would like to disable the keyboard backlight on a Dell Latitude E5570.
According to the official documentation this should be possible by selecting "disable" for the corresponding BIOS parameter. I did this several times but the BIOS setting automatically goes back on every time I boot to Ubuntu.
I found these old bug reports which appear to be related, but I don't know if these still apply for 20.04:

https://bugs.launchpad.net/dell-sputnik/+bug/1510344
https://bugs.launchpad.net/dell-sputnik/+bug/1583861

Any advice?
Answer: Try pressing Fn + Space Bar. Fn is the key between the windows key and ctrl.
This is the shortcut for toggling the backlight on the keyboard for my Lenovo laptop. It might be the same for Dell.
Edit: For the Dell Latitude, the toggle command is Fn +  F10.
Comment: In my case, my laptop remembers the last toggle, and keeps it that way. So if you toggle it off, it will probably stay off.
Comment: Oh you're right! I was so focused on the BIOS setting not working that I missed this simple thing. Thanks a lot, that solves it indeed. For anyone reading this later, the equivalent key on Dell Latitude is Fn + F10.
Comment: Glad I could help :)
Comment: Thank you for your answer but actually what I would like is to disable it completely, not having to turn it off at every boot.


Where can I find cars that are already modded?

Question: While driving around Los Santos, I stumbled across a Rat Rod at a gas station. Something on it looked different so I hopped in and drove it back to my apartment. To my amazement, when I took it to a mod shop, I saw that it already had a bunch of mods done to it.
Are there other cars in GTA Online that are already pre-modded? If so, where can I find them?
Not sure if it matters any, but I am playing on Xbox One.
Answer:
The only two places where I've found that modded cars consistently appear are the purple circles. One is a garage up the ally where you have a mission with the Photographer and Franklin at one point. The other is the mod shop where you fix Michel's car, though the second one is much less common to have cars.
Comment: Are you finding these in the story mode or online? Just wondering since you mention Franklin and Michael.
Comment: I was never in need of a moded car in online, as my Kuruma is more than enough for me. So I've only seen these in Story Mode, but I bet they will be there in Online too.
Comment: Just now I noticed you're talking about Gta online. Still give these spots a try, go around them few times. Also the hood around the mod shop in the city centre somtimes spawns a moded car.
Answer: You can buy moded cars from Benny's Original Motor Works.
Check their page in the GTA Webbrowser.
You can buy the unmoded car from them and bring that car to them. There you you will find the option to turn the car to their moded Version. That includes modification that are not available othewise. That obviously comes with a rather high cost.


Rails - how to save options chosen by user

Question: I have two models: Meal and Tag. They are associated by HABTM. What I want to do is to add new meal. So I have new.html where is name field, preparation field, and all tags (represented by toggle-buttons - every tag has own toggle-button). User can clicked tags, which want to save in this meal.
And here is a problem. I can display all tags, but I have no idea how can I tell rails to save only clicked tags.
Could you help me find right approach?
oh, and there is a user too (user has many meals), but I thing it doesn't matter.
Here is my view:
<%= form_for(@meal,:html => {:class => "meal-data-form"}) do |f| %>
<%= render 'shared/error_messages', object: f.object%>

<%= f.label :name, "Nazwa *" %>
<%= f.text_field :name, class: 'form-control'%>

<%= f.label :preparation, "Sposób przyrządzenia" %>
<%= f.text_area :preparation, class: 'form-control' %>

Określ tagi dla tego posiłku

Rodzaj posiłku

        <% current_user.nutrient_tags.each do |nutrient_tag| %>
            <button id="associated-type-tag-<%= nutrient_tag.id %>" type="button" class="btn btn-primary" data-toggle="button" aria-pressed="false" autocomplete="off">
                <%= nutrient_tag.name %>
            </button>
        <% end %>

<%= f.submit yield(:button_name), class: "btn btn-primary" %>

Answer: I would not use a toggle button to do this, I would probably use checkboxes.
This is what you would do if you used checkboxes:
<%= f.collection_check_boxes :nutrient_tags_ids,  current_user.nutrient_tags, :id, :name do |b| %>

    <%= b.check_box %>
    <%= b.label %>

Here is something for reference: http://www.sitepoint.com/save-multiple-checkbox-values-database-rails/
And here is the Rails collection_check_boxes official documentation: http://apidock.com/rails/v4.0.2/ActionView/Helpers/FormOptionsHelper/collection_check_boxes
Hope that helps.
Comment: Thanks, I saw similar approach for checkboxes, but I really want to use toggle-buttons. They should look like tags. Is any option to check toggle status by params[:toggle-name] in controller?
Comment: I would try this then: http://www.bootstraptoggle.com/ it's bootstrap checkboxes styled as toggles.
Comment: It looks good. But I have a problem with this gem. I followed instruction: add to Gemfile, install, add requires (ccs, js), and it doesn't work. Have you got any idea, why? Or maybe is other way to install it?
Comment: Ok I fixed it by adding lines from your link to the head section. I don't know why I didn't it before. By still I have a problem. Because these toggle-butons are like a switch option. Styling is unsuitable for my needs. Is it any option to change these toggle-button on common button with two states (different color for example)?


14.04 VLC libde265 unmet dependencies

Question: I can't seem to install vlc-plugin-libde265, it's looking for libde265(>=1.02). Any ideas what to do about this?
$ sudo apt-get install vlc-plugin-libde265
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have requested an
impossible situation or if you are using the unstable distribution that some
required packages have not yet been created or been moved out of Incoming.
The following information may help to resolve the situation:

 The following packages have unmet dependencies:
  vlc-plugin-libde265 :
        Depends: libde265 (>= 1.0.2) but it is not going to be installed
 E: Unable to correct problems, you have held broken packages.

VLC Version:
$ vlc --version
VLC media player 2.2.1 Terry Pratchett (Weatherwax) (revision 2.2.1~trusty2)
VLC version 2.2.1 Terry Pratchett (Weatherwax) (2.2.1~trusty2)
Compiled by buildd on lcy01-34.buildd (Feb 17 2016 20:00:02)
Compiler: gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.1)
This program comes with NO WARRANTY, to the extent permitted by law.
You may redistribute it under the terms of the GNU General Public License;
see the file named COPYING for details.
Written by the VideoLAN team; see the AUTHORS file.

apt-cache policy vlc-plugin-libde265 libde265
libde265:
  Installed: (none)
  Candidate: 1.0.2-1ppa1~utopic1
  Version table:
     1.0.2-1ppa1~utopic1 0
        500 http://ppa.launchpad.net/strukturag/libde265/ubuntu/ utopic/main amd64 Packages
     1.0.2-1ppa1~trusty1.1 0
        500 http://ppa.launchpad.net/mc3man/trusty-media/ubuntu/ trusty/main amd64 Packages
     1.0.2-1ppa1~trusty1 0
        500 http://ppa.launchpad.net/strukturag/libde265/ubuntu/ trusty/main amd64 Packages
vlc-plugin-libde265:
  Installed: (none)
  Candidate: 0.1.7-1ppa1~utopic1
  Version table:
     0.1.7-1ppa1~utopic1 0
        500 http://ppa.launchpad.net/strukturag/libde265/ubuntu/ utopic/main amd64 Packages
     0.1.7-1ppa1~trusty1.1 0
        500 http://ppa.launchpad.net/mc3man/trusty-media/ubuntu/ trusty/main amd64 Packages
     0.1.7-1ppa1~trusty1 0
        500 http://ppa.launchpad.net/strukturag/libde265/ubuntu/ trusty/main amd64 Packages

Comment: What is our output of `apt-cache policy vlc-plugin-libde265 libde265`? Please edit your question to add it and then notify me with a comment "@ByteCommander". Thanks.
Comment: Works fine here, that is a ppa version of vlc, (mine) & the ppa provides both the plugin (vlc-libde265 (0.1.7-1ppa1~trusty1.1)) & the lib, (libde265 (1.0.2-1ppa1~trusty1.1)) .  Just tested and both installed fine.  Don't find askubuntu good for troubleshooting like this, on ubuntu forums would gladly help you. Otherwise maybe try some apt-cache policy on both packages, ect.  & good luck
Comment: What ppa did you use? I'll try asking in ubuntu forums as well. Thanks!
Comment: The same where you got vlc, trusty-media. (I created & maintain it.)  So ck. post 3 in uf thread & we can fix this in short order. (though starting to get late here...
Comment: @ByteCommander I've edited my question adding the results of apt-cahce
Comment: @ByteCommander, I've already got the solution from Ubuntu Forums. You were on the right path too. Thanks a bunch!
Answer: So I got my answer in https://ubuntuforums.org/showthread.php?t=2332052. Asked the same question.
sudo apt-get install ppa-purge
sudo ppa-purge ppa:strukturag/libde265
sudo apt-get install vlc-plugin-libde265

14.04 VLC libde265 unmet dependencies


sql query to find matching pairs in mysql

Question: Hypothetical question for the community :
Given any 2 books in a library (book 1,book 2), how many customers have had both checked out at the same time within the year?
Table
CREATE TABLE `check0` (
  `lib_card_num` int NOT NULL,
  `first_name` varchar(45) NOT NULL,
  `last_name` varchar(45) NOT NULL,
  `checkout_timestamp_utc` timestamp(6) NOT NULL,
  `due_date` date NOT NULL,
  `type` varchar(10) DEFAULT NULL,
  `name` varchar(45) DEFAULT NULL,
  `unique_id` int NOT NULL,
  PRIMARY KEY (`unique_id`),
  KEY `parent_index1` (`lib_card_num`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
;

Data
INSERT INTO testlibrary.check0
(lib_card_num,FIRST_NAME,LAST_NAME,CHECKOUT_TIMESTAMP_UTC,DUE_DATE,TYPE,NAME,UNIQUE_ID)
VALUES
(1,'ROB','BLOW',DATE_ADD(current_timestamp(), INTERVAL -30 day),DATE_ADD(current_date(),INTERVAL -5 DAY),'PHYSICAL','SHEBA',100),
(1,'ROB','BLOW',DATE_ADD(current_timestamp(), INTERVAL -30 day),DATE_ADD(current_date(),INTERVAL -5 DAY),'ELECTRONIC','THUNDERPOINT',101),
(2,'JOHN','DOE',DATE_ADD(current_timestamp(), INTERVAL -15 day),DATE_ADD(current_date(),INTERVAL -1 DAY),'ELECTRONIC','THUNDERPOINT',102),
(2,'JOHN','DOE',DATE_ADD(current_timestamp(), INTERVAL -15 day),DATE_ADD(current_date(),INTERVAL -1 DAY),'PHYSICAL','SHEBA',103),
(3,'JANE','DOE',DATE_ADD(current_timestamp(), INTERVAL -45 day),DATE_ADD(current_date(),INTERVAL -20 DAY),'PHYSICAL','SHEBA',104),
(3,'JANE','DOE',DATE_ADD(current_timestamp(), INTERVAL -45 day),DATE_ADD(current_date(),INTERVAL -20 DAY),'ELECTRONIC','THUNDERPOINT',105)

Comment: Your question and your data have nothing to do with each other.  There is no obvious "customer" or "book" in the data.  Fortunately, it is a theoretical question.
Answer: Maybe try this
select count(lib_card_num) as result
from
(select distinct check0.lib_card_num from sys.check0
where check0.checkout_timestamp_utc in
(SELECT checkout_timestamp_utc
 FROM
(SELECT check0.checkout_timestamp_utc, COUNT(check0.checkout_timestamp_utc) count
 FROM sys.check0
 GROUP BY check0.checkout_timestamp_utc) sub1
WHERE sub1.count > 1)) sub2;

Answer:
Given any 2 books in a library (book 1,book 2), how many customers have had both checked out at the same time within the year?

This doesn't sound very theoretical.  But you can approach this using aggregation.  However, your description doesn't have a column called customer or book_title, so you'll need to adapt for your data model.  This is a theoretical question after all:
To get the customers with both books:
select customer
from check0 c
where book_title in ('book 1', 'book 2')
group by customer
having count(distinct book_title) = 2;

You can then count these with an additional subquery:
select count(*)
from (select customer
      from check0 c
      where book_title in ('book 1', 'book 2')
      group by customer
      having count(distinct book_title) = 2
     ) c;


Between two java application layer i have implemented a buffer using BlockingQueue. But don't want any lock when put and take happens

Question: I am building a high processing throughput application. So between two layers, i have implemented a buffer using BlockingQueue. But don't want any lock when put and take happens.
So which queue I can use or is there any other solution which will lock put and take so that speed is faster.
Now I am facing slowness while take because put is so faster so most of the time it's locking to take. So it's making the queue to grow up and slower in processing.
Thank you, everyone.
Comment: I highly doubt that the amount of time it takes to lock is your problem, probably your consumer takes more time to process than your producer.
Comment: It's not entirely clear what your problem is, but you can use `BlockingQueue#poll()` to not block on an empty queue.
Comment: How many producers / consumers will be using the queue?
Comment: Can you display your code please?
Comment: @Pranab And if your consumer is spending most of its time in `take()`, the put *isn't* faster and  the queue *isn't* growing.
Comment: @Oleg Of course, stupid of me.
Comment: Thanks to everyone.
Actually, my producer work is just put into the queue and consumer work is just take from the queue and assign the same to the available thread.

In this also I could observe that sometimes buffer queue is holding quite a number of requests.

So in this case how the consumer is not able to match up with the speed of producer when their work is similar.

Is producer locking the queue while producer trying to put the data or vice versa?
Answer: Take a look at this question, it looks like your needs are the same.
I wouldn't recommend to implement your own queue, even if you feel any of that is still too slow.
Comment: Thank You.

Thanks to everyone.
Actually, my producer work is just put into the queue and consumer work is just take from the queue and assign the same to the available thread.

In this also I could observe that sometimes buffer queue is holding quite a number of requests.

So in this case how the consumer is not able to match up with the speed of producer when their work is similar.

Is producer locking the queue while producer trying to put the data or vice versa?
Comment: Race conditions show up during concurrent write operations on the same memory, so concurrent read operations aren't usually problematic. In this case, write operations would be objects insertions, while read operations would be object remove operations; I would guess the queue has a mechanism similar to 2 different locks: one for inserting and the other for removing objects. This way, producer wouldn't block a consumer's removing operation while inserting an object, or at least as long as the queue isn't empty and the producer is inserting the first object


Format option not available in 11.10 as in 10.10?

Question: I'm using Ubuntu 11.10 on my laptop and Ubuntu 10.10 on my desktop.
In 10.10 there is an option to format a pen-drive by right-clicking the icon for the pen drive and selecting format, but I am unable to find it in 11.10.
There are tools for that... But isn't there any default tool available for this?
Answer: I use  Disk Managment that you can  find from the Dash (Dash > Disk managment). From there you can do what you want
Answer: Or also you can install gnome-format and it will appear in "My Computer" by right-clicking the device for installing it. Just run these commands in the Terminal:
sudo apt-get update
sudo apt-get install gnome-format

Answer: Just so you know, there is a quicklist option that is supposed to be getting added to the 12.04 release that will allow you to right click on the drive when it shows up in your panel giving you a format option.
Check it out here:
https://code.launchpad.net/~andyrock/unity/fix-814610/+merge/76857
and a picture here:
http://people.ubuntu.com/~andyrock/Format.png
This will be a much welcomed feature although I do have to say I wished it used gparted instead of 'Disk Utility'.
Answer: Install Nautilus Actions Extra in Ubuntu 11.10 or 12.04, use the commands below:
sudo add-apt-repository ppa:nae-team/ppa
sudo apt-get update
sudo apt-get install nautilus-actions-extra

Answer: in ubuntu there is many method by which you can format your pendrive
1 - by Disk utility see the video   // simplest way

2-  by Gparted tool see the video
// you can install it from Ubuntu software center
or
you can install is by typing

sudo apt-get install gparted

3- by using Terminal see the video
go to super mode by typing "su" followed by super mode password

fdisk -l

that will show all the volume in your pc or you can also use the

df

to see the usb flash drive suppose it may be /deb/sdb1

umount /dev/sdb1

that un mount the drive

mkfs.vfat /dev/sdb1

to format drive into fat32 format