WPF DataGrid Add select all checkbox in Header in code behind

Question: I am adding dynamically checkbox columns to WPF datagrid based on user interactions (button clicks, checkboxes etc). I need also to add an Select all checkbox to column header programmatically. Any ideas how to do it?
 DataGridCheckBoxColumn  checkBoxColumn=new DataGridCheckBoxColumn();
 checkBoxColumn.Header = "Title";
 checkBoxColumn.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
 checkBoxColumn.Binding = new Binding(e.PropertyName);
 checkBoxColumn.IsThreeState = true;

I would do it through XAML it should look something like this
<DataGridTemplateColumn>
            <DataGridTemplateColumn.Header>
                <CheckBox isChecked="{Binding SelectAll}"></CheckBox>
            </DataGridTemplateColumn.Header>
            <DataGridTemplateColumn.CellTemplate >
                <DataTemplate >
                    <CheckBox IsChecked="{Binding MyRowCheckProperty}"></CheckBox>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

Answer: Maybe I did not understand your question, but do you mean something like this?
Binding binding = new Binding("SelectAll");
binding.Mode = BindingMode.TwoWay;

CheckBox headerCheckBox = new CheckBox();
headerCheckBox.Content = "Title";
headerCheckBox.SetBinding(CheckBox.IsCheckedProperty, binding);

DataGridCheckBoxColumn checkBoxColumn = new DataGridCheckBoxColumn();
checkBoxColumn.Header = headerCheckBox;
checkBoxColumn.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
checkBoxColumn.Binding = new Binding(e.PropertyName);
checkBoxColumn.IsThreeState = true;

I hope so.
EDIT
It is strange the behavoiur that you describe in your comment. However this is the complete project (I used .NET 4.0).
XAML:
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="600">
    <StackPanel>
        <DataGrid Name="dataGrid" AutoGenerateColumns="False" ItemsSource="{Binding Mode=OneWay, Path=Parties}">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="*" />
                <DataGridTextColumn Header="Surname" Binding="{Binding Surname}" Width="*" />
            </DataGrid.Columns>
        </DataGrid>
    </StackPanel>
</Window>

Model:
namespace WpfApplication1
{
    public class Party : INotifyPropertyChanged
    {
        private bool isSelected;
        private string name;
        private string surname;

        public event PropertyChangedEventHandler PropertyChanged;

        public bool IsSelected
        {
            get
            {
                return isSelected;
            }
            set
            {
                if (isSelected != value)
                {
                    isSelected = value;
                    OnPropertyChanged("IsSelected");
                }
            }
        }

        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                if (name != value)
                {
                    name = value;
                    OnPropertyChanged("Name");
                }
            }
        }

        public string Surname
        {
            get
            {
                return surname;
            }
            set
            {
                if (surname != value)
                {
                    surname = value;
                    OnPropertyChanged("Surname");
                }
            }
        }

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

ViewModel (you can improve the INotifyPropertyChanged implementation, by creating a base class):
namespace WpfApplication1
{
    public class ViewModel : INotifyPropertyChanged
    {
        private bool selectAll;
        private readonly ObservableCollection<Party> parties = new ObservableCollection<Party>();

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public ObservableCollection<Party> Parties
        {
            get
            {
                return parties;
            }
        }

        public bool SelectAll
        {
            get
            {
                return selectAll;
            }
            set
            {
                if (selectAll != value)
                {
                    selectAll = value;
                    OnPropertyChanged("SelectAll");
                    SelectAllImpl(selectAll);
                }
            }
        }

        private void SelectAllImpl(bool isSelected)
        {
            foreach (Party party in parties)
            {
                party.IsSelected = isSelected;
            }
        }
    }
}

And then XAML code behind:
namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            ViewModel viewModel = new ViewModel();
            viewModel.Parties.Add(new Party() { Name = "Joe", Surname = "Redgate" });
            viewModel.Parties.Add(new Party() { Name = "Mike", Surname = "Blunt" });
            viewModel.Parties.Add(new Party() { Name = "Gina", Surname = "Barber" });

            DataContext = viewModel;

            Binding binding = new Binding("DataContext.SelectAll");
            binding.Mode = BindingMode.TwoWay;
            binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor);
            binding.RelativeSource.AncestorType = GetType();

            CheckBox headerCheckBox = new CheckBox();
            headerCheckBox.Content = "Is Selected";
            headerCheckBox.SetBinding(CheckBox.IsCheckedProperty, binding);

            DataGridCheckBoxColumn checkBoxColumn = new DataGridCheckBoxColumn();
            checkBoxColumn.Header = headerCheckBox;
            checkBoxColumn.Binding = new Binding("IsSelected");

            dataGrid.Columns.Insert(0, checkBoxColumn);
        }
    }
}

And this is the result:
Comment: Do you mean the checkbox does not appear in the column header? I can post more code if you need.
Comment: Something like this ... but your sample is not working unfortunately. CheckBox is not resolved in Header
Comment: Correct ... instead of checkbox a name of the control is shown... I would appreciate if you post somehing workable:) thx
Comment: Something that everybody seems to forget is that your header checkbox should be unticked/semi-ticked as soon as a row in the grid becomes unchecked. Hence, this image is invalid :)
Comment: You are right @mstaessen; indeed it is not so difficult to update the header checkbox. The ViewModel can handle this.
Comment: It is harder than you think, since there is no direct way to inform your viewmodel that a property has changed on a viewmodel of the bound collection
Comment: @mstaessen, you can register the ViewModel to the PropertyChanged event of each Party object for monitoring if a Party is selected.


bathtub drain stuck

Question: My bathtub drain is stuck, and I used lots of Drano Clog Remover in the past, but it only lasted for a few days. Also I tried all kinds of Drain Clog Remover Cleaning Tool, and none of them works.
Currently, I want to completely remove the existing bathtub stopper, and install a drain cap that looks like

However the current drain looks like

and it looks like there is a metal rob stick out of the drain, and i can't remove it. has anybody had similar issues in the past? thanks for any help.
Comment: can you provide a pic with better lighting, maybe with a flashlight?
Answer: In general, that center post will unscrew from the center, but that won't help remove the drain.  The drain screws in just like the new one in your picture.  Removing the center bar will allow you to get a drain removal tool in there.
Before trying anything, realize that drains that old usually do not come out in one piece.  The cross bar inside the drain could break when trying to remove the center post, but even if it doesn't, it can then break when trying to unscrew the drain.
Breaking out the center post or just removing it would allow you to put a normal strainer over the drain, and that might be good enough for you. Unless you have access to the under side of the tub to help make a repair, I wouldn't try very hard to remove the drain.
Comment: i removed the center post and put a plastic cover there to catch all hairs

bathtub drain stuck


calculate intersection on for logarithmic x axis with R

Question: Hey everyone I am trying to show the intersection of a geom_line on a logarithmic x axis. However, I always miss the geom line. Here's what I do:
library(data.table)
library(ggplot2)

x <- c(0.1, 0.2)
y <- c(0.2, 0.4)

dt <- data.table(x = x,
                 y = y)

dt_lm <- lm(y ~ x, data = dt)
dt_slope <- summary(dt_lm)$coefficients[2, 1]
dt_inter <- summary(dt_lm)$coefficients[1, 1]
dt_x <- (0.3 - dt_inter) / dt_slope

ggplot(dt, aes(x, y)) +
  geom_line() +
  geom_segment(aes(x = 0,
                   xend = dt_x,
                   y = 0.3,
                   yend = 0.3),
               color="red") +
  geom_segment(aes(x = dt_x,
                   xend = dt_x,
                   y = 0,
                   yend = 0.3),
               color="red") +
  scale_x_continuous(trans = "log2")

I guess I have to take the log2 into account at the lm, since without trans = "log2" everything looks fine. However, I fail here :D
Answer: The problem is that geom_line is simply drawing a straight line segment between the two points defined in dt. With a log transform on the x axis, this "straight" line should actually be a curve, but an axis transformation will not convert a straight line segment between two points to a curve. To do this, you would need to get the correct x and y co-ordinates at all the points along the line and plot these.
There are a couple of ways to do that. You could get the curve to intersect at the correct point by interpolating many points along the line. This will allow geom_line to draw hundreds of little line segments between the newly created co-ordinates, giving the visual effect of a smooth curve:
ggplot(as.data.frame(approx(dt$x, dt$y, n = 1000)), aes(x, y)) +
  geom_line() +
  geom_segment(aes(x = 0, xend = dt_x, y = 0.3, yend = 0.3), color = "red") +
  geom_segment(aes(x = dt_x, xend = dt_x, y = 0, yend = 0.3), color = "red") +
  scale_x_continuous(trans = "log2")

Perhaps a better approach is to get ggplot to do this for you. Although an axis transformation will not change a straight line to a curve, a coordinate transform will. For this, you need to use coord_trans instead of applying your transformation via scale_x_continuous
ggplot(dt, aes(x, y)) +
  geom_line() +
  geom_segment(aes(x = 0.1, xend = dt_x, y = 0.3, yend = 0.3), color = "red") +
  geom_segment(aes(x = dt_x, xend = dt_x, y = 0, yend = 0.3), color = "red") +
  coord_trans(x = "log2", xlim = c(0.1, 0.2))

Note that this gives you the transformed x axis "for free", and has much nicer breaks that emphasize the log scale of the axis.


Edit user modal box

Question:
Possible Duplicate:
Expressing that new password is optional

I have built a simple user management system on my webserver. There is a list of users, each of which is either "Administrator" or "Operator". Only administrators can change user details. Below is a screenshot of the "Edit user" modal, based on Bootstrap.
Each of the username, password and rights can be modified. I have opted to leave the "New username" and "New password" fields empty, to mean "Leave unchanged". (I do not want to populate the "New password" field with the actual old password!) As for the "New rights" choice, I have prepopulated it with the old rights.
The "New username" input field is focused when the modal is shown.
I hope the old username is visible enough in the modal title? Have my choices been wise? How would you tweak this modal to make it more usable and clear?

EDIT (using Peter's suggestions)

2nd EDIT (see live example here)
Answer: I would change "New username" to "Username" and prepopulate with the existing username. Have 3 password fields: existing, new and confirm new. Making a change requires the existing password to be entered regardless. Replace the "close" button with a "cancel" link - it's not the main call to action, and "close" does not make clear if the changes are saved or discarded. Also (sorry for going into so much detail!) remove the username from the title to avoid duplication, remove new from new rights, and have as a radio button - a bit more room to add new options if needed later on. Finally, I'm guessing you already have a double check on "remove"?
Comment: The more detail the better. Thanks a lot. What about the input field placeholders? I'll work on a new version and I'll be back with a new screenshot. :)
Comment: New screenshot added. I'm not sure about the radio button. It's actually already a "Bootstrap radio button" (see [here](http://twitter.github.com/bootstrap/javascript.html#buttons)).
Comment: Cool. I'd probably avoid having a separate password titl - with so few fields its not really needed. Maybe leave out the copy in the password fields - not really adding anything at the moment. You might consider only displaying the "confirm" field if the user types something in the "new" field
Comment: There is a bit of a problem by removing the original username in the modal title. Indeed, if the username gets edited then the "Remove" button becomes a bit ambiguous...

Edit user modal box


Scripting question (youtube-dl and xclip)

Question: I have youtube-dl and xclip installed.
Is there a way I could write a script that can run commands from both?
For example: youtube-dl -l --extract-audio (url) but instead of pasting a url could I have xclip paste what's in my clipboard with the command: xclip -o
I am a complete noob when it comes to scripting and not even sure what I should use to write the script, as far as I can tell I should use Bash.
Comment: Do I understand you correctly, you want to browse Youtube and copy a link of a video, then have a script that calls youtube-dl & xclip which automatically gives it the video link, In other words you won't have to open up your terminal and run the commands manually, whatever you copy to your clipboard will essentially be downloaded automatically in the background?
Comment: That would also work if you know of a way to do that.
Answer: You almost had the code:
youtube-dl -l --extract-audio "$(xclip -o)"

$(command) executes command and $(...) is then substituted for the standard output of command. The quoting is necessary to prevent output containing whitespace from breaking the command.
Comment: oh wow that did it. Thanks i feel pretty dumb because that was so easy xD


The computation of nullity and rank of a linear transformation.

Question: Let $V$ be the linear space of all real functions continuous on $[a, b]$. If $f\in V, g=T(f)$ means that $$g(x)=\int_a^b f(t)\sin(x-t)\,dt\hspace{1 cm} for\ a\le x\le b$$
We can see this as a linear transformation $T: V\to V$ the linearity of which is easy to show.$\\$ Now how do you compute the nullity and rank of this transformation?
I'm rather new to linear algebra so I'd appreciate it if you include lots of detail and explanation in your answer. Thank you in advance.
P.S: the final answer is infinite nullity and 2nd rank (according to the back of the book).
From calculus II by Tom M. Apostol - page 36
Answer: Start with definitions:
Nullility is the dimension of the null space, which for this problem is equivalent to asking for set of all non-zero, linearly independent functions $f$ such that $T(f)=0$.
To get some intuition for why the answer is infinite nullility, suppose $b=-a$ and $f$ is an even function (i.e. $f(x)=f(-x)$), I think you can show that $T(f)=0$ (think about the integral from a to 0 and then from 0 to b -- these must have equal magnitude but opposite signs). Now the question becomes how many linearly independent functions span the space of all even functions? I think you can show that the Taylor series for an even function must be of the form $\sum_{n=0}^{\infty}\alpha_n\frac{x^{2n}}{(2n)!}$, which gives you the result (you've written all possible even functions as a linear combination of even powers of $x$, of which there are infinitely many)
To chase after rank, you want to apply a similar line of reasoning: you want to count how many linearly independent functions $f_{n}$ there are such that $T(f_n)\ne0$


How to have variables of scores

Question: I have a question, how can I get a variable of scores from user and take that variable to divide to get the average number, I saw I could change line 19, the scores[] to something and the number to divide, can anyone show me how to do it ?
#include <stdio.h>
#include <cs50.h>
int main(void)
{
int n = get_int("How many scores you have? ");
int score[n];
  for( int i = 0; i < n; i++)
  {
    score[i] = get_int("Score: ");
  }
printf("Average: %.2f\n", (score[n] + score[n]+ score[n]) / 3.0);
}

Comment: Google _rubber duck debugging_. This is no joke.
Comment: An array of `n` elements have indexes from `0` to `n - 1`, as you seem to already know. Then think about what happens if you use `n` itself as an index (in `score[n]`). It will be *out of bounds*. If you want to calculate the average of the three first elements of `score` you need to use the tree first elements with the proper indexes: `score[0]`, `score[1]`, and `score[2]`. If you want the average of all elements from the array, you need a loop to calculate the sum, and then divide by `n`.
Comment: And unless you want to use the scores later, you don't actually need an array. All you need is a `sum` (initialized to `0`), and then in your existing loop add the input to `sum` (like `sum += get_int(...)`). Then divide `sum` with `(double) n` to get the average.
Answer: declare int i before the first loop make another loop to add up all the scores and divide at the end by i (the number of scores) to get the average.
like this:
#include <stdio.h>
#include <cs50.h>
int main(void)
{
    int n = get_int("How many scores you have? ");
    int score[n];
    double average = 0;
    for (int i = 0; i < n; i++)
    {
        score[i] = get_int("Score: ");
        average+=score[i] // if you just need the average you can delete the line int score[n] and the line above and change score[i] to get_int("Score: ");
    }
    average = average / n;
    printf("Average: %.2f\n", average);
}

Comment: This does not help. `score[n]` is still out of bounds access and without summing up all the numbers you will not get a proper average. Also, after the loop `i` will always be same as `n`.
Comment: you're right I didn't thought of that I'll update the answer soon.
Comment: update is uploaded!
Comment: I tested it and it works just fine
Comment: Now it is nearly correct. You don't initialize `average=0`. Also there is no need to use a second loop as you can do that in the first one. And no need to move definition of `i` out of the loop as you can use `n` instead.
Comment: "Works just fine" or "Works on my machine" is just one possible variant of undefined behaviour.
Comment: `int n = get_int("");  int score[n];` I thought this doesn't work, does it?
Comment: @zibidigonzales this is called a "Variable Length Array" (VLA) and was introduced in C99. It is optional on later versions. Of course you should keep an eye on stack usage...
Comment: now my answer should be fine!
Comment: the VLA isn't "really" an VLA since ist doesn't change anymore
Comment: tho you could change `int n` to `const int n`
Comment: It is variable but not dynamic
Comment: Yes that's true

How to have variables of scores


Are Stacks and Queue's considered LinkedList?

Question: Are Stacks and Queue considered LinkedList?
The time complexity of indexing a LinkedList is 0(n). So am I right to assume that's the same for stacks and queues.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: Stacks and Queues are logical data structures that describe the operations you can perform on them.
Both a Stack and Queue can be implemented by an underlying linked list or a continuous memory array (or, TBH, any number of other implementations you could think of). The time complexity of any operation on a queue or a stack would depend on the underlying implementation.
Comment: For the java Stack stack = new Stack<>(); That class extends vector so it would share the same time complexity as a dynamic array right?


Google Actions & Dialogflow v2 - webhooks

Question: Background: I setup a simple DialogFlow to with two intents.  Set as api v1 and webhook to a glitch server.   I used glitch.com to host some js to gather information (requested by the user).
Switching to v2 of the api breaks this.  All the examples I've found use firebase as opposed to your own server to host the java script which is why I'm stuck and hoping someone can point me in the right direction for getting/returning data to/from google assistant in v2 without firebase.
See code below
<code>            // init project pkgs
            const express = require('express');
            const ApiAiAssistant = require('actions-on-google').ApiAiAssistant;
            const bodyParser = require('body-parser');
            const request = require('request');
            const app = express();
            const Map = require('es6-map');

            // Pretty JSON output for logs
            const prettyjson = require('prettyjson');
            const toSentence = require('underscore.string/toSentence');

            app.use(bodyParser.json({type: 'application/json'}));
            app.use(express.static('public'));

            // http://expressjs.com/en/starter/basic-routing.html
            app.get("/", function (request, response) {
              response.sendFile(__dirname + '/views/index.html');
            });

            // Handle webhook requests
            app.post('/', function(req, res, next) {
              // Log the request headers and body to help in debugging.
              // Check the webhook requests coming from Dialogflow by clicking the Logs button the sidebar.
              logObject('Request headers: ', req.headers);
              logObject('Request body: ', req.body);

              // Instantiate a new API.AI assistant object.
              const assistant = new ApiAiAssistant({request: req, response: res});

              // Declare our action parameters
              const PRICE_ACTION = 'price';

              // Create functions to handle price query
              function getPrice(assistant) {
                console.log('** Handling action: ' + PRICE_ACTION);
                let requestURL = 'https://blockchain.info/q/24hrprice';
                request(requestURL, function(error, response) {
                  if(error) {
                    console.log("got an error: " + error);
                    next(error);
                  } else {
                    let price = response.body;

                    logObject('the current bitcoin price: ' , price);
                    // Respond to the user with the current temperature.
                    assistant.tell("The current bitcoin price is " + price);
                  }
                });
              }

              // Add handler functions to the action router.
              let actionRouter = new Map();
              actionRouter.set(PRICE_ACTION, getPrice);
              actionRouter.set(STATUS_ACTION, getStatus);

              // Route requests to the proper handler functions via the action router.
              assistant.handleRequest(actionRouter);
            });

            // Handle errors
            app.use(function (err, req, res, next) {
              console.error(err.stack);
              res.status(500).send('Oppss... could not check the bitcoin price');
            })

            // Pretty print objects for logging
            function logObject(message, object, options) {
              console.log(message);
              console.log(prettyjson.render(object, options));
            }

            // Listen for requests
            let server = app.listen(process.env.PORT, function () {
              console.log('--> Our Webhook is listening on ' + JSON.stringify(server.address()));
            });
</code>
Answer: Is there any particular reason you want to use your own server?
Firebase handles requests automatically, and if you intend to publish your Action to the public, Google's rewards program should offer a $200 / monthly Cloud credit towards your account, offsetting personally accrued costs.
You can learn more about Google's rewards & community programs here: https://developers.google.com/actions/community/
Comment: My code, applied to firebase didn't return the results, using node.js it worked well.   The ultimate version would be to have proper authorization setup so through a website each person's account would be linked however I don't have the resources to complete that.  So for now the code will be shared and anyone who wishes to use it would need to use their own hosting (Node.js or otherwise)   I've completed the code now, will post soon.


Is there a way to wear this special armor as a costume?

Question: During the last quest of the base game's main story (God of Schemes) you use…

 … the amulet of kings to transform into a badass super mega daedric killer-wall melting-god slayer hero and... not kill... but beat Molag Bal. (www.youtube.com/watch?v=_fmIPy7XTUY - I removed the link because it would show what's inside the spoiler tag)

I recently did the quest again on a new char and I realized it looked pretty good.
What I'm looking for is if there exist any way to have my character look like it did then. I haven't seen an option in crown store, and no transformation was added after completing the quest.
So... any way? Or it was like "here... fore 10 min you look awesome. then... get back to your 'eh' looking".
Answer: Meridia's gift to the Vestige manifests itself mimicking the cyrodiilic Emperor's Regalia, which is also closely associated with the Amulet of Kings.

So it is indeed possible to obtain this costume, but it won't be easy, all it takes you is to:
Become Emperor in Cyrodiil
Comment: Well... I think next month I won't go to work any more :).


efibootmgr - Moving Win10 from one drive to another, w/ EFI on different drive

Question: I'm running Ubuntu 20.04 on one drive (m.2) and Win10 on another (3.5" SSD).  I recently added another m.2 drive to my system and cloned my Win10 system onto it.  So here's what my drives look like now, where sda1 and nvme1n1p1 are clones:
root@cantankerous:~# lsblk -f

NAME                 FSTYPE      LABEL UUID                                   FSAVAIL FSUSE% MOUNTPOINT
sda
└─sda1               ntfs              9638B89D38B87E35
nvme1n1
└─nvme1n1p1          ntfs              9638B89D38B87E35
nvme0n1
├─nvme0n1p1          vfat              23FD-2B75                               478.1M     6% /boot/efi
└─nvme0n1p2          LVM2_member       cKt344-wOPa-y34D-j0Wg-y3wq-ZlFz-fIGpnr
  ├─vgkubuntu-root   ext4              27945eb2-45c3-48da-b887-6391111416e3    328.4G    23% /
  └─vgkubuntu-swap_1 swap              9bdb7f2f-ac7b-4322-ae8e-38c870a190cc                  [SWAP]

I'd like to get rid of /dev/sda now.
I believe that what I need to do next is use efibootmgr to modify my bootable drives.  Right now my EFI files live on the nvme0n1 drive that houses Ubuntu.  Here's the output of efibootmgr:
root@cantankerous:~# efibootmgr -v
BootCurrent: 0000
Timeout: 1 seconds
BootOrder: 0000,0002,0008,0001
Boot0000* ubuntu        HD(1,GPT,9ab61c6d-62f6-474f-99c4-64eae4e5b595,0x800,0x100000)/File(\EFI\UBUNTU\SHIMX64.EFI)
Boot0001* Windows Boot Manager  HD(1,GPT,9ab61c6d-62f6-474f-99c4-64eae4e5b595,0x800,0x100000)/File(\EFI\MICROSOFT\BOOT\BOOTMGFW.EFI)WINDOWS.........x...B.C.D.O.B.J.E.C.T.=.{.9.d.e.a.8.6.2.c.-.5.c.d.d.-.4.e.7.0.-.a.c.c.1.-.f.3.2.b.3.4.4.d.126.96.36.199.}....................
Boot0002* Hard Drive    BBS(HD,,0x0)..GO..NO........q.S.a.m.s.u.n.g. .S.S.D. .9.7.0. .E.V.O. .5.0.0.G.B....................A...........................%8Z.........4..Gd-.;.A..MQ..L.S.4.6.6.N.X.0.K.A.18.104.22.168.9.H........BO..NO........u.S.H.G.P.3.1.-.5.0.0.G.M.-.2....................A.......................................8..Gd-.;.A..MQ..L.C.S.0.9.N.188.8.131.52.18.104.22.168.9.G.3.K........BO..NO........u.S.a.m.s.u.n.g. .S.S.D. .8.5.0. .E.V.O. .2.5.0.G.B....................A.................................>..Gd-.;.A..MQ..L.2.S.5.R.X.N.H.A.0.3.4.9.1.2. .Z. . . . ........BO
Boot0008* Windows m.2   HD(1,GPT,2aba441a-2647-48c4-868c-b4ca31d4f5a3,0x800,0x3a385800)/File(\EFI\MICROSOFT\BOOT\BOOTMGFW.EFI)

I've tried using efibootmgr to create a new bootable entry, but what I can't figure out how to do is specify that, although the EFI image lives on "nvme0", I need it to boot onto "nvme1".  I see this being done with /dev/sda with this "bcdobject=([uuid])" but I can't find any information out there about how this is done.
That is, of course, assuming I'm on the right track!
Once that's done I'm assuming os-probe will pick up the new drive and I can integrate it with grub-mkconfig.
Thanks for any help!
Comment: Grub only boots working Windows, so make sure you can directly boot Windows from UEFI. UEFI entry uses GUID partUUID. Compare your `sudo efibootmgr -v` with partUUID from this for ESP: `lsblk -o name,mountpoint,label,size,fstype,uuid,partuuid | egrep -v "^loop"` They need to match as that is how UEFI finds correct FAT32 partition.
Comment: You cannot have duplicate UUIDs or GUID/partUUID that efibootmgr uses. Disconnect sda, before trying any updates to avoid confusion of which device is which. Some example efibootmgr entries: Sony, HP & others workarounds:
https://askubuntu.com/questions/486752/dual-boot-win-8-ubuntu-loads-only-win
 You have to use /dev/nvme & correct drive, partition. Like this but check if correct drive/partition `sudo efibootmgr -c -L "Windows Boot Manager" -l "\EFI\Microsoft\Boot\bootmgfw.efi" -d /dev/nvme1n1 -p 1`
Comment: Thanks for your help!  I did as you suggested and removed /dev/sda and ran the command you suggested (after removing my initial attempt).  It's interesting now--`efibootmgr -v` still shows my original "Windows Boot Manager", but also has the new one.  `os-prober` does not find the new drive (only nvme0), but when I boot into grub and select my old Windows option, it boots to the new drive just fine.  I feel like I'm missing something, but I'm glad to have it working!
Comment: My partUUID matches between the `lsblk` output and my `efibootmgr -v` output for the entry I added, but I can't boot the drive through UEFI in my BIOS.  There is no UEFI entry for the drive in my BIOS, and booting in legacy mode results in an unbootable disk error.  Here's what I have in my `efibootmgr`: `Boot0003* Windows Boot Manager  HD(1,GPT,[partUUID[)/File(\EFI\MICROSOFT\BOOT\BOOTMGFW.EFI)`
Comment: You do not see 0003 entry in UEFI boot menu? Normally Windows boot entry works, some like HP or Acer need additional changes to make ubuntu entry work.
Comment: No, none of the UEFI entries for that drive work.  That's okay, grub is booting Windows (and Ubuntu) just fine.  It looks like `os-prober` uses the UUID to identify a drive, and so it doesn't really care that the device has changed.  If you'd like to submit an answer instead of a comment I'd be happy to mark it solved at this point, you've been very helpful!
Answer: You cannot have duplicate UUIDs or GUID/partUUID that efibootmgr uses.
Disconnect sda, before trying any updates to avoid confusion of which device is which. Some example efibootmgr entries:
Sony, HP & others workarounds:
Dual boot Win 8 / Ubuntu loads only Win
You have to use /dev/nvme & correct drive, partition. Like this but check if correct drive/partition, compare GUID in UEFI boot entry and partUUID from lsblk. That will tell which ESP you are using to boot from.
sudo efibootmgr -v
lsblk -o name,mountpoint,label,size,fstype,uuid,partuuid | egrep -v "^loop"

sudo efibootmgr -c -L "Windows Boot Manager" -l "\EFI\Microsoft\Boot\bootmgfw.efi" -d /dev/nvme1n1 -p 1

Grub only boots working Windows. Windows will turn fast start up back on and then grub will not boot it, so best to fix UEFI boot entry to boot Windows directly.
Grub2's os-prober looks for .efi boot files in the ESP to find other installs to boot. It is not using UEFI entries.
Comment: Thanks again for the help!


limit PHP script to one domain per license

Question: I'm encoding my script with Ioncube and want to ensure that it works only on the licensed domain. How is this commonly done?
I was thinking something like:
<code>function domain(){

}

if($this_domain <> domain()){
   exit('no');
}
</code>
or
<code>$allowed_hosts = array('foo.example.com', 'bar.example.com');
if (!isset($_SERVER['HTTP_HOST']) || !in_array($_SERVER['HTTP_HOST'], $allowed_hosts)) {
    header($_SERVER['SERVER_PROTOCOL'].' 400 Bad Request');
    exit;
}
</code>
But I'm not sure if that's correct. Would strpos be better?
Comment: Ioncube PRO have bulit-in mechanism to generate lcence limited to IP/domain
Comment: You do know it's pretty easily possible to bypass obfuscation schemes for interpreted languages like PHP, right? Since you're trusting your customers anyhow, why not just trust them a little bit more and not put in the restriction? Besides, what does it mean to work "on a domain"? A domain is just a name...
Comment: in the arabic world, every thing differ
Answer: This is a wasted attempt. As any determined developer can hack your code and remove the blocking algorithm.
However, as per the algorithm goes, this is fine
<code>$allowed_hosts = array('foo.example.com', 'bar.example.com');
if (!in_array($_SERVER['HTTP_HOST'], $allowed_hosts)) {
    header($_SERVER['SERVER_PROTOCOL'].' 400 Bad Request');
    exit;
}
</code>
Comment: He mean `encode` instead of `decode`. Lookup what `Ioncube` is and you will know that it is not wasted attempt.
Comment: No need to shout dude :/. You can say what you want but no one will give you code of ioncube, and that's the whole point - prevent access to the source.
Comment: And where have I mentioned that it is impossible? I just don't think of it as `wasted attempt` because 99,99% customers who would like to remove this limitation will fail or try searching for a hacker who would charge them 10 times more as additional license...
Comment: @dev-null-dweller, I dont know whats your problem whether you didn't understand me or just passing away comment that mean nothing. My point in answer is, I could say `Give me the source code of ioncube, I will remove the verification, within less than a day`, because it can be removed. UNDERSTOOD?
Comment: @dev-null-dweller, I have coded many obfuscator, encoders, decoder myself, and I know its not the solution of the problem. This sort of stuff you cannot rely on. I hope i made by point clear. Have a NICE day!!!
Comment: @dev-null-dweller, May be i am talking to a wall. Ok, I will try again. Read their tagline `The ionCube PHP Encoder makes it easy to protect your PHP 4 & 5 source code from easy observation, theft and change`. Did you notice the **`easy observation...`** part, that's my point. It may not easy but still possible.
Answer: I know this is an old post, but I have to say that I suggest you to use IonCube "dynamic key" for licensing.
Except this, the new version of this software also has the new ability to build the license directly for each domain. I use it several years but I generate automatic licensing system that uses "dynamic key"
Comment: Dynamic Keys is really to allow code to be protected with strong encryption and without having the encryption key stored anywhere to be discovered by reverse engineering. Licensing related data could be factored into a custom Dynamic Key generation algorithm though. Licensing itself is best checked with Pro/Cerberus native features as the Loader acquires and validates request data before it could be modified by e.g. a PHP prepend script, which by modifying S_SERVER would be one way to attack a home-brew PHP based licensing scheme.


launcher, top panel disappeared and global menu & hud disabled

Question: This morning, I removed all the unity-webapps-something and didn't pay attention that removing unity-webapps-service or unity-webappas-common required to remove other key packages:
<code>The following packages will be REMOVED:
  bamfdaemon hud indicator-appmenu indicator-sound libbamf3-1 libunity-webapps0 lightdm-remote-session-uccsconfigure unity unity-tweak-tool unity-webapps-common
  unity-webapps-service xul-ext-unity xul-ext-websites-integration
0 upgraded, 0 newly installed, 13 to remove and 1 not upgraded.
After this operation, 10.3 MB disk space will be freed.
Do you want to continue [Y/n]? y
(Reading database ... 458920 files and directories currently installed.)
Removing unity-tweak-tool ...
Removing lightdm-remote-session-uccsconfigure ...
Removing unity ...
Removing indicator-sound ...
Removing indicator-appmenu ...
Removing hud ...
Removing libbamf3-1:amd64 ...
Removing bamfdaemon ...
Removing xul-ext-unity ...
Removing xul-ext-websites-integration ...
Removing unity-webapps-common ...
Removing libunity-webapps0 ...
Removing unity-webapps-service ...
</code>
Now, that I login to my unity session, I have no launcher, no top panel, global menu integration and hud are disabled.

I reinstalled all the packages removed above and restarted the computer but in vain.
I reconfigured these packages but in vain (sudo dpkg-reconfigure unity)
I issued:  unity --replace and compiz --replace  but in vain.

Any Ideas please. this is kind of frustrating.
PS: At the greeter stage, everything is fine. It's only when I log in.
I can also login to my gnome Fall back session without problems.
Comment: Did you re-install unity?  Take a look at this [Post](http://askubuntu.com/questions/95458/how-do-i-reinstall-unity).
Comment: Thanks, it was a matter of re-enabling the unity plugin.
Answer: SOrry! Just got the answer here: Unity doesn't load, no Launcher, no Dash appears
Since Unity package was removed, the unity plugin in Compiz manager got disabled. So opening compiz manager and re-enabling the plugin did the trick.


Do posts use a revision system?

Question: I made some too aggressive edits to a certain question, and the author has asked me to restore the text. I thought there was a revisions system where I could pick the old text, but I can't seem to find it.
I dug up the original text under my "activities" tab, so I can work the problem out from there, but

Is there a revisions system for content?
Under what conditions can it be accessed?
Answer: When a post has been edited after it has been created, the post shows the user who edited the question. The timestamp shown after "edited" is a link to the revision page, which shows all the revisions for that post.

It's not considered a new revision if the edit has been done in the 5-minute grace period; this means that if the user creates a post, and then edit it before 5 minutes are passed, the "edited" link will not appear.
In the revision page, you rollback a previous version by clicking on the "rollback" link shown for the revision you want to restore.

The "rollback" link is visible to the users who can edit the post, which means:

to the user who created the post, independently from the reputation that user has
to any user with the privilege of editing any post, which is a privilege gained when the user's reputation is at least 2000

When there is a pending suggested edit, you are probably not allowed to rollback a previous revision, without first approving the suggested edit; as I have never been in that situation, I cannot say it's exactly what happens.

Do posts use a revision system?


SerialPort.ReadLine() does not read data from USB COM port sent by Arduino

Question: I'm sending textual data to COM15 (via micro USB) using Arduino. On my desktop, I'm trying to read the data from my C# application. However, when I run it, the console simply shows nothing and the program stucks at the line "string s = myPort.ReadLine()".
The following is my C# program:
static void Main(string[] args)
{
    var myPort = new SerialPort("COM15", 115200);
    myPort.Open();
    while (true)
    {
        var s = myPort.ReadLine(); // execution stucks here waiting forever!
        Console.WriteLine(s);
    }
}

The following is the Arduino code (sends data to COM15):
int counter = 1;
void setup() {
  // put your setup code here, to run once:
 Serial.begin(115200);
}

void loop() {
  // put your main code here, to run repeatedly:
Serial.println(" Data Loop = " + String(counter));
counter++;
delay(500);
}

The arduino serial monitor does show the data being received at COM15. I also tried other software that read COM ports and verified that the data is available at the port.
Answer: By adding the following line before myPort.Open() command, I managed to fix my issue and read from the COM successfully:
myPort.DtrEnable = true;

You may ask what is Dtr flag. Dtr stands for "Data Terminal Ready" and according to Wikipedia:

Data Terminal Ready (DTR) is a control signal in RS-232 serial
  communications, transmitted from data terminal equipment (DTE), such
  as a computer, to data communications equipment (DCE), for example a
  modem, to indicate that the terminal is ready for communications and
  the modem may initiate a communications channel.


Best way to seal underground bore pipe which is in a pit

Question: I have a closed bore pipe whose width is 6 inches and the pipe goes upto 30 feet deep.
The bore pipe is in a pit whose depth is 6 feet.
I have other drainage pits whose water level is 1 to 2 feet from ground in normal time and 2 to 4 feet in summer time.
But this particular drainage pit whose ground is covered with gravel( broken red brick + river sand ) and which houses closed bore pipe , the water level either overflows or at the ground level.
The case is same even in summer as well.
So my theory is somehow water comes up from the sides of bore-well to the pit or the gravel reduces water pressure and hence less water filtration.
Please note all other pit has clay ground.
So what's the best way to close the bore-well once and for all. should I pour concrete or clay through the pipe or should I pull the pipe out of the ground and pour concrete or clay.I don't want water coming up from 30 feet to the ground at all.
I don't want to cause any differential settlement on the building by just pulling out the pipe and cause the ground earth to close the hole by itself.
Please leave your suggestions
Thanks
Update:
The property is located in a clay ground with high water table.
I have some percolation pits on both north and south sides of property.
I'm talking with local authorities to take the water away to the nearest water canal but there's a lengthy process.
My doubt:

Removing the gravel bed , would it help in faster draining of the water ?

How to properly seal the underground borewell pipe so water doesn't seep through to the pit ?

Update:
Please find the pic
Comment: How about adding a few pictures? An overview of the area, then a couple of close up and detailed pics showing the precise bore pipe/pit. Again, you're in India and the majority of your audience is in the US or EU. Your local building regulations & practices are different enough from what we're familiar with that your 1000 words would be much better served with a picture or two.
Comment: I'm not sure I'm understanding the question completely .  How can you have a bore pipe (not sure what that is, is it like a well?) that's 30' in a 6' drainage pit? Can you clarify please?   My first thoughts are that you have really poor soil conditions (clay, as you mentioned ) and a very high water table.   I have a similar situation:  I have a cistern, probably about 2,000 gallons that gets filled by slightly surficial ground water at the rate of about 3 gallons per hour.  Even if I pump it down, it's filled again within a few days. .....comment continued below....
Comment: Since I don't know any thing about your property layout, if you have a way to direct the water to a waste area or river, that might be a solution, but you might need to pump it there.   That said, if you would, please **update** your question adding info by your specific layout, property, etc.
Comment: Could it just be this pit is placed on lower ground than the others?  Water will tend to have the same level, but the ground might dip/be lower at that pit compared to the others.
Comment: @GeorgeAnderson - I mean to say the bore pipe has depth of 30 feet and the width of the pipe is 6 inch. Size of pit is 5 feet in width. The pipe was originally installed to draw ground water for domestic purpose but the ground water turned out to be saline. As we dug the pit , the bore pipe is closed using dummy.  so the close cap of bore well is at 6th feet now.
Comment: @crip659 - that might be possible but all the pits are 4 feet away from each other and it's clay soil. This pit might be a 2 feet deeper than others.
Comment: @FreeMan - I get that. Sorry , I've updated the question with a pic
Comment: I don't understand what you mean by the bore lining pipe being "closed." Does it ordinarily have a cap on it? I don't understand what you mean by "the bore pipe is closed using dummy, so the closed cap of bore well is at 6 feet now." What do you mean by "dummy"?
Answer: You seem to believe that this boring is encouraging flooding. This is very unlikely. It's possible that there's a more permeable lower soil layer beneath a relatively impermeable upper clay layer, where a higher water table than your local water table connects through the lower layer to your boring. You can read all about this Artesian well concept on the US Geological Survey's website if you're interested.
You can test if you've got an Artesian well by comparing the water's surface elevation to the water surface elevation in your other drainage pits. Since these drainage pits also maintain such high water surfaces, the likelihood of an Artesian well is small. I suppose it's possible that an Artesian well could raise the local water table and ultimately fill adjacent drainage pits to raise their water levels. It would be nice to have a history of when each drainage pit was dug and if the water elevation in these pits started at zero and rose in the years following the Artesian well candidate's construction. In the remote chance that you have an Artesian well, your plan to plug it with impermeable material would make sense.
In all likelihood, though, that's just a hole filling up to the elevation of your local water table. Filling it will not stop the ground in its neighborhood from being swampy. At some point in the distant future the PVC liner could fail, however, and that could impact your foundation depending on how close it is. The solution to that possible problem lurking in the distant future is to fill the pipe without removing it. Uniformly graded sand would be a good fill material because it naturally compacts fully after less than a year without any compaction equipment.


Notation for annihilator with ring and module interchanged?

Question: Let $M$ be an $R$-module. For a subset $S\subseteq R$, the set
$$\{m\in M\mid (\forall s\in S)[sm=0]\}$$
is clearly a submodule of $M$. Is there a name or notation for it? It is essentially the definition of annihilator with ring and module interchanged.
Comment: I saw it denoted by $Ann(S)$.
Comment: It can be expressed as the intersection of a bunch of kernels, one for each $s\in S$.
Answer: The notations $(0:_M S)$ and $\operatorname{Ann}_M(S)$ are both commonly used for this submodule. I'm not sure there's a standard name, but I've heard it informally referred to as "the annihilator of $S$ in $M$" before. More generally, if $N$ is a submodule of $M$ and $S \subseteq R$ (of course, we can always replace $S$ by the ideal it generates), we write $(N:_M S):=\{m \in M \mid Sm \subseteq N\}$.
Comment: @rschwieb Ah yes, thanks; I misstated it.
Comment: Oh, well all good then :)


Unchecked call to 'add(E)' as a member of raw type 'java.util.ArrayList'

Question: im trying to finish my school task and i am bothered in this warning im just new in programming and im seeking for advice here
public class Graphs {

    public static void main(String[] args) {
        ArrayList<ArrayList> adj = new ArrayList<>();
        char[] vertices;
        vertices = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g'};

        int num = 7;

        adj.add(new ArrayList<>());
        adj.add(new ArrayList<>());
        adj.add(new ArrayList<>());
        adj.add(new ArrayList<>());
        adj.add(new ArrayList<>());
        adj.add(new ArrayList<>());
        adj.add(new ArrayList<>());

        adj.get(0).add('b');
        adj.get(1).add('c');
        adj.get(2).add('d');
        adj.get(2).add('e');
        adj.get(3).add('c');
        adj.get(3).add('e');
        adj.get(3).add('f');
        adj.get(3).add('g');
        adj.get(4).add('c');
        adj.get(4).add('d');
        adj.get(4).add('f');
        adj.get(5).add('d');
        adj.get(5).add('e');
        adj.get(6).add('d');

        int c;
        int x;
        x = 0;
        c = 0;
        while (x < num) {
            System.out.println(vertices[c] + ":is connected to " + adj.get(x));

            x++;
            c++;
        }
    }
}

Unchecked call to 'add(E)' as a member of raw type 'java.util.ArrayList'
Comment: You can use a Array list instead where every element is an array itself
Answer: Your variable adj is of type list of list.
ArrayList<ArrayList> adj = new ArrayList<>();

But the inner list type parameter is not specified. Defining it as below would fix the warning.
ArrayList<ArrayList<Character>> adj = new ArrayList<>();


Getting ORA-00904: invalid identifier for a numeric column although it is present in the database

Question: I tried to run below query on oracle database
select distinct LABEL,EVENT_DATETIME,USL,LSL from
(select eventTbl.LABEL,eventTbl.EVENT_DATETIME,limitTbl.USL,limitTbl.LSL from EVENT_TABLE eventTbl
          INNER JOIN LIMITS_TABLE limitTbl on limitTbl.start_date <= eventTbl.EVENT_DATETIME
          AND limitTbl.end_date >= eventTbl.EVENT_DATETIME where eventTbl.plant_id = 'plant1')

That gives the below error:
ORA-00904: "LIMITTBL"."LSL": invalid identifier

00000 -  "%s: invalid identifier"

The DDL of LIMITTBL table is
create table LIMITS_TABLE(
plant_id varchar2(80),
start_date date,
end_date date,
USL number(11,5),
LSL number(11,5)
);

Comment: If you remove the LSL column from your query does the error go away? Out of habit, in Oracle I never mix case of identifers. Everything is always uppercase
Comment: If I remove LSL, it complains for USL. If I remove both, the query works fine
Comment: So when you remove it from the outside part it stops complaining? If you use `select distinct * from` in the outside part, does it return the columns you expect?
Comment: Yes, It complains the same if I remove from outside part and use "select distinct * from"
Comment: Are you certain you are using the table in the schema you think you are? This is going to be one of those things where there is some specific environmental thing causing it. If you run the SQL inside the brackets, I take it you get the same error? What if you just run `SELECT LSL FROM LIMITS_TABLE`? If you run `SELECT * FROM LIMITS_TABLE` do you see the `LSL` column? I predict this Q is deleted in 10 minutes when you work out what has happened
Comment: Looks like USL and LSL columns don't exist in LIMITTBL table. Could you post tables' descriptions?
Comment: Yes. When I run `SELECT * FROM LIMITS_TABLE` or `SELECT LSL FROM LIMITS_TABLE` I can see the values
Comment: @Littlefoot
create table LIMITS_TABLE(
plant_id varchar2(80),
start_date date,
end_date date,
USL number(11,5),
LSL number(11,5)
);
Comment: Did you, by any chance, create table and/or columns using **double quotes** and lower/mixed letter case?
Comment: Cannot replicate the problem as your query works [fiddle](https://dbfiddle.uk/POXqN7vl). (Your query could also be simpler - see the fiddle for an example.)
Answer: This is too much code to put into a comment; if columns really existed, your code would have worked:
SQL> WITH
  2     event_table AS (SELECT 'plant1' plant_id, 'A' label, SYSDATE event_datetime FROM DUAL),
  3     limits_table
  4     AS
  5        (SELECT 1 usl, 2 lsl, SYSDATE start_date, SYSDATE + 2 end_date FROM DUAL)
  6  SELECT DISTINCT LABEL,
  7                  EVENT_DATETIME,
  8                  USL,
  9                  LSL
 10    FROM (
 11            SELECT eventTbl.LABEL,
 12                   eventTbl.EVENT_DATETIME,
 13                   limitTbl.USL,
 14                   limitTbl.LSL
 15              FROM EVENT_TABLE  eventTbl
 16                   INNER JOIN LIMITS_TABLE limitTbl
 17                      ON     limitTbl.start_date <= eventTbl.EVENT_DATETIME
 18                         AND limitTbl.end_date >= eventTbl.EVENT_DATETIME
 19             WHERE eventTbl.plant_id = 'plant1'
 20         );

LABEL EVENT_DATE        USL        LSL
----- ---------- ---------- ----------
A     11.10.2023          1          2

SQL>

However, as I commented - if you enclosed column names into double quotes and used lower/mixed letter case, query would have failed; see line #5:
SQL> WITH
  2     event_table AS (SELECT 'plant1' plant_id, 'A' label, SYSDATE event_datetime FROM DUAL),
  3     limits_table
  4     AS
  5        (SELECT 1 "usl", 2 "LsL", SYSDATE start_date, SYSDATE + 2 end_date FROM DUAL)
  6  SELECT DISTINCT LABEL,
  7                  EVENT_DATETIME,
  8                  USL,
  9                  LSL
 10    FROM (
 11            SELECT eventTbl.LABEL,
 12                   eventTbl.EVENT_DATETIME,
 13                   limitTbl.USL,
 14                   limitTbl.LSL
 15              FROM EVENT_TABLE  eventTbl
 16                   INNER JOIN LIMITS_TABLE limitTbl
 17                      ON     limitTbl.start_date <= eventTbl.EVENT_DATETIME
 18                         AND limitTbl.end_date >= eventTbl.EVENT_DATETIME
 19             WHERE eventTbl.plant_id = 'plant1'
 20         );
                 limitTbl.LSL
                 *
ERROR at line 14:
ORA-00904: "LIMITTBL"."LSL": invalid identifier

If that's the case, you'll have to use double quotes and the same letter case every time you reference that column (lines #7, 8, 13, 14):
SQL> WITH
  2     event_table AS (SELECT 'plant1' plant_id, 'A' label, SYSDATE event_datetime FROM DUAL),
  3     limits_table
  4     AS
  5        (SELECT 1 "usl", 2 "LsL", SYSDATE start_date, SYSDATE + 2 end_date FROM DUAL)
  6  SELECT DISTINCT LABEL,
  7                  EVENT_DATETIME,
  8                  "usl",
  9                  "LsL"
 10    FROM (
 11            SELECT eventTbl.LABEL,
 12                   eventTbl.EVENT_DATETIME,
 13                   limitTbl."usl",
 14                   limitTbl."LsL"
 15              FROM EVENT_TABLE  eventTbl
 16                   INNER JOIN LIMITS_TABLE limitTbl
 17                      ON     limitTbl.start_date <= eventTbl.EVENT_DATETIME
 18                         AND limitTbl.end_date >= eventTbl.EVENT_DATETIME
 19             WHERE eventTbl.plant_id = 'plant1'
 20         );

LABEL EVENT_DATE        usl        LsL
----- ---------- ---------- ----------
A     11.10.2023          1          2

SQL>


What is the easiest way to remove the old grout?

Question: I am going to regrout the tile in the bath/shower area.  What is the easiest way to remove the old grout?
Comment: Jackhammer works great.
Answer: Easiest:

Easy:
A rotary tool (e.g. Dremel) with a grout removal bit:

Also Easy:
An oscillating multi-tool with a grout bit:

Least easy:
A grout saw:

Downright Painful:
Dr. Pickems approach:
Comment: The new style ultrasonic saws have nice grout removal blades.  I use a SonicCrafter by Rockwell  See:  www.rockwelltools.com/en-US/SC-Hyperlock-RK5140K.aspx?gclid=CMz2woGp1rUCFY6e4AodWREAXw
Comment: Dremel has 2 grout bits, 1/8 and 1/16.  The 1/16 is very delicate and breakable with side pressure, so go very lightly, if you need to use it for tightly spaced joints.
Comment: oscillating multitools usually have a grout bit that works well.
Comment: Unless your God, I think the C4 would damage the tiles (and the house). +1 for the laugh and an answer!
Comment: @Monso Yes, blowing up your home is an unfortunate side effect, but the grout would be "removed." :)
Comment: Sorry to hijack your answer but I could not resist. Feel free to edit it back off.
Comment: What about using a reciprocating saw with a grout removal bit?
Answer: Ok... this question asked easiest. (And also a method that I have successfully used).
Get a good quality breathing mask, stainless steel wire brush, some gloves and some pool acid (Hydrochloric Acid)
If you have normal tiles (porcelain or ceramic) you can simply pour the acid onto the shower floor... will eat away the grout in no time.  I would also use small amounts at a time so that you are not overwhelmed by the noxious gasses.
Please ensure that you have made your bathroom well ventilated at all times.
Wash away the small portion of acid with water after every application.
Comment: OP didn't ask for safest. He asked for easiest. :)
Comment: This doesn't sound very safe, even compared to the C4...


Jquery menu quirks

Question: Sorry the title isn't more specific.  I have some minor problems with a jquery menu I coded.  It can be seen on wlmtest.info
Its the main menu.  The trouble I'm having is as follows.
If you hover over a menu button at the top, the menu drops down.  Now move your mouse UPWARDS, do not hover over the actual drop down.  The menu drop continues to display even though the mouse has left the menu.
The only way to get rid of the dropdown is to hover over the menu dropdown and then move your mouse off it.
My code is as follows
<code>jQuery("ul.lmenutabs li").mouseenter(function()
{
    jQuery("ul.lmenutabs li").removeClass("active"); //Remove any "active" class
    jQuery(this).addClass("active"); //Add "active" class to selected tab
    jQuery(".lmenutab_content").hide(); //Hide all tab content

    var activeTab = jQuery(this).find("a").attr("href"); //Find the href attribute     value to identify the active tab + content
    jQuery(activeTab).fadeIn(); //Fade in the active ID content
    jQuery(".lmenutab_container").fadeIn()
    return false;
});

jQuery(".lmenutab_container").mouseleave(function() {
    jQuery(".lmenutab_content").hide(); //Hide all content
    jQuery(".lmenutab_container").hide(); //Hide all content
    jQuery("ul.lmenutabs li").removeClass("active");
    return false;
});
</code>
As you can see I have a mouseenter to get the drop down to display.  And then a mouseleave so that when you hover over the dropdown and leave, the dropdown div is hidden.
How can I get it so that the dropdown is hidden when you leave the menu buttons at the top as well?  Without the dropdown disappearing when you're leaving the button to hover over the dropdown menu.
Sorry if this sounds confusing, I'll try to explain again if you need me to.
Any help is much appreciated.
Answer: You are waiting for a mouseleave() event on the menu itself, but if the mouse never enters the menu, the mouse leave event is never triggered.
Add a mouseenter event on the header to hide the menu and a onClick() action on the page itself to make sure that the user can always get rid of your menu by clicking outside of it.
Comment: Thank you sylverdrag.  I'm aware of this, I just can't quite get my head round how I would solve the problem.

If I put a mouseleave on the buttons as well, all that happens is the menu drops down, but as soon as you hover to go to one of the items in the menu, the drop down disappears! this is of course expected, but I need a way for the buttons and the drop down div to somehow act as a group.
Comment: Thanks for that!  I decided, that instead of the onclick event, I would place 2 invisible divs either side of the menu and have a mouseenter hide on those.  I think all is well now
Comment: Cool, glad to be of assistance

Jquery menu quirks


printing key and value of json objects

Question: i have 2 external json files and i have to read data from those files using the key and value. my application is not dependent on the obj.name etc. Please help me to print these values.
Planets.json
 {
"Planets": [
  { "name": "Mercury",
    "color": "Orange",
    "distance": "57.91 km",
    "radius": "2340 km",
    "year": "0.24085 Earth",
    "day": "88 days",
    "mass": "0.054 Earth"
  },

  { "name": "second",
    "color": "Orange",
    "distance": "57.91 km",
    "radius": "2340 km",
    "year": "0.24085 Earth",
    "day": "88 days",
    "mass": "0.054 Earth"
  }

}
Airports.json
    {
"Airports": [
  {
    "listing": "East 34th Street Heliport",
    "iata": "TSS",
    "type": "Heliport",
    "size": "Tiny"
  }

}
and this is the code i am trying.
              $.ajax({
                url:"planets.json",
                dataType: "json",
                success:function(json){
                    $.each(json, function(key, value){
                        console.log(key + ": " + value);
                    });
                }

            });

and i am getting this out put in console
Planets: [object Object]
Answer: Get the nested object using json.Planets[0] and iterate over it.
$.each(json.Planets[0], function(key, value){
    console.log(key + ": " + value);
});

UPDATE 1 : If the object only contains one property then you can get it using Object.keys() and do the same as the previous example.
$.each(json[Object.keys(json)[0]][0], function(key, value){
    console.log(key + ": " + value);
});

UPDATE 2 :
In case there are multiple properties then use $.each() method twice.
$.each(json,function(k, v){
    $.each(v[0], function(key, value){
        console.log(key + ": " + value);
    });
})

UPDATE 3 : If you have nested array with multiple objects then use an additional Array#forEach method to iterate it.
json[Object.keys(json)[0]].forEach(function(v){
    $.each(v, function(key, value){
        console.log(key + ": " + value);
    });
});

UPDATE 3 : If your JSON consists multiple properties with nested multiple array element do the combination of above methods.
$.each(json,function(k, v){
    v.forEach(function(v1){
        $.each(v1, function(key, value){
            console.log(key + ": " + value);
        });
    });
})

Comment: if i change the my file name planets to airports then i have to modify everything
Comment: If you iterate over your top-level object (json), you can get the keys: Planets, Airports, etc.
Comment: for example if have 3 palnets and print those one by one ?
Comment: @SaqibSaqib : glad to help :)
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/118589/discussion-between-pranav-c-balan-and-saqib-saqib).
Answer: To achieve expected result, use below option
$.each(json, function(key, value) {
  $.each(value[0], function(k, val) {
    console.log(k + ":" + val);
  });
});

Codepen- http://codepen.io/nagasai/pen/GqGVGd
Answer: You can use a double each so that its not depended on the name "airports"
$.each(json, function(objectTitle, objects){
    console.log('List of ' + objectTitle + ':');
    $.each(objects, function(objectKey, objectValue){
        console.log(objectKey + ':' +  objectValue);
    });
});

printing key and value of json objects


Replace Assembly.LoadFrom(String, Evidence) call with Assembly.LoadFrom(String) - .NET 4

Question: I have to move some old .NET 2 code to the .NET 4 project. It has the next line:
`return Assembly.LoadFrom(filePath, Assembly.GetExecutingAssembly().Evidence);`

As it said in Microsoft's (MSDN):

Note: This API is now obsolete. The non-obsolete alternative is LoadFrom(String).

I'm not familiar with the Evidence class. What is the risk of just removing the Evidence parameter from the call? What is the real case when the Evidence parameter is necessary?
Thanks in advance for the help
Answer: The evidence argument was used to provide data that the Code Access Security (CAS) policy mechanism could use when deciding which CAS permissions to grant to the assembly being loaded.  However, in .NET 4.0, the "naked" CLR no longer uses CAS policy ( http://blogs.msdn.com/b/shawnfa/archive/2010/02/24/so-is-cas-dead-in-net-4-or-what.aspx, http://blogs.msdn.com/b/shawnfa/archive/2009/06/12/clr-v4-security-policy-roundup.aspx), so the used of evidence in API has been deprecated.  There are usually only two reasons why one might have provided evidence in a LoadFrom call in code targeting an earlier .NET version:

To allow the assembly to run with more permissions than it might have otherwise been granted, or
To restrict the permissions of the assembly, removing permissions that would otherwise have been granted under the default evidence for the assembly.

For #1, you probably have nothing to do in .NET 4.0 since all code will run with unrestricted CAS permissions (aka "full trust") by default.  For #2, the recommended approach is to use a sandboxed appdomain.


Excel is Converting date to Wrong Values

Question: I have a csv file which im opening in Excel.
When I try to convert the date column (which is previously General). I'm getting wrong Dates.
Below Images will elaborate the same:
Before Editing the column data type
If I select the column and change its data type to date , it is giving me wrong dates.
After Editing the column datatype
The dates should be in the range of 1973, but its showing 1905. How do I rectify it.
Comment: Open the CSV in excel without any modification and right click on 1 of the date cells and click format cells, on the number tab click "custom" and let  me know what its set to in the type box
Comment: Has been asked many times before and there are many answers out there. Just pick the one you want: http://stackoverflow.com/questions/7691485/how-to-globally-stop-excel-date-autoformatting OR http://superuser.com/questions/307496/how-can-i-set-excel-to-always-import-all-columns-of-csv-files-as-text (just to reference the ones which are most likely to be appropriate for you).
Comment: I'm voting to close this question as off-topic because it is not a programming question. It may be more suitable for [su] instead. (Although the answer there will be the same; you're expecting something that is absolutely not a date to be converted to a date. A date is not a range of years separated by a dot. Excel is converting that non-date to the proper value for the floating point number 1973.1667, which is one thousand, nine hundred and seventy three days after Dec 30, 1899 at midnight, which is the zero (base) date in Excel.)
Answer: The problem is different: what do you expect from 1973.1667 to be?
I suggest that this is YYYY.yyyy while yyyy is partial year and excel simply will not accept it that way. Excel dates are like DDDD.ddddd. Also: changing it to "Date" doesn't change the value itself, it is just the way to be displayed what changes.
You could calculate the date like this (for B2):
<code>=DATE(INT(B2),ROUND(MOD(B2,1)*12+1,0),1)
</code>


I am getting this error while creating new HDInsight cluster

Question: "You do not have the minimum cores available,12, to create a cluster in Est des Etats-unis, please select different location or subscription".
I tried with two subscriptions and many locations, but I got the same error.
Answer: You need to follow this document to request quota increase for a specific region you are interested in. This is a "routine" operation. Usually takes a couple of days (faster if you have EA support). Once your request if fulfilled you can proceed with creating your cluster.
Each subscription in Azure got its own quotas you have to adhere to. By default you are limited to 10 cores per VM type for most VM types.
Comment: I created a quota increase request and I am waiting for the reply. Thanks.
Comment: The quota increase request was approved and I can now create the cluster. Thanks again.


React app call to localhost node server on hostedVM

Question: I'm serving a built react file using Nginx. I am able to access the react app in the browser on my vm's IP address.
I have another server running on my VM on port 8080, the API of the react app.
In my react I use axios calls like
const http = "http://localhost:8080";
..
axios.post(`${http}/api/auth/login`, { credentials }).then(res => res.data.user),

In my browser after I access my VM's ip address I can see in the console that the so called axios calls go to http://myActualVMIpAddress/api/.. instead of the localhost path as I was expecting.
I have checked the routes using postman of the api server.
I don't have experience with deployment. How do I make the link between the react app and the api server to work?
Answer: It is not a good idea to hard code localhost:8080 into your client JS, when your user loads the client files they will try and make a request on your users computer which is what localhost resolves to.
Easiest is to serve your client files from your api server. If you want to keep these separate then you have to use the IP of your API server (not localhost) and setup CORS.
Comment: Yeah, I wanted to develop them separate from the start in case I want to run the api on a vm and the website on another. I guess that I could for start just serve the react compiled file using the api server on any other route that doesn't begin with `/api/` and use `nginx` to reroute to `8080` or straight run the server on port `80`. Does this sound appropriate in this situation?
Comment: Yes you could use nginx as a proxy and route requests to /api on port 80 to your api server on the local machine at whatever port you want quite easily.


Relevance of specifying Tool Locations in Jenkins Node Configuration

Question: What does specifying tools under "Tool Locations" in Jenkins Node configuration, exactly do?

I wanted to run a mvn command in free style project. I specified the Maven tool and its home under "Tool Locations" and that didn't help. The job failed for not being able to find mvn. I followed this solution and modified the PATH variable to include maven path. That did the trick.
So how exactly does specifying Tool Locations help? Is it just to help users see the tool paths when they visit Jenkins node configuration site?
Answer: In Global Configuration, you can configure different tools, such as Maven, JDK, Ant, etc. When you do that, you also provide an installation method (usually an automatic online installer).
Now, on the Job Configuration, when you configure a buildstep using one of the tools, for example Invoke Ant, you will see a drop down. The first option is Default, the next is whatever tool installations that you've configured in Global Configuration.
If you choose Default it will use whatever is already installed on the system by simply executing a command like java, ant, or mvn. Obviously, if those commands are not in the path, it will fail.
If you choose one of the configured options, Jenkins will install it to the system (if not already done), and use that particular version (as opposed to the one you have under path).
This installation will happen on both the master and the slave nodes. If you do not want to use this automatic installation on a particular node, you can manually specify the location of the particular tool in the screenshot you provided.
The above is only useful if in your Job Configuration, you are selecting a specific version of the tool, other than Default, because as already explained: Default will use whatever is already installed on the system (not by Jenkins).
Comment: Yes, Jenkins will install it to special Jenkins location, usually under `$JENKINS_HOME/tools`. It doesn't need it in `path`, cause it will invoke it directly with the full path to that location. Do realize that this is **only** for Jenkins specific implementations, such as "Invoke Ant", "Invoke Maven Targets", etc. You **cannot** use this automatic installation and then "Execute shell" with `ant` command there, as that will look for `ant` in `path` as any other command line executed directly on the system.
Comment: @cueedee read the 4th paragraph in my answer. It is an override per node, instead of using master's global Tool Configuration. As for why OP had original issues, his question is too incomplete to figure out what went wrong. For starters, he mentioned "freestyle" and "mvn" in the same sentence... most likely he did "execute shell" and typed "mvn" there. That is **not** using Tools, and therefore the whole question becomes irrelevant. My answer explained how to setup and use Tools correctly
Comment: @Slav, thanks for clarifying that. I guess the OP's confusion regarding the "Configure System ❱ Tool Locations" configuration section was, as it was mine, mainly one about documentation;  its tooltip says _"You can specify the location of certain tools on this node, overriding the global configuration. (You may prefer to use automatic tool installers instead, removing the need to configure each node separately.)"_ which without more background knowledge doesn't really help to understand what it is for.
Comment: You say that, choosing one of the configured options, prompts Jenkins to install it to the system and use it. Does that mean that I don't have to explicitly check if the command is in the path. Will Jenkins be responsible to put it in the path?
Comment: I don't see how this answers the OP's question about what the configuration entered under the "Tool Locations" section is actually supposed to achieve....
Answer: To answer your queries:

So how exactly does specifying Tool Locations help?

Well, not really i would say. It's meant to specify your custom installation directory path for any program that's already setup in your global config page in a different location. If you have configured mvn 2.0 in global settings but wish to use mvn 3.0 on this specific node, then you can use Tool Locations. However, it will work only if the path to the executable is already present in the PATH env variable of the user with which the slave process is running.

Is it just to help users see the tool paths when they visit Jenkins
  node configuration site?

Well, yes, you can say that. I am saying so because whenever you specify a custom path, it generally isn't in the PATH of the user with which the process is running. That's true in most of the cases because such binaries don't run independently. They need other dependent modules to work properly otherwise simply dropping a binary in one of the directories that's already present in the PATH would have sufficed. So, it's safe to say that you explicitly have to add the path to executable in PATH to make it work.
If you have noticed the Help (?) section in the Tool Locations, even that doesn't sound very excited about using this feature :P It says:
You can specify the location of certain tools on this node, overriding the global configuration. (You may prefer to use automatic tool installers instead, removing the need to configure each node separately.)
Comment: With due credit to Slav, I just want to qualify this statement of yours, "However, it will work only if the path to the executable is already present in the PATH env variable of the user with which the slave process is running.".

If you invoke the tool (e.g. mvn) in "Execute shell", only then do you need the executable in the PATH env variable.

If you are using Jenkins specific implementations, you DO NOT need to have the executable in the PATH env variable.
Comment: @Indrajeet: Thanks for pointing that out! @Slav is right. Well, so that's one good use of `Tool Locations`. :)


ActionView::Template::Error (undefined method `filename' for nil:NilClass):

Question: I am using rails Active storage to add attachments to my assignments model and it keeps throwing the above error
I had earlier used carrierwave gem but decided to use Active Storage instead. I need the views to show a file and a name but the error keeps showing.
When I comment out that line, the assignment views are working but cannot as images even if the files is a word or pdf or excel document.
  <% if @assignment.attachments.attached? %>

    Attachments

    <% @assignment.attachments.each do |attachment| %>
    <%= image_tag url_for(@assignment.attachment) %>
    <%= link_to rails_blob_path(@assignment.attachment.filename,
    disposition: "attachment") %>

  <% end %>

The model for assignments
    class Assignment < ApplicationRecord
     has_many_attached :attachments
    end

In the controller for assignments I have allowed attachments in params as follows
       attachments: []

Answer: Inside the .each loop, each of the attachment entries will be known as attachment and not as @assignment.attachment. In the case of the error, @assignment.attachment is nil.
Update your code to have the following two lines:
<%= image_tag url_for(attachment) %>
<%= link_to rails_blob_path(attachment.filename, disposition: "attachment") %>
Comment: When I update the code as per Dave Satchell, it throws the error undefined method `signed_id' for #
Comment: This is an ActiveStorage issue with direct uploads - take a look at the issue here https://github.com/rails/rails/issues/32365
Comment: If you are just testing while you are writing code and have nothing useful in the database, you can try clearing it, otherwise check some of the other solutions


Electrical circuit breakers, how do I check

Question: I had a 15 Amp GFIC/AFIC circuit breaker replaced. Everything is wired correctly. How do I test that the new one is not defective ? Lights still don't work.
Comment: How have you confirmed that "everything is wired correctly"?
Comment: I am not a big fan of some of the new code as the latest GFCI/AFCI breakers that I have worked with are not so good. With that said older equipment may trip a good one.
Answer: The only accurate test for a GFCI or AFCI is the built in test button on the breaker/device.
Anything else is convenient, but not completely accurate.
I have a suspicion that the circuit didn't work so you simply replaced the breaker, without troubleshooting to see if that was the actual problem. Most likely you have a problem with the circuit wiring or devices.
Answer: How do you test that the new one is not defective? Well, I guess you'd bolt fault it - not that I would nor do I recommend doing that. (of course I've never done that to find a CB... :)
How do you check a CB for continuity? Simple: remove it and check it for continuity. I've never had one that would still reset and not work.
I'd use a solenoid voltage tester (a Wiggy not a V/O meter) to confirm actual potential - with the branch disconnected and the CB powered-up. If test equipment can pop the breaker then it's bad (never had that happen to me) if it doesn't your problem is elsewhere. Which will become obvious when you test the UNLOADED disconnected branch and it shows continuity to ground.


Method in child class not called (properly)

Question: I have a class "FileButton". It's purpose is to link a file to a JButton, FileButton inherits from JButton. Child classes inherit from this to do usefull stuff with the file linked to the button.
The Class JingleCardButton is one of those child classes. This Child Class has a method that can play the jingle linked to the JingleCardButton when the button is clicked with the method "playSound()". This method isn't available in other child classes that inherit from FileButton
Also, i have a class Card that maintains a grid of FileButton objects on a specified JPanel. The Class JingleCard inherits from Card and maintains JingleCardButton objects.
Since every kind of Card needs to store all of its, the 2D buttonGrid array is declared in the base class Card.
   protected FileButton[][] buttonGrid; //the 2d area containing all FileButton objects is declared in "Card".

This is the constructor in JingleCard
  public JingleCard(JPanel p, int xdim, int ydim, JToggleButton editButton) {
        super(p,xdim,ydim,editButton); // calling the constructor in Card
        buttonGrid= new JingleCardButton[xdim][ydim];
        for (int row= 0; row< xdim; row++) {
          for (int column= 0; column< ydim; column++) {
            buttonGrid[row][column] = new JingleCardButton(null);
            buttonGrid[row][column].addActionListener(this);
            p.add(buttonGrid[row][column]);
        }

        p.doLayout();
    }
            p.doLayout();
        }
    }

Now i have a JingleCard, a 2D array filled with JingleCardButtons. After adding the mp3 file to the button (there's no file linked automatically when creating a card) with the GUI.
Now i should be able (i think so) to play the jingle assigned with the gui to a JingleCardButton somewhere in the JingleCard's ButtonGrid.
buttonGrid[row][column].playSound(); //syntax to play the sound is just like here: instance_of_JingleCardButton.playSound();

I have no idea why, but when compiling this in Netbeans, this produces an error...  According to Netbeans, the method PlaySound() can't be found in the class FileButton. (that's true, because it's in the child class JingleCardButton).
What's causing this problem? I'm sure that buttonGrid contains JingleCardButton objects, and calling playSound() should work. I don't see what's going wrong.
(some of the classes mentioned also implements ActionListener en Serializable)
Comment: For one, your classes shouldn't be extending JButton, but rather you will want to extend from AbstractAction, and then set each button's Action with your subclass.
Comment: The button's "action", what it does when pressed, is not part of the JButton itself, but of its ActionListener or better, its Action, and this is why I strongly urge you to make this fundamental change.
Comment: You said in your code that you are calling FileButton objects...
"protected FileButton[][] buttonGrid"
You need to change it or just cast it when you are calling method PlaySound(). Simply Try this: ((JingleCardButton)buttonGrid[row][collumn]).playSound();
Comment: @HovercraftFullOfEels: thank for the great tip. I'll keep that in mind for the future. I learned something new today.
Comment: @nosbor thanks for the simple solution. I think I confused some principles of inheritance.
Comment: The buttonGrid is indeed declared in the base class. I thought that it automatically will be casted to JingleCardButton when declaring it that way...
Answer: Your buttonGrid is an array of FileButton, and so the compiler sees each item in the array as being of FileButton type. Now even if you fill the array with JingleCardButton objects, the Java compiler will only allow you to call FileButton methods on the items in the array. You can sort of understand the rationale by thinking that since Java has no way of knowing that later you might not switch out an item in the array with a FileButton object of different sub-type, it has to err on the side of safety and limit what you can do with that variable.
One possible solution is to check the type object held by the variable using the instanceof operator, and then casting the variable to that of JingleCardButton
if (buttonGrid[row][column] instanceof JingleCardButton) {
    ((JingleCardButton) buttonGrid[row][column]).playSound();
}

... but that results in dirty code, code that is brittle and easily broken.
Better is to not even sub-type JButton since you don't appear to be wanting to change the innate properties of a JButton, but rather its behaviors when pressed. This behavior is not dictated by the button itself but rather by what Action it is set to, or what ActionListeners have been added to it. For this reason I strongly encourage you to create classes that extend AbstractAction and not JButton, not unless there are other JButton behaviors, behaviors that are unrelated to its action listener behavior, that you wish to modify.


How can I realize Act / Act Convention in Python?

Question: If there are two given dates(e.g., from Oct 12, 2016 to Nov 21, 2019). Based on the Act/Act Convention, how can I calculate the amount of days by the "While" or "IF" loop?
Comment: Does this answer your question? [How to calculate number of days between two given dates?](https://stackoverflow.com/questions/151199/how-to-calculate-number-of-days-between-two-given-dates)
Comment: Can you be more specific about what the issue is? Please see [ask], [help/on-topic].
Answer: You can use datetime module, i.e.:
<code>from datetime import datetime

df = "%b %d, %Y"
start = datetime.strptime('Oct 12, 2016', df)
end = datetime.strptime('Nov 21, 2019', df)
diff = end - start
print (diff.days)
# 1135
</code>
Demo
Answer: The fundamental rule is for days fall in a leap year you divide by 366 and for the rest you devide by 365.
Let me use the following example.
date1 = datetime(2020, 5, 8)
date2 = datetime(2021, 2, 26)

For the starting year 2020, which is a leap year, the REMAINING days should be divided by 366 to reflect ACT/ACT convention. For the ending year 2021, the PASSED days to date should be divided by 365.

So basically it becomes
(datetime(2020.12.31) - datetime(2020, 5, 8)).days / 366 + (datetime(2021, 2, 26) - datetime(2021, 1, 1)).days / 365

Expand on above example, assume date2 = datetime(2025, 2, 26). There are more years in between, i.e. [2020, 2021, 2022, 2023, 2024, 2025]. But the middle years should all count as one, and the tricky part sill remains in handling the starting and ending year.


What is the cleanest way to trim the drywall around this electrical box?

Question: I'm mounting a ceiling fan into an existing ceiling fan electrical box.
The drywall was finished around the box such that it's too close to the box and will be in the way of the hanging bracket and fan trim. I'll need to cut it back. What's the best way to trim back drywall in a situation like this?
Comment: I don't get it. It looks like your ceiling is at an angle. Won't the fan blades hit the ceiling?
Comment: Instead of cutting the drywall why not add on to the area where the fan trim will sit, that's assuming you can move the electrical box or get a deeper one.
Comment: @PlatinumGoose Good idea. I am not sure I want to replace the box, but perhaps I can cut a plate that can go between the box and the fan.
Comment: Extending the mounting plate down as suggested might be the simplest fix. Just keep in mind that you need to extend the box down as well (look for a "Ceiling Box Extender" of the right size). If you don't extend the box the enclosure does not meet fire code (also your house could burn down when a wire nut works loose).
Comment: @Harper, the fan hangs lower in the room from a down rod like this fan: http://www.eaglerc.org/wp-content/uploads/2017/12/vaulted-ceiling-fan-farmhouse-ceiling-fan-bedroom-rustic-with-exposed-beams-exposed-beams-vaulted-ceiling-angled-ceiling-fan-mount.jpg
Answer: I ended up following suggestions from @PlatinumGoose and @Stanwood by extending the electrical box lower using a 2x8 cut to fit, as well as a electrical box extender.
Comment: @ThreePhaseEel Yes, a good things to note. The fan bracket is secured with 6" lag screws that go through my block and up into whatever is above the original ceiling fan box.
Comment: Just make sure the fan mounting screws go into the 2x8 and not the extension


How to add multiple core plot plots on one screen

Question: Ok I'm stumped. I'm trying to use Core Plot 1.2 in my iOS app and I am trying to add two plots onto one screen. My code for my View Controller is below. There is a NIB file too but it is empty - the default view in just a UIView. I create two subviews of type CPTGraphHostingView, I add these as suvviews of self.view and then I create the graphs. In the code below I even commented out the method that creates one of the graphs to see if I could even get one graph to display, but all I get is a blank white screen.
I am using a simple X**2 function for testing purposes for each plot.
What am I doing wrong? Is there an easier way to get say 2 or 3 separate XY style plots onto a single screen?
<code>@interface SensorPlotSecondViewController : UIViewController <CPTPlotDataSource>
{
    CPTGraphHostingView *accelSubview;
    CPTGraphHostingView *gyroSubview;
    CPTGraphHostingView *magSubview;

    CPTXYGraph *accelGraph;
    CPTXYGraph *gyroGraph;
    CPTXYGraph *magGraph;
}

-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot;

-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)idx;

@end

@implementation SensorPlotSecondViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"Second", @"Second");
        self.tabBarItem.image = [UIImage imageNamed:@"second"];

        CGRect frm1=CGRectMake(0,0,320,150);
        accelSubview=[[CPTGraphHostingView alloc] initWithFrame:frm1];
        [self.view addSubview:accelSubview];

        CGRect frm2=CGRectMake(0,150,320,150);
        gyroSubview=[[CPTGraphHostingView alloc] initWithFrame:frm2];
        [self.view addSubview:gyroSubview];

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self createAccelGraph];

    //[self createGyroGraph];
}

-(void)createAccelGraph
{
    accelGraph = [[CPTXYGraph alloc] initWithFrame: accelSubview.bounds];

    //CPTTheme *theme=[CPTTheme themeNamed:kCPTPlainWhiteTheme];
    //[accelGraph applyTheme:theme];

    accelGraph.plotAreaFrame.borderLineStyle = nil;

    CPTGraphHostingView *hostingView = (CPTGraphHostingView *)accelSubview;
    hostingView.hostedGraph=accelGraph;
    accelGraph.paddingLeft = 0.0;
    accelGraph.paddingTop = 0.0;
    accelGraph.paddingRight = 0.0;
    accelGraph.paddingBottom = 0.0;

    //accelGraph.fill=nil;

    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)accelGraph.defaultPlotSpace;
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0)
                                                    length:CPTDecimalFromFloat(10)];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0)
                                                    length:CPTDecimalFromFloat(30)];

    CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
    lineStyle.lineColor = [CPTColor blackColor];
    lineStyle.lineWidth = 2.0f;

    CPTXYAxisSet *axisSet = (CPTXYAxisSet *)accelGraph.axisSet;
    axisSet.xAxis.majorIntervalLength = CPTDecimalFromString(@"5");

    axisSet.xAxis.minorTicksPerInterval = 4;
    axisSet.xAxis.majorTickLineStyle = lineStyle;
    axisSet.xAxis.minorTickLineStyle = lineStyle;
    axisSet.xAxis.axisLineStyle = lineStyle;
    axisSet.xAxis.minorTickLength = 5.0f;
    axisSet.xAxis.majorTickLength = 7.0f;
    axisSet.xAxis.labelOffset = 3.0f;

    axisSet.xAxis.visibleAxisRange=[CPTPlotRange plotRangeWithLocation:CPTDecimalFromString(@"0") length:CPTDecimalFromString(@"10")];

    axisSet.yAxis.majorIntervalLength = CPTDecimalFromString(@"5");
    axisSet.yAxis.minorTicksPerInterval = 4;
    axisSet.yAxis.majorTickLineStyle = lineStyle;
    axisSet.yAxis.minorTickLineStyle = lineStyle;
    axisSet.yAxis.axisLineStyle = lineStyle;
    axisSet.yAxis.minorTickLength = 5.0f;
    axisSet.yAxis.majorTickLength = 7.0f;
    axisSet.yAxis.labelOffset = 3.0f;

    axisSet.yAxis.visibleAxisRange=[CPTPlotRange plotRangeWithLocation:CPTDecimalFromString(@"0") length:CPTDecimalFromString(@"25")];

    accelGraph.plotAreaFrame.paddingLeft = 40.0;
    accelGraph.plotAreaFrame.paddingTop = 80.0;
    accelGraph.plotAreaFrame.paddingRight = 40.0;
    accelGraph.plotAreaFrame.paddingBottom = 300.0;

    CPTScatterPlot *xSquaredPlot = [[[CPTScatterPlot alloc] initWithFrame:accelSubview.bounds] autorelease];
    //CPTScatterPlot *xSquaredPlot = [[[CPTScatterPlot alloc] init] autorelease];
    xSquaredPlot.identifier = @"X Squared Plot";

    CPTMutableLineStyle *dataLineStyle = [CPTMutableLineStyle lineStyle];
    dataLineStyle.lineWidth = 1.0f;
    dataLineStyle.lineColor = [CPTColor redColor];
    xSquaredPlot.dataLineStyle=dataLineStyle;
    xSquaredPlot.dataSource = self;

    [accelGraph addPlot:xSquaredPlot];

    CPTPlotSymbol *greenCirclePlotSymbol = [CPTPlotSymbol ellipsePlotSymbol];
    greenCirclePlotSymbol.fill = [CPTFill fillWithColor:[CPTColor greenColor]];
    greenCirclePlotSymbol.size = CGSizeMake(2.0, 2.0);
    //xSquaredPlot.defaultPlotSymbol = greenCirclePlotSymbol;
    xSquaredPlot.plotSymbol = greenCirclePlotSymbol;

    /****
     CPTScatterPlot *xInversePlot = [[[CPTScatterPlot alloc] init] autorelease];
     xInversePlot.identifier = @"X Inverse Plot";

     CPTMutableLineStyle *dataLineStyle2 = [CPTMutableLineStyle lineStyle];
     dataLineStyle2.lineWidth = 1.0f;
     dataLineStyle2.lineColor = [CPTColor blueColor];
     xInversePlot.dataLineStyle=dataLineStyle2;
     xInversePlot.dataSource = self;
     [accelGraph addPlot:xInversePlot];
     ****/

}

-(void)createGyroGraph
{
    gyroGraph = [[CPTXYGraph alloc] initWithFrame: gyroSubview.bounds];

    CPTTheme *theme=[CPTTheme themeNamed:kCPTPlainWhiteTheme];
    [gyroGraph applyTheme:theme];

    gyroGraph.plotAreaFrame.borderLineStyle = nil;

    CPTGraphHostingView *hostingView = (CPTGraphHostingView *)gyroSubview;
    hostingView.hostedGraph=gyroGraph;
    gyroGraph.paddingLeft = 0.0;
    gyroGraph.paddingTop = 0.0;
    gyroGraph.paddingRight = 0.0;
    gyroGraph.paddingBottom = 0.0;

    gyroGraph.fill=nil;

    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)gyroGraph.defaultPlotSpace;
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0)
                                                    length:CPTDecimalFromFloat(10)];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0)
                                                    length:CPTDecimalFromFloat(30)];

    CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
    lineStyle.lineColor = [CPTColor blackColor];
    lineStyle.lineWidth = 2.0f;

    CPTXYAxisSet *axisSet = (CPTXYAxisSet *)gyroGraph.axisSet;
    axisSet.xAxis.majorIntervalLength = CPTDecimalFromString(@"5");

    axisSet.xAxis.minorTicksPerInterval = 4;
    axisSet.xAxis.majorTickLineStyle = lineStyle;
    axisSet.xAxis.minorTickLineStyle = lineStyle;
    axisSet.xAxis.axisLineStyle = lineStyle;
    axisSet.xAxis.minorTickLength = 5.0f;
    axisSet.xAxis.majorTickLength = 7.0f;
    axisSet.xAxis.labelOffset = 3.0f;

    axisSet.xAxis.visibleAxisRange=[CPTPlotRange plotRangeWithLocation:CPTDecimalFromString(@"0") length:CPTDecimalFromString(@"10")];

    axisSet.yAxis.majorIntervalLength = CPTDecimalFromString(@"5");
    axisSet.yAxis.minorTicksPerInterval = 4;
    axisSet.yAxis.majorTickLineStyle = lineStyle;
    axisSet.yAxis.minorTickLineStyle = lineStyle;
    axisSet.yAxis.axisLineStyle = lineStyle;
    axisSet.yAxis.minorTickLength = 5.0f;
    axisSet.yAxis.majorTickLength = 7.0f;
    axisSet.yAxis.labelOffset = 3.0f;

    axisSet.yAxis.visibleAxisRange=[CPTPlotRange plotRangeWithLocation:CPTDecimalFromString(@"0") length:CPTDecimalFromString(@"25")];

    gyroGraph.plotAreaFrame.paddingLeft = 40.0;
    gyroGraph.plotAreaFrame.paddingTop = 200.0;
    gyroGraph.plotAreaFrame.paddingRight = 40.0;
    gyroGraph.plotAreaFrame.paddingBottom = 150.0;

    CPTScatterPlot *xSquaredPlot = [[[CPTScatterPlot alloc] initWithFrame:gyroSubview.bounds] autorelease];
    //CPTScatterPlot *xSquaredPlot = [[[CPTScatterPlot alloc] init] autorelease];
    xSquaredPlot.identifier = @"X Squared Plot";

    CPTMutableLineStyle *dataLineStyle = [CPTMutableLineStyle lineStyle];
    dataLineStyle.lineWidth = 1.0f;
    dataLineStyle.lineColor = [CPTColor redColor];
    xSquaredPlot.dataLineStyle=dataLineStyle;
    xSquaredPlot.dataSource = self;

    [gyroGraph addPlot:xSquaredPlot];

    CPTPlotSymbol *greenCirclePlotSymbol = [CPTPlotSymbol ellipsePlotSymbol];
    greenCirclePlotSymbol.fill = [CPTFill fillWithColor:[CPTColor greenColor]];
    greenCirclePlotSymbol.size = CGSizeMake(2.0, 2.0);
    //xSquaredPlot.defaultPlotSymbol = greenCirclePlotSymbol;
    xSquaredPlot.plotSymbol = greenCirclePlotSymbol;

    /****
     CPTScatterPlot *xInversePlot = [[[CPTScatterPlot alloc] init] autorelease];
     xInversePlot.identifier = @"X Inverse Plot";

     CPTMutableLineStyle *dataLineStyle2 = [CPTMutableLineStyle lineStyle];
     dataLineStyle2.lineWidth = 1.0f;
     dataLineStyle2.lineColor = [CPTColor blueColor];
     xInversePlot.dataLineStyle=dataLineStyle2;
     xInversePlot.dataSource = self;
     [accelGraph addPlot:xInversePlot];
     ****/

}
</code>
Comment: Advice for future: find most appropriate example in corePlot demo project and modify it step by step.
Answer: Your padding on the plot area frame is too big. The graph is only 150 pixels high, yet you're trying to inset the plot area by 380 pixels, leaving no room to draw the plots.