CRUD table - should Edit be engaged in gridview or detail view?

Question: Let's say a gridview is being created. Each row shows a few high-level items, but there is more information in a detail view.
Which is a more appropriate pattern for a user who wishes to see all details, and optionally edit them?

Option A: View Detail action in gridview, edit mode in detail view

Pros: Shows all information before engaging in an edit mode, which might be expected by the user
Cons: Always requires an extra click for users who know they want to edit

Option B: Provide direct access to editing from the grid view

Pros: Saves a click, all information is still viewable
Cons: "Edit" doesn't imply there is more information in a detail view. Is it weird for a user to be able to edit information they haven't seen yet (the Other Information section)?

Option C: Show both View and Edit options on the gridview
This seems kind of redundant, because Option A would take care of both cases.

I'm leaning toward sending the users directly into Edit mode, but would that create any confusion or hindrances with a heavy detail view?
Comment: Option C is not redundant, it adds affordance. A user has to know what each record has to offer: More details and an option to edit. See my edited answer, as it is all about adapting to the user's needs.
Answer: Why don't you provide both? You might want to shorten "View details" into just "view", "more" or "details":

"EDIT" shows the modal in edit mode, "DETAILS" shows the modal in view mode with the edit button present, just like in your examples.
Having two links and a same modal with a view and edit mode is not redundant, it adds affordance. A user has to know what each record has to offer: More details and an option to edit.
Adapt to the path the user takes

Is a user curious what more information there is, then show a readable view of the information. Does that user want to edit from there, provide a button to edit.

Is a user directly interested in editing the information in the table, then allow to open that view in an editable mode.

So your ideas A and B are good, you just have to combine them.
Comment: I'm struggling a little with the user looking at the details and then wanting to enter an edit state from there... which is option 1.
Answer: Option 1
If the text choice in the cell implies confusion regarding the action involved, remove the text and put an icon for each action

Option 2
Add interactivity

Hovering : show the details and replace "View details" by "Edit"

Clicking : edit the content
Comment: I wanted to add an example with icons too, but found the magnifier icon look too much like a search action. I like the idea in option 2! Only does it still hide the edit ability in grid view.
Comment: Can be a magnifier or an eye, I just put the one it looks better   About the text, maybe *View/Edit*.
Comment: I like option 2 as well, but let's say there are 20 more pieces of information to view/edit - I think the sheet is still our best bet for that, to allow scrolling.
Comment: For 20 or more pieces to change I don't think a modal pop up is a good choice. Actually modals with a long info (or form) is the opposite of a good UX
Comment: It's likely a big sheet, not a small modal dialog, but I see your point.
Answer: I made some assumptions about what you described.
Assumptions n1:
User#A has a basic IT education.
User#B is a millennial.
Assumption n2:
User doesn´t need to update this information quite often.
Answer: I will prioritize the "view details" as label for the button instead of "edit".
Maybe I am wrong; if you provide more context, it could help find a better answer :)
Assumptions n3:
every user can use a keyboard and mouse as input devices.
Modal box:
The update button is disabled from default because the user needs at least to edit a field successfully.
Editing feature
Path#1. Click on the edit button, and the first field will be on focus. The user can confirm by clicking on the key Enter.
Path#2. Double-click the mouse on the field to edit. The user can confirm by clicking on the key Enter.
I am attaching the short prototype.
Having two paths for the same feature could be confusing, but you can have a quick usability test to understand the best solution for your user. ;)
I attached a lo-fi prototype. I hope it will help you to understand my explanation.
May my answer support you to find the solution or inspiration.
Cheers.
Comment: This is how I was thinking my Option A would work. Sounds like a vote for it!


How can I append my dataframe to itself (cbind) a given number of times? in R

Question: I am basically trying to produce a REALLY large dataset for testing purposes, and I have an example dataset with 600,000 rows.
I want to append this df to itself n times, how would I do this?
I could cbind it to itself multiple times manually, but there must be an automated way to do specify the number of times I want it to append to itself?
Comment: Take a look at `do.call`, `cbind` & `rep`. See also `purrr::map_dfc(cbind)`
Answer: You could use [ and repeat the relevant row indices. Example:
df <- data.frame(x = 1:2, y = letters[11:12])
df[rep(1:nrow(df), 10), ] # or rep(seq_len(nrow(df)), 10)

    x y
1   1 k
2   2 l
1.1 1 k
2.1 2 l
1.2 1 k
2.2 2 l
1.3 1 k
2.3 2 l
1.4 1 k
2.4 2 l
1.5 1 k
2.5 2 l
1.6 1 k
2.6 2 l
1.7 1 k
2.7 2 l
1.8 1 k
2.8 2 l
1.9 1 k
2.9 2 l

Answer: Consider replicate (wrapper to sapply) to build a list of duplicate data frames to then run cbind (or rbind for append) once at end:
n <- 5
df_list <- replicate(n, mydata, simplify = FALSE)

final_df <- do.call(cbind.data.frame, df_list)
head(final_df)

Online demo
Answer: Here is another solution using dplyr
library(dplyr)

#bind by column the same df repeated n times (in this example = 3)
rep_df<-bind_cols(rep(df,3))

Comment: Yes. I ran the previous code with some dummy data and seemed to generate the desired output.


TPLink Archer T2U Ubuntu 20.04

Question: I had really big ping problems with games, so my friend said that i should get a new network adapter. I got a TP-Link Archer T2U Plus. I installed drivers I found here. It shows up as a device but I cant connect to any networks.
Here`s my lsusb:
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 004: ID 041e:4088 Creative Technology, Ltd Live! Cam Chat HD [VF0700]
Bus 001 Device 034: ID 2357:0120 TP-Link 802.11ac WLAN Adapter
Bus 001 Device 006: ID 09da:f6f3 A4Tech Co., Ltd.
Bus 001 Device 005: ID 046d:c24b Logitech, Inc. USB2.0 HUB
Bus 001 Device 002: ID 214b:7000  USB2.0 HUB
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

I have Ubuntu 20.04
Answer: You should try the aircrack drivers.
See https://github.com/aircrack-ng/rtl8812au
sudo apt install git dkms
git clone https://github.com/aircrack-ng/rtl8812au.git
cd rtl8812au
sudo make dkms_install

Reboot
Comment: After these commands I had to do `sudo modprobe 88XXau` to make it work.
Answer: dkms_install initially failed "recipe for target failed error 127
on Lubuntu 18.04 32 bit
127 error was simply that dkms was not installed.  Learned this from notes in README.md (created during git clone) and be sure to scroll all the way down to get the full info.  Took quite a while to compile on old T22 Thinkpad. Note that DKMS checks to see if the compile module is unique then inserts it. Rebooted and had wifi bars.
fyi

TPLink Archer T2U Ubuntu 20.04


Solution to non-homogenous second-order differential equation from Navier-Stokes equation.

Question: I was using the simplified Navier-Stokes equations to find the velocity profile within a cylindrical pipe, where I got the equation as:
$ \alpha = \frac{\partial V^2}{\partial r^2}+\frac{1}{r}\frac{\partial V}{\partial r}$
I understand this is a second-order differential equation but am unable to derive the solution which is stated as:
$V= \frac{\alpha r^2}{4}+Aln(r)+B$
where $A$ and $B$ are some constants.
Usually, if there is a number in place of $1/r$, I understand how to find a general solution by using the quadratic method and then finding a particular solution, however, this is a variable? Any ideas on how to approach this problem? Thank you.
Answer: $$ \alpha = \frac{\partial V^2}{\partial r^2}+\frac{1}{r}\frac{\partial V}{\partial r}$$
Multiply both sides by $r$
$$rV''+V'=\alpha r$$
$$\implies (rV')'=\alpha r$$
Integrate
$$\implies (rV')=\alpha \frac {r^2}2 +c_1$$
It's a first order DE now.
$$\implies V'=\alpha \frac {r}2 +\frac {c_1} r$$
Integrate again
$$\implies V=\alpha \frac {r^2}4 +c_1 \ln r+c_2$$
Comment: Thank you. How did you go from:

$rV''+V'=\alpha r$

to

$(rV')'=\alpha r$
Comment: If you dont understand that step try to go from step 3 to step 2 Asif Differentiate $(rV')$
Comment: Ahhhh thank you so much !!!!!!!
Comment: You welcome Asif... I just differentiated $(rV')$
Comment: You can also substitute $Z=V'$ and $Z'=V''$ and treat that equation as a  first order DE and then use whatever method you like. For example integrating factor..


Lambda inheritance using pack expansion

Question: I am studying about lambda inheritance  and I try to change  the following example
under this stackoverflow link. I modified the code using template deduction guide and fold expression.
The piece of code
#include <iostream>
using namespace std;

template<class... Ts>
class FunctionSequence :Ts...
{
    using Ts::operator()...;
};
template <class...Ts> FunctionSequence(Ts...) -> FunctionSequence<Ts...>; // (1)

int main(){

    //note: these lambda functions are bug ridden. Its just for simplicity here.
    //For correct version, see the one on coliru, read on.
    auto trimLeft = [](std::string& str) -> std::string& { str.erase(0, str.find_first_not_of(' ')); return str; };
    auto trimRight = [](std::string& str) -> std::string& { str.erase(str.find_last_not_of(' ')+1); return str; };
    auto capitalize = [](std::string& str) -> std::string& { for(auto& x : str) x = std::toupper(x); return str; };

    auto trimAndCapitalize = FunctionSequence{trimLeft, trimRight, capitalize};
    std::string str = " what a Hullabaloo     ";

    std::cout << "Before TrimAndCapitalize: str = \"" << str << "\"\n";
    trimAndCapitalize(str);
    std::cout << "After TrimAndCapitalize:  str = \"" << str << "\"\n";

    return 0;
}

However  I get  the following error
<source>: In function 'int main()':
<source>:19:78: error: no matching function for call to 'FunctionSequence<main()::<lambda(std::string&)>, main()::<lambda(std::string&)>, main()::<lambda(std::string&)> >::FunctionSequence(<brace-enclosed initializer list>)'
   19 |     auto trimAndCapitalize = FunctionSequence{trimLeft, trimRight, capitalize};
      |                                                                              ^
<source>:5:7: note: candidate: 'constexpr FunctionSequence<main()::<lambda(std::string&)>, main()::<lambda(std::string&)>, main()::<lambda(std::string&)> >::FunctionSequence(const FunctionSequence<main()::<lambda(std::string&)>, main()::<lambda(std::string&)>, main()::<lambda(std::string&)> >&)'
    5 | class FunctionSequence :Ts...
      |       ^~~~~~~~~~~~~~~~
<source>:5:7: note:   candidate expects 1 argument, 3 provided
<source>:5:7: note: candidate: 'constexpr FunctionSequence<main()::<lambda(std::string&)>, main()::<lambda(std::string&)>, main()::<lambda(std::string&)> >::FunctionSequence(FunctionSequence<main()::<lambda(std::string&)>, main()::<lambda(std::string&)>, main()::<lambda(std::string&)> >&&)'
<source>:5:7: note:   candidate expects 1 argument, 3 provided
ASM generation compiler returned: 1

What goes wrong?
Code example --> demo
Answer: using Ts::operator()...;

This "hoists" all the operator() from base classes into the class namespace.
That's apparently not what you want here. It looks like you want to perform the constituent base-class operations in sequence.
Here's how you could write that in a nifty way using the comma operator:
template<class... Ts>
struct FunctionSequence : Ts...  {
    auto operator()(std::string& str) const {
        return (Ts::operator()(str), ...);
    }
};

Live On Coliru
#include <iostream>
using namespace std;

template<class... Ts>
struct FunctionSequence : Ts...  {
    auto operator()(std::string& str) const {
        return (Ts::operator()(str), ...);
    }
};
template <class...Ts> FunctionSequence(Ts...) -> FunctionSequence<Ts...>; // (1)

int main(){
    //note: these lambda functions are bug ridden. Its just for simplicity
    //here.  For correct version, see the one on coliru, read on.
    auto trimLeft = [](std::string& str) -> std::string& { str.erase(0, str.find_first_not_of(' ')); return str; };
    auto trimRight = [](std::string& str) -> std::string& { str.erase(str.find_last_not_of(' ')+1); return str; };
    auto capitalize = [](std::string& str) -> std::string& { for(auto& x : str) x = std::toupper(x); return str; };

    auto trimAndCapitalize = FunctionSequence{trimLeft, trimRight, capitalize};
    std::string str = " what a Hullabaloo     ";

    std::cout << "Before TrimAndCapitalize: str = \"" << str << "\"\n";
    trimAndCapitalize(str);
    std::cout << "After TrimAndCapitalize:  str = \"" << str << "\"\n";

    return 0;
}

Prints
Before TrimAndCapitalize: str = " what a Hullabaloo     "
After TrimAndCapitalize:  str = "WHAT A HULLABALOO"

Notes
I would suggest inheriting privately, and making the functions either void-operations working on the argument, or make them pure (taking const-references and returning copies). Also, see function composition in C++ / C++11 e.g.
Comment: Note that you do `f(x), g(x), h(x)` whereas OP might want `h(g(f(x)))` (which does same result in OP example)
Comment: How does this address the construction failure in the question?
Comment: @DavisHerring the problem in the question wasn't construction failure, it was ambiguous `operator()`
Comment: @sehe: The question quotes a compiler error for the construction; perhaps that's not reproducible and should be edited?
Comment: @DavisHerring mmm yeah maybe the message OP copied was from different code, now that I read it closely. I just copied and observed the error with the code given

Lambda inheritance using pack expansion


Azure custom Policy that allows only Azure Functions creation on ASE

Question: I have an Azure ASE v3 environment to be used for compute needs of Azure Functions.
I want to ensure only Azure Functions can be deployed onto this ASE environment.
Logic Apps or Web Apps should NOT be allowed to be even created.
"Microsoft.Web/sites" seems to be a catch all for all of Logic Apps, Web Apps and Functions.
How to achieve ensure separated identification of just Azure Functions to achieve this objective ?
Answer: You can use kind to filter Function Apps.
    "type": "Microsoft.Web/sites",
    "kind": "functionapp", // windows
    "kind": "functionapp,linux", // linux

Could be something like this:
"if": {
    "allOf": [
        {
            "field": "type",
            "equals": "Microsoft.Web/sites"
        },
        {
            "field": "kind",
            "equals": "functionapp"
        }
    ]
},

Comment: hmm - does not work- still allows Logic APps to be created. is the Then clause to deny right?
Comment: You can change the kind to the value for logic apps if you use deny, or negate the check to deny if kind is not function app.


Lebesgue measurability of a set

Question: Prompted by this question I was looking for $A \subset (0,1)$ such that for any interval $(a,b)\subset (0,1), A \cap (a,b)$ and $A^c \cap (a,b)$ are both uncountable.  One such $A$ is the set of all numbers that have a finite number of $1$'s in their base $3$ expansion.  As no choice was used in the construction, it should be Lebesgue measurable, but I can't prove it.  How is it proved?
Answer: For each $n$, let $A_n$ be the subset of elements of $A$ that have at least a $1$ in the first $n$ digits of their ternary expansion, but no $1$s after the $n$th digit. Your set $A$ is equal to the union of the $A_n$s and the Cantor set. Each $A_n$ is a finite union of scaled translates of the Cantor set (take $3^{-n}C$, where $C$ is the Cantor set, to get all numbers that have ternary expansion with no $1$s and that have $0$ in the first $n$ positions; then you can "translate" by adding a suitable number that has a tail of $0$s and appropriate $1$s in the appropriate coordinates).
So each $A_n$ is a finite union of Lebesgue-measurable sets (scaled Cantor sets are Lebesgue-measurable, and translates of a Lebesgue-measurable set are Lebesgue-measurable), hence Lebesgue measurable. $A$ is a countable union of Lebesgue measurable sets, hence Lebesgue measurable.
Added. As Andres Caicedo points out in the comments below, the argument above shows that the set $A$ is in fact not merely Lebesgue measurable, but Borel.
Comment: @Ross, note that the description Arturo gives shows that, in fact, $A$ is *Borel* (this is much stronger than simply being Lebesgue measurable). Just about any set that you explicitly describe can be easily shown Borel by unraveling the given description: In this case, if only finitely many 1s are used, then your set is a countable union (depending on where the last 1 appears), etc.
Comment: This would prove that $A$ is null, as we might expect.
Comment: Indeed it would.
Comment: @Andres:  Thanks.  Good point.
Answer: The number $x_n$ in the $n^\text{th}$ place after the radix point in the ternary expansion of $x$ is a measurable function of $x$.  This is true because the floor function is Borel measurable, and $x_n=\left\lfloor 3\cdot\left(3^{n-1}x-\lfloor3^{n-1}x\rfloor\right)\right\rfloor$.  The set $\{x:x_n\neq 1\}$ is measurable for each $n$, and so therefore is the set $$\bigcup_{n=1}^\infty\bigcap_{k=n}^\infty \{x:x_k\neq 1\}.$$

Certain null sets of the second category give further examples of this.  The complement of such a set can be contructed by taking a countable union of closed sets with empty interior whose complements have progressively smaller measure (e.g., using fat Cantor sets).
Comment: Yes, the functions involved are Borel measurable (floor is Borel, continuous functions are Borel, and compositions of Borel functions are Borel), and the inverse image of the open set $\mathbb{R}\setminus\{1\}$ under a Borel map is Borel.  The Borel sets form a $\sigma$-algebra, so the countable union of countable intersections of Borel sets is Borel. (The set is even an $F_\sigma$, but that isn't as clear in my answer as in Arturo's.)  The construction of null sets of the second category I mentioned also yields Borel sets ($G_\delta$s, even).
Comment: Following on Andres' comment in Arturo's answer, you have also proved the set Borel, right?  I only see countably many of the allowable operations here.

Lebesgue measurability of a set


External TV antenna grounded inside attic?

Question: I want to install an OTA external antenna to an existing satellite dish mast, I have removed the dish and plan on just attaching the antenna.  The existing dish mast was never grounded, there are also coax grounding blocks on the outside of the house, but they are not grounded either.
The location of the mast is within a valley about mid way up the roof, between the main roof and the garage, its below the ridge of the house.  Its not in a very good location to run a ground wire, the wire would have to run across the top of the roof then down to the side of the house grounding stake.
My question I'm wondering is if its ok to ground the external antenna somewhere within the attic?  I could run 2 sheathed ground wires, one from the mast grounding block, the other from the coax grounding block into the attic where the coax goes into the house, then into the house ground, either to a cold water line or possibly into an electrical ground (that I'm not sure how to do).  Is this an ok solution, or would it be better to run a ground wire across the roof ?  I really don't want to re-locate the mast or the antenna.  Any assistance would be greatly appreciated.
I'm probably a little less then 20 miles from the towers, so a mohu leaf might be an option.  I already have the antenna so was wanting to just try that and see, but if it worked, I wanted to make sure I got it grounded properly.
Comment: Isn't coaxial cable 2 wires?  What does the coaxial outer mesh wire  attach to electrically?
Comment: this doesn't answer your questions, but why not just get something like a mohu leaf and put that up in your attic? That is what I do and i get every station that is available in my area. How far are you from the tower?
Comment: Do you have an intersystem bonding termination block anywhere? (It's usually by the service equipment or meter base, or barring that, attached to the grounding electrode conductor *somewhere*)
Answer: You should run a ground wire from the the mast grounding block, but I would not ground it to anything other than the grounding electrode conductor at the source. If you have a ground rod that is where I would connect it. If there is lightning, your mast could be subject to a strike and I would want it to go directly to ground and not through any other part of my system that could be upstream of some pieces of equipment that may be damaged. Use at least a solid #10 and make sure any radius has a nice long arch.
The metal sheath in a coax is not a ground, it is a shield which drains off misc radio and electronic interference. So it needs to be grounded on one end and left open on the other. So if it has a coax block you can ground it there just make sure you are not grounded at the other end. You also need to make sure the the coax block is grounded to the mast.
Good Luck
Answer: Harper, I'm not sure I understand your question.  the 2 wires I mention above are ground wires, one for the antenna mast, the other for the coax grounding block.
Right now the coax is attached to a coax grounding block that's attached to the outside of the house close to the antenna mast, but that grounding block is not grounded, my question is can I ground that to something inside the attic, as well as the antenna mast.
Comment: Sorry, I'm new to this site, I'm not sure how to add a comment, this isn't an answer.
Comment: If you're unable to 'Add a comment' under your question you should still be able to 'edit' your question to add more details.
Comment: Hi, Ken. You've created two separate accounts: [this one](https://diy.stackexchange.com/users/95772/ken) and [this one](https://diy.stackexchange.com/users/95769/ken). You should use the SE contact form to request that they be merged.
Comment: Submitted request to Community Team to merge accounts for Ken.
Answer: rabbit ears don't need direct ground, antenna on windows, don't need grounding... in my case, it is 75 ft to the Ground from the center top of my roof where the antenna is, so if lightning were to "follow the wire" it would set a lot of things on fire.
Codes don't require it either.
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://diy.stackexchange.com/help/whats-reputation) you will be able to [comment on any post](https://diy.stackexchange.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/176823)


How to reject and push the elements to an array at a time

Question: For Example i have an array like ["a", "b", "c", "d"]. I want add "a", "e" to that array. In that time how to "a" will get reject and how to "e" will push to that existing array.
Comment: what is the input, and what is the expected output?
Comment: @UriAgassi expected output is `["a", "b", "c", "d", "e"]`
Comment: I bet it is: no dup in array.
Comment: Uri gave you a good answer but I suggest that in future you hold off awhile before selecting your preferred answer.  There's no rush at all. It's very common to wait a couple of hours, or more, before making a selection. A quick selection can discourage other (possibly better) answers, and for some it's a bummer to see the green checkmark come on while they are still preparing an answer.
Comment: You should edit your question to add your reply to Uri's question (The expected....). If you don't, the votes to close will probably increase. More generally, you should always clarify by editing the question, rather than trying to do so in comments. However, make sure you do not change the question by your edit. Sometimes it's wise to preface your edit with 'Edit:'. When you give an example (which is appreciated), always give the desired result.
Comment: Why down vote for that question ? Can explain any one please. :(
Answer: Use the union (|) operator:
["a", "b", "c", "d"] | ["a", "e"]
# => ["a", "b", "c", "d", "e"]


How should a global tooltips behavior be defined?

Question: I defined a global tooltips behavior for the developers to use in all cases they will face as a guideline.
I did a research about this issue but I didn't find anything really relevant. Finally, I decided to divide the screen into 6 parts, where in each area the tooltips will behave differently:
Top: left, middle, right.
Bottom: left, middle, right.
See below the map I created:
Is there any other way to define it?
Comment: What is the purpose of creating this map? what do you want to communicate o specify?
Comment: @ColdCat I think that's what the image is meant to convey: depending on which "region" the item-being-tool-tipped is located, you drop-down/push-up from where the mouse is, and either display the box to the right/centre/left of that point. I would also question whether the OP "created" this map, since I'm almost certain I've seen it (or a very close variant) before in one of the standard web frameworks.
Comment: Why not always the same tooltip, and change the position/size where it opens if the default position wont fit, like operating systems do.
Answer:
I've faced similar issue
I'm more comfortable with the following layout, since it take less note of variations and is uniform throughout most of the screen.
Although this problem doesn't arise if a proper plugin is used by the developer.
Comment: Can you add a little bit more explanation as to how your solution works? Is it a grid system? What is it exactly?
Answer: If the default tooltip position is set to below and on the right of the mouse pointer coordinates (bottom-right), check against 2 window edges (bottom and right) and set 2 rules:
Rule 1: If it overlaps the bottom edge move it above (up).
Rule 2: If it overlaps the right edge of the window, align it to the right edge.
With this behavior, in most cases tooltips will hide less usefull/relative content (text/lists) from usersand developers will love you.
Comment: That would be "below", not "bellow"
Answer: If I'm reading your graphic correctly:

If the activation point (AP) is in the top half of the screen, the tool-tip should descend below the AP, otherwise it should ascend above the AP.
If the AP is in the left-hand eighth [estimated] of the screen, the tool-tip should extend to the right of the AP. If it is in the right-hand eighth, then the tool-tip should extend to the left. Otherwise, it should be centred on the AP.

If the situation warrants it, you may need to specify what happens if the above rules mean the tool-tip would go off the screen (i.e. a very long tool-tip activated near the centre of the screen).
Answer: Your question doesn't tell much what research you did. In case your research was reading documents or asking colleagues I suggest you to build a UI prototype and test with your intended users. Then you'll know for sure.
Comment: Thanks Mike. The question was rhetorical, but to be clear I formulated it better.
Comment: You're welcome. I appreciate your quick reaction.
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://ux.stackexchange.com/help/whats-reputation) you will be able to [comment on any post](https://ux.stackexchange.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/low-quality-posts/50855)


Creating a dataset based on a different dataset

Question: I've been looking and thus far haven't been able to figure out if this is possible.
Say I have a datasource, SOURCE1.  I create a dataset from it, SET1.  Now, I'd like to be able to make another Dataset that uses SET1 as the data source.  Is there any way I can do this?  I'd like to be able to run a series of queries that work together to build a final result which would be reported.
ie:
SET1 = SELECT * FROM SOURCE1 WHERE ...
SET2 = SELECT * FROM SET1 WHERE ...
Otherwise, would the only option be to just keep embedding the queries? I'd rather avoid this if possible, because it would become very unreadable since I have to run at least a dozen queries that all build off of each other.
SET 2 = SELECT * FROM (SELECT * FROM SET 1 WHERE ...) WHERE ...
Comment: You say you want to build a series of queries that are used to get a final result. If you only need one result why do you think you have to create multiple datasets? Are you trying to create a series of shared datasets that you can use across multiple reports? Give us a bit more info and there might be a workaround or best practice as using a dataset in another dataser is not really possible in the way you are (probably) thinking
Comment: @AlanSchofield Basically, I have a series of queries in Access that I want to switch over to being created through queries in SSRS. The main reason I want to create multiple datasets is because I'm not sure if it is possible to generate the goal dataset by just using one query,  It takes a series of about 15 queries to get to the final end result, and it seems like it would be easier to create the dataset in steps as opposed to trying to incorporate all 15 queries into one massive query.
Answer: I would guess (not knowing your queries) that you would be able to write it as a single query. The lazy approach would just be to run each query in a batch outputting each result to a series of temp tables then join the temp tables for your final output. If might not be efficient but it would work. The best solution would, almost certainly, be to rewrite it from scratch though as Access SQL is not as powerful or flexible as T-SQL.
So you would need something like..
SELECT * INTO #t1 FROM myTable WHERE blah blah...
SELECT * INTO #t2 FROM myOtherTable WHERE blah blah...
SELECT *
    FROM #t1 a
    JOIN #t2 b on a.myField = b.myField

You can put this query directly into your dataset query. It will dump the results of each query into temp table (#t1, #t2 etc) and then the final statement would join them all.
If you plan to use the individual queries in several places, then you might also consider creating a view for each query if this is possible then just join the views in your SSRS dataset query to get your final results.
In SSMS create the views with something like
CREATE VIEW AccessQuery1 AS
SELECT * FROM myTable where blah blah...

CREATE VIEW AccessQuery2 AS
SELECT * FROM myOtherTable where blah blah...

Then in SSRS your dataset query would just be something like
SELECT *
    FROM AccessQuery1 a
    JOIN AccessQuery2  b on a.myField = b.myField

Hope that helps...


Regular Expression word boundary breaks on '-'

Question: I have a string in the following format.

"ad60 ad60-12 ad60 12-ad60"

now I want to find the matches only where "ad60" is written.
I started off with

/\bad60\b/i

but regex finds that '-' is not part of the character string. which returns 4 matches.
I tried many things but they all either return 4 matches or return nothing.
Any kind of help would be appreciated.
Comment: What is your expected output?
Comment: Just where 'ad60' is written, surrounded by space start of line end of line, but if its somewhere within a string it should not match.
as in "12-ad60" and ("ad60-12") should not match.
Comment: @anubhava the "ad60" can chnage, it's just a token I enter.

PS: I am a noob at Regex
Comment: List possible rules what you have and what you want to get
Answer: You can use:
<code>var s = "ad60 ad60-12 ad60 12-ad60";
var r = s.replace(/(^|\s)ad60(?=\s|$)/g, "$1@@");
//=> @@ ad60-12 @@ 12-ad60
</code>
Comment: Sure let me explain. `(^|\s)` matches line start OR space. `(?=\s|$)` is a positive lookahead that looks ahead a space or line end.
Comment: That is just amazing, s.match(/(^|\s)ad60(?=\s|$)/ig) did the trick
Comment: Please explain the answer a bit. will appreciate it
Answer: this should find any word starting from letter
<code>/[a-z][a-z\d]+/i
</code>
ADDED
if you wish to find any words which are included ad60 string try this
<code>/[a-z\d\-\_]*ad60[a-z\d\-\_]*/i
</code>
but words separated by space will not get in result
Comment: It is no good, I think I was not clear enough in my question. I want to find what ever is inside "\b" tags, "\b" means string boundary, but a word written as 'ad60-something' matches ad60 from it, which is something I don't want, thanks though
Answer: <code>"ad60 ad60-12 ad60 12-ad60".match(/(^ad60\s+)|(\s+ad60$)|(\s+ad60\s+)|(^ad60$)/ig);
</code>
will result in ["ad60 ", " ad60 "]
then you can trim the white spaces in matched elements.


Avoid caching files inside web folder

Question: I have a real time application working with Symfony 4 and ffmpeg. It works great in development environment, but it hangs on production because the cache.
Through ffmpeg, I write a mpd file from a RTSP stream in my /public/build/video folder.
I need to avoid caching this mpd because it always changes while the real time video is displayed (ffmpeg is running on background).
Please, could you help me to exclude "/public/build/video" folder and its content to be cachable.
Find attached a screenshot:

Thanks
Answer: What about deleting the line containing :
#$kernel->loadClassCache();  // <-- comment out this line

in your front controller.
Answer: According to the documentation of the header Cache-Control you should try using Cache-Control: no-cache. Docs

Avoid caching files inside web folder


How to Commit Changes into Version Editor Everytime I compile the Project

Question: Anyone knows that? Or say every hour of programming. That way I don't have to remember committing my work.
Answer: If you want a shotgun approach to version control, just turn on Time Machine, or Snapshots in Xcode. (Don't know if that works automagically, but Time Machine does.
Doing what you are proposing defeats the point of having and using version control in the first place.
Comment: Okay maybe not every time I compile. Say once a day.


Minecraft 1.8.8 gives error "Couldn't initialize twitch stream"?

Question: I don't need twitch, so what do I do when this pops up?
<code>24-09-15 21:22:38: Starting Launcher...
24-09-15 21:22:38: Online mode...
24-09-15 21:22:38: Checking Minecraft for updates...
24-09-15 21:22:38: Last checked for updates: less than an hour ago
24-09-15 21:22:38: Loading Launcher profiles...
24-09-15 21:22:38: Loading User profiles...
24-09-15 21:22:38: Loading versions list...
24-09-15 21:22:42: Loading Launcher profiles...
24-09-15 21:22:42: Loading User profiles...
24-09-15 21:22:42: Loading versions list...
24-09-15 21:22:44: Launching minecraft...
24-09-15 21:22:44: Something went wrong due unpacking tv\twitch\twitch-external-platform\4.5\twitch-external-platform-4.5-natives-windows-64.jar: Cannot read that as a ZipFile
24-09-15 21:22:44: Unpacking natives completed. Total recovered 10 files
24-09-15 21:22:44: Launch command: C:\Program Files (x86)\Java\jre1.8.0_60\bin\java.exe -Xmx1G -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode -XX:-UseAdaptiveSizePolicy -Xmn128M -Djava.library.path=C:\Users\MDJC\AppData\Roaming\.minecraft\\natives -cp C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\oshi-project\oshi-core\1.1\oshi-core-1.1.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\net\java\dev\jna\jna\3.4.0\jna-3.4.0.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\net\java\dev\jna\platform\3.4.0\platform-3.4.0.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\com\ibm\icu\icu4j-core-mojang\51.2\icu4j-core-mojang-51.2.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\net\sf\jopt-simple\jopt-simple\4.6\jopt-simple-4.6.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\com\paulscode\codecjorbis\20101023\codecjorbis-20101023.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\com\paulscode\codecwav\20101023\codecwav-20101023.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\com\paulscode\libraryjavasound\20101123\libraryjavasound-20101123.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\com\paulscode\librarylwjglopenal\20100824\librarylwjglopenal-20100824.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\com\paulscode\soundsystem\20120107\soundsystem-20120107.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\io\netty\netty-all\4.0.23.Final\netty-all-4.0.23.Final.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\com\google\guava\guava\17.0\guava-17.0.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\org\apache\commons\commons-lang3\3.3.2\commons-lang3-3.3.2.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\commons-io\commons-io\2.4\commons-io-2.4.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\commons-codec\commons-codec\1.9\commons-codec-1.9.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\net\java\jinput\jinput\2.0.5\jinput-2.0.5.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\net\java\jutils\jutils\1.0.0\jutils-1.0.0.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\com\google\code\gson\gson\2.2.4\gson-2.2.4.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\com\mojang\authlib\1.5.21\authlib-1.5.21.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\com\mojang\realms\1.7.24\realms-1.7.24.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\org\apache\commons\commons-compress\1.8.1\commons-compress-1.8.1.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\org\apache\httpcomponents\httpclient\4.3.3\httpclient-4.3.3.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\commons-logging\commons-logging\1.1.3\commons-logging-1.1.3.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\org\apache\httpcomponents\httpcore\4.3.2\httpcore-4.3.2.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\org\apache\logging\log4j\log4j-api\2.0-beta9\log4j-api-2.0-beta9.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\org\apache\logging\log4j\log4j-core\2.0-beta9\log4j-core-2.0-beta9.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\org\lwjgl\lwjgl\lwjgl\2.9.4-nightly-20150209\lwjgl-2.9.4-nightly-20150209.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\org\lwjgl\lwjgl\lwjgl_util\2.9.4-nightly-20150209\lwjgl_util-2.9.4-nightly-20150209.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\libraries\tv\twitch\twitch\6.5\twitch-6.5.jar;C:\Users\MDJC\AppData\Roaming\.minecraft\\versions\1.8.8\\1.8.8.jar net.minecraft.client.main.Main --username violetassassin1124 --version Violeta --gameDir C:\Users\MDJC\AppData\Roaming\.minecraft\ --assetsDir C:\Users\MDJC\AppData\Roaming\.minecraft\assets\ --assetIndex 1.8 --uuid 57362f464412a2f32975408257cad494 --accessToken N3K00TD3KC4RC --userProperties {"luncher":["extremeLauncher"]} --userType mojang
24-09-15 21:22:45: [21:22:45] [Client thread/INFO]: Setting user: violetassassin1124
24-09-15 21:22:45: [21:22:45] [Client thread/INFO]: (Session ID is token:N3K00TD3KC4RC:57362f464412a2f32975408257cad494)
24-09-15 21:22:46: [21:22:46] [Client thread/INFO]: LWJGL Version: 2.9.4
24-09-15 21:22:48: [21:22:48] [Client thread/INFO]: Reloading ResourceManager: Default
24-09-15 21:22:48: If on Windows, make sure to provide all of the necessary dll's as specified in the twitchsdk README. Also, make sure to set the PATH environment variable to point to the directory containing the dll's.
24-09-15 21:22:48: [21:22:48] [Client thread/ERROR]: Couldn't initialize twitch stream
24-09-15 21:22:58: Minecraft closed.
</code>
Answer: The error is that the game can't read the file responsible for Twitch. This means the game files are corrupted. Uninstalling, then reinstalling should fix this.
Comment: The only way I can think of off the top of my head is to reinstall minecraft, it doesn't matter if you need twitch or not, the problem is that the game needs that file to launch, and it can't read it. Deleting the file would cause the same thing to happen, it would just change the error.
Comment: @user125678 - You should be able to keep your `saves` folder when you delete everything else in the `.minecraft` directory if that's what you're worried about
Comment: Can I not do that and try deleting something instead? I dont need Twitch.
Comment: @user125678 Yeah Robotnik is correct just back up your save files.


Java GUI Resize Images

Question: I would like to resize multiple imageIcons that I have attached to certain panels, but I'm not sure how to do that. After much research I've attempted to use .getScaledInstance but have had no luck, is that what I'm supposed to use? Since I define my panels outside of the main class but need to use the scaled instances of the images in multiple methods, would I add a line such as
image.getImage().getScaledInstance(30,30,whatever);

or would I need to do a different action?
Answer: getScaledInstance doesn't effect the original image, but instead returns a new instance of the image scaled to meet your parameters, make sure you are assigning the result to a variable, for example
image = image.getImage().getScaledInstance(30,30,whatever);

Then pass this to your what ever needs to use it
Beware, the quality of the operation is pretty poor, especially over a large range.
Take a look at

Quality of Image after resize very low -- Java
Java: maintaining aspect ratio of JPanel background image
The Perils of Image.getScaledInstance()

For details and ideas.
Comment: Is getScaledInstance the only way to resize an image? If it's of a poor quality what's a higher quality version
Comment: Check the linked examples.  The first one offers a slightly different approach (multi stage downsizing). You could also consider having a look at [imgscalr](http://www.thebuzzmedia.com/software/imgscalr-java-image-scaling-library/)

Java GUI Resize Images


Read.csv is not Counting NAs in my Data Set

Question: First post on SO ever so I'm looking forward to getting some feedback from some veterans in R on the forum. :)
I have a CSV file (2.52KB) that I'm currently unable to identify NAs when I run the following NA identifying script (particularly in ORG column):
 mydata = read.csv("DF_Cleanup_isNAError_Test.csv" header = TRUE, sep = ",", quote = "", dec = ".", fill = TRUE)
 nan_count <-sapply(mydata, function(y) sum(length(which(is.na(y)))))
 nan_count <- data.frame(nan_count)
 nan_count

When I isolate the records with NA values in ORG column though (only 30 total rows) in the control data set, running the same NA identifying script returns a count of 30 for column ORG.  This is expected for the script above as well but that's not happening.
mydata = read.csv("DF_Cleanup_isNAError_Control.csv" header = TRUE, sep = ",", quote = "", dec = ".", fill = TRUE)
nan_count <-sapply(mydata, function(y) sum(length(which(is.na(y)))))
nan_count <- data.frame(nan_count)
nan_count

I'm completely stumped right now on why there would be a difference with the addition of other records in the data set when nothing's changed about the individual records in question.  The test data set is still only a subset of the total population data; I have about 850K total rows but I figured this is a good start to isolating what the issue is.
Here's my current session info
    R version 3.4.1 (2017-06-30)
    Platform: x86_64-w64-mingw32/x64 (64-bit)
    Running under: Windows 7 x64 (build 7601) Service Pack 1

   Matrix products: default

   locale:
   [1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United
   States.1252    LC_MONETARY=English_United States.1252
   [4] LC_NUMERIC=C                           LC_TIME=English_United States.1252

   attached base packages:
   [1] stats     graphics  grDevices utils     datasets  methods   base

   other attached packages:
   [1] dplyr_0.7.2

   loaded via a namespace (and not attached):
    [1] compiler_3.4.1   magrittr_1.5     assertthat_0.2.0 R6_2.2.2
    tools_3.4.1      bindrcpp_0.2     glue_1.1.1       tibble_1.3.3
     [9] Rcpp_0.12.12     pkgconfig_2.0.1  rlang_0.1.1      bindr_0.1

Comment: Try adding `na.strings = ""` to your `read.csv` call.
Comment: It could be it's being read as `"NA"`. Could you try `which(y=="NA")` (in the context of your code) to test this?
Comment: side issue: your `sapply` can be replaced by `colSums(is.na(myData)`
Comment: @ChiPak Yep, I tested that before; it doesn't find anything in `DF_Cleanup_isNAError_Test.csv` and I've checked the CSV file as well.  Its not a 'NA' string but an actual blank value that the code isn't picking up for some reason between the test and control data sets.
Comment: That does it! It shows up with count = 30 for both control and test data sets.  Thanks @jav
Answer: @jav answered this in the comments section but I figured this should actually be listed out as an answer.  If he ever reposts his comment as an answer, I'll delete this.
Adding na.strings = "" to read.csv("filename.csv") solves the problem.


How to deal with this pair of wires coming out of transformer?

Question: This monstrosity is in my attic. There is one attic light.
There is a legitimate wire from the light junction 'fixture' to a junction box elsewhere. (It's the white wire that you see behind the light.)
HOWEVER, there is another wire coming out of the light fixture that goes to a transformer...which then splits into two loose wires that have a suspect connection using electrical tape. At places along the two wires there seems to be some wear and tear with the insulator. I probably should use some electrical tape.
I didn't trace the wires to the end but they seem to go towards the front door where there is a doorbell and a porch light. (The roof pitches down near there and there's hardly any space to see where the wires go)
I used a voltage tester and it beeps to indicate that it is hot.
What should I do with this wire?  I want to cut it. How do I figure out what it's connected to?
Do I turn off the breaker to the attic light and then disconnect that transformer? If I do that then the device that is connected to it should stop working.
Comment: It would be AC (it's just a transformer, no rectifier or anything else of the sort)
Comment: That looks like an *ancient* Class II doorbell transformer.  Can you get a voltmeter reading on its output somehow?
Comment: If it is for doorbell would it be DC or AC?
Answer: It's a doorbell transformer. Line voltage input and probably 24 vac output. Turn off the breaker and look closely at the transformer, the specs will be on it.
You should mount it in a covered electrical box (modern ones are designed with a 1/2" threaded post to facilitate just that) so the line voltage connection is properly enclosed, rewiring where necessary to replace deficient wire and connections. I would probably replace the transformer too but it's not strictly necessary.
Comment: So, rewire from lightbulb jbox to new jbox that will hold the transformer?  And then rewire to doorbell?  I think that may be too much effort.  I probably will remove wires, transformer, wires from bulb to transformer...and then get a wireless doorbell.  :)
Answer: EEK!  Kill it with fire, before it kills you with fire!
I'm referring to the breakable Edison screw base bulb that is on the floor and underfoot, ready to be tripped over, tearing the porcelain base socket off and exposing you to 120V.  UGH.  Remember, if you bust that bulb, you will have live 120V inside broken glass right next to grounds, and there you are groping around in the pitch black! Unacceptable!
Here's what I would do.

Get a modern transformer that's built into a junction-box lid, like this one.  Not for this junction box - this box gets a blank lid, so you can climb across it without touching anything electrical.
In the (illegal) hole the transformer wiring went through, I'd get some EMT conduit and extend it along that joist, toward the eave, as far as practical before the clearances get too close to work.  I'd install another junction box there, screw it to the joist with 2 screws.  I'd fasten the EMT to the joist rather firmly with lots of clamps so you can climb/step across it or put stuff on it. There'll be a 1/4" or so gap between EMT and joist, the usual practice is 4 subtle bends, I'd just put shims under it.
In that new box I'd install the new "in the lid" transformer.
Out of the side of that junction box, I'd go EMT, flexible conduit or armored cable to a suitable location for LED lights.  I'd put two there, selecting models unlikely to be damaged from rough handling of boxes etc. in the attic.  Two, so I can use cheapies and still have light to fix one when it fails.

Ground wires needed also, I'm not showing the grounds since wherever you use metal EMT, that can be the ground.   I also overlooked a light switch, I don't know how the attic light turns on now.  If needed you can run some flexible armored cable over to a convenient location for a switch.
You could also relocate the existing box to be on the sides of the rafters instead of the top, but that's more than I wanted to get into here.
By the way, the transformer is the "ridiculously easy" part of this.  The REAL work, and real win, is fixing that dangerous lighting situation and making your attic space a lot more usable.  Besides, wireless doorbells look cheap IMO and hurt your resale. If you've got a real one, it's not hard to keep it.
Comment: @milesmeow like above. Brown is wood.  Pink is EMT but I'm not showing the shims.  The existing box is an octagon box, I'd use a deep 4"x4" box for the new box, since that's what the transformer wants and deep so you have more room for wires.  Make sure it has 1/2" holes.
Comment: Thanks Harper. Could I trouble you for a diagram? A hand drawn one on a napkin is fine. :)
Comment: really nice diagram.  Thank you for also including the wiring diagram.  My attic is pretty big so I might run two more LED lights to the other side.  Do you think that I can have 4 LED lights for the circuit?  I don't know what is connected to the circuit in the house.


NSLog Context Causing App Stuck

Question: I have a very weird error.
So I try to print my NSManagedObjectContext context. In the past my app worked perfectly. But just recently that my app got stuck on my below code:
NSLog("%@", context);

Anyone has same experience with me? I can remove that line for sure, but I am just curious why it happens.
Comment: "Got stucked"? Can you explain?
Comment: Yeah the app stucks, doesn't proceed to next code and without any error.
Comment: No SIG_ABORT or EXC_BAD_ACCESS or anything at all? No breakpoint?
Answer: because the context isn't from your thread and printing it on another thread accesses it and causes a deadlock!
contextes arent really safe to use in multiple threads/queues
Comment: yeah actually I print it inside block `[operation setWillSendRequestForAuthenticationChallengeBlock:
  ^(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge)` which `operation` is `AFHTTPRequestOperation`. So it is not safe if I want to get some value from my Core Data entity inside that block?
Comment: check if the thread is the same thread as the one you created the context on (use 'dispatch_get_current_queue() for debugging!)

NSLog Context Causing App Stuck


How to insert text into a file

Question: How do I insert a string at the beginning of a text file using batch? Would it be possible to do so without creating a temp or a new file?
I am currently merging two files using copy, but that is very inefficient since my files are several GB big.
I would like to do something like copy "string1"+file1 file1
Thanks!
Comment: @Dai, obviously this would work only for cluster-sized strings.
Comment: @Dai, that applies only to the last cluster, not the first or any intermediate.
Comment: @Dai, the point is that your idea won't work for arbitrary-sized strings. Only the last cluster of a file can be filled less than 100%.
Comment: @Dai, also you may want to delete your comments after the first one after reading some in-depth article about Windows NTFS file system. On the other hand I'd be very pleasantly surprised if you can name *any* file system that may have clusters of arbitrary size with *byte* granularity except for the last one.
Comment: Hypothetically it is possible to prepend content to a file without copying anything on-disk, simply by adding a new disk-cluster and declaring the new cluster is the start of the file and then setting the next-cluster link (of the new cluster) to the old first-cluster. This requires low-level filesystem access, however.
Comment: @wOxxOm No, clusters don't have to be filled so it can be shorter, and if it's longer then just allocate new clusters before linking to the original.
Comment: I note that my approach doesn't work if the file has a Unicode BOM (or any other kind of header or prefix), or else ensure any reader will ignore the BOM as they read the file.
Comment: @wOxxOm I'm sorry but I don't understand the point you're trying to make.
Answer: You can't avoid copying when inserting text in the beginning of a file.
The only thing you can do to speedup the process in case your file is on a conventional HDD drive (not SSD) is copy it to a different local physical drive (preferably a faster one), then move the file back.
>tmp.txt echo Some text
copy /b tmp.txt + bigfile d:\another_physical_drive\file.tmp
del tmp.txt
move /y d:\another_physical_drive\file.tmp bigfile

It works on HDDs because sequential write or read speed is 10 times higher (or even much more) than frequent seeking-reading-seeking-writing (also called disk-thrashing) when copying within the same physical drive using the built-in commands. Only some rare 3rd-party utilities are smart and can read in very big chunks filling the RAM up to 50% for example, then do an unbuffered write to skip OS caching, thus essentially always doing a sequential access.
Comment: Why would the fact that it is another physical drive be a benefit? (Unless you _want_ it slower)
Comment: Your solution writes the entire results twice, once to a fast temp drive, and once to an allegedly slow main drive. It is much faster to simply write the temporary file directly to the final main location, and then use MOVE to nearly instantaneously rename the temp file to overwrite the original. This still writes the file once to the slow drive, but bypasses the need to also write it to the fast drive.
Comment: @StefanBormann, because on hard drives (which still are used more than SSD, especially for large files) sequential write speed is 10 times higher (or more) than seeking-reading-seeking-writing when copying on the same physical drive. Some rare utilities are smart and can read in very big chunks filling the RAM up to 50% for example, then do an unbuffered write to skip OS caching, but the built-in utilities don't do that.
Comment: but moving in the same drive is O(1), moving accross drives is essentially another copy with O(n)
Comment: @StefanBormann, the pure mathematics doesn't account for the extremely slow seeking on the conventional hard drives. This was the entire point of my lengthy explanation.
Comment: Well, anyway, thanks for the question, the answer lacked an explanation and I've updated it now.
Comment: @dbenham, my solution avoids disk-thrashing due to slow HDD-seeking if doing everything within the same physical drive, which can slow down the process several times. I thought I've explained it clear enough... Of course if there is enough RAM and no need to process a lot of huge files it's okay to do it using the same folder.
Comment: OK, it took a while, but I understand the issue now. It is counter intuitive, but I can see how your design can improve performance in some situations. I wonder what impact a striped RAID configuration might have. I can envision how RAID might be able to minimize thrashing on logically in place copies if the read and write are always (or frequently) on different physical drives. Such a configuration might be the best of both worlds.
Comment: Well, an average PC has 4-8GB of RAM, the file cache is 256MB-1GB, and maybe only in half of cases an SSD is used for the storage. So I'd say in about ~50% of situations my solution would be faster. And in case we only look at HDDs the percentage would be higher.
Comment: Also, you are assuming exclusive use of the disk resource. A busy shared network resource might be thrashing no matter what you do.
Comment: What network resource? I only meant local physical drives. I'll add that clarification into the answer.
Answer: There is no way to avoid writing the entire result to disk. I would use the following:
>"bigfile.txt.new" ( echo Some text&type "bigfile.txt" )
move /y "bigfile.txt.new" "bigfile.txt" >nul

The important thing is that the MOVE is nearly instantaneous, and it is a single operation that is equivalent to deleting the original file and then renaming the temp to the original name.
Comment: This is prone to disk-thrashing unlike using a different physical drive: as you can see in [procmon](https://technet.microsoft.com/en-us/library/bb896645.aspx) the system reads in extremely small chunks and immediately writes each chunk hundreds times per second: http://puu.sh/kFhlR/f74b40430a.png To cache the entire 1GB file in write cache the PC would need a lot of *free* RAM because Windows limits the percentage of memory allocated for cache. This means that after a while every read operation will be interspersed with HDD-seeking and a write operation (disk-thrashing).

How to insert text into a file


Can't install Ubuntu Touch on BQ Aquaris M10

Question: Recently I received my BQ Aquaris M10 Ubuntu Edition but to my surprise there is no Ubuntu installed on it. It's Android!
So I'm trying to install Ubuntu myself but I'm stuck on the following:
<code>ubuntu-device-flash -v touch --device frieza --channel ubuntu-touch/stable/bq-aquaris-pd.en --bootstrap --recovery-image recovery-frieza.img
2016/04/23 10:05:59 Device is |frieza|
2016/04/23 10:05:59 Flashing version 3 from ubuntu-touch/stable/bq-aquaris-pd.en channel and server https://system-image.ubuntu.com to device frieza
can't flash recovery image
</code>
Comment: If you ordered the ubuntu tablet your better off getting onto BQ support and get the proper one delivered to you.
Comment: They will help you [here](https://t.me/ubports) on Telegram. Assuming you have an Ubuntu laptop or desktop, you download the installer from [this website](https://ubports.com/en/) and follow the instructions.
Answer: Hej, I have received the Ubuntu version, but wanted to try out the difference with Android. I have been flashing back and forth with no problems. But it seems you need to use the MediaTek Flash tool (http://spflashtool.com), and the Ubuntu image for the M10 you can get from "http://www.mibqyyo.com/en-download/". If you google for "bq has released the MediaTek" the first hit will direct you to someone that has used the tool to flash his E4.5 from Ubuntu Touch to Android, but I found it works both ways for the M10. Now I just want Dual Boot to work...
I guess the first comment is more correct... you should get what you paid for, considering the Android version is cheaper.
Comment: Why is this firmware for Ubuntu 15.04 (which I don't even think is still supported now that 16.04 is out)? My BQ M10 won't update successfully; perhaps this is why?
Comment: OTA10.1 which is the latest version, is based on 15.04. So I guess you have the latest version alright. You can check in the About section, where OS says Ubuntu 15.04 (OTA-10.1). I have heard rumours, that the next release, OTA-11, will be based on Ubuntu 16.04. But I can only hope :-D
Comment: Jelle, did you use the Android 5.1 on that mibqyyo.com link to get the Android install?  After getting my M10 I find that Ubuntu Touch is really completely unusable, even for a Linux geek like me.  I'd love to put Android on it.  Using the black FHD version.
Comment: Hej Tony... yes, that is where I got the Android 5.1 update. I find it very responsive on the M10. I feel exactly the same way, as a geek, I was willing to accept quite a lot just to get convergence, but I quite simply could not live with it... I'm happy with the performance of the M10 FHD now, although I find it disappointing that it now is just another Android tablet... Let me know if you need help.
Answer: I followed the steps on this website http://a25.co/ubuntu-phone-how-to-install-android/#fnref:3 that was already mentioned in the previous post and it worked for me.
I flashed Android 5.1 on my M10 FHD Ubuntu Tablet. I found the Windows driver and flash tools on this http://www.mibqyyo.com/en-download/categorias/aquaris-m10-fhd-ubuntu-edition/ website for the M10 FHD Ubuntu.
The Android Firmware was the one for the Aquaris M10 FHD on this mibqyyo.com/en-download/categorias/aquaris-m10-fhd/ site. If you follow the process as described on the a25.co website you should change the batch file according to the instructions. I tried using the original one and that didn't work in the end.
After the flashing process was successful, the first initialization of the tablet took quite some time. So for the first 5 to 10 minutes don't worry. In the end every flashing process still caries a risk.
Answer: Find the right tool and instructions at bq's own site:
http://www.mibqyyo.com/comunidad/discussion/75471/is-there-any-guidance-i-can-replace-the-ubuntu-with-android-for-m10-fhd/p1
Comment: Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.
Answer: I succeed to install Ubuntu Touch from my Android tablet by following this great tutorial : https://www.lucaswilliams.net/index.php/2017/02/11/install-ubuntu-touch-on-bq-aquaris-m10-fhd/
Comment: Please share the essential part of the answer and share the link only as reference and perhaps for more detail


Compiling 32-bit app on 64-bit, cannot find -lX11

Question: I'm invoking a command like:
g++ ... -o"myapp" -lX11 ...

And getting
/usr/bin/ld: cannot find -lX11

I've installed the following packages to support multiarch:
ia32-libs, libc6-dev-i386 and g++-multilib

But to no avail. There does not appear to be any X11.so in /usr/lib32, actually there are only 52 libraries in that directory. I'm under the impression you should manually install libraries, but I'm at a loss as to what I should check next.
Any help appreciated.
Comment: Can you show the output of the command `ldconfig -p | grep libX11\\.`?
Answer: You need the header files, which are provided by -dev packages, and not in the library packages themselves. So, try installing libx11-dev. That should fix this particular build error, though you may get similar errors about other libraries (and then you can install their -dev packages.)
Even though these packages provide header files rather than binaries, and in general header files account for all supported architectures through the use of preprocessor macros, nonetheless -dev packages in Ubuntu tend to be architecture-specific, and this is the case for libx11-dev (as can be seen here by expanding a release and finding the .deb packages listed for libx11-dev in that release). Since your Ubuntu system is 64-bit and you're compiling a 32-bit program which must link against the 32-bit version of the library, you'll probably need to install the 32-bit version of libx11-dev. If you're installing with apt-get or aptitude, you can specify that by indicating libx11-dev:i386 as the package to install (since multarch is supported and being used).
http://packages.ubuntu.com/ is a good resource for finding the name of the -dev package corresponding to a library package. It's not always the library package's name immediately followed by -dev; sometimes version numbers present in the library package name, especially after a -, are absent in the name of the corresponding -dev package.


GFCI vs. 40v 5ah battery for water safety

Question: My wife has recently taken to running a cord out near our pool to watch TV. She's very careful, but I was thinking of doing what I can to make it safer, since the outlet in question is NOT a GFCI outlet (It's a standard US 110v outlet).
One obvious solution is an inline GFCI (or installing a GFCI outlet)
The other more expensive idea that occurred to me is using a 5ah 40v lithium battery that I can purchase a 300w inverter for.
My guess here is that if the wired TV were to go into the water, a GFCI would be better than nothing, but unsafe...whereas the battery would be practically speaking likely to be completely safe. Can anyone enlighten me as to which approach would be the safest, and if either or both is actually "safe"?
The water is typical "saline-pool" water.
Comment: An inverter is also taking the voltage back to 120 VAC. You can still deal enough current (2.5 A) to kill with a 300W inverter (death can occur with significantly less than 1 A).
Comment: @user253751 This is not true. An isolation transformer's secondary circuit is not grounded, but if you put both poles into water, there will be an electric field in the water which will not only form directly between the poles, but also within a certain range.
Comment: 40v DC in water can be dangerous.
Comment: I'd love to hear your thinking of why the battery and inverter would add any safety at all. You'll still be delivering potentially lethal 110 AC with no mechanism to shut the power off should a circuit complete through a person.
Comment: @DavidSchwartz - No thinking.  My intuition, which I know to be often wrong when it comes to electricity, which is why I asked.  I don't really understand electricity well enough to think about it.  Very glad I asked.
Comment: Um, watch TV on a tablet instead? You can get water-proof floating cases and just use it like a swimming foam board. Exercise + TV = win.
Comment: At least theoretically, an isolation transformer would give you the same protection as a battery-powered solution, without the risk of the battery exploding if it gets wet. (I have no idea what the code says about isolation transformers)
Comment: @glglgl That is also true of inverters.
Comment: @user253751 Fully true.
Comment: Not for nothing but you should consider increasing her life insurance policy.
Answer: It doesn't need to be a GFCI outlet.  It needs to be GFCI protected.  GFCI protection is conferred by having any particular outlet obtain power power from the LOAD side of a GFCI device somewhere.  On most string-topology circuits, a single well-placed GFCI device will protect the whole circuit.
If you stick a GFCI tester in there, push the button and the outlet goes dead, you're sympatico.
The bigger problem is the temptation to bring cords to the pool area
Your #1 safety risk is the fact that people wanting to plug things in, in the pool area, feel a need to run an extension cord from some distant location. This requires a social-engineering solution.  You need to rearrange your home to suppress that desire.
So either put GFCI protection on every outlet they might ever dream to tap... or, install a plethora of outlets, actually poolside, that are protected by a GFCI device somewhere.  I prefer to have my GFCI devices indoors, so I make extensive use of the LOAD feature of GFCIs. Now there's no reason for someone to run an extension cord to the pool area; there are outlets all over the place.
GFCI is safe as you're going to get
A properly installed GFCI setup, with the protection device some distance from the outlet, is as safe as things can be.  It will trip the GFCI if hot or neutral current takes a path other than the normal one.
Higher DC voltages bite.  HARD.
Electronics and car people tend to believe DC is docile and harmless.  It is at 12V, yes.  However, somewhere in the 20s it starts getting a personality, and by about 60 volts it goes full honey-badger.  Can 40V bite you?  Oh, yes it can! And it won't let go, either.  So ixnay on the 40V battery pack.  I encourage you to develop a little bit of fear of it.
TVs are 12 volts, anyway
Besides, now that TV tubes are gone, lot of TVs these days actually use a low voltage, typically 12 volts.  Better off just using a battery pack that size than do a double conversion.
Comment: *"TVs are 12 volts"* LCD panel with CCFL backlight contains an high-voltage circuit to power it (probably low-current but still couple thousand volts). Only LED-backlit TV are full low voltage outside the main transformer.
Comment: Also: lithium batteries are liable to explode violently if they fall in water. Is that better or worse than the GFCI?
Comment: @user253751 A small explosion is preferable over electrocution, but I'd prefer to avoid both.
Comment: I recall many years ago being stung by a POTS line, gave it more respect after that.
Comment: It's going to be hard to forget the image of the full honey-badger battery pack!
Comment: @user253751 "lithium batteries are liable to explode violently if they fall in water" - [Not always](https://youtu.be/cTJh_bzI0QQ?t=430).
Comment: For the permanent outlets you may install make them at least rain/splash resistant to fully in-use outdoor rated depending on how close they are to the splash zone.
Comment: Is there a bathroom nearby where the extension cord can be plugged in? If your house is under 30 years old, code requires that the bathroom outlet have GFCI protection.
Comment: This is why I have come to like GFCI breakers for most general -purpose receptacle ckts. (Not for the fridge!)
Answer: High voltages may be present inside the TV, and eliminating ground does not make the electricity harmless in water.
When energized electrodes are applied to water, an electric field is created which extends far from the electrodes.  Depending on the voltage, whether there's pulsing or AC, and current this can induce muscle contractions and make people and animals unable to leave the water, or maintain a safe posture above the water.
So, in short, no - a battery and inverter combination is not safe, and certainly not safer than a GFCI protection unit.
While a properly used GFCI will stop the current very quickly once a wire or electrical appliance drops into the water - it will only do so if the appliance doesn't have an isolated power supply.  Most electronics, however, do have voltage converters that isolate internal power from the power line, which means it's possible for a partially submerged electronic device to create an electric field in the water without causing the GFCI to trip.
The only adequate solution is to mount the TV and all wiring in a permanent fashion so it cannot come into contact with the water, and to GFCI protect it.  If the TV is mounted to the wall, for instance, and connected via a short cord to a GFCI outlet mounted high on the wall with a tamper evident cover and lock (to discourage others plugging in extension cords which could reach to the water) then you'll achieve a reasonable level of safety.  You may need a larger TV to make up for the distance from the water, and you may need more weather proofing if this is outdoors.
Any solution where it's possible for the electronics or wires to come into contact with the water is inadequate, regardless of the care of those using the equipment, or the protections you might put in line.
An alternative is using a tablet in a waterproof case, or one of the many newer waterproof or rugged tablets.  It will probably be cheaper and more flexible than the TV, and if you have cable or satellite service you can use it with online streaming to get essentially the same content without having to use a real TV.  If you already have a suitable tablet, the waterproof case would be cheaper than hiring an electrician to mount the TV and wire in a GFCI outlet.
Comment: (Very bad) 9" Tablets pretty much start around $80, which was the price of this TV.  Mounting the TV is not possible (there's no wall).  However using GFCI is not at all a problem and the TV itself can be kept well away from the water and untouched when plugged in if desirable (and it sounds like it is).  That would leave the only potential contact with water being the cord itself with nothing plugged into it, or an unplugged TV.
Answer: How about bolting the TV set to the wall permanently (above the possible splashes) AND employing GFCI for all circuits that go somewhere near the pool? It is just a matter of time someone to bring a hair dryer.


How does compiler know if a variable is spilled in code generation?

Question: I am implementing a compiler using visitor pattern.
Here is the general algorithm I use.
regs gives the number of registers needed and top give the next free register.
generate(T,n) =
    if T is a leaf write ``load top(), T"
    if T is an internal node with children l and r then
    if regs(r) = 0 then { generate(l); write ``op top(), r" }
    else{
        generate(l,n)//Stored in Rn
        generate(r,n+1)//Stored in Rn+1
        write "op Rn, Rn+1" // rresult is stored in Rn
        push(R) }

But in the case where there's not enough registers, we need to spill variables.
Suppose we use a greedy allocator that spills the last used register. It means that, when we generate(r) if there's no register left to store the result, we push Rn to the stack and store result in Rn and then retrieve spilled variable to compute the operation.
The complete schema become:
generate(l,n)//Stored in Rn
push Rn // push to stack
generate(r,n)//Stored in Rn
mov Rn R0 // move
pop Rn // retrieve from stack
write ``op Rn, R0" // result is stored in Rn

What I tried is to modifty the function top to make it return a register if any available and push last register before returning it if no-one is available so when generating r children, we can save to stack if there's no space...
generate(l,top())//Stored in Rn
generate(r,top())//Spill if no space and store in Rn
mov Rn R0 <--- my problem is here
pop Rn <--- my problem is here
write ``op Rn, R0" <---my problem here

But after generation of l and r, how does the operation knows that it needs to unspill* some variable (if it has to) ?
My question is :
Programmatically, how can I implement it in the compiler to make it oblivious to operation code.
Ideally ... code should look like:
generate(l,something())//Stored in Rn
generate(r,something())
write ``op somethingelse(), againsomethingelse()" <--- taking into account when space is available or not

Comment: Typical graph colouring register allocators, for example, rebuild the interference graph if spilling occurs. So, they operate over a normalised (usually three-address code) format and use standard liveness algorithms to compute the interference - so if a value is spilled, the program is rewritten (to insert the spill code to commute the temporary to/from memory upon defs and uses), and the algorithm goes again. What you're implementing appears ad-hoc and of your own creation, so I can't comment on how you would incorporate spill awareness; like most things, probably more book keeping.
Comment: @contificate If we suppose that it is spilled using a complex strategy like graph coulouring...when backtracking operations, how does the compiler knows that a particular temp has been spilled and needs to be unspilled ? I think my (long) question sums up to that. Is there a known data structure used like a mapping from AST node to location in register/stack used by the compiler ?
Comment: That's the thing, spilling rewrites the program (so you don't need to remember what you spilled - but it's good to prioritise spill candidates). If you know you need to spill some temp, you rewrite its definitions and uses; you put a load before each use, and a store after each definition. The fact that uses immediately follow a definition (that loads the value from a stack slot) offloads the liveness (as definitions kill liveness). So, the interferences change and must be recomputed. Generally, you don't do this at the level of an AST - it's often over three address code for a basic block.
Answer: The comments made by contificate are right. I'll just try to elaborate a little more.
First, I suggest you to read the following slides: https://web.cs.wpi.edu/~kal/courses/compilers/module6/RastislavBodikregalloc.PDF
On slide number 28, you can see how spilling works. You enter a loop: try to assign the registers by coloring. If it fails, spill a register and try to coloring again. Repeat until you're successful.
How do you track which variable are spilled or not? You don't. When you rewrite the code to accommodate the spilling, you get for free the tracking. On slide 28 it says

Before each operation that uses f, insert f := load fa

After each operation that defines f, insert
store f, fa

So if in your program, you have a
t2 = t0 + t1
...
t10 = t2 + t3

And by whatever reason you can't assign a register for temporary t2, this means that its interference graph is overloaded with too many edges. You need to eliminate some of those edges. How do you do that? By making a variable alive for less time. How do you achieve that? By inserting loads and stores as soon as you need to use the variable. So the example I gave becomes:
t2 = t0 + t1
store t2    // immediately stores t2 after its use
...
// loads t2 just right before it is used
t2 = load t2
t10 = t2 + t3

This way t2 is going to be alive just for a brief moment of time. This will reduce the pressure in the interference graph which will allow a new round trying to assign registers to the temporaries in a graph with fewer interferences. If can't again find a colouring, choose another temporary, spill it (insert loads and stores where needed) and repeat.
This is isn't the only way to do it, but I believe it is one of the simplest.


Keyboard is not working in GRUB menu

Question: My Laptop key is not working in GRUB menu. I don't have a dual-boot or USB keyboard attached.
I have searched : here , here or here but all the options are either for Dual boot system or for external usb [PS/2] keyboards but my system is a Laptop. *(so this question is not a duplicate!)
When my system starts it automatically shows GRUB (Advance Recovery) menu but no keys are working so how do I enter? + the FAN rotates heavily and after a minute my laptop shuts down automatically.
What do I do, please help?
Info : Sony Vaio C series, Ubuntu 14.04 x64 updated
Answer: I got the answer myself! If anyone is facing the same problem then :-

Use Page UP / Page Down to select any option.
In my case it went to the last option in the list ( - Memory check)
I opted for Memory Check and used 'Esc' to return to the GRUB menu
Now the Up/Down arror key started working.
PROBLEM SOLVED

My actual problem was ATI graphics card driver so I followed the amazing instruction in askubuntu post

Keyboard is not working in GRUB menu


New user question about passwords

Question: Just got a refurbished computer with Ubuntu as the OS.  Have never even heard of the OS and now I'm trying to learn.  When I boot the system, it starts up great.  But, if I try to navigate around, it requires a password.  Is there a trick to finding the initial password?  Please advise.
Comment: Have you tried contacting the re-furbisher for the password?
Comment: @Sneetsher No, even if that question is in some way aequivalent, it is very different from the perspective of the user asking here. And that user is representing a very valid - and even common - use case: The user wants to try Ubuntu and aquires a used computer - where he may not even know the previous user, not to think of his password. Or he aquires an old computer, and needs to try Ubuntu, which turns out to be installed. So, the use case is: Solving the password reset as first action ever on a unix-like OS.
Comment: Thank you @VolkerSiegel for comment, I just thought about answer (not question itself), the 1st high votes answer should be then the answer he is looking for, no?
Comment: @Sneetsher Oh, I'm just about to finish my own answer, and did not read the related question and it's answers in detail. You are right, that would be a solution. My approach is pretty different, concentrating on building a context for a user who initially has just no idea what he's doing. Roughly, my answer *ends* with refering the user to that related question or similar to find how to reset the password from a running live CD. Wait a few minutes to see my answer here.
Comment: @VolkerSiegel, never mind, if you think it will add some thing compared to one mentioned. please post it. As it's still open. many others may find it helpful for future reference.
Comment: I'd be really curious about feedback from you, @user279162, whether my answer did provide additionoal help above [How do I reset a lost administrative password?](http://askubuntu.com/questions/24006/how-do-i-reset-a-lost-administrative-password). It's really hard to imagine being in your situation, and what would help best; But it would also be very userful to find that out!
Answer: No,
there is not trick to find the initial password [1].
But to solve your actual problem, you do not need that [2].
Important: before continuing here, try if the answers on
How do I reset a lost administrative password? make sense to you. If yes, use them. Otherwise, continue here, I will give you some context to understand what problem you need to solve, and propose an approach to start.
Normally, an Ubuntu system used by one person has a user name, and a password for that user name, defined during setup. That password can be used to log in at startup, and to allow actions that change system data.
But - important -  it can not be used to log in as the system administrator with the user name "root", as you could expect from similar unix-like systems.
On an Ubuntu system, user root normally can not log in at all in the usual sense of loging in.
So if you are looking for the root password - that does not even exist. You need the user name, and the password for that user, to log in.
But if you can not get hold of that password, you can forget about the normal login, and find another way.
You could start the system independently of the installed OS, and reset the password to nothing, or set a password choose.
To have the programs you may need available, use an Ubuntu live DVD (or CD, USB-stick etc.) to boot it as an independent OS, that just happens to be a similar version. Then, you have a clean system running, that you are fully in control of.
In your situation, it would be good to use the opportunity to start getting used to the system. One reason is that it's nice that you can try things that may mess up your system, and just restart if tha happens. The other reason is that you now have a simple, normal system, while the old system may have personal configuration changes that could confuse you (and people trying to help).
Now you need to find the hard disk partition that contains the old Ubuntu system, and how to reset the password on that partition, from working from your live CD.
I'll stop here and refer you to other answers. You could start at the same place I mentioned at the beginning: How do I reset a lost administrative password?.
(One approach would be to use the method titled "The Drastic Measures" from the answer of @keepitsimpleengineer - but it is more difficult than others if you are not used to the system. Of course you can just try again if the old system still does not work because of a typo.)

Notes:

There is no fixed default password in Ubuntu, in case you are looking for that.
This approach does not work if the harddisk containing the old Ubuntu is encrypted.

[1] Except for classic "hacking" approaches - like automatically trying all possible short passwords, or all from a list with known common passwords.
[2] See X/Y problem

New user question about passwords


Serverless logs on AWS CloudWatch dont work

Question: I'm trying to get logs of a production Serverless deployment (nestjs) on AWS CloudWatch. I tried setting cloudwatchLog on the function as well as the logs block on the api level to no avail. I only see the general startup logs appear and then empty logs (console.log is supposed to write to the logs but it doesn't). How this can be fixed?

2023-08-03T09:39:10.945+02:00   INIT_START Runtime Version: nodejs:16.v16 Runtime Version ARN: arn:aws:lambda:eu-west-2::runtime:c1983f4e9ce3930d3093fa38128e12edac2324f4fe99adfb8e0d5fb6b6afadbc

2023-08-03T09:39:34.476+02:00   START RequestId: 41d79246-7bd6-48bf-8eac-f4ab5f65e9c1 Version: $LATEST

2023-08-03T09:39:34.945+02:00   [32m[Nest] 8 - [39m08/03/2023, 7:39:34 AM [32m LOG[39m [38;5;3m[NestFactory] [39m[32mStarting Nest application...[39m

controllers mapped etc...

2023-08-03T09:39:35.607+02:00   [32m[Nest] 8 - [39m08/03/2023, 7:39:35 AM [32m LOG[39m [38;5;3m[NestApplication] [39m[32mNest application successfully started[39m[38;5;3m +22ms[39m

2023-08-03T09:39:35.632+02:00   END RequestId: 41d79246-7bd6-48bf-8eac-f4ab5f65e9c1

2023-08-03T09:39:35.632+02:00   REPORT RequestId: 41d79246-7bd6-48bf-8eac-f4ab5f65e9c1 Duration: 1155.60 ms Billed Duration: 1156 ms Memory Size: 1024 MB Max Memory Used: 192 MB Init Duration: 2183.01 ms

2023-08-03T09:39:37.100+02:00   START RequestId: 8de822b4-a562-46cd-8f45-68d58df9bcc6 Version: $LATEST

2023-08-03T09:39:37.106+02:00   END RequestId: 8de822b4-a562-46cd-8f45-68d58df9bcc6

2023-08-03T09:39:37.106+02:00   REPORT RequestId: 8de822b4-a562-46cd-8f45-68d58df9bcc6 Duration: 5.27 ms Billed Duration: 6 ms Memory Size: 1024 MB Max Memory Used: 193 MB

2023-08-03T09:39:39.005+02:00   START RequestId: 4d6c8e4f-b840-4200-a1e4-b7a087f36cad Version: $LATEST

2023-08-03T09:39:39.010+02:00   END RequestId: 4d6c8e4f-b840-4200-a1e4-b7a087f36cad

2023-08-03T09:39:39.010+02:00   REPORT RequestId: 4d6c8e4f-b840-4200-a1e4-b7a087f36cad Duration: 5.00 ms Billed Duration: 5 ms Memory Size: 1024 MB Max Memory Used: 193 MB

2023-08-03T09:44:02.337+02:00   START RequestId: c5028e01-8a5f-4bc5-97dc-d99231b4bee5 Version: $LATEST

2023-08-03T09:44:02.357+02:00   END RequestId: c5028e01-8a5f-4bc5-97dc-d99231b4bee5

I created the cloudwatch log group and set the cloudwatchLog line to it, but that log group is completely empty so I'm using the default aws/lambda/x log group.
Answer: Most likely the console.log() statements are not being called. I sit part of a function which is probably not reached? Maybe, put the first line as console.log('hello') and see if it is outputted.
Iam role and internet or endpoint settings are correct since it's writing some messages are to cloudwatch.


Why does a 403 error suddenly occurs?

Question: I'm using Spring Social to get some informations via the LinkedIn API. Everything works fine : I can connect to my application using LinkedIn, I can recover some granted informations about my connections...
However, sometimes, I can't access anymore to LinkedIn and get this error :
<code>16:28:00,741 WARN  [RestTemplate] GET request for "https://api.linkedin.com/v1/people/id=FNXqbb779g:(id,first-name,last-name,headline,location,industry,distance,relation-to-viewer,current-share,num-connections,num-connections-capped,summary,specialties,proposal-comments,associations,honors,interests,positions,publications,patents,languages,skills,certifications,educations,three-current-positions,three-past-positions,num-recommenders,recommendations-received,phone-numbers,im-accounts,twitter-accounts,date-of-birth,main-address,member-url-resources,picture-url,site-standard-profile-request:(url),api-public-profile-request:(url),site-public-profile-request:(url),api-standard-profile-request,public-profile-url)?format=json" resulted in 403 (Forbidden); invoking error handler
</code>
According to the error message, I'm not authorized to get the required informations (despite the fact that one minute before, I could access them).
Any ideas why ?
Answer: It seems that either your session token is getting expired or you're probably running into throttle limits. A session token is valid for some duration, you may need to check logs and see whether you are getting something like

"Your session has expired and the post data is lost. Please
  re-authenticate and re-post the data"

Also check about throttle limits here:
https://developer-programs.linkedin.com/documents/throttle-limits
Comment: I'm gonna check that, I'll let you know if I find an answer.*
Comment: Well, according to LinkedIn, I'm way below my throttle limit. I didn't find informations about expired session either (I tried logging out and in again, didn't change something).
Comment: By "session token" Juned probably means "access token". LinkedIn's documentation says their access tokens last 60 days: http://developer.linkedin.com/documents/authentication Check this page's "Refreshing an access token" information for how to get a fresh access token when the one you have expires: http://developer.linkedin.com/documents/handling-errors-invalid-tokens

Why does a 403 error suddenly occurs?


C++ Chess Engine producing write access error

Question: I am working on a basic chess engine in C++, and I want to make a move by getting a string from a user. I want to write a move like 1144, that means column 1, row 1, to column 2, row 2. I type that in, and I get an error: > ChessUltimate.exe!std::_String_valstd::_Simple_types<char>::_Large_string_engaged() Line 2282 C++
ChessUltimate.exe!std::_String_valstd::_Simple_types<char>::_Myptr() Line 2274    C++
ChessUltimate.exe!std::string::operator=(const std::string & _Right) Line 3230  C++
ChessUltimate.exe!ChessBoard::makeMove(int from_number, int from_letter, int to_number, int to_letter) Line 80  C++

ChessUltimate.exe!main() Line 18    C++
in the Call Stack section of Visual Studio.
ChessEngine.h:

#pragma once

#include <iostream>
#include <sstream>

using namespace std;

class ChessBoard
{
    public:
        string** board;
        ChessBoard(string FEN)
        {
            // Make a 2D Array
            board = new string * [8]; // Rows
            for (int i = 0; i < 8; ++i)
            {
                board[i] = new string[8]; // Columns
            }

            // FEN parsing logic here
            int row = 7;
            int col = 0;

            for (char c : FEN)
            {
                if (isdigit(c))
                {
                    col += c - '0';
                }
                else if (c == '/')
                {
                    row--;
                    col = 0;
                }
                else if (c != ' ')
                {
                    board[row][col] = c;
                    col++;
                }
            }
        }

        ~ChessBoard()
        {
            for (int i = 0; i < 8; ++i)
            {
                delete[] board[i];
            }
            delete[] board;
        }

        void drawChessBoard()
        {
            for (int i = 7; i >= 0; --i)
            {
                cout << i + 1 << " ";
                for (int j = 0; j < 8; ++j)
                {
                    if (board[i][j].empty())
                    {
                        if ((i + j) % 2 == 0)
                            cout << "|#";
                        else
                            cout << "|_";
                    }
                    else
                    {
                        cout << "|" << board[i][j];
                    }
                }
                cout << "|\n";
            }
            cout << "   1 2 3 4 5 6 7 8\n";
        }

        void makeMove(int from_number, int from_letter, int to_number, int to_letter)
        {
            board [to_number-1][to_letter-1] = board[from_number-1][from_letter - 1];
            board [from_number-1][from_letter-1] = "";
        }
};

ChessUltimate.cpp (main file):
#include <iostream>
#include "ChessBoard.h"

using namespace std;

ChessBoard* board;

int main()
{
    board = new ChessBoard("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR");
    board->drawChessBoard();
    while (true)
    {
        string move;
        cin >> move;

        board->makeMove(move[1], move[0], move[3], move[2]);
        board->drawChessBoard();
    }

    delete board;
}

Comment: After typing in "1144" you might be surprised to learn that `move[0]` will not be 1, but 49, and `move[2]` will not be 4, but 52. VTC as a typo.
Comment: You are using too many pointers.  You could make your life much more easier if you use `std::vector> board;`.  Right now, this two line program shows the flaws in your class: `int main() { ChessBoard b("a"); ChessBoard b2 = b; }`
Comment: `board = new ChessBoard("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR");` -- There is no need to use `new` here.  Just `ChessBoard board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR");`.  It looks like you are using Java, C#, or python techniques in C++ code.  If you are, don't do this.  Instead, pretend none of those other languages exist.
Comment: It's for the same reason why you had to write `col += c - '0';` in `Chessboard::Chessboard`. This is a very common mistake. a typo, that occurs when there's confusion between characters and integers in C++. Did you try, already, to investigate this? Simply by adding `std::cout << from_number << "\n";`, or something along the same lines, ditto for the other four values, and seeing for yourself that you get 49 instead of 1?
Comment: [You don't need a single pointer in your code](https://godbolt.org/z/Yz1zj18va).
Comment: I recommend never using `new`.  But if you do have to use it, I recommend not using `new` until you have had several years of programming C++ under your belt.
Comment: You don't need to use dynamic memory or `new`.  A chess board is 8 x 8 which is 64 slots of your favorite type.  Still small enough to be a local variable.  If not convinced, you could make the board `static` and pass it by reference to other functions.
Comment: @SamVarshavchik why? What do you mean VTC as a typo? Please clarify.
Answer: Thanks to @SamVarshavchik, I looked up converting chars to ints, and figured it out!
My new code:
#include <iostream>
#include "ChessBoard.h"

using namespace std;

int main()
{
    ChessBoard board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR");
    board.drawChessBoard();
    while (true)
    {
        string move;
        cin >> move;

        board.makeMove(move.at(1)-48, move.at(0)-48, move.at(3)-48, move.at(2)-48);
        board.drawChessBoard();
    }
}

Answer: Why is you board a std::string ** to begin with? You have a board, not a pointer-to-pointer-to-strings. First string already holds multiple values, so std::string [] or char ** would be fine, but it would be better to use a different type - like enum. They are perfect for that as you have a small fixed number of possible chess-pieces. And it is a chess-board. It will always be 8x8.
putting that together and we have:
enum chessPiece {empty = 0, pawn_w, rook_w, knight_w, ..., pawn_b,....queen_b };
chessPiece board[8][8];

And for the user-input on the move: the ascii-characters for digits are not the same as their numeric values. '0' does not have the value 0 but 48. to get the corresponding integer to the users input you need to subtract that 48.
so your board [to_number-1][to_letter-1] would have to be board [to_number-'0'][to_letter-'0'].
And of course it would be a good idea to have a function that takes in the user-input, checks if it is of valid length (always 4 characters long), if the 1st and 3rd character are numeric, if the 2nd and 4th are numeric or letters, if they are all within range, and then convert them to a representation you like - like 4 ints.