text:
Q: Menubar not working For my school i need to make a website, i'm trying for days now to fix this problem. The menubar looks great. But i can't click the links. If you hoover above the links it should show a line, by the first two it does: Home and Componenten. By the rest it doesn't show up and i can't click on it.
here is my html and css, i really can't find the problem
<!DOCTYPE html>

<link href="contact.php" type="text/php">
<link rel="stylesheet" href="layout.css" type="text/css">
<title>webshop game artikelen</title>

Home
Componenten
Randapparatuur
Laptop & PC
Tablets & Telefoons
Netwerk
Software
Printing
Contact

<video poster="poster.jpg" width="618" height="347" controls preload>
<source src="stopmotion.mp4" media="only screen and (min-device-width: 568px)"></source>
<source src="stopmotion.mp4" media="only screen and (max-device-width: 568px)"></source>
<source src="video.ogv"></source>
</video>

2014, all right reserved
Webmaster

and this is my css
#page {width: 800px;
position: relative;
min-height: 100%;
height:auto !important; /* voor moderne browsers */
height:100%; /* voor IE */
}

/* blauwe menubalk */
.header-tabs {
float: left;
border-collapse: collapse;
border-spacing: 2px;
font-size: 11pt;
}
.header-tabs td a, .header-tabs td a:visited{
height: 26px;
background-color: #424C77;
color: #eff2fe;
font-size: 0.8em;
text-decoration: none;
display: block;
line-height: 24px;

}
.header-tabs td.actief a{
background-color: #eff2fe;
color: #424C77;
}

.header-tabs td:hover a{
text-decoration: underline;
}

/* //menu */

#content
{
background-color: ######;
width: 80%;
position:relative;

#footer
{position: absolute;
bottom: 0; /* heel belangrijk */
height: 20px;
width: 100%;
}

A: 1) Remove the float from:
.header-tabs {
   border-collapse: collapse;
   border-spacing: 2px;
   font-size: 11pt;
}

Demo
2) Or you can clear the floats after the table, like so:
#container { position: relative; overflow: hidden; }

Demo
3) Or you can add height to the container:
#container { height: 26px; }

Demo
And tell your school to teach you modern html/css, drop the use of the tables for such things.


text:
Q: Changes to /etc/sysconfig/keyboard without restart? cat /etc/sysconfig/keyboard
KEYBOARDTYPE="pc"
KEYTABLE="uk"
Question:

*

*Do you have to restart for changes to effect?

A: Yes, you'll need to restart for /etc/sysconfig changes to take effect, unless you can run whatever script that reads them again (i.e., /etc/init.d/networking for /etc/network/).
That said, one of /etc/init.d/{console-screen,keymap}.sh might do what you want, but they look like stuff that's only run at boot time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I am having trouble with the program skipping over the first input when looping. Please help Ok, so I had to modify my already working program to use 2 separate classes...one to perform the task and one to store info. Once it does the first calculation and it gets to the second entry, it skips over employee name. Why? Please help. Here is the code:
package payroll_program_3;
import java.util.Scanner;

        public class payroll_program_3
{
            public static void main(String[] args)
    {

            Scanner input = new Scanner( System.in );

            employee_info theEmployee = new employee_info();

            String eName = "";
            double Hours = 0.0;
            double Rate = 0.0;
while(true)
        {
System.out.print("\nEnter Employee's Name: ");
eName = input.nextLine();
theEmployee.setName(eName);
if (eName.equalsIgnoreCase("stop"))
                {     return;
                }

System.out.print("\nEnter Employee's Hours Worked: ");
Hours = input.nextDouble();
theEmployee.setHours(Hours);
while (Hours <0)                                                                 {                                                                                System.out.printf("Hours cannot be negative\n");
                    System.out.printf("Please enter hours worked\n");
                    Hours = input.nextDouble();
                    theEmployee.setHours(Hours);
                }

System.out.print("\nEnter Employee's Rate of Pay: ");
Rate = input.nextDouble();
theEmployee.setRate(Rate);
while (Rate <0)                                                                 {                                                                                System.out.printf("Pay rate cannot be negative\n");
                    System.out.printf("Please enter hourly rate\n");
                    Rate = input.nextDouble();
                    theEmployee.setRate(Rate);
                }

System.out.print("\n Employee Name:     " + theEmployee.getName());
System.out.print("\n Employee Hours Worked:     " + theEmployee.getHours());
System.out.print("\n Employee Rate of Pay:     " + theEmployee.getRate() + "\n\n");
System.out.printf("\n %s's Gross Pay: $%.2f\n\n\n", theEmployee.getName(), theEmployee.calculatePay());
        }
    }
}

PART 2:

package payroll_program_3;

        public class employee_info
{
            String employeeName;
            double employeeRate;
            double employeeHours;

public employee_info()
    {
    employeeName = "";
    employeeRate = 0;
    employeeHours = 0;
    }

public void setName(String name)
    {
    employeeName = name;
    }

public void setRate(double rate)
    {
    employeeRate = rate;
    }

public void setHours(double hours)
    {
    employeeHours = hours;
    }

public String getName()
    {
    return employeeName;
    }

public double getRate()
    {
    return employeeRate;
    }

public double getHours()
    {
    return employeeHours;
    }

public double calculatePay()
    {
    return (employeeRate * employeeHours);
    }
}

A: There are two places where an infinite loop can occurring, as Hours & Rate are not changing inside of them.
while (Hours <0)
{
  System.out.printf("Hours cannot be negative\n");
  System.out.printf("Please enter hours worked\n");
}

while (Rate <0)
{
  System.out.printf("Pay rate cannot be negative\n");
  System.out.printf("Please enter hourly rate\n");
}

Haven't read all the code, but it is likely this needs to be an if statement containing a continue.

A: You need hours= input.next double to change hour var so it fails the while condition


text:
Q: Is it possible to add a global X11 binding via/to Sublime Text 3? I would want to add a global X11 binding, preferably via ST3 configuration, that when activated, would:

*

*move the focus to a ST3 window and view,

*this would also involve switching to the right virtual desktop,

*invoke a sublime command (a text command or other).

Is this possible?
I'm doing some Xlib / EWMH coding and I can do the activation and desktop switching "manually". All I need is a global X11 binding that would invoke a Sublime Text command. Is such binding possible via Sublime configuration? If not, then how to accomplish the above?

A: I'm not sure exactly what you mean by a global X11 binding but I'd say what you want to achieve is possible with Xlib and EWMH in conjunction with a Sublime Text plugin to focus the required view and invoke the ST command.
Below is a fully working basic mock up of the required logic which uses a Bash script to focus the window and switch virtual desktops and then to call a Sublime Text plugin which changes the view and runs the required command.
The script uses wmctrl a useful utility which issues commands to EWMH/NetWM compatible X Window Managers.
Save this file as a Bash script and give it executable permission:
#!/bin/bash

# EWMH WM_CLASS for Sublime Text 3: "sublime_text.Sublime_text"
#
# EWMH WM_NAME examples: "~/Path/FileName.ext (Project Name) - Sublime Text"
#                        "~/Path/No Project.ext - Sublime Text"
#                        "untitled - Sublime Text"
#                        "~/Path/FileName.ext • (Project) - Sublime Text"
#
# Note: The project file name without the extension will be shown in brackets
# if there is a project file. '•' (see last example above) will be added if
# the file is unsaved and the suffix " - Sublime Text" is always added.

# Example: "~/Programming/Projects/MyProject.sublime-project" --> "MyProject"
target_project="MyProject"

# Example "wmctrl -lx" line:
# 0x02400003 0 sublime_text.Sublime_text host ~/File.ext (MyProject) - Sublime Text
# WinID   Desktop      WM_CLASS        hostname             WM_NAME
target_window=$(wmctrl -lx | grep ".*sublime_text.Sublime_text.*($target_project).*")
if [ "$target_window" = "" ]; then
    exit
fi

target_window_id=$(echo "$target_window" | grep -Eo '0x[0-9a-f]+')
if [ "$target_window_id" = "" ]; then
    exit
fi

# Switch focus to the window, wmctrl will switch virtual desktops if needed.
wmctrl -ia "$target_window_id"

# Call the Sublime Text window command:
# [This assumes Sublime Text is already running.]
subl --background --command "focus_view_invoke_cmd"

Save this file somewhere in the ST3 config Packages directory tree with a .py extension. e.g. ~/.config/sublime-text-3/Packages/User/FocusViewInvokeCommand.py:
import os.path
import sublime
import sublime_plugin

# Command created by ST for this class: focus_view_invoke_cmd
# How to set or find the command name of a Sublime Text plugin
# see this answer: https://stackoverflow.com/a/63979147/2102457

class FocusViewInvokeCmdCommand(sublime_plugin.WindowCommand):

    def run(self):

        # view_name_to_match is a file or unsaved buffer
        # name that the focus should be switched to. e.g.
        view_name_to_match = "MyToDoList"

        for view in self.window.views():
            if view_name_to_match in self.view_name(view):
                self.window.focus_view(view)
                self.run_command(view)
                break

    def view_name(self, view):

        # Return the file name (not full path) if the buffer is saved.
        if view.file_name():
            path = view.file_name()
            return os.path.basename(path)

        # Return the buffer name; i.e. the name the user has assigned,
        # or the buffer's 1st line auto. assigned by ST, or "untitled".
        else:
            # "untitled" is the default displayed name shown by ST
            # for all buffers which are both unsaved and unnamed,
            # but view.name() returns "" for "untitled" buffers.
            return view.name() if view.name() else "untitled"

    def run_command(self, view):

        command_to_run = "insert"
        command_args = {"characters": "This is a test! :)"}

        # In each of the run_command() methods the
        # command_args parameter may be omitted.

        # Use to run a *text command* on the view.
        view.run_command(command_to_run, command_args)

        # Use to run a *window command*.
        # self.window.run_command(command_to_run, command_args)

        # Use to run an *application command*.
        # sublime.run_command(command_to_run, command_args)


text:
Q: How do I make the Java file chooser display in front of the NetBeans interface? This problem is due to the basic setup that I have, which is a simple yes/no verification before the program brings up a filechooser. How do I make the filechooser display in front of NetBeans? The program works, I just need the browse file window to appear up front.
package txtkeyverifier2;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

public class TxtKeyVerifier001 {

public static void main(String[] args) throws FileNotFoundException {

    Scanner keyboard = new Scanner(System.in);

    System.out.print("Do you wish to continue yes/no: ");
    String answer = keyboard.nextLine();

    switch (answer) {
        case "yes":
        case "y": {

            ChooseFile fileChooser = new ChooseFile();
            File keyfile = fileChooser.getFile();

            Scanner sc = new Scanner(keyfile);
            String input = sc.nextLine();

            if (authenticate1(input)) {

                System.out.println("This program is working if this text is found within outputfile.txt.");

                File outputfile = new File("outputfile.txt");
                FileOutputStream fos = new FileOutputStream(outputfile);
                PrintStream ps = new PrintStream(fos);
                System.setOut(ps);
                System.out.println("This program is working if this text is found within outputfile.txt.");

            } else if (authenticate2(input)) {

                System.out.println("It works.");

            } else {
                System.out.println("Error: Wrong password.");
            }
        }
        break;
        case "no":
        case "n":

            break;
        default:
            System.out.println("Invalid entry");
            break;
    }
}

private static boolean authenticate1(String password1) {

    return ((password1.length() == 6)
            && (password1.matches("beep11"))
            && (password1.matches("beep11"))
            && (password1.matches("beep11")));
}

private static boolean authenticate2(String password2) {

    return ((password2.length() == 6)
            && (password2.matches("beep22"))
            && (password2.matches("beep22"))
            && (password2.matches("beep22")));
}
}

class ChooseFile {

private JFrame frame;

public ChooseFile() {

    frame = new JFrame();
    frame.toFront();
    frame.setVisible(true);

}

public File getFile() {
    JFileChooser fc = new JFileChooser();
    if (JFileChooser.APPROVE_OPTION == fc.showOpenDialog(null)) {
        frame.setVisible(false);
        return fc.getSelectedFile();
    } else {
        System.out.println("Next time select a file.");
        System.exit(1);
    }
    return null;
}

private void BringToFront() {
    frame.setExtendedState(JFrame.ICONIFIED);
    frame.setExtendedState(JFrame.NORMAL);
}
}

A: Instead of passing null to fc.showOpenDialog, you should pass its parent, usually the JFrame's content pane, returned by frame.getContentPane()


text:
Q: Is there any way to make the input global? I want to use textBox1.Text in a different class not just in the main where the text boxes are defined so to say. Is there any way to make it global? Because it only allows me to use it in the main thing, not in the seperate class that I have to make in my task.
I need to store the text from the textBox in a List that is in a different class so the user can't add the same name twice so I need to remember what was typed in in the first input.
This is the class where I created a List and where I want to store those inputs:
internal class Clanovi
{
    public static List<Clan> Dodaj()
    {
        List<Clan> clanovi = new List<Clan>();
        clanovi.Add(new Clan() { KorIme = textBox1.Text, Lozinka = textBox2.Text });
        return clanovi;
    }
}

class Clan
{
    public string KorIme { get; set; }
    public string Lozinka { get; set; }
}

This is WinForm btw.

A: Your variable names are in another language so it is hard to understand but I think you want this
internal class Clanovi
{
    public static List<Clan> Dodaj()
    {
        Global.clanovi.Add(new Clan() { KorIme = textBox1.Text, Lozinka = textBox2.Text });
        // you don't need to return this since it is already global
        return clanovi;
    }
}

public static class Global
{
    public static List<Clan> clanovi = new List<Clan>();
}

public static class Clan
{
    public static string KorIme { get; set; }
    public static string Lozinka { get; set; }
}

Whenever you want to access your global variables, you use the Global class with the static items in it.

A: i suggest to:

*

*change the modifiers property in the properties of the textbox to public.

*write this code in the other class :
Form_name/class_name myTextbox = new form_name/class_name();

ex:
Form1 myTextbox = new Form1();

*now u can use in any other class/form: mytextbox.Textbox.text.
internal class Clanovi
{
   Clan myTextbox = new Clan();

   public static List<Clan> Dodaj()
   {
     List<Clan> clanovi = new List<Clan>();
     clanovi.Add(new Clan() { KorIme = myTextbox.textBox1.Text, Lozinka = textBox2.Text });
     return clanovi;
   }
}


text:
Q: apt-get install unexpectedly removed Firefox I executed the command:
$ sudo apt-get install ssh-import-id

The output was (as people in the comments asked providing it comletely):
$ sudo apt-get install ssh-import-id
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
  gdbserver gstreamer1.0-gtk3 libabw-0.1-1 libatkmm-1.6-1v5 libbabeltrace1 libc6-dbg libcairomm-1.0-1v5 libcdr-0.1-1
  libcolamd2 libdw1 libe-book-0.1-1 libepubgen-0.1-1 libetonyek-0.1-1 libfreehand-0.1-1 libglibmm-2.4-1v5 libgtkmm-2.4-1v5
  libilmbase12 libmspub-0.1-1 libmwaw-0.3-3 libnuma1 libodfgen-0.1-1 libopenexr22 libpangomm-1.4-1v5 libsuitesparseconfig5
  libvisio-0.1-1 libwpd-0.10-10 libwpg-0.3-3 libwps-0.4-4 libxss1 libxvmc1 lp-solve vim-common x11-apps x11-session-utils
  xbitmaps xinit xserver-xorg-video-amdgpu-hwe-18.04 xserver-xorg-video-ati-hwe-18.04 xserver-xorg-video-fbdev-hwe-18.04
  xserver-xorg-video-intel-hwe-18.04 xserver-xorg-video-nouveau-hwe-18.04 xserver-xorg-video-qxl-hwe-18.04
  xserver-xorg-video-radeon-hwe-18.04 xserver-xorg-video-vesa-hwe-18.04 xxd
Use 'sudo apt autoremove' to remove them.
Recommended packages:
  openssh-server
The following packages will be REMOVED:
  brltty firefox gdb google-chrome-stable gparted irqbalance libcc1-0 libglu1-mesa libllvm6.0 libmagickcore-6.q16-3-extra
  libpagemaker-0.0-0 libproxy1-plugin-gsettings libreoffice-avmedia-backend-gstreamer libreoffice-base-core libreoffice-calc
  libreoffice-draw libreoffice-gnome libreoffice-gtk3 libreoffice-help-en-us libreoffice-impress libreoffice-math
  libreoffice-ogltrans libreoffice-writer libxatracker2 lshw printer-driver-brlaser printer-driver-splix thermald
  ubuntu-desktop ubuntu-minimal ubuntu-standard vim-tiny xorg xserver-xorg-video-all-hwe-18.04
  xserver-xorg-video-vmware-hwe-18.04 zeitgeist-core
The following NEW packages will be installed:
  ssh-import-id
0 upgraded, 1 newly installed, 36 to remove and 0 not upgraded.
Need to get 10,4 kB of archives.
After this operation, 595 MB disk space will be freed.
Do you want to continue? [Y/n] Y
Get:1 http://us.archive.ubuntu.com/ubuntu bionic/main amd64 ssh-import-id all 5.7-0ubuntu1 [10,4 kB]
Fetched 10,4 kB in 1s (14,5 kB/s)
(Reading database ... 127288 files and directories currently installed.)
Removing brltty (5.5-4ubuntu2.0.1) ...
Removing firefox (68.0.1+build1-0ubuntu0.18.04.1) ...
Removing gdb (8.1-0ubuntu3) ...
Removing google-chrome-stable (76.0.3809.100-1) ...
Removing gparted (0.30.0-3ubuntu1) ...
Removing irqbalance (1.3.0-0.1ubuntu0.18.04.1) ...
Removing libcc1-0:amd64 (8.3.0-6ubuntu1~18.04.1) ...
Removing ubuntu-desktop (1.417.3) ...
Removing xorg (1:7.7+19ubuntu7.1) ...
Removing libglu1-mesa:amd64 (9.0.0-2.1build1) ...
Removing xserver-xorg-video-all-hwe-18.04 (1:7.7+19ubuntu8~18.04.2) ...
Removing xserver-xorg-video-vmware-hwe-18.04 (1:13.3.0-2build1~18.04.1) ...
Removing libxatracker2:amd64 (19.0.2-1ubuntu1.1~18.04.2) ...
Removing libllvm6.0:amd64 (1:6.0-1ubuntu2) ...
Removing libmagickcore-6.q16-3-extra:amd64 (8:6.9.7.4+dfsg-16ubuntu6.7) ...
Removing libreoffice-ogltrans (1:6.0.7-0ubuntu0.18.04.8) ...
Removing libreoffice-impress (1:6.0.7-0ubuntu0.18.04.8) ...
Removing libreoffice-draw (1:6.0.7-0ubuntu0.18.04.8) ...
Removing libpagemaker-0.0-0:amd64 (0.0.4-1) ...
Removing libproxy1-plugin-gsettings:amd64 (0.4.15-1) ...
Removing libreoffice-avmedia-backend-gstreamer (1:6.0.7-0ubuntu0.18.04.8) ...
Removing libreoffice-help-en-us (1:6.0.7-0ubuntu0.18.04.8) ...
Removing libreoffice-writer (1:6.0.7-0ubuntu0.18.04.8) ...
Removing libreoffice-calc (1:6.0.7-0ubuntu0.18.04.8) ...
Removing libreoffice-base-core (1:6.0.7-0ubuntu0.18.04.8) ...
Removing libreoffice-gnome (1:6.0.7-0ubuntu0.18.04.8) ...
Removing libreoffice-gtk3 (1:6.0.7-0ubuntu0.18.04.8) ...
Removing libreoffice-math (1:6.0.7-0ubuntu0.18.04.8) ...
Removing ubuntu-standard (1.417.3) ...
Removing lshw (02.18-0.1ubuntu6.18.04.1) ...
Removing printer-driver-brlaser (4-1) ...
Removing printer-driver-splix (2.0.0+svn315-6fakesync1) ...
Removing thermald (1.7.0-5ubuntu2) ...
Removing ubuntu-minimal (1.417.3) ...
Removing vim-tiny (2:8.0.1453-1ubuntu1.1) ...
Removing zeitgeist-core (1.0-0.1ubuntu1) ...
Selecting previously unselected package ssh-import-id.
(Reading database ... 126362 files and directories currently installed.)
Preparing to unpack .../ssh-import-id_5.7-0ubuntu1_all.deb ...
Unpacking ssh-import-id (5.7-0ubuntu1) ...
Processing triggers for mime-support (3.60ubuntu1) ...
Processing triggers for libreoffice-common (1:6.0.7-0ubuntu0.18.04.8) ...
Processing triggers for desktop-file-utils (0.23-1ubuntu3.18.04.2) ...
Processing triggers for cups (2.2.7-1ubuntu2.6) ...
Updating PPD files for cups-filters ...
Updating PPD files for foomatic-db-compressed-ppds ...
Updating PPD files for openprinting-ppds ...
Updating PPD files for c2esp ...
Updating PPD files for foo2zjs-common ...
Updating PPD files for gutenprint ...
Updating PPD files for hpcups ...
Updating PPD files for m2300w ...
Updating PPD files for postscript-hp ...
Updating PPD files for ptouch ...
Updating PPD files for pxljr ...
Updating PPD files for sag-gdi ...
Processing triggers for libc-bin (2.27-3ubuntu1) ...
Processing triggers for man-db (2.8.3-2ubuntu0.1) ...
Processing triggers for gnome-menus (3.13.3-11ubuntu1.1) ...
Processing triggers for dbus (1.12.2-1ubuntu1.1) ...
Processing triggers for hicolor-icon-theme (0.17-2) ...
Setting up ssh-import-id (5.7-0ubuntu1) ...

After that my Firefox was deleted despite the fact that it was running during the above operation. Well, I saw that some packages were going to be deleted but couldn't even imagine that Firefox was among them.
So the questions:

*

*Why command named install was about to delete something?

*Why apt-get decided that Firefox is no longer needed?

*How to use apt-get so that it doesn't automatically delete the applications and packages that I need and don't want to delete?

*Where can I read about the topics connected to this issue?

UPD
Firefox was deleted. It was still working but after I closed it I couldn't start it again as it was no longer present in my applications. Then I reinstalled it (via Ubuntu Software application) and needed to adjust it from scratch as nothing of my previous settings preserved.
As asked in the comments:
$ apt-cache policy firefox
firefox:
  Installed: (none)
  Candidate: 59.0.2+build1-0ubuntu1
  Version table:
     68.0.1+build1-0ubuntu0.18.04.1 -1
        100 /var/lib/dpkg/status
     59.0.2+build1-0ubuntu1 500
        500 http://us.archive.ubuntu.com/ubuntu bionic/main amd64 Packages

Oh, no! Seems VI was also removed:
$ sudo vi /etc/apt/sources.list
sudo: vi: command not found
$ which vi
<nothing>

It worked before the discussed operation.
Possible duplicate
Suggested possible duplicate How do I restore the default repositories? doesn't answers the questions asked here. But it helped eliminate the root cause of the discussed problem. After enabling "Important security updates" and "Recommended updated" in tab "Updates" package installation problems ceased.
Conclusion
mook765 completely answered the question.

A:
Why command named install was about to delete something?

The lengthy removals looks like a holdover from a previous incomplete (error, aborted, etc) package manager action. Apt remembers what you told it to do, and will resume trying to accomplish it during the next session. Any apt action will trigger the re-try, including telling apt to install an unrelated package.

Why apt-get decided that Firefox is no longer needed?

This depends upon that previous apt session, which we know nothing about. You can see what you told at to do in /var/log/apt/history.log. It's possible that you (or Unattended Upgrades) attempted to run autoremove. Lots of possibilities.

How to use apt-get so that it doesn't automatically delete the
  applications and packages that I need and don't want to delete?

Apt is not psychic, and does not know your intent. It is a tool, like a saw or a hammer. Bringing wisdom to package management is the human's role.
Happily it's not difficult:

*

*Read your output before agreeing to apt's proposed actions. That's why the developers put the continue? prompt there.

*Use apt-marking properly. Apt keeps track of which packages you explicitly told it to install ("manual"), and which were merely dragged in as dependencies ("auto"). Apt WON'T remove any "manual" packages automatically. You must explicitly tell apt to remove a "manual" package.
Ubuntu's Desktop installer uses apt-marking to prevent mass-autoremoval of the base system, by apt-marking all the base system packages as "manual" during the install process.
Since the ubuntu-desktop, ubuntu-minimal, and ubuntu-standard metapackages were all eligible for autoremoval, you likely used the Netboot image (or some similar minimal image) to build your system, bypassing that extra layer of protection.
You can see your "manual" packages using apt-mark showmanual. Those are your top-level packages - everything else in your system depends upon one of those top-level items. The moment you remove one, all the dependent orphaned packages that are no longer needed become eligible for autoremoval.
This kind of mass-removal happens occasionally to unskilled users on minimal installs. Well, it happens ONCE, then the user apt-marks their key packages to prevent a re-occurrence.

Here's an example of how a mass autoremoval can happen (and, according to many AskUbuntu stories, has happened to some folks):

*

*User installs the system using the Netboot image.

*User installs the ubuntu-desktop metapackage. This is now the ONLY "manual" package. All the base system packages and desktop environment stack are "auto" dependencies of this lone package.

*User tries to remove one of the Desktop Applications (like Shotwell) that they don't use. Apt refuses, because shotwell is a dependency of ubuntu-desktop. This confuses the user, who doesn't grasp the relationship.

*While fiddling around with bad advice from various websites, the user removes both shotwell and ubuntu-desktop. The entire desktop stack and base system are still in place, but are now orphaned and are eligible for autoremove.  There is no longer any "manual" package anchoring the package system. But the system still works.

*One day, the user learns about "orphans", decides to try this nifty new 'autoremove' command to remove bloat...and promptly uninstalls their entire system back to the minimal image.

A: Before you install a package with apt or apt-get you should make sure that the package cache is up to date and the system is upgraded.
sudo apt update
sudo apt upgrade
sudo apt install <package-name>

apt manages deb-packages and the dependencies of the packages. That means if you install a package that depends on other packages, apt will handle that and install also the dependecies.
Some packages can not coexist (be installed) in the system at the same time, they conflict with each other. apt will also handle this situation, if you install package1 but package1 conflicts with package2 which is installed in your system, apt will remove package2 to make it possible to install package1.
This is going to be pretty complex if it comes to dependencies, if a dependency of an installed package is going to be removed, the dependent package is going to be removed too. Due to version conflicts this can happen easily if the system and the package-cache are not up to date or you added third party repositories (PPA's) to /etc/sources.list or /etc/sources.list.d/.
apt will always tell you what's going to happen, so in your case, you just need to read carefully:
The following packages will be REMOVED:
  brltty firefox gdb ...

and you have the chance to abort the operation by typing N and hitting Enter. So please, take the time and read command output carefully, you lose more time for troubleshooting if something goes wrong.
When I install install ssh-import-id on my system (18.04.3), it doesn't remove packages:
~$ sudo apt install ssh-import-id
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
  ncurses-term openssh-server openssh-sftp-server
Suggested packages:
  molly-guard monkeysphere rssh ssh-askpass
The following NEW packages will be installed:
  ncurses-term openssh-server openssh-sftp-server ssh-import-id
0 upgraded, 4 newly installed, 0 to remove and 0 not upgraded.
Need to get 637 kB of archives.
After this operation, 5,316 kB of additional disk space will be used.
Do you want to continue? [Y/n] n
Abort.
So you have either a system which is not up to date or made changes to the repositories, we can't see that from the output you provided.
The packages apt told you that they are not longer needed and you should remove them with sudo apt autoremove are a leftover from a previous action, you removed other packages from your system before and some packages were left over.
Update:
As you provided the full command output recently, I'd recommend that you
reinstall the 36 packages which have been removed before you do anything else, there are essential packages among them and you might end up with a broken system if you shutdown before reinstalling them.


text:
Q: Images not visible through smartphone www.michaelpeyron.com/wp
That's a demo of a site i'm working on. Whenever I visit it in browser and I reduce the window to smartphone size all images are there. But when I use my iphone 6 and visit the site, the images of instagram, twitter and facebook just isn't there.
I've zero clues about what the reason can be behind this behavior.
The twitter, facebook and instagram images are all from: https://fortawesome.github.io/Font-Awesome/cheatsheet/


text:
Q: media query overriding the precedent css I have used mobile-first development to style a web page. The problem is that the media query for the bigger screen overrides the media query for mobile screen. here is how my mobile screen should look like

Here is instead how it looks like with the media query that shouldn't affect it

here is my css file
 *{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    -webkit-animation: bgcolor 170s infinite;
    animation: bgcolor 170s infinite;
    -webkit-animation-direction: alternate;
    animation-direction: alternate;
    font-family: 'Varela Round', sans-serif;

}

#message{
    padding-left: 30px; position: fixed; bottom: 80px; width: 100%; height: 100px; padding-bottom: 20px;
    z-index: 9;

}

#message input{
    width: 80%;
    border: 1px solid darkgrey;
    height: 100%;
    padding: 30px;
    border-radius: 10px;
    -webkit-box-shadow: -9px -9px 21px 0px rgba(54,54,54,0.66);
    -moz-box-shadow: -9px -9px 21px 0px rgba(54,54,54,0.66);
    box-shadow: -9px -9px 21px 0px rgba(54,54,54,0.66);
    outline: none;
}

#message input:hover{
    cursor: pointer;
    font-size: 30px;
}

#message button{
    width: 10%;
    z-index: 9;

    height: 100px;
    border: none;
    background: white;
    border-radius: 10px;
    margin-left: 10px;
    outline: none;
    -webkit-box-shadow: -9px -9px 21px 0px rgba(54,54,54,0.66);
    -moz-box-shadow: -9px -9px 21px 0px rgba(54,54,54,0.66);
    box-shadow: -9px -9px 21px 0px rgba(54,54,54,0.66);
}

#message button:hover{
    cursor: pointer;
}

#chat-area{
    height: 90%;
    width: 100%;
    position: fixed;
    z-index: 7;
    overflow-y:auto;
    margin-bottom: 0;
    margin-top: 40%;
    border-radius: 100px;
    -webkit-box-shadow: 0px -7px 62px 1px rgba(0,0,0,0.75);
    -moz-box-shadow: 0px -7px 62px 1px rgba(0,0,0,0.75);
    box-shadow: 0px -7px 62px 1px rgba(0,0,0,0.75);
}

.messageL{
    float: left;
    margin-left: 30px;
    border-radius: 10px;
    max-width: 45%;
    min-width: 400px;
   // min-height: 100px;
    background-color: white;
    padding: 20px;
    margin-bottom: 10px;
    margin-top: 20px;
    clear: both;

}

.user{
    margin-bottom: 5px;
    font-size: 22px;
}
.content{
    font-size: 18px;
}
.messageR{
    float: right;
    margin-right: 30px;
    border-radius: 10px;
    max-width: 45%;
    min-width: 400px;
    //min-height: 100px;
    background-color: white;
    padding: 20px;
    margin-bottom: 10px;
    margin-top: 20px;
    clear: both;

}
.messageG:last-of-type{
    margin-bottom: 400px;
}

.messageC{
    text-align: center;
    border-radius: 10px;
    max-width: 70%;
    min-width: 400px;
    min-height: 70px;
    font-weight: bold;
    font-size: 20px;
    margin-left: 20%;
    margin-right: 20%;
    padding: 20px;
    margin-bottom: 45px;
    margin-top: 20px;
    background:rgba(110,109,109,0.5);
    clear: both;
}
.messageC:first-of-type{
    margin-top: 160px;
}
#header{
    position: fixed;
    padding: 10px;
    margin-bottom: 70px;

    min-height: 100px;
    width: 100%;

    font-family: 'Varela Round', sans-serif;

}
#roomname{
    font-size: 70px;
    width: 90%;
    text-align: center;
    border: 3px solid red;
    margin: 15px;
    padding: 15px;
    border-radius: 40px;
    position: relative;
}
#typing{
    max-width: 90%;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
    margin: 40px;
    font-size: 30px;
    position: absolute;
    left: 75px;
    top:170px;
   border: 3px solid red;
    background-color: white;
    border-radius: 30px;
    padding: 30px;
}

#online{
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
    margin: 40px;
    font-size: 30px;
    position: absolute;
    left: 35px;
    top:80px;
    background-color: red;
    color: white;
    border-radius: 30px;
    padding: 30px;
}

@media only screen and (min-width:450px) {
    #header {
        min-height: 50px;
    }
    #roomname {
        font-size: 17px;
        text-align: left;
        width: 50%;
    }
    #online{
        font-size: 17px;
        left: 480px;
        top:15px;
        padding: 10px;

    }
    #typing{
        font-size: 12px;
        left: 100px;
        min-width: 200px;
        top:30px;
        padding: 10px;
        background-color: white;
    }
    #chat-area {
        margin-top: 15%;
    }

    #message {
        height: 20px;
        padding: 5px;
        font-size: 10px;
        bottom: 60px;

    }
    #message input {
        height: 50%;
        padding: 20px;

    }
    #message input:hover{

        font-size: 15px;
    }
    #message button {
        height: 40px;
    }
    .messageC {
        min-height: 30px;
        padding: 10px;
        margin-bottom: 25px;
        margin-top: 10px;
        font-size: 15px;
        max-width: 50%;
        text-align: center;

    }
    .messageC:first-of-type{
        margin-top: 80px;
    }
    .messageR {
        max-width: 23%;
        min-width: 200px;
        font-size: 13px;
        padding: 10px;

    }
    .user{
        font-size: 18px;
    }

    }

I would like the query to affect just the screens with the right size


text:
Q: OleDbException was unhandled - Data type mismatch for Int-Field Type I have a free table My_Table1.
My_Table1 ia having the following field
Field-Name  ->  sl_no Integer - Width 4

Therefore from c# while I insert through OleDb its' giving the error like
"Data Type Mismatch"

And My OleDbCommand is
int a1 = 3;

OleDbCommand OleCmd1 = new System.Data.OleDb.OleDbCommand("Insert into My_Table1 values('"+a1+"')", OleCon1)

Thanks For The Helps

A: The INSERT statement is inserting a character value 'a1'.  That cannot be stored in an integer field.  If a1 is a variable in the code, then maybe you are looking for this:
System.Data.OleDb.OleDbCommand("Insert into My_Table1 values("+a1.ToString()+")", OleCon1)

From a "best practices" perspective, it is probably better to use a parameterized query just to get in the habit of avoiding SQL injection attack problems.  With an integer value, the above statement is probably okay, but it is not generally good to get comfortable with building SQL statements with simple concatenation.


text:
Q: Lazysodium for Java cannot initialize sodium object Following the tutorial from documentation I added the lazysodium library with Maven but seem like lazycode is trying to load another class but cannot find it.
Error message
Exception in thread "main" java.lang.NoClassDefFoundError: co/libly/resourceloader/SharedLibraryLoader
    at com.goterl.lazycode.lazysodium.utils.LibraryLoader.loadBundledLibrary(LibraryLoader.java:115)
    at com.goterl.lazycode.lazysodium.utils.LibraryLoader.loadLibrary(LibraryLoader.java:84)
    at com.goterl.lazycode.lazysodium.SodiumJava.<init>(SodiumJava.java:34)
    at com.goterl.lazycode.lazysodium.SodiumJava.<init>(SodiumJava.java:23)
    at aitmed.crypto.main(crypto.java:12)

This is my main class, I make the simplest class possible to just test the library.
package groupme;

import com.goterl.lazycode.lazysodium.*;

public class crypto {

    public static void main(String args[])  {

        LazySodiumJava lazySodium = new LazySodiumJava(new SodiumJava());
    }

}

This is my pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>aitmed</groupId>
    <artifactId>androidsdk</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <!-- required for jdk9 -->
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>

        <java.version>1.11</java.version>
        <maven.compiler.source>1.11</maven.compiler.source>
        <maven.compiler.target>1.11</maven.compiler.target>
    </properties>

    <repositories>
        <repository>
            <id>lazysodium-java</id>
            <url>https://dl.bintray.com/terl/lazysodium-maven</url>
        </repository>
    </repositories>

    <dependencies>

        <dependency>
            <groupId>com.goterl.lazycode</groupId>
            <artifactId>lazysodium-java</artifactId>
            <version>4.2.3</version>
        </dependency>

        <dependency>
            <groupId>net.java.dev.jna</groupId>
            <artifactId>jna</artifactId>
            <version>5.4.0</version>
        </dependency>

    </dependencies>

</project>


text:
Q: Why is No data message showing? (trying to create google charts) I am new to the Google Charts API. I was following some examples to create a chart with a search function, involving MySQL on XAMPP, but it only returns "options part" and "no data" messages.
I tested the SQL query, and it works.
My code:
<?php
include("config.php");
$query1  = "SELECT partido, COUNT(*) as num_faltas FROM reuniao WHERE presenca LIKE '%Injustific%' GROUP BY partido";
$query2  = "SELECT DISTINCT partido FROM reuniao";
$result1 = mysqli_query($conn, $query1);
while ($row = mysqli_fetch_array($result1)) {
    echo "['" . $row['partido'] . "'," . $row['num_faltas'] . "],";
}
?>

<!DOCTYPE HTML>

    <title> Graficos </title>

A: I changed the code and it's working:
var data = new google.visualization.arrayToDataTable([
            ['Partido', 'Faltas injustificadas'],
            <?php
            $query1  = "SELECT partido, COUNT(*) as num_faltas FROM reuniao
            WHERE presenca LIKE '%Injustific%' GROUP BY partido";
            $result1 = mysqli_query($conn, $query1);
            while ($row = mysqli_fetch_array($result1)) {
                echo "['" . $row['partido'] . "'," . $row['num_faltas'] . "],";
            }
            ?>
        ]);


text:
Q: Why does a single click generate multiple click events? I have added a button dynamically. But when I click it, it fires multiple click events and calls the associated function with alert('clicked'); several times and not just one time.
Can you tell me why and how I can fix it?
Code
 var root = document.getElementById('current_page');
 var button = document.createElement('input');
 button.type = 'button';
 button.title = 'Add new book to list';
 button.className = 'btn btn-primary';
 button.id = 'get_new';
 button.setAttribute('value', 'No Thanks,Get New');
 button.setAttribute('style', 'position:relative; top:-5px;left:900px');
 root.appendChild(button);

Handler
$('body').on('click', '#get_new', function () {
            alert('clicked');
});

A: Since you're already using jQuery, you may as well create the element using jQuery and bind the click function on its creation. This will likely solve whatever is causing your double-firing issue.
Fiddle: http://jsfiddle.net/f9PX4/
function myFunction() {
    alert('clicked');
}

$(function() {
    var button = $("<input>");
    button.attr("type", "button")
        .attr("title", "Add new book to list")
        .attr("id", "get_new")
        .css({ position: "relative", top: -5, left: 900 })
        .val("No Thanks,Get New")
        .addClass("btn btn-primary");
    button.click(function() {
        return myFunction();
    });
    $("#current_page").append(button);
});


text:
Q: Ways to find one number in a pair given another number and their greatest common di I would like to know if there is a way to find number in a pair of number given another number and their greatest common divisor.
Example: find all n values given n <= 50 and gcd(n,50) =5.

A: In your example, we can find $n$ values by first factoring the given integer ($50$ in this case) as
$$50 = 2\cdot 5^2$$
Then, $n$ must have exactly one multiplier $5$, and it must have no power of $2$, i.e. $2, 2^2, 2^3,...$ But it may have powers of other primes such as $3^k,7^k,11^k,13^k,...$, $k \in \mathbb{Z^+}$ but notice that not all them satisfies the condition $n < 50$ when multiplied by $5$ (like $5
\cdot 11 = 55$ or $5 \cdot 3^3 = 135$, etc.), which $n$ must have as a multiplier. So we can have

*

*$n = 5$,

*$n = 5\cdot 3 = 15$, $n = 5 \cdot 3^2 = 45$,

*$n = 5 \cdot 7 = 35$
When $n$ or the given numbers gets larger, this algorithm may be hard to use but for small numbers as in this case, this algorithm should work.


text:
Q: How to create a semi-transparent map collar in QGIS composer? In QGIS 2.14, how can I create a semi-transparent "map collar" (white space around the outside of the page) in Composer?
I imagine the map collar would be some sort of graphic shape (not a feature) that is maybe 1 inch wide and covers the current data map.  Think of it like a donut:  white space that is semi-transparent white, while the interior is transparent.  The end goal is to create a "masking" effect that would focus the users eye on the interior of the map, but still allow them to see features around the edge of the map (and "hidden" under the collar).
A couple of ideas I had but cannot figure out a way to implement:

*

*Buffer the map frame (to the outside only)

*Create a graphic shape and "cut out" the interior

A: You can create a collar using data frame or map frame within the layout view, as follows

*

*Set the data map position for both X and Y to 0 (Zero)

*Increase the thickness of the frame to desired value (I used 20 mm), The thickness increased from the center of the line (both outside and inside of the line), that is why I set the X and Y position to 0 to exclude the outside from being shown when exporting the map to an image or a PDF.

*Choose the desired color, and set the opacity to 50% or 60%.
The result is shown below:

If you want to exclude the yellow color in the right side of the frame you can add a rectangle to hide that color and lock the layer to become a space to put some legend and other information, and the result will be like this:

The output when you save the layout as image is like this:

Also, there is another option to create a collar using rectangle object, but  a lens-like shape, using the following steps:

*

*Create a rectangle shape that covers map frame completely. The extent of the rectangle is same as the extent of the map frame.

*Under Items -> select the new rectangle -> Style and click on Change

*Change the style from simple fill to shapeburst fill, and change the settings as shown below:

*You will get an output a focus lense-like shape, as shown below:

Update
Using also @RyanDalton's method,  it is better to change the transparency of the rectangle (collar) itself rather than the map frame to keep the map frame very clear. Also, changing the "Blend mode" to 'Soft light' OR 'Overlay' can some effects, but it is still a personal preference, as shown below:
(1) Blending mode: Soft light

(2) Blending mode: Overlay with 25% transparency

A: Thanks to the answer by @ahmadhanb, it led me in the right direction to find what I was looking for.
Step-by-Step instructions:

*

*Add a rectangle shape that represents the "frame" that you want your map to sit within.

*The default will be a polygon with simple fill.  Change its style to transparent fill and dark border.  Adjust border width and style as needed.

*Add an additional fill type of "Outline: Simple line".  This will be your "collar".

*Change the color to the outline fill to the color of your collar.  Set the pen width large enough to go off the page (I used 20mm), and set the Offset to negative half of the pen width (I used -10mm). Save the style.

*Back on the Composer>Item Properties, set the transparency of the map frame/collar to desired transparency (I chose 25%).

Even though the collar fill runs off the map canvas, only map canvas area will be exported to file.  You can see the result leave the outer edge slightly shaded, but semi-transparent.

A: I don't think you can make a "donut hole" in a graphic like you can in a feature. One way would be to create 4 graphic rectangles of equal transparency (transparency is under Item Properties > Rendering) and use them to build a frame around the edge of your layout. Here I used 2 red ones on the bottom and right and 2 white ones along the top and left.

A: You can use Mask plugin.
Create polygon layer over the space you want to show, then use Mask plugin on it. Should work


text:
Q: KNP Menu Bundle won't access entities when being run in controller being functionally tested This one really has me stumped.
I'm trying to run functional tests on my application, but am running into problems with the KNP Menu Bundle, and I'm not entirely sure where I'm going wrong.
I have some entities being loaded by Doctrine Fixtures, and I know they are there - no other part of the testing suite has an issue with finding them and asserting they are what I want them to be.
In my setUp() method of the test (extending WebTestCase), I create a client and inject the entity manager into it, like so:
/**
 * Create Client and inject services
 */
$this->client = static::createClient();
$this->client->getContainer()->set( 'doctrine.orm.entity_manager', $this->em );

None of the other tests have an issue with using that entity manager and finding the entities.
I'm using the menu as a service, and the definition is as follows:
the_site.menu_builder:
    class: TheSite\SiteBundle\Menu\MenuBuilder
    arguments: [ "@knp_menu.factory", "@doctrine.orm.entity_manager" ]

the_site.menu.breadcrumb:
    class: Knp\Menu\MenuItem
    factory_service: the_site.menu_builder
    factory_method: breadcrumbMenu
    arguments: [ "@request" ]
    scope: request
    tags:
        - { name: knp_menu.menu, alias: breadcrumb }

The code that it seems to choke on is this:
public function breadcrumbMenu( Request $request )
{
     // ......

      /**
       * @var $category NewsCategory
       */
      $category = $this->em->getRepository( 'TheSiteSiteBundle:Category' )->findOneByCanonical( $request->get( 'category' ) );
      $categories = [];

      do
      {
        $categories[] = $category;

        $category     = $category->getParent();
      } while( $category !== null );

      // .....
}

I did a little investigation (including some very complex var_dump'ing ;) ) and it seems that it just can't find any of the categories set by the fixtures. If it helps at all, the entities are being set inside of a doctrine transaction, but still - the other tests proved that the client managed to find those entities just fine before!
$request->get( 'category' ) produces exactly what it should do, so as far as I can see it's an issue with the entity manager.
If more code is needed I'd be more than happy to share.
Edit: I might take what I said back - now it doesn't seem to be loading entities anywhere. Maybe there where still some in the database or something!


text:
Q: Can you list the keyword arguments a function receives? I have a dict, which I need to pass key/values as keyword arguments.. For example..
d_args = {'kw1': 'value1', 'kw2': 'value2'}
example(**d_args)

This works fine, but if there are values in the d_args dict that are not accepted by the example function, it obviously dies.. Say, if the example function is defined as def example(kw2):
This is a problem since I don't control either the generation of the d_args, or the example function.. They both come from external modules, and example only accepts some of the keyword-arguments from the dict..
Ideally I would just do
parsed_kwargs = feedparser.parse(the_url)
valid_kwargs = get_valid_kwargs(parsed_kwargs, valid_for = PyRSS2Gen.RSS2)
PyRSS2Gen.RSS2(**valid_kwargs)

I will probably just filter the dict, from a list of valid keyword-arguments, but I was wondering: Is there a way to programatically list the keyword arguments the a specific function takes?

A: In Python 3.0:
>>> import inspect
>>> import fileinput
>>> print(inspect.getfullargspec(fileinput.input))
FullArgSpec(args=['files', 'inplace', 'backup', 'bufsize', 'mode', 'openhook'],
varargs=None, varkw=None, defaults=(None, 0, '', 0, 'r', None), kwonlyargs=[],
kwdefaults=None, annotations={})

A: This will print names of all passable arguments, keyword and non-keyword ones:
def func(one, two="value"):
    y = one, two
    return y
print func.func_code.co_varnames[:func.func_code.co_argcount]

This is because first co_varnames are always parameters (next are local variables, like y in the example above).
So now you could have a function:
def get_valid_args(func, args_dict):
    '''Return dictionary without invalid function arguments.'''
    validArgs = func.func_code.co_varnames[:func.func_code.co_argcount]
    return dict((key, value) for key, value in args_dict.iteritems()
                if key in validArgs)

Which you then could use like this:
>>> func(**get_valid_args(func, args))

if you really need only keyword arguments of a function, you can use the func_defaults attribute to extract them:
def get_valid_kwargs(func, args_dict):
    validArgs = func.func_code.co_varnames[:func.func_code.co_argcount]
    kwargsLen = len(func.func_defaults) # number of keyword arguments
    validKwargs = validArgs[-kwargsLen:] # because kwargs are last
    return dict((key, value) for key, value in args_dict.iteritems()
                if key in validKwargs)

You could now call your function with known args, but extracted kwargs, e.g.:
func(param1, param2, **get_valid_kwargs(func, kwargs_dict))

This assumes that func uses no *args or **kwargs magic in its signature.

A: Extending DzinX's answer:
argnames = example.func_code.co_varnames[:func.func_code.co_argcount]
args = dict((key, val) for key,val in d_args.iteritems() if key in argnames)
example(**args)

A: Just use this for a function name 'myfun':
myfun.__code__.co_varnames

A: A little nicer than inspecting the code object directly and working out the variables is to use the inspect module.
>>> import inspect
>>> def func(a,b,c=42, *args, **kwargs): pass
>>> inspect.getargspec(func)
(['a', 'b', 'c'], 'args', 'kwargs', (42,))

If you want to know if its callable with a particular set of args, you need the args without a default already specified.  These can be got by:
def get_required_args(func):
    args, varargs, varkw, defaults = inspect.getargspec(func)
    if defaults:
        args = args[:-len(defaults)]
    return args   # *args and **kwargs are not required, so ignore them.

Then a function to tell what you are missing from your particular dict is:
def missing_args(func, argdict):
    return set(get_required_args(func)).difference(argdict)

Similarly, to check for invalid args, use:
def invalid_args(func, argdict):
    args, varargs, varkw, defaults = inspect.getargspec(func)
    if varkw: return set()  # All accepted
    return set(argdict) - set(args)

And so a full test if it is callable is :
def is_callable_with_args(func, argdict):
    return not missing_args(func, argdict) and not invalid_args(func, argdict)

(This is good only as far as python's arg parsing. Any runtime checks for invalid values in kwargs obviously can't be detected.)

A: For a Python 3 solution, you can use inspect.signature and filter according to the kind of parameters you'd like to know about.
Taking a sample function with positional or keyword, keyword-only, var positional and var keyword parameters:
def spam(a, b=1, *args, c=2, **kwargs):
    print(a, b, args, c, kwargs)

You can create a signature object for it:
from inspect import signature
sig =  signature(spam)

and then filter with a list comprehension to find out the details you need:
>>> # positional or keyword
>>> [p.name for p in sig.parameters.values() if p.kind == p.POSITIONAL_OR_KEYWORD]
['a', 'b']
>>> # keyword only
>>> [p.name for p in sig.parameters.values() if p.kind == p.KEYWORD_ONLY]
['c']

and, similarly, for var positionals using p.VAR_POSITIONAL and var keyword with VAR_KEYWORD.
In addition, you can add a clause to the if to check if a default value exists by checking if p.default equals p.empty.


text:
Q: What is the total number of additions and multiplications in the following code? I'm in a discrete math class and he explained very little about programming and code so far.  He also said he likes to throw in crazy questions to our homework to throw us off.  Thus, I'm here to learn from you for this particular question! (I don't know how to further research this question since I'm not sure what language this is, I think it might be C++?)
What is the total number of additions and multiplications in the following code?
s := 0
for i := 1 to n
    s:= s + i
    for j:= 1 to i
        s := s + j*i
    next j
next i
s := s+10

(a) n
(b) n^2
(c) n^2 + 2n
(d) n(n + 1)
(e) (n + 1)^2
(f) none of these.

A: There are n additions to s in the outer loop, and n(n+1)/2 inner iterations each containing an addition and a multiplication (multiply by 2), so n^2 + n operations in the inner loop plus the single addition at the end for a total of:
[n additions to s] + [n(n + 1) inner loop operations] + [the very last line]
= n + n(n+1) + 1
= n + n^2 + n + 1
= n^2 + 2n + 1
= (n + 1)^2 operations (e)

This is of course assuming that the implicit operations performed on i and j are not counted as additions. Presumably you wouldn't be asked to know how the compiler treats range-based loops.


text:
Q: return Eventsource Observable from Server sent event in angular I have a Observable from a server sent event which returns data und errors using the following solution Allow creation of Observable from EventSource (server-sent events): enhancement
To solve connection issues I want to separate the
const eventStream = new EventSource(evtSourceAdress);
part into an separate Observable
if connection succeeds do further logic
using the solution from
streamHandler(evtSourceAdress: string) {

    return new Observable<MessageEvent<any>>(subscriber => {

      const eventStream = new EventSource(evtSourceAdress);

      eventStream.onmessage = e => subscriber.next(e);
      eventStream.onerror = e => subscriber.error(e);
      /* add if else clause if error is returned */

      return () => {
        if (eventStream.readyState === 1) {

          /* TODO add reconnect  */
          eventStream.close()
        }
      }

    })

  }

I modified the code to get the eventStream as an Observable
 openEventSource(url: string): Observable<any> {
    return new Observable<MessageEvent>(subscribe => {
       const sse = new EventSource(url);
      //  return sse.readyState
    })
    // return new Observable<MessageEvent>(subscriber => {
    //   const sse = new EventSource(url);
  }

this.eventStreamHandlerServ.openEventSource('http://localhost:3000/sse/event').subscribe(e => console.log(e))

which does not return anything
adding a return statement  return sse.readyState
gives me Type 'number' is not assignable to type 'TeardownLogic'.
is there a way to only get the event as an observable ?
considered answers
Creating an RxJS Observable from a (server sent) EventSource

A: You can retry  the connection using retry.
openEventSource(url: string): Observable<any> {
  return new Observable<any>((subscriber) => {
    const eventSource = new EventSource(url);
    eventSource.onmessage = (ev) => subscriber.next(ev.data);
    eventSource.onerror = (ev) => subscriber.error(ev);

    return () => eventSource.close();
  });
}

And in order to introduce the retry logic, you just use the retry operator mentioned above:
this.eventSourceService
  .openEventSource(url)
  // retry the connection 5 times, with 500 milliseconds delay
  .pipe(retry({ count: 5, delay: 500 }))
  .subscribe({
    next: (data) => {
      console.log('data from event source', data);
    },
    error: (error) => {
      console.log('event source has an error', error);
    },
  });


text:
Q: Inject Schema JSON using Google Tag Manager We are trying to inject schema JSON for SEO using GTM, however, the page isn't able to detect the schemas while doing the rich result test or schema markup validator.
The schema is getting triggered the - when inspecting the network call. schema json trigger using
Is there something I am missing out on?

*

*Is GTM the right way to trigger schema JSON on a webpage?

*Will multiple triggers and GTM tags impact the page speed for the website?

A: *

*It is possible to inject structured JSON data using GTM. The main downside is, that it is only visible for JavaScript crawlers. In my experience, it is detected and processed by Google, but it works better implementing it backed-side directly into the .

*Everything you do impacts page speed. The problem with GTM is, that it appends custom HTML tags to the end of the  and moves it up into the  afterwards, thus consuming some extra computation power.


text:
Q: Asp.Net Razor Page cannot display image My project is Asp.net Core App with framework 5 and
problem is that I can't display image using a virtual directory
Example code:
@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

    //Doesn't work

    //this settings work normally

Is it really so that images have to be located on the same website as pages.

A:
When running you app it is loaded over SSL using the HTTPS Protocol. Therefore the Browser prohibts images and other resources to be loaded over HTTP. Thats because it enforces that every asset is loaded using the same protocol. Therefore the Get request to show your image gets upgraded to HTTPS but because this URL doesnt exist the image cant be displayed.


text:
Q: Bash Shell Tutorials What are some good bash tutorials? I would like to learn more about the bash shells commands and how to use them.

A: I find Greg's Bash Guide and Bash FAQ very helpful, even for beginners.
Also, I remember learning bash from Daniel Robbins' series, Bash by example, which is a very good read in my opinion.

A: If you don't mind to pay for the best resources in book format:

*

*http://oreilly.com/catalog/9780596526788/ (Bash Cookbook)

*http://oreilly.com/catalog/9780596009656/ (Learning Bash - slightly outdated)

*http://oreilly.com/catalog/9780596527761/ (bash Quick Reference - I do use it frequently...)

*http://oreilly.com/catalog/9780596003302/ (Unix power tools - OK, not only bash. But it's a must have)

A: Advanced Bash Scripting Guide from The Linux Documentation Project pages.
(Also available as a PDF file if you prefer that).

*

*Recommended online resources for learning bash scripting

*How to learn your way through Linux's shell
General search tags:

*

*Stackoverflow: bash+scripting, bash+script

*Serverfault: bash+scripting, bash+script, etc

*Command Line Fu -- for quick tricks (think of them as short tutorials)

Empty at this time... :-)

*

*Superuser: bash+scripting, bash+script
But, don't go by that.

A: This is a great video tutorial for command line editing: http://teachmetocode.com/screencasts/bash-command-line-editing/


text:
Q: How to move multi files using SHFILEOPSTRUCT? How to move multi files using SHFILEOPSTRUCT?
            vector<CString> srcPaths;
            vector<CString> dstPaths;
    SHFILEOPSTRUCT FileOp;//定义SHFILEOPSTRUCT结构对象;
    int fromBufLength = MAX_PATH * imageVec.size() + 10;

    TCHAR *FromBuf = new TCHAR[fromBufLength];
    TCHAR *ToBuf = new TCHAR[fromBufLength];

    shared_array<TCHAR> arrayPtr(FromBuf);
    shared_array<TCHAR> arrayPtr2(ToBuf);
    ZeroMemory(FromBuf, sizeof(TCHAR) * fromBufLength);
    ZeroMemory(ToBuf, sizeof(TCHAR) * fromBufLength);

    // 拼接移动自目录字符串
    int location = 0;
    TCHAR* tempBuf = FromBuf;
    for (int i = 0; i < srcPaths.size(); ++i)
    {
        const CString& filePath = srcPaths[i];
        if (i != 0)
        {
            location ++;
        }
        tempBuf = FromBuf + location;
        wcsncpy(tempBuf, (LPCTSTR)(filePath), filePath.GetLength());
        location += filePath.GetLength();
    }
    // 拼接移动到目录字符串
    location = 0;
    tempBuf = ToBuf;
    CString filePath;
    for (int i = 0; i < dstPaths.size(); ++i)
    {
        filePath = dstPaths[i];
        if (i != 0)
        {
            location ++;
        }
        tempBuf = ToBuf + location;
        wcsncpy(tempBuf, (LPCTSTR)(filePath), filePath.GetLength());
        location += filePath.GetLength();
    }
    tempBuf = NULL;

    FileOp.hwnd = NULL/*this->m_hWnd*/;
    FileOp.wFunc=FO_MOVE;
    FileOp.pFrom = FromBuf;
    FileOp.pTo = ToBuf;
    FileOp.fFlags = FOF_NOCONFIRMATION;
    FileOp.hNameMappings = NULL;
    int nOk=SHFileOperation(&FileOp);

Is there anything wrong?
It always say no XXX directory. XXX the dstPaths[0]....

A: By the look of it you are forming your pFrom and pTo lists wrongly.
You need to form them such that each has a NULL terminator between them and a double null terminator at the end.
An example re-implementation of your function would be:
TCHAR* tempBuf = FromBuf;
for (int i = 0; i < srcPaths.size(); ++i)
{
        const CString& filePath = srcPaths[i];
        _tcscpy_s( tempBuf, fromBufLength, filePath.GetString() );
        tempBuf += filePath.GetString() + 1; // Include null terminator in the increment.
}
*tempBuf = '\0'; // Add extra null terminator.

The main problems in your original code is that you are not payign attention to the required null terminators between each file name.  Have you tried running what you have through the debugger and looking at what FromBuf contains?  I suspect you would have seen the problem very quickly if you had.
Hope that helps!


text:
Q: When would I use @Bean instead of @Component? I'm confused as to a few things in Spring.
First, when would I want to use @Component over an explicit @Configuration class with a @Bean for what would have been a @Component?
The only reason I can think of for using @Component is to save myself the creation of a @Bean method in a @Configuration class. Are there other reasons?
That said, if I am using a @Configuration class it seems like I can hand code the wiring of these beans. IOW, where I did use @Inject on a @Component I can now explicitly specify dependencies in the @Bean constructor (when I create it in my bean method). So when would I want to use @Inject? I feel like I'm going down a rabbit hole here.
Are there any good tutorials or blogs that cover the best practices or rules for making these kinds of decisions?
Thanks

A: An example:
@Component
public class SomeComponent { }

The above will in practice create the same as:
public class SomeComponent { }
@Configuration
public class SomeComponentConfig {
    @Bean
    public SomeComponent someComponent() {
        return new SomeComponent();
    }
}

The advantage of @Component is clear: It is less code!
On the other hand, @Bean is powerful and has many use cases; for example if SomeComponent is in an existing library that you can't edit, or you simply don't want to clutter it with Spring or @Injectannotations.


text:
Q: how to open an array of object based on the name I have an array with multiple objects having the same name. How can I segregate the array based on the name?
I tried with map, filter but didn't work finally I used reduce also but not getting the output.
const result = Object.values(this.optionsArr.reduce((a, c) => {
        a[c.name] = a[c.name] || {name: c.name};
        a[c.name].options.push(c.options);
        return a;
      }, {})).map(item => ({...item, accessDetails: Object.values(item.accessDetails)}));

Input:
[
{name: "audio", options: [
    {name:'true', value: 'T'},
    {name:'false', value: 'F'},
    {name:'yes', value: 'Y'}]
},
{name: "video", options: [
    {name:'true', value: 'T'},
    {name:'false', value: 'F'},
    {name:'yes', value: 'Y'}]
},
{name: "call", options: [
    {name:'true', value: 'T'},
    {name:'false', value: 'F'},
    {name:'yes', value: 'Y'}]
}]

Expected Ouput:
const arr = [{name: "audio", options:{name:'true', value: 'T'}},
{name: "audio", options:{name:'false', value: 'F'}},
{name: "audio", options:{name:'yes', value: 'Y'}},
{name: "video", options:{name:'true', value: 'T'}},
{name: "video", options:{name:'yes', value: 'Y'}},
{name: "video", options:{name:'false', value: 'F'}},
{name: "call", options:{name:'true', value: 'T'}},
{name: "call", options:{name:'No', value: 'N'}},
{name: "call", options:{name:'false', value: 'F'}}];

A: Input is an array of object so array.map:
let newArray = []
input.map(function(item) {
  item.options.map(function(option) {
    newArray.push({name:item.name, options: option})
  })
})
console.log(newArray);

should work

A: You should use map to transform the array,
arr = arr.map((element) => {
    const temp = [];
    element.options.forEach(option => {
        temp.push({
            name: element.name,
            options: option
        });
    })
    return temp;
}).flat();

A: Yes, .reduce is the way to go, here is a way of doing it:

const input = [{name: "audio", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]},
    {name: "video", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]},
    {name: "call", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]}];

const output = input.reduce((acc, cur) => {
  const newEntries = cur.options.reduce((a, c) => ([...a, { ...cur, options: c }]), []);
  return [
      ...acc,
      ...newEntries
    ];
},[]);

console.log(output);

In this example I'm reducing the original array (input) and then I'm reducing each entry's options array to create a new element for each of them, and then I'm adding these new entries to the return array.

A: You can use the sort method and localeCompare.
Try This:
arr.sort((a, b) => a.name.localeCompare(b.name))

A: Try this:
let output = [];

input.map(item => {
  item.options.forEach(o => {
    output.push({
      name: item.name,
      options: {
        name: o.name,
        value: o.value
      }
    });
  });
});


text:
Q: Probability that a 5-card poker hand contains a flush or a three of a kind Please excuse me if I don't type this right, this is my first posted question. I hope I do this right....
I'm having problems with a question from my Intro to Math Analysis course. It is not from any book, but a worksheet that the professor made himself. I need to find the probability of getting a flush or a three of a kind in a 5-card poker hand. It is a standard deck, and I need to exclude "better hands", like straight flushes and full houses. I know the denominator is ${52\choose {5}}$. For the numerator I have calculated the following:
Number of ways to get a flush but not a straight flush: $4\cdot {13\choose {5}} -4 \cdot 10
$
Number of ways to get a three of a kind but not a full house: $13 \cdot {4\choose {3}} \cdot 4 \cdot{12\choose {1}}  \cdot4 \cdot{11\choose {1}} $
I know I need to add these together, and I know I don't have to worry about subtracting the number of hands that have been counted in both because you can't have a three of a kind of the same suit anyway. So I have a numerator of $114,932$. But this is far from the answer, which has a numerator of $60,020$. Please help. Thank you.

A: No that looks almost okay.  If Ace may be high or low, then:
$$\dfrac{(\binom {13}{5}-\binom{10}1)\binom 4 1 + \binom {13} 1\binom 4 3\binom {12} 2{\binom 41}^2}{\binom{52}5} =\dfrac{ 60,020}{2,598,960}$$
In the selection of the two singleton cards in the three-of-a-kind you used $12\times 11$ rather than $^{12}C_{2}$.


text:
Q: Trying to solve this inequality for a collection of sets Let $\mathcal{F}=\{A_1,A_2,A_3,...,A_n\}$ be a collection of non-empty sets (meaning $A_i's$ are non-empty sets).
$\textbf{Step 1}$
Find $A_i,A_j\in\mathcal{F}\ (i\neq j)$ such that $A_i\cap A_j\neq\emptyset$
$\textbf{Step 2}$
Redefine $\mathcal{F}$ as
$$\mathcal{F}=(\mathcal{F}\setminus\{A_i,A_j\})\cup \{A_i\setminus A_j,\,A_j\setminus A_i,\,A_i\cap A_j\} .$$
$\textbf{Step 3}$
$\textbf{Check if}$ $\forall A_i,A_j\in\mathcal{F} (i\neq j)$ we have $A_i\cap A_j=\emptyset$, then set $\mathcal{D}=\mathcal{F}$,
$\textbf{Otherwise}$ go back on $\textbf{Step 1}$, $\textbf{Step 2}$ and $\textbf{Step 3}$
$\textbf{ Now I am trying to prove mathematically:}$
$$|\mathcal{D}|\leq 2^n-1.$$
Any lead about how it can be proved mathematically?

A: I will assume that you know that $\vert \mathcal{P}(A)\vert=2^{\vert A\vert}$. We assume that $A_i\neq \emptyset$ and I prove the theorem by induction on $\vert \mathcal{F}\vert=n$. The case in which $\mathcal{F}$ has one element is trivial and so is the case in which $\mathcal{F}$ is empty. Now assume that the theorem holds for all collections of $n$ elements and let $\mathcal{F}=\{A_1,\dots, A_{n+1}\}$ now I apply the induction hypothesis to the first $n$ elements $\{A_1,\dots,A_n\}$ so by applying the steps $1$ to $3$ to this family of sets I get at most $2^n-1$ disjoint sets $B_1,\dots, B_k$ where $k\leq 2^n-1$. So we have that after applying such steps to $\mathcal{F}$ we have it will be of the form $\mathcal{F}=\{B_1,\dots,B_k,A_{n+1}\}$. Using the fact that the $B_j$ are all disjoint if I re apply the steps to $\mathcal{F}$ I get
\begin{equation*}
\mathcal{F}=\{B_1\setminus A_{n+1},B_1\cap A_{n+1},\dots, B_k\setminus A_{n+1}, B_1\cap A_{n+1}, A_{n+1}\setminus(B_1\cup\dots \cup B_k)\}
\end{equation*}
Meaning for each $i\leq k$ $\mathcal{F}$ contains $B_i\setminus A_{n+1}$ and $B_i\cap A_{n+1}$ and it will also contain the set $A_{n+1}\setminus(B_1\cup\dots \cup B_k)$. Some of these sets might be empty it doesn't matter what matters is at this point all the sets are pairwise disjoint and there can be no more than $2k+1\leq 2(2^n-1)+1=2^{n+1}-1$. I'm willing to add more details if needed.

A: Let $\mathcal G$ be the collection of sets of the form $\cup_{i=1}^nX_i$ where each $X_j$ is equal to either $A_j$ or $A_j^c$ (the complement set of $A_j$ in $\cup_{i=1}^nA_i$) and at least one of them is $A_j$. (These sets are pairwise disjoint but some of them may be empty.)
By induction, at each loop, any $A_i\in\mathcal F$ is a union of elements of $\mathcal G$.
Let $\mathcal D=\{B_1,\dots,B_d\}$ be the final collection of $d$ non-empty paiwise disjoint sets. Since the $B_j$'s are non-empty, we may choose, for each $j=1,\dots,d$, a non-empty $C_j\in\mathcal G$ such that $C_j\subset B_j$. And since the $B_j$'s are disjoint, the $C_j$'s are distinct.
Hence
$$|\mathcal D|=d\le|\mathcal G|\le 2^n-1.$$


text:
Q: Google Sheet Stuck and unable to update, too many old versions? TLDR:
Our Google Spreadsheet is broken and cannot be edited / saved. It keeps saying Trying to reconnect. To edit offline, turn on offline sync when you reconnect, and Reconnecting. Can it be due to the many versions saved? If so, what can be done if we don't want the sheet to change its ID?
Any help is highly appreciated!
Detailed Background:
We have a large Google Spreadsheet in our project (< 700k cells) and it's well under the 2 million cells size limit as described in here .
We have been programmatically updating this sheet by creating CSVs in the google drive with python, then using Google App Script to update the sheet with contents from the CSVs.
It has been fine for several weeks, today we started to have an issue, that is, when we manually open the sheet, it just keeps saying "Trying to reconnect. To edit offline, turn on offline sync when you reconnect", and "Reconnecting". We can make no changes to the sheets.
We tried to use different browsers (chrome, firefox, edge) and different OS (Windows, Mac), and we still have the same issue. So I don't think it's anything related to firewall / browser configuration.
We tried to make a copy of the sheet, and we are able to make changes to the copy. We can also access any other sheets and make changes without any problem.
The only difference between the actual sheet and the copied sheets is probably that the actual sheet has a lot of old versions (it has been updated every 3 minutes for weeks). Can that be a reason of failure to edit?
Another possibility is that many other scripts read this sheet. Can this be why? (It will be a pain to stop all the scripts / redirect all the scripts to another Spreadsheet)
Thanks a lot in advance!
Additional Details / Conclusions:

*

*Using a database is definitely a better idea than a spreadsheet for such a large scale dataset.

*An ".edu" domain was used. I believe we are using the G Suite version.

*Just like the PC case, I am unable to make any changes when I use mobile version on Android.

*From various sources, it seems that the old versions cannot be deleted (http://www.sevenminutescientist.com/2016/06/03/no-you-cannot-remove-a-revision-history-from-a-google-doc/)

*When I look into the version history, it shows the following: "Google Docs encountered an error. Please try reloading this page, or coming back to it in a few minutes." I am unable to access any of the old versions.

A: Having issues with Google Drive constantly disconnecting you in Chrome? Error message: "Trying to connect. To edit offline, turn on offline sync when you reconnect"
This issue was encountered on a PC running Windows 10 64bit and Google Chrome (happens in the 32-bit and 64-bit versions). It doesn't appear to happen in Firefox.
Cause: Kaspersky SSL Scanning (although it may still be an issue in Chrome as it doesn't happen with other browsers and will likely be fixed by one of the parties soon)
Solution: Disable Kaspersky 2015 Encrypted Connection Scanning. Settings > Additional > Network > Disable encrypted connection scanning. NOTE: even if you disable Kaspersky via the temporary disable feature Google Docs still doesn't work you have to turn off Encrypted Connection Scanning as it's obviously always running even when Kaspersky is temporarily stopped (another bug as turning Kaspersky off should disable this).


text:
Q: Anyone encounter the ecs agent changing file permissions on the containers We're using the ECS Agent container on Ubuntu 16.04.  The services' containers all start correctly and have the correct file permissions internally; the Dockerfile for each container creates a user called app for better security.
Somewhere along the way the file permissions inside the containers are changed to root:root which causes the app to stop functioning.
Has anyone encountered this?
Here's the code which creates the ECS agent.  It's a chef recipe.  Does any of the below look off to anyone?
*Note : the same set of services are installed on an ECS Optimized instance (which is of course based of Amazon linux) and all works fine.  So it's not an app related issue.  We are forced to move to Ubuntu by the security team.
platform = node['platform']
env = node.chef_environment

docker_image 'amazon/amazon-ecs-agent'

ENVIRONMENT = [
 'ECS_LOGFILE=/log/ecs-agent.log',
 'ECS_DATADIR=/data/',
 'ECS_ENABLE_TASK_IAM_ROLE=true',
 'ECS_ENABLE_TASK_IAM_ROLE_NETWORK_HOST=true',
 'ECS_CLUSTER=devops2',
 'ECS_AVAILABLE_LOGGING_DRIVERS=["json-file","syslog","awslogs"]',
 'ECS_AGENT_CONFIG_FILE_PATH=/etc/ecs/ecs.config',
 'ECS_ENGINE_AUTH_TYPE=dockercfg',
 "ECS_ENGINE_AUTH_DATA=#{node['common']['ECS_ENGINE_AUTH_DATA']}"
]

VOLUMES = [
  '/var/run/docker.sock:/var/run/docker.sock',
  '/var/log/ecs:/log',
  '/var/lib/ecs/data:/data'
]

# start the container and map it to port 8484
docker_container 'amazon-ecs-agent' do
  repo 'amazon/amazon-ecs-agent'
  tag 'latest'
  network_mode 'host'
  restart_policy 'on-failure'
  env ENVIRONMENT
  volumes VOLUMES
  action :run_if_missing
end


text:
Q: How can I use sed to extract lines between two patterns and do post processing on it in a loop? I want to do something like this. Say I have the text below:
Start-pattern
orange
apple
grape
orange
orange
End-pattern
#######
bla bla bla
########
Start-pattern
orange
apple
grape
apple
orange
End-pattern
#######
bla bla bla
########
Start-pattern
orange
orange
orange
End-pattern
#######
bla bla bla
########

Here I want to print how many oranges,apples and grapes are there in between each of Start-pattern and End-pattern.
In the above example, we have 3 "orange", 1 "apple" and 1 "grape" in between 1st Start-pattern and end-pattern. 2 "orange", 2 "apple" and 1 "grape" in 2nd SP and EP and so on.
Waiting for your valuable answers.

A: You can try this awk:
awk '$1 ~ /^Start-pattern$/{p=1;next} $1 ~ /^End-pattern$/{p=0; for (var in a) {print var,a[var];a[var]=""}; print "######"; next} p{a[$1]++}' file

More readable awk:
$1 ~ /^Start-pattern$/ {
    p=1;
    next
}
$1 ~ /^End-pattern$/ {
    p=0;
    for (var in a) {
        print var,a[var];
        a[var]=""
    }
    print "######";
    next
}
p {
    a[$1]++;
}

Explanation:
We can split this awk as 3 blocks of code.

*

*Check for Start-pattern pattern, then enable p=1.

*Check for End-pattern pattern, then disable p=0. Then, print a[] with corresponding count.

*This will store the number of occurrences of each item between these two patterns in an associative array.

A: This might work for you (GNU sed, echo, sort and uniq):
sed -nr '/Start/,/End/!b;/Start/h;//!H;/End/!b;x;s/^[^\n]*\n(.*)\n.*/echo "\1"|sort|uniq -c/e;s/\n//g;p' file

Turn on seds grep like nature with -n. Store lines between Start and End in the hold space (HS) and on encountering the End string, replace the pattern space (PS) from the HS. Remove the start and end header/footers and using the evaluate flag of the substitution command; echo the enclosed lines into a sort and then count the unique lines using the uniq command. Remove any newlines and print the contents of the PS.


text:
Q: jQuery two childrens selector It's possible to select two childrens without repeating parent element ?
$('section#id > h4, section#id > hr ').hide(); // OK

$('section#id > h4 + hr ').hide(); // Maybe ?

Thanks !

A: You can use  .children() method

Get the children of each element in the set of matched elements, optionally filtered by a selector.

$('section#id').children('hr, h4').hide();

OR, .find() method

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

$('section#id').find('> hr, > h4').hide();

The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree.

A: Not within a selector itself.
However, you can use find() after specifying the parent
$('section#id').find(' > h4,> hr ').hide();


text:
Q: python pandas crosstab sumproduct square matrix i'm looking for help creating a sub-dataframe from an existing dataframe using a sumproduct-like function. I want to convert this table, into a small sum product using the column headings:
    dan ste bob
t1  0   2   0
t2  2   0   1
t3  2   1   0
t4  1   0   2
t5  0   1   2

Column heading become index and sum product is the value:
    dan ste bob
dan 9   2   4
ste 2   6   2
bob 4   2   9

dan x dan = 9  (0*0)+(2*2)+(2*2)+(1*1)+(0*0)
Thanks in advance!

A: You can use the dot with its transpose:
In [11]: df.T.dot(df)
Out[11]:
     dan  ste  bob
dan    9    2    4
ste    2    6    2
bob    4    2    9

A: You should using .dot this is just for fun
df1=pd.DataFrame(index=df.columns,columns=df.columns)
df1.apply(lambda x : [sum(df[x.name]*df[y]) for y in x.index])
Out[65]:
     dan  ste  bob
dan    9    2    4
ste    2    6    2
bob    4    2    9


text:
Q: Keep li selected after filter search angular js I have three list items in a ul. There are three first names: Roy, Sam, David. I could toggle each li on click just fine. However, when I do a search and come back, the selected items are not highlighted anymore. Any suggestion on how I could keep them selected. Here is the my js fiddle:

var app = angular.module("ap",[]);

app.controller("con",function($scope){
  $scope.firstNames = ['Sam', 'David', 'Roy'];

});

app.directive('toggleClass', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('click', function() {
                element.toggleClass(attrs.toggleClass);
            });
        }
    };
});
.active {
  background-color:red;
}

<input type="text" ng-model="searchText"/>

{{firstName}}

http://jsfiddle.net/baa2G/126/
Thanks.

A: Edited, because I didn't read your question properly!
Use Angular to store your selections in your controller.
I've modified your firstNames to users and changed each entry to an object.
$scope.users = [
    {name: 'Sam', isSelected, false},
    {name: 'David', isSelected, false},
    {name: 'Roy', isSelected, false}
];
$scope.toggleSelection(user){
    user.isSelected = !user.isSelected;
}

{{user.name}}

A: Use ng-class instead. Always think about how to use your data model first...and let it control the view

{{firstName}}

Controller:
   $scope.selected = selected = {};
   $scope.toggleSelected = function(name){
      selected[name] = !selected[name];
   }

Demo


text:
Q: How to maintain MainActivity UI and state when returning from SettingsActivity I am building a weather app, and I'm having trouble with the "back" functionality from my Settings page.  As you can see in the gift below, I switch the city to New Orleans, and then open the settings page.  When I click the back button from the settings page, it goes back, but reloads the MainActivity, which sets the city to the user's default, as it would when they first open the application.  I would like for it to go back to the screen exactly as it was when the user opened the settings, without reloading the data.  The data is retrieved in onCreateView() of MasterFragment, which is the main weather screen shown here.
SettingsFragment extends PreferenceFragmentCompat and is in the xml of SettingsActivity, which is launched from MainActivity like this:
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);

I do not have onBackPressed() implemented in SettingsActivity.
I've gone through several SO questions about back stacks, but none of them seem to work with the setup that I have.
gif of current behavior
Edit:
MainActivity.java (the activity_main.xml file is the container for the main weather fragment)
public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private DrawerLayout drawer;
    private NavigationView navigationView;
    private SharedPreferences prefs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        prefs = getSharedPreferences("com.jggdevelopment.simpleweather", Context.MODE_PRIVATE);
        if (prefs.getBoolean("useDarkTheme", false)) {
            setTheme(R.style.DarkTheme);
        } else {
            setTheme(R.style.LightTheme);
        }

        super.onCreate(savedInstanceState);

        // Setup the content view
        setContentView(R.layout.activity_main);

        drawer = findViewById(R.id.drawer_layout);
        navigationView = findViewById(R.id.nav_view);

        navigationView.setNavigationItemSelectedListener(this);

        // This is a mostly blank activity, so MasterFragment needs to be pushed onto the content_frame
        MasterFragment master = new MasterFragment();
        pushToFragmentManager(getSupportFragmentManager(), R.id.content_frame, master, false);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_settings) {
            Intent intent = new Intent(this, SettingsActivity.class);
            startActivity(intent);
        }

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}


text:
Q: get touchstart coordinate on current element So I have an element that looks like this:
 ____________________________________
/                                    \
|                                    |
|                                    |
+------------------------------------+
|                                    |
|                                    |
|                                    |
+------------------------------------+
|                                    |
|                                    |
\____________________________________/

I have attached a touchstart listener to it, like this:
    other_options.addEventListener('touchstart', function(e) {
        event.preventDefault();
    }, false);

What I want to do, and I've already looked through the values of 'e' but I can't find any value consistent enough (values don't seem right to me when I try them) to do what I want.
I know the size of those rows. I just want to be able to take the Y coordinate of where the touchstart event fired, being 0 the upper coordinate of the element. That way, Math.floor(y / ROW_SIZE) will give me the row the touchstart event was started on.

A: You have to access like this.
e.touches[0].clientX/clientY.

the number touchs and touch information can be access via e.touches.
Take look at this FAQ.
How to get the  x/y coordinates in touch events ?
here is the touch event documentation.
By the way, events will return x/y coordinates relative to the window only. we can't changed that. what you can do this. top= 0 - element.top; x= clientx-top.

A: It is better to use getBoundingClientRect() method to calculate top & left values of an element.
The above approach, element.top, may not give top & left values relative to the viewport if the element is inside another container.
So to calculate touch co-ordinates relative to the element, we can do as below.
var rect = element.getBoundingClientRect();
xCoordinate = event.touches[0].clientX - rect.left;
yCoordinate = event.touches[0].clientY - rect.top;

To find out more about getBoundingClientRect() method, click here.


text:
Q: Smarty, count length of array key string? {$smarty.post.email} outputs "john@yahoo.com"
{$smarty.post.email|count} outputs "1" instead of "14" - string length.
{$smarty.post.email[0]|count} outputs "1" as well.
How can i find length of key named "email"?

A: use
{$smarty.post.email|count_characters:true}

source : http://www.smarty.net/docsv2/en/language.modifier.count.characters.tpl

A: $count = strlen($smarty.post.email);

$count = strlen($smarty[post][email]);

strlen returns the length of a string. Key names are strings.
count returns the number of keys in an array.


text:
Q: Writing C++ .dlls and access them Unity-3D I have been writing a basic dll in c++ with the end-goal of accessing some of it's methods in Unity. I started this tutorial in : http://docs.unity3d.com/Documentation/Manual/Plugins.html which helped me understand the concept but after I write the class in Unity and access the .dll it throws me an entry point exception error when I hit play. And yes, I have a plugin folder where i keep my .dll file.

EntryPointNotFoundException: addition PluginImport.Start () (at
  Assets/Test/PluginImport.cs:20)

Here is my .dll class.
The Header File:
#ifndef MATHASSISTANT_ARITHMETICS_ARITHMETIC_H
#define MATHASSISTANT_ARITHMETICS_ARITHMETIC_H

namespace ma{
    extern "C"
    {
    class Arithmetic
    {
    public:
        Arithmetic();//ctor
    protected:
        virtual ~Arithmetic();//dtor
    public:

        static __declspec(dllexport) float addition(float& val_1, float& val_2);
        static __declspec(dllexport) float substraction(float& val_1, float& val_2);
        static __declspec(dllexport) float multiplication(float& val_1, float& val_2);
        static __declspec(dllexport) float division(float& val_1, float& val_2);
    };
    }
}

#endif

This is the source file:
#include "Arithmetic.h"
#include <stdexcept>

namespace ma{

    Arithmetic::Arithmetic(){
        //TODO: Initialize items here
    }
    Arithmetic::~Arithmetic(){
        //TODO: Release unused items here
    }

    //FUNCTION: adds two values
    float Arithmetic::addition(float& val_1, float& val_2){
        return val_1 + val_2;
    }
    //FUNCTION: substracts two values
    float Arithmetic::substraction(float& val_1, float& val_2){
        return val_1 - val_2;
    }
    //FUNCTION: multiplies two values
    float Arithmetic::multiplication(float& val_1, float& val_2){
        return val_1 * val_2;
    }
    //FUNCTION: divide two values
    float Arithmetic::division(float& val_1, float& val_2){
        if(val_2 == 0)
            throw new std::invalid_argument("denominator cannot be 0");
        return val_1 / val_2;
    }
}

This is the class I created in Unity3D:
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.InteropServices;

public class PluginImport : MonoBehaviour
{
    //Lets make our calls from the Plugin
    [DllImport("Arithmetic")]
    private static extern float addition(float val_1, float val_2);
    [DllImport("Arithmetic")]
    private static extern float substraction(float val_1, float val_2);
    [DllImport("Arithmetic")]
    private static extern float multiplication(float val_1, float val_2);
    [DllImport("Arithmetic")]
    private static extern float division(float val_1, float val_2);

    void Start()
    {
        Debug.Log(addition(5, 5));
        Debug.Log(substraction(10, 5));
        Debug.Log(multiplication(2, 5));
        Debug.Log(division(10, 2));
    }
}

If anyone can help me find what I am doing wrong I will be most appreciative. Thanks in advance!

A: The reason you're getting this error and the reason why you've found that you can access it by using the obfuscated name of the method is because you forgot to correctly import each method on the C# side using the correct CallingConvention.
For example, your Addition method should look like this:
[DllImport("Arithmetic"), EntryPoint = "addition", CallingConvention = CallingConvention.Cdecl)]
private static extern float addition(float val_1, float val_2);

A: I found the answer. I had to do some tweaking to the code but basically I will show you:
This is my MathHelper.dll
Header:
#ifndef MATHASSISTANT_ARITHMETICS_ARITHMETIC_H
#define MATHASSISTANT_ARITHMETICS_ARITHMETIC_H
#include <Windows.h>

#include <WbemCli.h>
namespace ma{
    extern "C"
    {
    class Arithmetic
    {
    public:
        Arithmetic();//ctor
    protected:
        virtual ~Arithmetic();//dtor
    public:
        BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID);
        __declspec(dllexport) float addition(float val_1, float val_2);
        __declspec(dllexport) float substraction(float val_1, float val_2);
        __declspec(dllexport) float multiplication(float val_1, float val_2);
        __declspec(dllexport) float division(float val_1, float val_2);
    };
    }
}

#endif

The source file:
#include "Arithmetic.h"
#include <stdexcept>

namespace ma{

    Arithmetic::Arithmetic(){
        //TODO: Initialize items here
    }
    Arithmetic::~Arithmetic(){
        //TODO: Release unused items here
    }

    //FUNCTION: adds two values
    __declspec(dllexport) float addition(float val_1, float val_2){
        return val_1 + val_2;
    }
    //FUNCTION: substracts two values
    __declspec(dllexport) float substraction(float val_1, float val_2){
        return val_1 - val_2;
    }
    //FUNCTION: multiplies two values
    __declspec(dllexport) float multiplication(float val_1, float val_2){
        return val_1 * val_2;
    }
    //FUNCTION: divide two values
    __declspec(dllexport) float division(float val_1, float val_2){
        if(val_2 == 0)
            throw new std::invalid_argument("denominator cannot be 0");
        return val_1 / val_2;
    }
}

In Unity-3D here is the class:
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.InteropServices;

public class PluginImport : MonoBehaviour
{
    //Lets make our calls from the Plugin
    [DllImport("MathAssistant", EntryPoint = "?addition@ma@@YAMMM@Z")]
    private static extern float addition(float val_1, float val_2);
    [DllImport("MathAssistant", EntryPoint = "?substraction@ma@@YAMMM@Z")]
    private static extern float substraction(float val_1, float val_2);
    [DllImport("MathAssistant", EntryPoint = "?multiplication@ma@@YAMMM@Z")]
    private static extern float multiplication(float val_1, float val_2);
    [DllImport("MathAssistant", EntryPoint = "?division@ma@@YAMMM@Z")]
    private static extern float division(float val_1, float val_2);

    void Start()
    {
        Debug.Log(addition(5, 5));
        Debug.Log(substraction(10, 5));
        Debug.Log(multiplication(2, 5));
        Debug.Log(division(10, 2));
    }
}

The error I was getting before was that the code was not recognizing my functions, addition, divide, etc. Even though I was declaring them correctly. However, when I created my .dll it somehow changed the name of my function, i.e: "addition" became: "?addition@ma@@YAMMM@Z". I went to this website and it made it clear: http://msdn.microsoft.com/en-us/library/system.entrypointnotfoundexception(v=vs.110).aspx and that is where I realized that the problem was not in my structure or the logic but in the actual function name once it was converted into .dll. If that is your case then what you need is a tool to help you find what your function name is. I used DependancyWalker.exe. Here is the is the site: http://dependency-walker.en.softonic.com/ That was my litle adventure trying to solve this issue. Hopefully this will help out anyone who has run into thi sisuue and has not resolved it yet. Power to the user!


text:
Q: Emulating sscanf's %*s with istreamstream
Possible Duplicate:
C++ alternative to sscanf()

I have the following line of code
sscanf(s, "%*s%d", &d);

How would I do this using istringstream?
I tried this:
istringstream stream(s);
(stream >> d);

But it is not correct because of *s in sscanf().

A: The %*s used with sscanf basically means to ignore a string (any characters up until a whitespace), and then after that you're telling it to read in an integer (%*s%d). The asterisk (*) has nothing to do with pointers in this case.
So using stringstreams, just emulate the same behaviour; read in a string that you can ignore before you read in the integer.
int d;
string dummy;
istringstream stream(s);

stream >> dummy >> d;

ie. With the following small program:
#include <iostream>
#include <sstream>
using namespace std;

int main(void)
{
   string s = "abc 123";

   int d;
   string dummy;
   istringstream stream(s);

   stream >> dummy >> d;

   cout << "The value of d is: " << d << ", and we ignored: " << dummy << endl;

   return 0;
}

the output will be: The value of d is: 123, and we ignored: abc.

A: There is no pointer manipulation in your code.
As AusCBloke has said, you need to read the all of the unwanted characters before the int into a std::string. You also want to ensure that you handle malformed values of s, such as those with any integers.
#include <cassert>
#include <cstdio>
#include <sstream>

int main()
{
    char s[] = "Answer: 42. Some other stuff.";
    int d = 0;

    sscanf(s, "%*s%d", &d);
    assert(42 == d);

    d = 0;

    std::istringstream iss(s);
    std::string dummy;
    if (iss >> dummy >> d)
    {
        assert(dummy == "Answer:");
        assert(42 == d);
    }
    else
    {
        assert(!"An error occurred and will be handled here");
    }
}