How can I enable button only when user clicks check box in Blazor

Question: <button id="btn1" type="submit" disabled="@true">Submit</button>
<input type="checkbox" @onclick="@btn1"=disabled="@false"/>
<button disabled="@isDisable">button</button>

I am trying to get my submit button disabled, it should be enabled only when a user clicks the checkbox (Privacy Policy); how can I do so using Blazor?
Answer: The most straight-forward way would be to bind a boolean property to the checkbox input like so:
<input type="checkbox" @bind="HasChecked" />
<button type="submit" disabled="@(!HasChecked)">Submit</button>

@code {
    private bool HasChecked { get; set; }
}

@binding to a checkbox with a boolean uses the checked state of the element to determine the bound property value.
Alternatively, if you need more control, you can bind an @onchange handler:
<input type="checkbox" @onchange="HandleCheckboxChange" />
<button type="submit" disabled="@IsDisabled">Submit</button>

@code {
    private bool IsDisabled { get; set; }

    private void HandleCheckboxChange(ChangeEventArgs args)
    {
        IsDisabled = !(args.Value is true);
    }
}

Comment: Ok I tried the first one and it worked well much appreciation.


What team compositions are viable?

Question: So basically I want to know all the metas for league of legends? Some that I know would be AOE comp and Poke comp that's pretty much all I know. Are there any others and what counters what?
edit Ahh you know what as pointed out by Kleme Quixote the question is more about comps and not the meta.
Comment: @Scootaloo This question has a weird title. If you read the description, the original goal was to learn more about the different team comps. I would recommend that we change the title of this one.
Comment: @Shaun What do you think we should change it to?
Comment: @Scootaloo Something like "What are the types of team comp strategies that are viable?" :)
Answer: The current Meta for North American Servers as I understand it goes like this:

Top Lane is manned by a champion that has enough sustain to hold the lane on his own without much help from the jungler. This can be a bruiser, but can also be many other heroes, with the only important criteria being filled is the hero is solid enough of a pick that he can at least hold his own ground and farm enough to be of assistance when laning phase ends.
@PunDefeated also made a good point, that sometimes the enemy team will swap their duo bot lane with their top laner. The purpose of this is to pressure the top lane with a 2v1 matchup to quickly bring down the enemy tower and give the aggressive team an early gold advantage. It's important to know this may happen, so optimally, your top lane hero should be able to hold his own against a 2v1 matchup, at least long enough for the friendly jungler to get his butt in gear and give top lane a hand. (I personally almost never see this happen, but it DOES happen from time to time)
Mid Lane is manned by a carry of some sort, usually AP type or Assasin type. These Champions serve to burst down key members of the enemy team in teamfights once laning ends. They often have extremely high, if not sustained burst damage, and also usually but not always have a Crowd Control ability of some sort.
Jungle is usually manned by a bruiser of some sort (but not always), with a heavy focus on mobility and ganking potential. It's also extremely popular at this time that the jungler has the ability to counter-jungle, that is, not only clear the friendly jungle, but safely clear the enemy jungle as well so as to stunt the growth of the opposing jungler.
Bot lane is manned always by a RANGED AD Carry of some sort, and a Support for said AD Carry.

The ADC should be farming as much minions as possible, while staying in lane as much as possible, and killing the enemy bot laners also, as much as possible, with the focus being to farm minions and NOT DIE. The idea is to have a smooth early and mid game so to bring to the late-game High sustained DPS.
The Support should be not farming CS, doing most (but not all) of the warding for the team, as well as doing everything possible to make the life of the friendly ADC easier. A skilled player once told me its the Supports job to carry the ADC so the ADC can carry the team. Supports generally (but not always) have some combination of these abilities: they can heal, they can shield, they can speed up allies, they can slow down enemies, they have some sort of damage steroid for allies, they have some sort of damage nerf for enemies, and they have some form of CC. It is also necessary that a support's abilities work good enough to produce the desired effect all game, with minimal items to help, as without CS supports tend to make very little money compared to other champions on the team.

Any META that involves a 'poke' or an 'aoe' strategy in NA still follows the guidelines stated above, only it narrows down champion choices to involve champions that carry to the game a strong presence of the stated mechanics.

Poke is the ability to repeatedly damage enemy champions from a safe distance, with the purpose of wearing them down so they can be killed by a final 'all in' burst of damage.
AOE is the concept of abilities that damage multiple champions simultaneously.

In closing, the Meta tends to be somewhat different for each region. If your interested in the other floating Metas I cannot help you, but enough research into the pro-league games of their respective region should give you some insight into how others are playing.
Comment: @Ender The purpose of a block quote, though, is to actually *quote* something. If those are related you could do so with a separate heading or I believe markdown may support sub-bullets.
Comment: It may be important to note the prevalence of lane swapping in professional play, where one team (generally purple, I think) sends their "bot lane" to top lane, in order to take the enemies top turret quickly and give their own team a favorable gold advantage.  This has had an interesting effect of lowering the variety of top lanes played at a high level, because they need to be able to deal with the pressure of a 2v1 and being forced to farm under turret.
Comment: @StrixVaria ok, ill give that a try. :)
Answer: "Meta" has been interpreted into so many different ways throughout the community.
Today's "Meta" is more so an overall composition on how all teams are set.
It consists of the Bruiser Top, Bruiser Jungle (Keep in mind, almost all champions can jungle now), AP Caster Mid, AD Carry Bot, 0 CS Support Bot.
Some counters would be anti-mages mid, such as Kassidan or Sivir, and anyone with strong harass bot, to prevent the enemy carry from farming.
This counters the current meta, as in my interpretation.
For AOE Comps, A quick silver sash and cleanse work wonders against escaping heavy CC.
For Poke Comps, I suggest high sustain, High durability.
Answer: Pushing comp beats poke comp, by experience and proven by many many teams.
Comment: How does that explain what possible metas exist out there? You said "X beats Y", while the question demands "There are A, B, C, D, E, F, G..."
Answer: Try the Tank comp, pick 5 heavy tanks on ranked get into lategame and win
(cho, Singed, Rammus, Mundo, Galio, Malph, Volibear...)
We got till 1500Elo in season 1 with that ^^
EDIT: counter would be an awesome early game comp or tank busters (kog maw^^)
Comment: Lots of Atma's on your team and Deathfire Grasp on the opponents? ;)
Comment: Doesn't work as well now in Season of the Ruined King.

What team compositions are viable?


arduino json parser failing to parse a uri

Question: HI I am trying to use the Json Library by Benoit Blanchon 2014-2016 from this URL https://github.com/bblanchon/ArduinoJson
I struggled at first as I had the second generation ethernet shield.  Got it going once I realised I needed the second ethernet library.
However I get the error message unable to parse json and I am unsure why, and how debug.
// Sample Arduino Json Web Client
// Downloads and parse http://api.sunrise-sunset.org/json?lat=53.440&lng=0.200&date=today
//
// Copyright Benoit Blanchon 2014-2016
// MIT License
//
// Arduino JSON library
// https://github.com/bblanchon/ArduinoJson
// If you like this project, please add a star!

#include <ArduinoJson.h>
#include <SPI.h>
#include <Ethernet.h>

EthernetClient client;
const char* server =    "api.sunrise-sunset.org";                  // server's address
const char* resource =  "/json?lat=53.440&lng=0.200&date=today";   // http resource
const unsigned long BAUD_RATE = 9600;                              //     serial connection speed
const unsigned long HTTP_TIMEOUT = 10000;                          //       max respone time from server
const size_t MAX_CONTENT_SIZE = 512;                               // max size of the HTTP response

// The type of data that we want to extract from the page
struct UserData {
char sunrise[32];
char sunset[32];
};
// ARDUINO entry point #1: runs once when you press reset or power the board
void setup() {
// initSerial();
//  initEthernet();
 Serial.begin(9600);
 Serial.println("Serial ready");
 byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
 byte ip[] = { 192,168,0,202 };
 Ethernet.begin(mac, ip);
 Serial.println("Ethernet ready");
 delay(1000);
 }

 // ARDUINO entry point #2: runs over and over again forever
 void loop() {
  if (connect(server)) {
   if (sendRequest(server, resource) && skipResponseHeaders()) {
   char response[MAX_CONTENT_SIZE];
    readReponseContent(response, sizeof(response));
    UserData userData;
  if (parseUserData(response, &userData)) {
    printUserData(&userData);
  }
}
disconnect();
}
wait();
}

// Initialize Serial port
void initSerial() {
Serial.begin(BAUD_RATE);
while (!Serial) {
 ;  // wait for serial port to initialize
}
Serial.println("Serial ready");
}

// Initialize Ethernet library
void initEthernet() {
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
if (!Ethernet.begin(mac)) {
 Serial.println("Failed to configure Ethernet");
 return;
 }
Serial.println("Ethernet ready");
delay(1000);
}
// Open connection to the HTTP server
bool connect(const char* hostName) {
Serial.print("Connect to ");
Serial.println(hostName);
bool ok = client.connect(hostName, 80);
Serial.println(ok ? "Connected" : "Connection Failed!");
return ok;
}

// Send the HTTP GET request to the server
bool sendRequest(const char* host, const char* resource) {
Serial.print("GET ");
Serial.println(resource);
client.print("GET ");
client.print(resource);
client.println(" HTTP/1.1");
client.print("Host: ");
client.println(server);
client.println("Connection: close");
client.println();
return true;
}

// Skip HTTP headers so that we are at the beginning of the response's body
bool skipResponseHeaders() {
// HTTP headers end with an empty line
char endOfHeaders[] = "\r\n\r\n";
client.setTimeout(HTTP_TIMEOUT);
bool ok = client.find(endOfHeaders);

if (!ok) {
 Serial.println("No response or invalid response!");
}
return ok;
}
// Read the body of the response from the HTTP server
void readReponseContent(char* content, size_t maxSize) {
size_t length = client.readBytes(content, maxSize);
content[length] = 0;
Serial.println(content);
}
// Parse the JSON from the input string and extract the interesting values
// Here is the JSON we need to parse
//{
//  "results":{
//    "sunrise":"5:45:00 AM",
//    "sunset":"5:58:51 PM",
//    "solar_noon":"11:51:55 AM",
//    "day_length":"12:13:51",
//    "civil_twilight_begin":"5:10:15 AM",
//    "civil_twilight_end":"6:33:36 PM",
//    "nautical_twilight_begin":"4:28:54 AM",
//    "nautical_twilight_end":"7:14:57 PM",
//    "astronomical_twilight_begin":"3:45:29 AM",
//    "astronomical_twilight_end":"7:58:22 PM"
//  },
//  "status":"OK"
//}

bool parseUserData(char* content, struct UserData* userData) {
// Compute optimal size of the JSON buffer according to what we need to parse.
// This is only required if you use StaticJsonBuffer.
const size_t BUFFER_SIZE =
  JSON_OBJECT_SIZE(2)     // the root object has 2 elements
  + JSON_OBJECT_SIZE(10);   // the "result" object has 10 elements
// Allocate a temporary memory pool on the stack
StaticJsonBuffer<BUFFER_SIZE> jsonBuffer;
// If the memory pool is too big for the stack, use this instead:
// DynamicJsonBuffer jsonBuffer;

JsonObject& root = jsonBuffer.parseObject(content);
 if (!root.success()) {
  Serial.println("JSON parsing failed!");
  return false;
 }
 // Here were copy the strings we're interested in
 strcpy(userData->sunrise, root["results"]["sunrise"]);
 strcpy(userData->sunset, root["results"]["sunset"]);
 // It's not mandatory to make a copy, you could just use the pointers
 // Since, they are pointing inside the "content" buffer, so you need to make
 // sure it's still in memory when you read the string
return true;
}
// Print the data extracted from the JSON
void printUserData(const struct UserData* userData) {
Serial.print("Name = ");
Serial.println(userData->sunrise);
Serial.print("Company = ");
Serial.println(userData->sunset);
}
// Close the connection with the HTTP server
void disconnect() {
Serial.println("Disconnect");
client.stop();
}
// Pause for a 1 minute
void wait() {
 Serial.println("Wait 60 seconds");
 delay(60000);
 }

Comment: sure that your json buffer is not overflowed ? What does Serial.println(content); in readReponseContent() exactly prints ?
Comment: the contents is strange it has 161 in front of the json and 0 afterwards, 161
{"results":{"sunrise":"5:59:04 AM","sunset":"5:39:19 PM","solar_noon":"11:49:11 AM","day_length":"11:40:15","civil_twilight_begin":"5:24:27 AM","civil_twilight_end":"6:13:56 PM","nautical_twilight_begin":"4:43:47 AM","nautical_twilight_end":"6:54:36 PM","astronomical_twilight_begin":"4:01:50 AM","astronomical_twilight_end":"7:36:32 PM"},"status":"OK"}
0
what is the best way to remove these?
Comment: Lets put a memset(response, 0, MAX_CONTENT_SIZE); after response definition.
Comment: sorry trying to figure this as I go, what part do you mean after response definition thanks.
Comment: I mean just put after the char response[MAX_CONTENT_SIZE];
Comment: Hi made that change and still getting this output:    161
{"results":{"sunrise":"6:00:50 AM","sunset":"5:36:54 PM","solar_noon":"11:48:52 AM","day_length":"11:36:04","civil_twilight_begin":"5:26:13 AM","civil_twilight_end":"6:11:31 PM","nautical_twilight_begin":"4:45:37 AM","nautical_twilight_end":"6:52:07 PM","astronomical_twilight_begin":"4:03:49 AM","astronomical_twilight_end":"7:33:55 PM"},"status":"OK"}
0
Comment: So after memset you have whole null array..so remove content[length] = 0;
Comment: I have made that change but it has made no difference same result as before
Answer: There is a 161 before the JSON string because the server is using Chunked transfer encoding.
It is a feature of the HTTP 1.1 specification and the only way to disable it is to use HTTP 1.0 in the request.
See:

New JsonHttpClient.ino, which uses HTTP 1.0 and doesn't require the response buffer.
FAQ: Why parsing fails?


Single Zone has Little Pressure, New Problem

Question: My in-ground sprinkler system worked well, all zones. Now today, I try one single zone and the heads don't have even close to enough pressure to even pop. They dribble, barely. I'm thinking it could be a solenoid? Is there any easy way to test it? Any advice?
Thanks,
Josh
Comment: Do you have the same problem with all of the zones or only one?
Comment: Just one. The rest are great.
Comment: Is it an automatic system? Does it use potable (drinking) water, or is it pressurized irrigation water?
Comment: It's automatic with city water. Drinkable or not, not sure.
Comment: Brand new controller and heads too. (year old, I guess.)
Comment: Hello, and welcome to Home Improvement. Where are you located? And, is this the first time you've tried them after a sub-freezing winter?
Comment: It could be the solenoid but more likely there is a leak in the pipes of that zone.  You should walk around the bad zone and look for water bubbling up or grass that feels like a water bed.
Comment: No bubbling water and it worked this morning for a quick 5 minute test. No problems with freezing. Florida.
Comment: ...to be clear, now it doesn't work. It did this morning but not again.
Comment: Leak from a pipe - damaged over winter and failed from the earlier test...
Comment: So is there a way to test for that or test for other things before I start digging up pipe?
Answer: If the sprinkler controller can cause that zone to start dribbling then the solenoid is fine. (Note that "solenoid" is just one part of a complete valve.)
Do an experiment to figure out whether you have a broken pipe or a malfunctioning valve. For example, turn on one working zone, then (at the same time) turn on another working zone. (You may have to operate the valves manually rather than using the timer/controller.) Notice how much the spray of the first zone drops when the second zone comes on. Turn off that second zone, and while the first continues to run, turn on the malfunctioning zone. Does the spray of the first zone drop again? If it does then water in your malfunctioning zone is going somewhere, but not out the heads -- you'll have to locate and repair a broken pipe. But if the spray level of the first zone does not drop, then the valve of the malfunctioning zone is not opening as it should.
If you conclude the valve is malfunctioning there's a chance it could be caused by debris (a grain of sand, a small weed seed, etc) lodged inside. This could happen even on a drinking water system, but it's less likely.
I suggest that you consider how you would go about replacing that valve, have the required supplies on hand, and then try carefully disassembling the existing valve. Start by fully unscrewing the solenoid, and if there's no debris found there, take off the top of the valve. After cleaning it out, reassemble and test.
If things go well the valve could work normally again. If things go badly.. you're already prepared to replace the valve, so go ahead and do that.
Comment: If you end up replacing the valve, buy two.  If one has gone south, chance are that another will get lonely, and wander after him.


Attaching a motorized flip down tv mount to my apartment ceiling

Question: I would like to attach a motorized flip down mount for a 50" tv to my apartment ceiling. This is the exact mount.
My apartment is a new building that was built 2 years ago.  It was built with post tensioned flat plate cast in place concrete.  I know one part of the ceiling is concrete.  The other another part of the ceiling is made out of an unknown material and dips down 14 inches.. that is ideally where I'd like to attached the mount.
On the diagram to the far left you will see a little cubby that I opened up to see what is in that 14" of ceiling.  I have included 4 of the best pictures I could get.  Do you think this is possible? If so, what do you recommend doing?
Comment: Do you have power nearby? Do you rent?
Comment: Someone else might have more info for you, but taking a guess I'd assume that's just a hollow chase to run the ductwork, sprinkler, possibly some other stuff. Without seeing back into the cavity, I'm guessing the center of it will likely only be drywall and there won't be enough structure there to support a tv.
Comment: Yes I have power near by and yes I do rent
Answer: I like that mount.
It appears your soffit housing the duct work is made of steel studs covered in drywall.
This is a challenge for the weight of large TV, especially a hanging one that moves.
I would mount a Thick, long, wide board to the drywall spanning  3  studs. The board or boards need to be wider than the depth or length of the mounting plate of the the TV mount.
I would use Toggler anchors to attach the board to the studs, the toggle would/must go through the wall of the metal studs, at least 2 if not 3 anchors per stud.
You need to know exactly how the soffit is constructed, I.E. where the studs are and make sure you are mounting to them and not just drywall.
Here is good YouTube video of how to install the toggler toggle anchors.
Once you have a good solid board installed you have something strong enough to mount you TV too.
Before you install your board you should determining where the TV mount will be located and mark the location of the plate and the holes for the mounting bolts on the board.
Since it is a hanging mount i would not use lags or screws but instead i would use machine bolts into T-nuts.  Pre-drill your holes and mount the T-nut on the back side of the board. You will need to size the bolts, washers and T-nuts to work with your TV mount holes.
Here is a good YouTube video on T-nuts.
Comment: Good plan, because the steel studs will be prone to flexing under the weight and stress. The only thing is, be prepared to have your landlord insist on a full repair back to original when you leave.
Comment: Would it be easier to mount it to the concrete instead?
Comment: It could be mounted on A concrete ceiling with the proper anchors, would it be easier, that depends on your skills and tools. It also depends on the construction of the concrete ceiling. to mount it on the soffit would require a normal drill and a few drillbits, to mount it on the concrete ceiling would require a hammer drill and masonry bits. If you are a renter then Patching the drywall will be easier than patching the concrete.


Microsoft Lync crashes on double clicking any user from the contacts list

Question: I applied couple of working certificates after a quick install (Lync). Soon-after logging Lync, I tried to message by double-clicking one of the users from my contacts list; suddenly, I face app crash that prompts me to restart the application. This continues after restarting the app.
<code>Microsoft Error Reporting log version: 2.0

Error Signature:
Exception: EXC_BAD_ACCESS
Date/Time: 2014-11-28 05:44:49 +0000
Application Name: Microsoft Lync
Application Bundle ID: com.microsoft.Lync
Application Signature: UCCP
Application Version: 220.127.116.11024
Crashed Module Name: unknown
Crashed Module Version: unknown
Crashed Module Offset: unknown
Blame Module Name: Microsoft Lync
Blame Module Version: 22.214.171.124024
Blame Module Offset: 0x02019556
Application LCID: 1033
Extra app info: Reg=English Loc=0x0409
Crashed thread: 0
</code>
Comment: Could you confirm the Lync Client version and your OS version which I suspect may be Lync 2011 and Mac OS respectably.
Answer: There is a hot fix released for the Mac client to stop Lync crash when accessing various USB devices available from http://support.microsoft.com/kb/2926055.
Comment: Thank you! let me try and get back to you. Cheers!!
Comment: Tried, but no luck :(


use De Moivre's theorem to show that: $\cos(3\theta) = 4\cos(3\theta)-3\cos(\theta)$ and $\sin(3\theta) = 3\sin(\theta) - 4\sin(3\theta)$

Question: let $z = \cos(\theta) + i\sin(\theta)$.
a) Find $z^3$ using binomial expansion.
b) Use De Moivre's theorem to show that:
\begin{equation*}
\cos(3\theta) = 4\cos(3\theta)-3\cos(\theta)~\text{and}~\sin(3\theta)  = 3\sin(\theta)-4\sin(3\theta).
\end{equation*}
I found the first part to be:
\begin{equation*}
\cos^3(\theta) +3\cos^2(\theta)(i\sin(\theta)) - 3\cos(\theta)\sin^2(\theta) -i\sin^3(\theta)
\end{equation*}
but I'm stuck on part b.
i tried doing it by equating the binomial expansion answer to the answer we get from De Moivre's theorem and then using double angle identities, but I got no where with that.
I've spent a really long time trying to do this! it would be really nice if i could just get some direction on what i should do next.
Answer: For part a), use the Binomial expansion
\begin{equation*}
(x+y)^n=\binom{n}{0}x^ny^0_+\binom{n}{1}x^{n-1}y^1+\binom{n}{2}x^{n-2}y^2+...+\binom{n}{n-1}x^1y^{n-1}+\binom{n}{n}x^0y^n
\end{equation*}
with $n=3,~x=\cos(\theta)$ and $y=i\sin(\theta)$. This gives
\begin{equation*}
\cos^3(\theta)+3i\cos^2(\theta)\sin(\theta)-3\cos(\theta)\sin(\theta)-i\sin^3(\theta).
\end{equation*}
For part b), these identities do not hold. If you rearrange them you get
\begin{equation*}
3\cos(\theta)=3\cos(3\theta)~\text{and}~5\sin(3\theta)=3\sin(\theta)
\end{equation*}
which do not hold. There are identities which are similar to the one you want:
\begin{equation*}
\sin(3\theta)=3\sin(\theta)-4\sin^3(\theta), \\
\cos(3\theta)=4\cos^3(\theta)-3\cos(\theta)
\end{equation*}
which you can prove by manipulating both sides (start with the addition formulas
\begin{equation*}
\sin(\theta+2\theta)=\sin(\theta)\cos(2\theta)+\sin(2\theta)\cos(\theta)~\text{and}~ \\
\cos(\theta+2\theta)=\cos(\theta)\cos(2\theta)-\sin(\theta)\sin(2\theta)
\end{equation*}
to expand the left side). Does this help? I'll go into anything in more detail if you like.
Comment: omg! thank you so much! i think i just forgot to split theta in terms of 2theta and theta. but thanks a lot!
Comment: Sure. No problem


Need a list of Android devices with specs

Question: I am looking for a list of Android devices that has the following info (at least):

Device Name
User Agent String
Screen Format (of the three supported Android screen sizes)
Touch Enabled?
Maximum HTML5 Database Size

There are some lists online (like the one on Wikipedia), but it does not have all of this data.
Answer: Unfortunately, I think you'll have to compile a list of this information yourself. That list you mentioned is a great place to start. The problem is that there are so many manufacturers and so many different models, I don't know that anyone has bothered to catalog all of them with all of their particular specs in one easy-to-read place.
Finding the maximum HTML5 DB size for each device will probably be the most difficult thing. If you're looking for an upper bound on space usage, just go with the lowest you find.
If you do end up finding or compiling this list, be sure to post it here... there's a lot of Android devs who would be interested in seeing it.


How to fire liquibase rollback script from spring application

Question: I am using spring with liquibase to update my database. Since know I have not need to user rollback functonality, but the times come where I would like to make it work.
But I cant seems to fire it from my application.
I know that maven has plugin which helps with that, but until know I was not using it and when I add it I need to provide source and credentials to my database.
In this moment liquibase is configured in xml.
<bean id="liquibase" class="liquibase.integration.spring.SpringLiquibase">
  <property name="dataSource" ref="p6spyDataSource"/>
  <property name="changeLog" value="classpath:db.changelog-master.yaml"/>
  .
  .
</bean>

And in maven I have only dependency to liquibase-core.
And the place where I set liquibase.shouldRun is in application.properties
DataSource is taken from TomEE configuration server.xml file
So the question is if I can maybe somehow add maven plugin without adding credentials (should be taken from dataSource). Or is there other way to run rollback script from my changelog?
Answer: There are several related questions that have been posted previously about using Liquibase rollback with Spring Boot. This one seems the most similar to your post: Perform a liquibase:rollback from the command line when properties are in Spring-boot files (application.properties) and not liquibase.properties
Here is the answer as provided by Robert Kleinschmager:

The property names within springs application.properties and liquidate.properties are not compatible. You have three options
#1 just create a separate liquibase.properties file with the content you need - see liquibase doc as you only need to fix your current setup
#2 give the database parameters via command-line arguments
mvn liquibase:rollback -Dliquibase.rollbackCount=1    -Dliquibase.url=jdbc:postgresql://localhost:5432/comptesfrance -Dliquibase.username

see rollback goal for all arguments
#3 if you need a permanent solution, then you may add the liquibase properties into your application.properties and reuse them in the same file. i.e.
liquibase.url=jdbc:postgresql://localhost:5432/comptesfrance
spring.datasource.url=${liquibase.url}


Java - Why stackoverflow error in my JSON method?

Question: I need your help to understand why in my method the object allocation returns Stack Overflow error.
Here is the method:
public String toJson(){

        JSONObject json;
        json = new JSONObject(this); //error happens here...

        return json.toString();
    }

Here all code from this class:
package com.neocloud.model;

import java.io.Serializable;

import com.amazonaws.util.json.JSONObject;
import com.neocloud.amazon.AwsSns;
import com.neocloud.model.dao.DeviceDAO;
import com.neocloud.model.dao.GroupDAO;
import com.neocloud.model.dao.SubscriptionDAO;

public class Subscription implements Serializable{

    private static final long serialVersionUID = -3901714994276495605L;
    private long id;
    private Device dispositivo;
    private Group  grupo;
    private String subscription;

    public Subscription(){

        clear();

    }

    public void clear(){

        id = 0;
        subscription = "";
        grupo = new Group();
        dispositivo = new Device();

    }

    public String toJson(){

        JSONObject json;
        json = new JSONObject(this); //error happens here...

        return json.toString();
    }

    public String registerDB(boolean registrarSNS){

        GroupDAO gDAO = new GroupDAO();
        DeviceDAO dDAO = new DeviceDAO();

        gDAO.selectById(this.grupo);
        dDAO.selectById(this.dispositivo);

        if (registrarSNS)
            registerSNS(this.dispositivo.getEndPointArn(), this.grupo.getTopicArn());

        SubscriptionDAO sDAO = new SubscriptionDAO();
        return sDAO.insert(this);
    }

    public String registerSNS(String endpointArn, String topicArn){

        String resposta;
        AwsSns sns = AwsSns.getInstance();
        resposta = ""+sns.addSubscriptionToTopic(endpointArn, topicArn);
        setSubscription(resposta);

        return resposta;
    }

    public String delete(){

        AwsSns sns = AwsSns.getInstance();
        SubscriptionDAO sDAO = new SubscriptionDAO();
        sDAO.selectById(this);

        sns.deleteSubscriptionFromTopic(this.subscription);

        return sDAO.delete(this);

    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        if (this.id != id)
            this.id = id;
    }

    public String getSubscription() {
        return subscription;
    }

    public void setSubscription(String subscription) {
        if (subscription != null){
            if (!this.subscription.equals(subscription))
                this.subscription = subscription;
        }else
            this.subscription = new String();
    }

    public Device getDispositivo() {
        return dispositivo;
    }

    public void setDispositivo(Device dispositivo) {
        if (dispositivo != null){
            if (dispositivo.getId() != this.dispositivo.getId())
                this.dispositivo = dispositivo;
        }else
            this.dispositivo = new Device();
    }

    public Group getGrupo() {
        return grupo;
    }

    public void setGrupo(Group grupo) {
        if (grupo != null){
            if (grupo.getId() != this.grupo.getId())
                this.grupo = grupo;
        }else
            this.grupo = new Group();
    }

}

Here is the Device class:
package com.neocloud.model;

import java.io.Serializable;
import java.util.ArrayList;

import com.amazonaws.util.json.JSONException;
import com.amazonaws.util.json.JSONObject;
import com.neocloud.amazon.AwsSns;
import com.neocloud.model.dao.DeviceDAO;
import com.neocloud.model.enums.EEnvironment;
import com.neocloud.model.enums.EProduct;
import com.neocloud.model.enums.ESystem;

public class Device implements Serializable{

    private static final long serialVersionUID = 8515474788917476721L;
    private long id;
    private String development;
    private String SSL = "tls://gateway.push.apple.com:2195";
    private String feedback = "tls://feedback.push.apple.com:2196";
    private String sandboxSSL = "tls://gateway.sandbox.push.apple.com:2195";
    private String sandboxFeedback = "tls://feedback.sandbox.push.apple.com:2196";
    private String message;
    private String endPointArn;
    private String deviceToken;
    private EProduct appID;
    private String appVersion;
    private String deviceUID;
    private String deviceName;
    private String deviceModel;
    private String deviceVersion;
    private boolean pushBadge;
    private boolean pushAlert;
    private boolean pushSound;
    private ESystem system;
    private EEnvironment environment;
    private ArrayList<Subscription> subscriptions;
    private String deviceUser;

    public Device(){

        clear();

    }

    public String deleteToken(){
        /*
         *
         * terminar aqui ainda...
         *
        DeviceDAO dDAO = new DeviceDAO();

        AwsSns sns = AwsSns.getInstance();

        sns.deleteDeviceEndpoint(getEndPointArn());

        ArrayList<String> subscriptions = dDAO.getSubscriptionsFromEndpointArn(this);

        for (int i=0; i<subscriptions.size();i++){

            sns.deleteSubscriptionFromTopic(subscriptions.get(i));

        }

        return dDAO.delete(this);
        */ return "";
    }

    public String updateToken(){

        if ((system == ESystem.IOS) && (deviceToken.length() != 64))
            return "deviceTokenlen64";

        AwsSns sns = AwsSns.getInstance();
        String jsonResposta = ""+sns.updateDeviceEndpoint(getEndPointArn(), deviceToken);

        DeviceDAO dDAO = new DeviceDAO();
        dDAO.update(this);

        return jsonResposta;

    }

    public String registerDevice(){

        if (appVersion.length() == 0)
            return "applen0";
        if (deviceUID.length() > 40)
            return "deviceUID40";
        if ((system == ESystem.IOS) && (deviceToken.length() != 64))
            return "deviceTokenlen64";
        if (deviceName.length() == 0)
            return "deviceNamelen0";
        if (deviceModel.length() == 0)
            return "deviceModellen0";
        if (deviceVersion.length() == 0)
            return "deviceVersionlen0";

        AwsSns sns = AwsSns.getInstance();
        String jsonResposta = null;

        switch (getAppID()) {
            case MODULE: {
                if (system == ESystem.IOS)
                    jsonResposta = ""+sns.createDeviceEndpoint(deviceToken, Constants.ENDPOINTMODULEIOS);
                else if (system == ESystem.ANDROID)
                    jsonResposta = ""+sns.createDeviceEndpoint(deviceToken, Constants.ENDPOINTMODULEANDROID);
                break;

            }
            case HOSTPRO: {
                if (system == ESystem.IOS)
                    jsonResposta = ""+sns.createDeviceEndpoint(deviceToken, Constants.ENDPOINTHOSTPROIOS);
                else if (system == ESystem.ANDROID)
                    jsonResposta = ""+sns.createDeviceEndpoint(deviceToken, Constants.ENDPOINTHOSTPROANDROID);
                break;

            }
            case CONNEXOON: {
                if (system == ESystem.IOS)
                    jsonResposta = ""+sns.createDeviceEndpoint(deviceToken, Constants.ENDPOINTCONNEXOONIOS);
                else if (system == ESystem.ANDROID)
                    jsonResposta = ""+sns.createDeviceEndpoint(deviceToken, Constants.ENDPOINTCONNEXOONANDROID);
                break;

            }
            case TAHOMA: {

                break;
            }
            case MINIBOX: {

                break;
            }
            case NONE: {

            }
            default: {

            }
        }

        if (jsonResposta != null){

            JSONObject json;
            try {
                jsonResposta = jsonResposta.replace("}", "\"}").replace("arn", "\"arn");
                jsonResposta = jsonResposta.replace("{EndPointArn:", "{\"EndPointArn\":");
                json = new JSONObject(jsonResposta);
                setEndPointArn(json.getString("EndpointArn"));
            } catch (JSONException e) {

                e.printStackTrace();
            }

        }

        Subscription subscription;

        switch (getAppID()){
            case MODULE: {

                subscription = new Subscription();
                subscription.getGrupo().setId(19);
                subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICMODULEGERAL);
                subscriptions.add(subscription);

                if (system == ESystem.IOS){

                    subscription = new Subscription();
                    subscription.getGrupo().setId(25);
                    subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICMODULEIOS);
                    subscriptions.add(subscription);

                }
                else if (system == ESystem.ANDROID){

                    subscription = new Subscription();
                    subscription.getGrupo().setId(22);
                    subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICMODULEANDROID);
                    subscriptions.add(subscription);

                }
                break;

            }
            case HOSTPRO: {

                subscription = new Subscription();
                subscription.getGrupo().setId(10);
                subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICHOSTPROGERAL);
                subscriptions.add(subscription);

                if (system == ESystem.IOS){

                    subscription = new Subscription();
                    subscription.getGrupo().setId(16);
                    subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICHOSTPROIOS);
                    subscriptions.add(subscription);

                }
                else if (system == ESystem.ANDROID){

                    subscription = new Subscription();
                    subscription.getGrupo().setId(13);
                    subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICHOSTPROANDROID);
                    subscriptions.add(subscription);

                }
                break;

            }
            case CONNEXOON: {

                subscription = new Subscription();
                subscription.getGrupo().setId(1);
                subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICCONNEXOONGERAL);
                subscriptions.add(subscription);

                if (system == ESystem.IOS){

                    subscription = new Subscription();
                    subscription.getGrupo().setId(7);
                    subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICCONNEXOONIOS);
                    subscriptions.add(subscription);

                }
                else if (system == ESystem.ANDROID){

                    subscription = new Subscription();
                    subscription.getGrupo().setId(4);
                    subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICCONNEXOONANDROID);
                    subscriptions.add(subscription);

                }
                break;

            }
            case TAHOMA: {

                break;
            }
            case MINIBOX: {

                break;
            }
            case NONE: {

            }
            default: {

            }
        }

        DeviceDAO dDAO = new DeviceDAO();
        return dDAO.insert(this);

    }

    public void clear(){

        development = "";
        message = "";
        endPointArn = "";
        deviceToken = "";
        appID = EProduct.NONE;
        appVersion = "";
        deviceUID = "";
        deviceName = "";
        deviceModel = "";
        deviceVersion = "";
        pushBadge = false;
        pushAlert = false;
        pushSound = false;
        system = ESystem.NONE;
        environment = EEnvironment.HOMOLOGATION;
        subscriptions = new ArrayList<Subscription>();
        deviceUser = "";

    }

    public String toJson(){

        JSONObject json;
        json = new JSONObject(this);

        return json.toString();

    }

    public String getDevelopment() {
        return development;
    }

    public void setDevelopment(String development) {
        if (development != null){
            if (!development.equals(this.development))
                this.development = development;
        }
        this.development = new String();
    }

    public String getSSL() {
        return SSL;
    }

    public void setSSL(String sSL) {
        if (sSL != null){
            if (!sSL.equals(this.SSL))
                this.SSL = sSL;
        }
        else
            this.SSL = new String();
    }

    public String getFeedback() {
        return feedback;
    }

    public void setFeedback(String feedback) {
        if (feedback != null){
            if (!feedback.equals(this.feedback))
                this.feedback = feedback;
        }
        this.feedback = new String();
    }

    public String getSandboxSSL() {
        return sandboxSSL;
    }

    public void setSandboxSSL(String sandboxSSL) {

        if (sandboxSSL != null){
            if (!sandboxSSL.equals(this.sandboxSSL))
                this.sandboxSSL = sandboxSSL;
        }else
            this.sandboxSSL = new String();
    }

    public String getSandboxFeedback() {
        return sandboxFeedback;
    }

    public void setSandboxFeedback(String sandboxFeedback) {
        if (sandboxFeedback != null){
            if (!sandboxFeedback.equals(this.sandboxFeedback))
                this.sandboxFeedback = sandboxFeedback;
        }else
            this.sandboxFeedback = new String();
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        if (message != null){
            if (!message.equals(this.message))
                this.message = message;
        }else
            this.message = new String();
    }

    public String getEndPointArn() {
        return endPointArn;
    }

    public void setEndPointArn(String createPlatformEndpointResult) {
        if (createPlatformEndpointResult != null){
            if (!createPlatformEndpointResult.equals(this.endPointArn))
                this.endPointArn = createPlatformEndpointResult;
        }else
            this.endPointArn = new String();
    }

    public String getDeviceToken() {
        return deviceToken;
    }

    public void setDeviceToken(String deviceToken) {
        if (deviceToken != null){
            if (!deviceToken.equals(this.deviceToken))
                this.deviceToken = deviceToken;
        }else
            this.deviceToken = new String();
    }

    public EProduct getAppID() {
        return appID ;
    }

    public void setAppID(EProduct appID){
        if (appID != this.appID)
            this.appID = appID;
    }

    public String getAppVersion() {
        return appVersion;
    }

    public void setAppVersion(String appVersion) {
        if (appVersion != null){
            if (!appVersion.equals(this.appVersion))
                this.appVersion = appVersion;
        }else
            this.appVersion = new String();
    }

    public String getDeviceUID() {
        return deviceUID;
    }

    public void setDeviceUID(String deviceUID) {
        if (deviceUID != null){
            if (!deviceUID.equals(this.deviceUID))
                this.deviceUID = deviceUID;
        }else
            this.deviceUID = new String();
    }

    public String getDeviceName() {
        return deviceName;
    }

    public void setDeviceName(String deviceName) {
        if (deviceName != null){
            if (!deviceName.equals(this.deviceName))
                this.deviceName = deviceName;
        }else
            this.deviceName = new String();
    }

    public String getDeviceModel() {
        return deviceModel;
    }

    public void setDeviceModel(String deviceModel) {
        if (deviceModel != null){
            if (!deviceModel.equals(this.deviceModel))
                this.deviceModel = deviceModel;
        }else
            this.deviceModel = new String();
    }

    public String getDeviceVersion() {
        return deviceVersion;
    }

    public void setDeviceVersion(String deviceVersion) {
        if (deviceVersion != null){
            if (!deviceVersion.equals(this.deviceVersion))
                this.deviceVersion = deviceVersion;
        }else
            this.deviceVersion = new String();
    }

    public boolean isPushBadge() {
        return pushBadge;
    }

    public void setPushBadge(boolean pushBadge) {
        if (pushBadge != this.pushBadge)
            this.pushBadge = pushBadge;
    }

    public boolean isPushAlert() {
        return pushAlert;
    }

    public void setPushAlert(boolean pushAlert) {
        if (pushAlert != this.pushAlert)
            this.pushAlert = pushAlert;
    }

    public boolean isPushSound() {
        return pushSound;
    }

    public void setPushSound(boolean pushSound) {
        if (this.pushSound != pushSound)
            this.pushSound = pushSound;
    }

    public ESystem getSystem() {
        return system;
    }

    public void setTipoSmartphone(ESystem system) {
        if (system != this.system)
            this.system = system;
    }

    public EEnvironment getEnvironment() {
        return environment;
    }

    public void setEnvironment(EEnvironment environment) {
        if (environment != this.environment)
            this.environment = environment;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        if (this.id != id)
            this.id = id;
    }

    public void setSystem(ESystem system) {
        if (system != this.system)
    this.system = system;
    }

    public ArrayList<Subscription> getSubscriptions() {
        return subscriptions;
    }

    public void setSubscriptions(ArrayList<Subscription> subscriptions) {
        if (subscriptions != null)
            this.subscriptions = subscriptions;
        else
            this.subscriptions = new ArrayList<Subscription>();
    }

    public String getDeviceUser() {
        return deviceUser;
    }

    public void setDeviceUser(String deviceUser) {
        if (deviceUser != null){
            if (!deviceUser.equals(this.deviceUser))
                this.deviceUser = deviceUser;
        }else
            this.deviceUser = new String();
    }

}

Here is the Group class:
package com.neocloud.model;

import java.io.Serializable;
import java.util.ArrayList;

import com.amazonaws.util.json.JSONException;
import com.amazonaws.util.json.JSONObject;
import com.neocloud.amazon.AwsSns;
import com.neocloud.model.dao.GroupDAO;

public class Group implements Serializable{

    private static final long serialVersionUID = -5032857327241801763L;
    private long id;
    private String nome;
    private String topicArn;

    public Group(){
        this.clear();
    }

    public void clear(){
        this.id = 0;
        this.nome = new String();
        this.topicArn = new String();
    }

    public String registerGrupo(){

        AwsSns snsClient = AwsSns.getInstance();

        String topic = ""+snsClient.createTopic(this.nome);

        JSONObject json;
        String jsonResposta = topic;
        try {
            jsonResposta = jsonResposta.replace("}", "\"}").replace("arn", "\"arn");
            jsonResposta = jsonResposta.replace("{TopicArn:", "{\"TopicArn\":");
            json = new JSONObject(jsonResposta);
            setTopicArn(json.getString("TopicArn"));
        } catch (JSONException e) {

            e.printStackTrace();
        }

        GroupDAO grupoDAO = new GroupDAO();
        return grupoDAO.insert(this);

    }

    public String deleteGrupo(){
        AwsSns snsClient = AwsSns.getInstance();

        GroupDAO grupoDAO = new GroupDAO();
        ArrayList<Group> grupos = grupoDAO.select(this);

        if (grupos.size() > 0){

            for (int i = 0; i<grupos.size(); i++){
                this.topicArn = grupos.get(i).getTopicArn();
                this.nome = grupos.get(i).getNome();
                this.id = grupos.get(i).getId();
                snsClient.deleteTopic(this.topicArn);

            }

            return grupoDAO.delete(this);

        }

        return "-1";
    }

    public String toJson(){

        JSONObject json;
        json = new JSONObject(this);

        return json.toString();

    }

    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
    public String getTopicArn() {
        return topicArn;
    }
    public void setTopicArn(String topicArn) {
        this.topicArn = topicArn;
    }

}

Here is the Tomcat log:

Exception in thread "http-bio-8080-exec-5"
  java.lang.StackOverflowError  at
  java.lang.reflect.Executable.(Unknown Source)   at
  java.lang.reflect.Method.(Unknown Source)   at
  java.lang.reflect.Method.copy(Unknown Source)     at
  java.lang.reflect.ReflectAccess.copyMethod(Unknown Source)    at
  sun.reflect.ReflectionFactory.copyMethod(Unknown Source)  at
  java.lang.Class.copyMethods(Unknown Source)   at
  java.lang.Class.getMethods(Unknown Source)    at
  com.amazonaws.util.json.JSONObject.populateMap(JSONObject.java:930)
    at com.amazonaws.util.json.JSONObject.(JSONObject.java:285)   at
  com.amazonaws.util.json.JSONObject.wrap(JSONObject.java:1540)     at
  com.amazonaws.util.json.JSONObject.populateMap(JSONObject.java:960)

Thanks for all help!
Comment: have you tried debugging your application?
Comment: Can you show more of the stack trace do you can see the section which is repeating?
Answer: Maybe a circular reference in your object.
Answer: json = new JSONObject(this);

You're trying to JSONify this
id = 0;
subscription = "";
grupo = new Group();
dispositivo = new Device();

And i think that somehow, it cant JSONify Group and Device. Could you show us the code for those classes ?
UPDATE : In your Subscription.clear() method, you affect a new Group() & a new Device(). When creating a new Device(), the method Device.clear() get called and create a new ArrayList<Subscription>(), that'll call the method Subscription.clear(), that'll affect a  new Group() & a new Device() and so on. You're infinitely looping, that's why you get the StackOverflow error. It's weird that you're subscription is made of a Group that is made of an ArrayList of subscription who are also mades of Groups etc.
Comment: @pedro.olimpio glad i've been able to help you out. Cheers buddy !
Comment: @pedro.olimpio updated, check if you could work around your model
Comment: Thanks for help @Jorel I'm changing the circular reference here... Thanks a lot.
Answer: Maybe you have a circular reference...
Object a = X;
Object c = Y;

a.prop = Y;
c.prop2 = X;

then, your JSON(a) is
{
    prop : {
      prop2 : {
       prop : Y (Y have prop2 again)
       /*infinite..*/
      }
    }
 }


Constructor in VBA - Runtime error 91 "Object variable not set"

Question: I am trying to write some code in excel VBA using the Object Oriented Concept. Therefore I wanted to initialize my objects with constructors, like we usually do in Java. However I discovered that the default Class_Initialize() Sub that is offered in VBA does not take arguments. After searching a bit, I found that the answer for this Question proposed a pretty good alternative.
Here is a sample of my Factory Module (I Named it Creator):
Public Function CreateTool(ToolID As Integer) As cTool
    Set CreateTool = New cTool
    CreateTool.InitiateProperties (ToolID)     '<= runtime error 91 here
End Function

The class cTool:
Private pToolID As Integer
Private pAttributes As ADODB.Recordset
Private pCnn As ADODB.Connection

Public Sub InitiateProperties(ToolID As Integer)
    Dim sSQL As String
    Set pCnn = connectToDB()     'A function that returns a connection to the main DB
    pToolID = ToolID
    sSQL = "SELECT Tool_ID, Status, Type, Tool_Number " _
                 & "FROM Tool  WHERE Tool_ID = " & pToolID
    pAttributes.Open sSQL, pCnn, adOpenKeyset, adLockOptimistic, adCmdText
End Sub

This is how I call the constructor:
Dim tool As cTool
Set tool = Creator.CreateTool(id)

My issue is that when I run the code, I get the following error:
Run-Time error '91' : Object Variable or With Block Variable not Set
The debug highlights the CreateTool.InitiateProperties (ToolID) line of my CreateTool Function.
I know that this usually happens when someone is setting a value to an object without using the keyword Set but it does not seem to be my case.
Any help, advice to resolve this issue would be greatly appreciated!
Thanks.
Comment: You haven't create pAttributes object in your cTool.InitateProperties.
Comment: Thank you! I never tought about checking my *cTool* class as the debugger was pointing somewhere else. Adding the line `Set pAttributes = New ADODB.Recordset` solved the issue. Thanks again for the fast reply. I will edit my post to include you answer
Comment: Don't do that. This is a Q&A site, not a forum. The Question should contain the question, and Answers should contain the answer.
Comment: Well noted @Mat'sMug . I did not notice that you already made an answer. My bad, i am still new here. I will not edit the question.
Comment: No worries - if your code works as intended now, feel free to post it (all!) on [codereview.se] for tips to make it cleaner and easier to maintain.
Answer: Might not be the cause of your error, but this:
Public Function CreateTool(ToolID As Integer) As cTool
    Set CreateTool = New cTool
    CreateTool.InitiateProperties (ToolID)     '<= runtime error 91 here
End Function

Is problematic for a number of reasons. Consider:
Public Function CreateTool(ByVal ToolID As Integer) As cTool
    Dim result As cTool
    Set result = New cTool
    result.InitiateProperties ToolID
    Set CreateTool = result
End Function

Now, looking at the rest of your code, you're doing the VBA equivalent of doing work in the constructor, i.e. accessing database and other side-effects to constructing your object.
As @Jules correctly identified, you're accessing the unitialized object pAttributes inside InitiateProperties - that's very likely the cause of your problem.
I'd strongly recommend another approach - if you come from Java you know doing work inside a constructor is bad design... the same applies to VBA.
Get your code working, and post it all up on Code Review Stack Exchange for a full peer review.
Comment: @OscarAnthony Keep in mind that Code Review is a place where **working** code is reviewed and not a place to ask _how to make it work_, but rather _how to make it work_ **better**.
Comment: Thank you, I will modify my code accordingly. I did not know about Code Review Stack Exchange. I will start using it more often!


Can't boot to Ubuntu, after messing with GRUB file

Question: I use Ubuntu 14.04 (alone, no dual boot) and today it installed a new kernel (3.13.0-49). For some reason, it did not work well with my system, the mouse did not respond, and neither did my network. So I booted using an older kernel (3.13.0-37) and it worked fine.
But every time I booted I had to press shift and choose the working kernel, so I looked around on how to configure my boot so it loaded the previous one.
Not knowing exactly what I was doing, i followed the steps on this thread, basically editing the /etc/default/grub file where it read GRUB_DEFAULT=0 to GRUB_DEFAULT=2. And then running sudo update-grub on Terminal.
Then I restarted my PC and all I got was the ASUS UEFI BIOS Utility. No Grub, no Ubuntu, no nothing. Holding shift or c did not do anything. I made a Live USB from a freshly downloaded .iso of Ubuntu and now I'm running Ubuntu from the USB drive. But I can't recover my old grub file (I did had it backed up before messing with it). I can access my HDD, with three partitions: sda1,  where I think (as I am very ignorant in these matters) my PC boots from; sda2 (not sure what it is) and sda3, where most of my files are, but it is in a file system called "crypto_LUKS"
I got this by reading in the BootInfo summary from boot-repair.
I've tried solving the problem three different ways:

using boot-repair recommended repair (like this) -- it says it finds the /boot, says it does the repairing, but after booting I just go back to my UEFI BIOS. If I choose "advanced options" I cannot see anything under the tabs "GRUB location", "GRUB options" or "MBR options".
following these steps (answer #2) via terminal. After trying
sudo mount /dev/sda1 /mnt
and
sudo grub-install --root-directory=/mnt /dev/sda

(with both sda1 and sda3), I get
Installing for i386-pc platform.
grub-install: warning: this GPT partition label contains no BIOS Boot Partition; embedding won't be possible.
grub-install: warning: Embedding is not possible.  GRUB can only be installed in this setup by using blocklists.  However, blocklists are UNRELIABLE and their use is discouraged..
grub-install: error: will not proceed with blocklists.

editing the grub file in my sda3 (now in /media/ubuntu/5810cd14-bf74-4b7d-a312-81129f4bc7aa/etc/default) back to the way it was, which I managed to do using sudo su (the drive was read-only) -- but then when I try to run sudo update-grub it gives me the following error message: "/usr/sbin/grub-probe: error: failed to get canonical path of `/cow'."

What should I do? I really don't want to reinstall Ubuntu, all my files seem to be intact and all I need to do is get my system to boot! I can't believe I'm in all this mess by simply (and stupidly) editing a single character in a single file.

EDIT:
I combined oldfred's link about UEFI boot repairing with the other one I had posted, about encrypted partitions boot repairing and did get grup-install to run installing grub-efi-amd64.
Then I got an error message saying I should change my /etc/default/grub config file to include the line GRUB_ENABLE_CRYPTODISK=1. Did it and it did not work. Then I've seen here there's a bug, the correct line would be GRUB_ENABLE_CRYPTODISK=y.
Did it and got yet another error message I can't recall now.  Got fed up after two days working on this and reinstalled Ubuntu with a fresh format.  Working well since then, although booting is taking a little longer since then.
Comment: From Boot-Repair run the Summary report and post above the link it gives, so we can see details. But it sounds like an UEFI install and now you are trying to boot or repair in BIOS mode. Report will give us details.
Comment: http://paste.ubuntu.com/10869407/
Comment: You have an UEFI system with efi, /boot & LVM install partition with full drive encryption. I do not know LVM nor encryption, but with Boot-Repair or any manual repairs you must use pass phase to unencrypt partitions so you can update them. Be sure to always boot in UEFI mode especially when making repairs.
Comment: OK, so knowing that that's trhe problem, how do I go about solving it? Let me state that I am almost completely ignorant as to what I'm doing here.
Comment: I followed [this](https://pzolee.blogs.balabit.com/2010/07/grub-helyreallitas-titkositott-es-lvm-particiok-eseten/) and got to the point where I can activate my partitions, but I don't know which of them should I mount in order to run install-grub and update-grub.
Comment: My `ls -la /dev/mapper` results are: `lrwxrwxrwx  1 root root       7 Apr 23 18:19 luks-98484e8b-b595-4b21-86cc-2a882c7afddb -> ../dm-0
lrwxrwxrwx  1 root root       7 Apr 23 18:19 ubuntu--vg-root -> ../dm-1
lrwxrwxrwx  1 root root       7 Apr 23 18:19 ubuntu--vg-swap_1 -> ../dm-2`
Comment: Your sudo grub-install that said installing for i386-pc is the grub-pc version for BIOS boot. You need to be sure to install grub-efi-amd64 for UEFI boot. You should have only gottine the grub-pc version if booted in BIOS mode, unless somehow update uninstalled UEFI and installed BIOS by mistake?? If so that is a bug.
Comment: How do I force grub-install to install grub-efi-amd64 instead of i386-pc?
Comment: IF you boot Boot-Repair in UEFI mode it should work.  Or you need to chroot, but use your LVM and decrypted partitions as mounts. Do not know enough about LVM to help otherwise. http://askubuntu.com/questions/53578/can-i-install-in-uefi-mode-with-the-alternate-installer/57380#57380  Some more info: http://askubuntu.com/questions/226969/how-do-i-create-a-multiboot-environment-using-lvm-for-your-buntu-operating-syst/226982#226982
Comment: Thanks a lot oldfred! You did what you could and you almost got me there... I guess UEFI and partition encryption are still very hard to work with in Ubuntu, specially with someone not so tech-savvy like me.
Answer: If you still have access to Linux, try using Grub Customizer.
http://ubuntuhandbook.org/index.php/2014/04/install-grub-customizer-ubuntu-1404/
See if you can find your old Ubuntu partition, put it at the top of the list (it doesn't necessarily have to be at the top of the list. I just suggested the top so that it would boot automatically if you don't press any keys within 10 seconds) and save the file.
Comment: Running it now, but when I choose sda1 as partition, i get "this seem not to be a root file system (no fstab found)". When i choose sda2, I get "Mount failed" and I can read in terminal `mount: unknown filesystem type 'crypto_LUKS'`.
Comment: BTW, i also get errors in Grub Customizer for both DEVICEMAP_FILE and OUTPUT_FILE (red "!" instead of green "V").


Pagination in master-detail view

Question: I'm trying to show a master-detail view, where each cell in the master table (the one on the left) represents a list.
When Clicking a cell, the list is opened in the right panel.
The table and the list have pagination.
My problem is, in case the user selected a cell, (for example, Column 1, ID 6, as in the example), and then moves to a different page in the left table, what should I do with the contents of the right panel?
The possibilities as I see them, are:

Hide the right panel. I'm not sure that this is a good option, because the user might want to keep seeing it, even after he moved to another page.
Keep the right panel. This might be confusing, because the user will see in the right panel details about a row that doesn't appear in the left table.

Both of these options are not good, as each has its drawbacks.
I couldn't think, or find any other way, though it seem like a common problem for master-detail views, and I thought that I will find a solution quickly.
Infinite scroll isn't relevant, as the users said that it isn't comfortable for them.
So my question is, Is there a known pattern to handle pagination in master-detail view? and if there is non, have anyone experienced in such design and can add a better idea then the ones listed above?

Extra details about the usage of the table

The user will explore the table, mostly by sorting it according to its columns, and inspecting the extreme values. Then after finding an interesting cell, he will click it and explore further.
Occasionally, the user will know which cell he is looking for (i.e. a cell that he already saw in the past), and will search it explicitly, with the filter.

Related Question: Displaying million records in Master Detail Grid (Million in both master detail)
I couldn't find what I was looking for here.
EDIT
as per @Luchadora 's answer:

The user will occasionally want to make comparison between 2 cells in different pages, but it will be relatively rare
I thought to leave the panel empty, and not tottaly collapse it, because it will make the screen "bounce", and I don't need this extra "real-estate"
Comment: What does prev and next buttons do in your grid? Is it left/right or up/down?
Comment: @IliasBennani they show other items of the same list, i.e. for the lefthand table, clicking next will show items IDs 10-18 (now 1-9 are shown)
Answer: It does not have to be a problem if you think about the following additions to the design;

Mention the content of the cell in the detail pane (I now only see the column/ID but not the value)
Visually highlight the cell of the master page when selected for the
detail view. If the user navigates to a next page, the missing
highlighted cell already indicates that the detail list is from an
off-page grid-cell.
Include a subtle dynamic quicklink back to the matching master-page
from the detail-view. The quicklink will only be visible if the
master view is on a different page. Very quick mockup
Comment: Actually, I have the highlights in my original design, but I didn't want to load the example with too many details, so I've omitted it, but you are right, the fact that there will be no highlighted cell will indeed indicate that the list is from an off-page cell.                  **Regarding the quicklink**, do you have an idea of how it can be shown?
Comment: See the edit for a link to a very quick mockup. I was wondering about the pagination in the detail pane...what does it do? I would expect a vertical scrolling list if the list was longer than the detail view....
Comment: the clients said that vertical scrolling isn't comfortable for them, they want pagination for both of the panels. Each of the lists might contain *a lot* of rows, and infinite scroll isn't comfortable for them, so both of the panels need pagination. *About the mockup* that you've uploaded, the quicklink makes me as a user feel that it will change something in the right panel, and not in the left panel, so I'm not comfortable with it. Do you have another idea? (and thanks a lot for the mockup!)
Comment: Fair enough with the pagination. You might add a clickable icon on the border between the two panes to indicate the connection of navigating the master pane back to the page containing the grid-cell. See updated mockup. A tooltip might help here. Otherwise you could just add a clickable link on the master page somewhere, perhaps next to the pagination.
Answer: That would depend on the goal of the user.
Does the user want to compare the details of a cell? If so, I would keep the panel with the previous information (option 2 that you mentioned).
E.g.: I want to see the details of Column 1, ID 6. After seeing the details I want to compare the information with Column 2, ID 22 (which would be on the next page). In that case it's useful to keep the panel with the Column 1, ID 6 open, so I can compare easily when clicking on the Column 2, ID 22.
In other cases I would hide the panel or leave it empty when going to the next page. Will the left tabel scale to full width when the panel collapses?
Comment: 1. The user will occasionally want to make this comparison, but it will be relatively rare.
So I'm not sure what's better - hide info that might be relevant occasionally, or show info that is confusing and not clear what is its origin.
2. I thought to leave the panel empty, and not totaly collapse it, because it will make the screen "bounce", and I don't need this extraa "real-estate"
Comment: Yes, I agree we shouldn't want a bouncing screen and also leaving the panel empty feels a bit weird (like something is wrong). Maybe you can still keep the previous information, combined with the tips Dave Senden mentioned above, like highlighting cells and adding a link back.

Pagination in master-detail view


How to add cardapio to panel?

Question: I followed the instructions shown for downloading (I'm on Maverick) at the launchpad site for this main menu replacement:
https://launchpad.net/cardapio
It indicates that once you do this, it should show up in the Add to Panel list of applets, but I'm not seeing it. This is the first time I've installed a new applet; do I need to restart my session to see it?
Answer: You can either restart your session or just issue
pkill gnome-panel.
That will restart your panel(s) and then cardapio will be visible. Good choice by the way. I'm using it and it's a realy good replacement for gnome-do plus any menu.

How to add cardapio to panel?


Token works in Dev but not Prod. EDAMSystemException AuthenticationToken

Question: I am having trouble getting my app to work in production environment.
First of all I created API credentials and used them to authenticate my website on Evernote sandbox.. I only need to grab some notes, not creating a web service as such so I'm assuming dev token will suffice?
I've generated a dev token and now using it to connect to the client. All is working great on dev.
I have now moved to production and had Evernote move my API credentials to their live servers... As with sandbox I generated a new dev token on my account and also authenticated my site on my live account.
However, whenever I try to return some notes through their PHP Cloud SDK I get the following error:
EDAMSystemException in UserStore.php line 3210:
authenticationToken

Here is my code I am using to call the API:
$this->client = new Client($token);
$note = $this->client->getNote($this->request->guid); // note guid

Then I can do stuff like $note->title - this works great in dev, just not production.
Token looks like this:
S=s123:U=4567ab1:E=12ecf234a67:C=2345678fa58:P=1cd:A=en-devtoken:V=2:H=12adf1b71184568a7434e1a966g0b1d1
(not my real token)
The token was generated from my live Evernote account.
Thanks
Comment: A bit confused - sorry. For production, are you using your Developer Token, or are you using an API consumer key and secret (via oauth)?
Answer: I managed to fix it myself by providing the rest of the arguments to the Client method.
Looking into SDK code Client.php:
public function __construct($token = null, $sandbox = true, $advancedClient = null, LoggerInterface $logger = null, $china = false)
Everything has default values so I guess any work I was doing over use the live account was being forced back into sandbox here.
\Client($token, false, null, null, false) fixed the issue.
I probably should have looked in to it a little deeper but Evernotes dev docs are shockingly poor.
Answer: Seems like you're doing everything right...
What I can suggest is to double-check that you don't have extra characters in your PHP string (a space for example).
If you're sure your token is right, you may want to contact evernote support and ask them to check your credentials.
It might be an error on their side.


How can I explain my 9 years old brother that $8a\cdot4a \neq 64a$

Question: My youngest brother had a pre-algebra test yesterday and he was asked to tell if two expressions are equal or not.
We agreed on most of the things but on this one I find it hard to make him accept my answer.
He was asked to tell if $8a\cdot4a [\space\space\space\space\space\space\space\space] 64a$ are equal or not. He checked for a specific case (one of the only 2 cases where this equation is true) and showed that for $a = 2$ the equation stands, and I find it hard to make him agree with me that if the equation stands only for $a = 0,2$ than the two expression are equal for those $a$'s only and thus the expression can't be called equal.
I think I'm having a hard time explaining him the definition of equality with variables, and here's where you enter the picture.
Comment: Try this: $a[ ~~~]5$.  Would he say "equal" for this one too?
Comment: @vadim123 haha that actually worked! (he's sitting right next to me right now)
Comment: I think your little brother is perplexed by the subtle difference between an *equation* and an *identity*.
Comment: "=" means "always equal", not "sometimes equal".  Try literally any other value of $a$.
Comment: I tried *always*, I also tried to demonstrate the definition as a scale where the two sides of the scale must always weight the same, no matter what weight they carry.
Comment: Try $a=1$ ft (or $a=1$ meter, depending on where you are). One side of the claim is an area, the other a length.
Answer: There are different kinds of so-called "equality". An identity identifies two different forms of the same expression, whether it is $$1/2 ≡ 2/4,\\1/2 ≡ 0.5,\\x+x ≡ 2x, \\(x-1)(x-2) ≡ x²-3x+2, \\f(x) ≡ x+1,$$ and so on.
Equivalence is an essential concept that is found throughout mathematics. We should have been introduced to it in the very beginning; and it would be clearer if we always used the equivalence sign for it. The $≡$ sign means that we are looking at two different forms of the same thing. Forms and equivalence are enormously important concepts.
Then there is conditional equality which would be clearer if we limited use of the equals sign to it. This is an equivalence for only certain values of the variables, if any.
Answer: I think he can get this if he knows the commutative and associative properties of arithmetic:
Commutative: $a \cdot b = b \cdot a$.
Associative: $(a \cdot b) \cdot c = a \cdot (b \cdot c)$
Applied to your expression:
$(8 a) \cdot (4 a) \\\underbrace{=}_{associative} 8 \cdot (a \cdot 4) \cdot a \\\underbrace{=}_{commutative} 8 \cdot (4 \cdot a) \cdot a \\\underbrace{=}_{associative} (8 \cdot 4) \cdot (a \cdot a) = 32 a^2$
Comment: Really? For a 9 years old?
Comment: I'm not sure he does but that might be a great opportunity to teach him those cornerstones of mathematics and algebra especially.
Comment: @JPLF, I can give it a shot, doesn't it worth a try?
Comment: @JPLF: I saw "pre-algebra test."  My kids learned these properties in pre-algebra.
Comment: People learn these properties in pre-algebra, but I think most of them fail to get understanding out of them until much later. Perhaps that's OK-surely it's better for him to get the right answer, and later on start getting it for the right reasons.
Comment: I tried, I really did, but then he almost started crying, shouting 'he doesn't know math, and does want to' and the last thing I want this boy to gain is antagonism for math. The problem is that the kids nowadays are taught that $x \cdot x = x^2$ but they're not told why. When they teach them that $2 \cdot 2 = 4$ they give them visual examples for motivation but whenever they start dealing with variables motivation goes to hell and they just learn everything by heart.
Answer: This is a late answer, but I think none of the others address the real issue. Basically, your brother agrees that if $a=2$, then $4a \times 8a = 64a$. But when people write "$4a \times 8a = 64a$" all by itself, they implicitly are stating "$4a \times 8a = 64a$ for every $a$", where the type of $a$ is inferred from the context. In this case every object is assumed to be a (real) number if not specified. It will no longer be the case when he learns about other kinds of mathematical objects, so it would be good to point out these kinds of implicit assumptions. In other words, it is a matter of convention in what it means rather than something you can ever convince someone of. As for formalism, I hope he understands that mathematics is about logical reasoning and not guessing and so he would in time appreciate formal manipulation using the field axioms.


replacing flooring under walls (2nd story)

Question: I am wanting to tile my master bath.
When I pulled up the old linoleum flooring, it was particle-board.  I've read nightmares about tiling over particle board so I'm planning on replacing it with plywood + cement backer.
This is the 2nd story of my house and the walls are sitting on top of the particle-board.  On the exterior wall, I was planning on just cutting along the length of the wall as close as I can get to it and reinforcing the new plywood from underneath between the joists (which run perpendicular to the exterior wall).
However, on the interior wall near the toilet, there has obviously been a previous leak causing damage to the flooring under the wall and causing a gap (just over a 1/4in).  The level of the floor here has definitely sunk (revealed by using a level) to this point.
The other side of this wall is another toilet in another bathroom which I do not plan on renovating (yet) since it is the only other bathroom in the house.
How do I fix this?
Comment: So the joists for the walls are actively supported by the particleboard? Not other 2x4s?
Comment: Is the particle board acting as subfloor?  Or is there a layer of 2x6s under the particle board?
Comment: @DarthCaniac - correct (I think).  I cut a hole in the flooring (to get started tearing it up) and there is no visible cross beam/flooring seam that would be underneath where this wall is.  I updated the OP with a cross section diagram.  I don't know for sure that the wall studs line up with the joists underneath the flooring.
Comment: @wallyk - correct - I was hoping that the particle-board was simply underlayment for the linoleum and that I would find something underneath but when I cut through it, there is nothing.  It sits directly on top of the floor joists and the walls sit on top of it.
Answer: I think I would jack the wall up a tiny bit (1/16 inch), enough to slide out the particle board and slide in plywood.
Given the difficulties of jacks being in the way of the work, cut the plywood so it is only 12-16 inches wide (and 8 feet long or whatever) so the jacking support can be away from the wall.
Comment: This makes sense.  However, how do I cut the existing particle board (that is sandwiched between the wall and the joists) to allow me to pull the existing flooring out once the wall is jacked up?  Additionally, the same sheet of flooring extended into the other bathroom on the other side of the wall that I REALLY don't want to deal with right now (wife would kill me if I tear up both bathrooms in our house at the same time).
Comment: Actually, now that I think about it a bit more, I should be able to cut it from the underside since there is no support between the joists on the bottom side of the flooring.  Of course I won't know for sure until I tear the rest of the flooring out to see if there are pipes/drains in the way.
Comment: @kinar:  Does it extend under the wall?  Cut it next to the wall, and then reach underneath and cut it with a [small circular saw](http://www.google.com/imgres?imgurl=&imgrefurl=http%3A%2F%2Ftoolguyd.com%2Frockwell-circular-saw-rk3441k%2F&h=0&w=0&tbnid=iC1gjnTS2zVGRM&zoom=1&tbnh=161&tbnw=313&docid=RTwJRISvmvBTJM&tbm=isch&ei=Od5sVMDsAY34igLzjoDgBg&ved=0CAQQsCUoAA).  At the joists, you'll probably have to chisel the last nubs out.  If you were going to replace the floor in the other bathroom, doing so now would make this one a lot easier.
Comment: agreed, doing it in 1 step would make it easier but I simply don't have the option of tearing both bathrooms apart right now.  The 2nd bathroom may not get touched for a couple years down the road.  Additionally, the back oth other toilet (other side of the wall) is only a few inches away from the base of the wall so I don't even have an option of taking out part of it.  However, that seems to be beyond the scope of this question.  Answer accepted.


How is $\frac{1}{\sqrt{-16}} = -\frac{1}{4}$?

Question:
Simplify $(-16)^{ -\frac{1}{2}}$

Here is my attempt at solving this question:
\begin{align}
(-16)^{ -\frac{1}{2} } &= \frac{1}{(-16)^\frac{1}{2}} \\
&= \frac{1}{\sqrt{-16}}
\end{align}
$$ \therefore \text{The answer is undefined} $$
This was the answer:
\begin{align}
(-16)^{ -\frac{1}{2} } &= \left( \frac{1}{-16} \right) ^\frac{1}{2} \\
&= \frac{1}{\sqrt{-16}} \\
&= -\frac{1}{4}
\end{align}
Isn't $\sqrt{-16}$ invalid? How can $\frac{1}{\sqrt{-16}}$ be simplified to $-\frac{1}{4}$?
Comment: Which textbook? Try to get your money back.
Comment: the answer $-{1\over4}$ is incorrect. The (principle) answer would be $i\over 4$, but if you are only considering real numbers, then you are correct that this isn't defined.
Comment: The titular equality is false. LHS is imaginary, whereas RHS is real.
Comment: Are you sure it is $(-16)^{-1/2}$ and not $-16^{-1/2}$?
Answer: If you disallow imaginary numbers, it is undefined.  Otherwise, there are two solutions to $x^2=-1/16$, namely $$\pm\frac{1}{4i}=\pm\frac{i}{4},$$ where $i=\sqrt{-1}$.  In any case, it is not $-1/4$.
Comment: Are you sure? Where $-\frac{i}{4}$? Also, are you sure that $\sqrt{-1}=i$?
Comment: That depends on how you define the square root function. If there are two results, then it is not simply a function.
Comment: Yes, corrected.


Can you commit incest?

Question: I want to know if you can have the offspring mate with one of his or her own parents. It's odd, yes, but I'm curious if Bethesda thought this through.
Edit: I'm going to cross breed, by this I mean like this
<code>Parent 1 + Parent 2   Parent 3 + Parent 4
    = Child 1            = Child 2

Parent 1 + Child 2    Parent 2 + Child 3
    = Child 3            = Child 4
</code>
I hope this visual (somewhat) representation will show what I'm planning to do.
Comment: Sounds like a pretty simple thing to try.
Comment: Kids grow in 3 hours, and no one ever seems to die of old age. I wouldn't overthink this.
Comment: "Can you..." is an easy question to ask, but "Should you..." might be more important with this question...
Comment: I but spaces in between but it didn't work... Sigh
Answer: I believe there is actually a catch regarding parents/children.  Instead of flirting, when you put them in the same residence the characters remark about "how nice it is to spend time with family".   I am not sure how it affects subsequent generations though!
Comment: I have caught this too, I was very happy to see that happen!
Comment: This is indeed the case. I had a guy and girl in a room for freaking ever as they were a good pair and no smillies! I thought maybe it was the religous outfit the guy was wearing but when another girl was added to the mix they had no issues.. I zoomed in and they are both happy to be with family... Oi! So much time wasted by not zooming in.
Answer: Putting two dwellers who were both born of the same two dwellers (ie siblings) in the living quarters will also give the "nice to spend time with family" message. So while you can almost definitely mate half-brothers/sisters, direct siblings are still counted as "family" and they won't reproduce.
Answer: You can't mate full- or half-siblings - if a pair of dwellers shares even one parent, they will not mate. You can't mate parents to their children. You CAN mate grandparents to grandchildren, aunts/uncles to nieces/nephews, cousins to cousins, etc. In other words, the game won't let you mate first-degree relatives, but everything else is fair game. Source: experimentation.
Answer: Well I've already tried it and the children were just normal as all others.
Comment: Oddly, they're all automatically given the last name of Lannister.
Comment: What do you mean by 'were just normal as all others'? Will they breed or will they not?
Comment: They produce baby's as all other people would do in the barracks. :-) And the baby's are normal too.
Comment: @Sterno Is this true? That would be one hell of an Easter Egg :D
Comment: Well I haven't noticed that. But I should say that I haven't an eye on that as I'm not a GoT fan. :-D
Comment: I may have been joking.
Comment: What? Never! We'll I have noticed it - never mind. ;-)
Answer: I have just found out that breeding can occur between a Great Grand Child and their Great Grand Parent.  This means that with a restriction of only three of one sex technically a quite disturbed Lannister cycle can be formed!

Can you commit incest?


Problem with remapped key when changing between languages

Question: I've remapped a certain key (` to w) with this way:

xmodmap -e "keycode 49 = w"

I use Greek language, not only English and I change between languages with ALT+SHIFT. When I turn the keyboard layout to Greek it should output a greek character that is assigned to w key at greek keyboards (the character ς). It continues to output w when I turn the keyboard to Greek. The name that is given to this greek character (when I press w/ς key after xev at the terminal with the language turned to Greek) is Greek_finalsmallsigma
Temporarily I did the following in order to output the greek character by pressing Shift

xmodmap -e "keycode 49 = w Greek_finalsmallsigma"

Is there a way to change the output of that key when I change between Greek and English with ALT+SHIFT ?
Answer: Open a terminal (Ctrl+Alt+T), or press Alt+F2 for a run-command textbox. Type:
gksu gedit /usr/share/X11/xkb/symbols/gr

Find the line starting with:
key <AD02>

and replace it with:
key <AD02> { [ Greek_finalsmallsigma,    Greek_SIGMA ] }; // ς Σ

Then save the file and restart your computer.


How to configure up arrow to search the history?

Question: How can I configure the ↑ key to get commands from history?
Example:
If I type p and press ↑ then it should only show commands in the history starting with "p" like python, php, perl, etc.
Please can anyone help me to configure this feature?
I've edited .bashrc, but it doesn't work for me.
Comment: How did you 'edit .bashrc' before which didn't work?
Answer: Both methods below are almost equivalent, it just depends on which file you want to edit. I'd recommend .bashrc myself, as it doesn't involve editing a local copy of a system file.
If you experience any problems with this, please comment below so that it can be fixed.
Using ~/.bashrc

Edit ~/.bashrc with this command:
gedit ~/.bashrc

Add the following lines:
bind '"\e[A": history-search-backward'
bind '"\e[B": history-search-forward'

Save then close the file.
Execute this command in a terminal:
source ~/.bashrc

Using ~/.inputrc

Execute this command in a terminal:
cp /etc/inputrc ~/.inputrc

Edit the new ~/.inputrc file with this command:
gedit ~/.inputrc

Append these lines to the file:
"\e[A": history-search-backward
"\e[B": history-search-forward

References:

incremental history searching with .inputrc ?
In bash, how do I bind a function key to a command?
Comment: @Trim if it solved your problem then you can mark the answer as solved by clicking the tick under the voting buttons so that it can help future visitors.
Comment: Thank you Dear friend, I edited bashrc file as you said, its now working.
Answer: As alternative, you can press Ctrl+R then start typing the command or any part of the command that you are looking for. You'll see an auto-complete of a past command at your prompt. If you keep typing, more specific options will appear. You can also press Ctrl+R again as many times as you want to, this goes back in your history to the previous matching command each time (source: Navigating Bash History with Ctrl+R).
Another suggestion, if you want to find, for example, the last 5 commands from your history starting with "p", you can use the following command:
grep "^p" ~/.bash_history | tail -n 5


Removing Values from a HashSet that are connected to a key?

Question: I want to withdraw a student from a school class. The following method is not removing the value? Ideas please:
public static void withdrawStudent(String student) {
    enrollments.values().remove(student);

}

public static void main(String[] args) {
        enroll("101", "Pat");
        withdrawStudent("Pat");
}

// Here is part of the class.
private static HashMap<String, Set<String>> enrollments = new HashMap<String, Set<String>>();

public static void enroll(String unit, String student) {
    Set<String> studentsSet = enrollments.get(unit);
    if(studentsSet == null) {
        studentsSet = new HashSet<>();
    }
    studentsSet.add(student);
    enrollments.put(unit, studentsSet);
}

Comment: Try `enrollments.remove("101");`
Comment: re-reading your question, I believe what you want is to remove `Pat` from the `101` Set - right?
Comment: @ScaryWombat I tried that, wasn't working. printing out the value still
Answer: Your problem is that you are trying to remove a String, while enrollments.values() returns a Set of String. A possible fix would be this, but keep in mind that this would remove the student from every enrollment.
public static void withdrawStudent(String student) {
    for (Set<String> studentSet : enrollments.values()) {
        studentSet.remove(student);

    }
}


How to seal seams between wooden deck rails?

Question: A contractor apparently did not a good job on rebuilding my deck and after a couple of months caulking in between wooden moving deck railings doesn't provide any sealing from water dripping into the half-wall underneath.
What's a good way to seal those corners? Assuming those wooden railings continue shrinking and expanding.
Answer: Miter joints are almost always susceptible to expansion issues like this. It's worse when exposed to direct moisture and heat. Caulking isn't going to entirely stop that from happening--may make it worse if it clogs the joint and leads to worse separation.
Some ideas:

Fabricate a metal wrap and drip ledge for the corner, if not the whole rail.
Rebuild with a different wood that's more stable.
Rebuild out of a composite material that'll never move.
Rebuild with a different joint maybe a simple butt or lap. In either case, consider sealing the end grain with epoxy or spar varnish to inhibit moisture wicking up the grain.
Comment: Thank you. Well, rebuilding is not an option. Building this one took them forever and I don't want to deal with that anymore. I'll take a look into the metal wrap idea. I was also thinking about a T-shaped piece of plastic or other material to insert there that would prevent leaking into it.
Comment: I'd pull up that 1x1" square molding and tack down a metal sheath under it then put the molding back -- kinda like flashing. I'd imagine a gutter or siding specialist could knock it out for you. The corner will be the trickiest bit to bend/cut correctly and someone who knows what they're doing will save a lot of time and possible lacerations.


How do you completely reset monitor configuration (e.g. what used to be dpkg-reconfigure xserver-xorg)?

Question: Using unity 11.04. I have a secondary monitor (actually two, one at home, one at work). The home twin monitor set up works perfect (Viewsonic monitor). At work, I get very buggy behaviour, such as full screen applications 'ghosting' when maximized, and other strange effects. I would like to try and completely reset the monitor configurations (not unity or compiz), before doing anything else. In 10.10 this would be accomplished:
dpkg-reconfigure xserver-xorg

Comment: This question appears to be abandoned, if you are experiencing a similar issue please [ask a new question](http://askubuntu.com/questions/ask) with details pertaining to your problem. If you feel this question is *not* abandoned, please flag the question explaining that. :)
Comment: We need more hardware information to help you, can you look at [this question](http://askubuntu.com/questions/14008/i-have-a-hardware-detection-problem-what-logs-do-i-need-to-look-into) and then edit your question adding the information.
Answer: If you think it's some user preferences settings, then you can create a new user "temp", login as a "temp" and see if it's ok.
You can also try xrandr --auto.
Comment: It's *xrandr --output  --auto*


R Dplyr: Summarizing a column, if it is present

Question: In R, working in the tidyverse:
My data sources change. There's a column which is only present some weeks.  When it is, I want to summarize it.  Using iris as an example, suppose that Sepal.Width is sometimes missing.  Conceptually, I want a function like this
library(tidyverse)

summIris <- function(irisDf){
  irisDf %>%
    group_by(Species) %>%
      summarise_ifPresent(
                Sepal.Length = mean(Sepal.Length),
                Sepal.Width = mean(Sepal.Width))
}

Which'd return
R >  summIris(iris  )
# A tibble: 3 x 3
  Species    Sepal.Length Sepal.Width
  <fct>             <dbl>       <dbl>
1 setosa             5.01        3.43
2 versicolor         5.94        2.77
3 virginica          6.59        2.97

 > summIris(iris %>% select(- Sepal.Width ))
# A tibble: 3 x 2
  Species    Sepal.Length
  <fct>             <dbl>
1 setosa             5.01
2 versicolor         5.94
3 virginica          6.59

I could work around by wrapping the logic in if else.  But is there something more concise and elegant?
Comment: Does this answer your question? [Execute dplyr operation only if column exists](https://stackoverflow.com/questions/45146688/execute-dplyr-operation-only-if-column-exists)
Comment: Since you're doing a summarize, do you want to do a `summarize_all`? Otherwise it's unclear how you would summarize the other columns, or would you just drop them?
Answer: summarize_at allows you to define on which columns you execute the summary, and you can use starts_with, ends_with, matches, or contains to dynamically select columns.
library(dplyr)
iris %>%
  group_by(Species) %>%
  summarize_at(vars(starts_with("Sepal")), funs(mean(.)))
# # A tibble: 3 x 3
#   Species    Sepal.Length Sepal.Width
#   <fct>             <dbl>       <dbl>
# 1 setosa             5.01        3.43
# 2 versicolor         5.94        2.77
# 3 virginica          6.59        2.97
iris %>%
  select(-Sepal.Length) %>%
  group_by(Species) %>%
  summarize_at(vars(starts_with("Sepal")), funs(mean(.)))
# # A tibble: 3 x 2
#   Species    Sepal.Width
#   <fct>            <dbl>
# 1 setosa            3.43
# 2 versicolor        2.77
# 3 virginica         2.97

Another one also works but gives a warning with unfound columns:
iris %>%
  select(-Sepal.Length) %>%
  group_by(Species) %>%
  summarize_at(vars(one_of(c("Sepal.Width", "Sepal.Length"))), funs(mean(.)))
# Warning: Unknown columns: `Sepal.Length`
# # A tibble: 3 x 2
#   Species    Sepal.Width
#   <fct>            <dbl>
# 1 setosa            3.43
# 2 versicolor        2.77
# 3 virginica         2.97

Comment: Or use `matches` to select either one of them `summarize_at(vars(matches("Sepal.*(Width|Length)")), mean)` without warning.  The `funs` would be replaced in the recent versions with `list`


Script command to manipulate binary file (on linux)

Question: I am looking for a mechanism to manipulate my eeprom image with a unique device id. I'd like to do this in a make file so that the device would automatically obtain a new ID and then update it to the data image, then flash it. In pseudocode:
wget http://my.centralized.uid.service/new >new.id
binedit binary.image -write 0xE6 new.id
flash binary.image into device

So first we get an id into a separate file, then we overwrite the image (from given offset) with the contents of this ID file. Then flash. But how to do the second part? I looked up bvi, which seems to have some scripting abilities, but I did not fully understand it, and to be honest vi always gave me the creeps.
Thanks for help beforehand!
Comment: possible duplicate of [Bash Scripting: How to patch files? (write a given string in a given position of a file)](http://stackoverflow.com/questions/5196096/bash-scripting-how-to-patch-files-write-a-given-string-in-a-given-position-of)
Answer: (Full disclosure: I made the initial vote to close as a duplicate. This answer is adapted from the referenced question.)
Use dd with the notrunc option:
offset=$(( 0xe6 ))
length=$( wc -c < new.id )
dd bs=1 if=new.id of=binary.image count=$length seek=$offset conv=notrunc

You may want to try this on a copy first, just to make sure it works properly.
Comment: You are right, is a duplicate. I did not include "patching" in original keyword searches. And the answer is exactly what I was after. Thanks!
Answer: If you know the offset of the file that you want to replace from, you can use the split command to split the initial file up until the offset. The cat command can then be used to join the required pieces together.
Another useful tool when working with binary files is od which will let you examine the binary files in human readable format.
Comment: mm, the split/cat solution is quite innovative, never thought of that.
Answer: I would perhaps use something like Perl. See here and in particular the section labelled Updating a Random-Access File (example here)


Homomorphism between two algebras

Question: So I know from ring theory that if we have a homomorphism $\phi: A \rightarrow B$ then it must be the case that for some ideal $I \subseteq A$ we have $\phi(I) \subseteq B$ and $\phi(I)$ is an ideal of $B$ (of course, this assumes that $\phi$ is surjective).
My question is is the same true of homomorphisms between two algebras? For instance, between $M_2(\mathbb{C})$ and $\mathbb{C}$, is it true that all homomorphisms map $$\begin{bmatrix}0 &0\\0& 0\end{bmatrix} \mapsto 0 $$ and $$\begin{bmatrix}a &b\\c&d\end{bmatrix}\mapsto a+b+c+d,$$ since these are the only two ideals of $M_2(\mathbb{C})$ and $\mathbb{C}$ respectively?
Answer: It is a standard exercise to show that $M_2(\mathbb{C})$ is a so called simple algebra, i.e. it has no non-trivial ideals (the same holds for all matrix algebras over any field). This places a severe constraint on all algebra (or ring) homomorphisms
$\phi:M_2(\mathbb{C})\to \mathbb{C}.$ Namely $\ker\phi$ has to be an ideal. There are only two choices. The kernel can't be all of the matrix algebra, because then $\phi(I)\neq1$. The kernel cannot be trivial either, because then $\phi$ would be injective. If $\phi$ were injective, then $M_2(\mathbb{C})$ would be isomorphic to a subring of $\mathbb{C}$. Consequently it would be both commutative and have no zero-divisors :-)
The conclusion: There are no algebra/ring homomorphisms $M_2(\mathbb{C})\to \mathbb{C}$.
Comment: Aha, it was the injective property that I couldn't make sense of in my head! I had scratchings on paper that showed that $M_2(\mathbb{C})$ (and $\mathbb{C}$) was simple; indeed I am also aware that $\mathbb{C}$ and $M_2(\mathbb{C})$ are Morita equivalent (I don't know enough category theory to fully appreciate this, but I do know this means it is essentially a direct copy of a few $\mathbb{C}$'s. Unfortunately, apparently my brain then decided to turn off and accept that $\phi$ (and _not_ $ker(\phi)$) had to be an ideal! thanks for the help.

Homomorphism between two algebras