Silent printing in electron

Question: I am currently building an electron app. I have a PDF on my local file system which I need to silently print out (on the default printer). I came across the node-printer library, but it doesn't seem to work for me. Is there an easy solution to achieve this?
Answer: Well first of all it is near impossible to understand what you mean with "silent" print. Because once you send a print order to your system printer it will be out of your hand to be silent at all. On Windows for example once the order was given, at least the systemtray icon will indicate that something is going on. That said, there are very good described features for printing with electron even "silent" is one of them:
You need to get all system printers if you do not want to use the default printer:
contents.getPrinters()

Which will return a PrinterInfo[] Object.
Here is an example how the object will look like from the electron PrtinerInfo Docs:
{
  name: 'Zebra_LP2844',
  description: 'Zebra LP2844',
  status: 3,
  isDefault: false,
  options: {
    copies: '1',
    'device-uri': 'usb://Zebra/LP2844?location=14200000',
    finishings: '3',
    'job-cancel-after': '10800',
    'job-hold-until': 'no-hold',
    'job-priority': '50',
    'job-sheets': 'none,none',
    'marker-change-time': '0',
    'number-up': '1',
    'printer-commands': 'none',
    'printer-info': 'Zebra LP2844',
    'printer-is-accepting-jobs': 'true',
    'printer-is-shared': 'true',
    'printer-location': '',
    'printer-make-and-model': 'Zebra EPL2 Label Printer',
    'printer-state': '3',
    'printer-state-change-time': '1484872644',
    'printer-state-reasons': 'offline-report',
    'printer-type': '36932',
    'printer-uri-supported': 'ipp://localhost/printers/Zebra_LP2844',
    system_driverinfo: 'Z'
  }
}

To print your file you can do it with
contents.print([options])

The options are descriped in the docs for contents.print():

options Object (optional):
silent Boolean (optional) - Don't ask user for print settings. Default is false.
printBackground Boolean (optional) - Also prints the background color and image of the web page. Default is false.
deviceName String (optional) - Set the printer device name to use. Default is ''.

Prints window's web page. When silent is set to true, Electron will pick the system's default printer if deviceName is empty and the default settings for printing.
Calling window.print() in web page is equivalent to calling webContents.print({silent: false, printBackground: false, deviceName: ''}).
Use page-break-before: always; CSS style to force to print to a new page.
So all you need is to load the PDF into a hidden window and then fire the print method implemented in electron with the flag set to silent.
// In the main process.
const {app, BrowserWindow} = require('electron');
let win = null;

app.on('ready', () => {
  // Create window
  win = new BrowserWindow({width: 800, height: 600, show: false });
  // Could be redundant, try if you need this.
  win.once('ready-to-show', () => win.hide())
  // load PDF.
  win.loadURL(`file://directory/to/pdf/document.pdf`);
 // if pdf is loaded start printing.
  win.webContents.on('did-finish-load', () => {
    win.webContents.print({silent: true});
    // close window after print order.
    win = null;
  });
});

However let me give you a little warning:
Once you start printing it can and will get frustrating because there are drivers out there which will interpret data in a slightly different way. Meaning that margins could be ignored and much more. Since you already have a PDF this problem will most likely not happen. But keep this in mind if you ever want to use this method for example contents.printToPDF(options, callback). That beeing said there are plently of options to avoid getting frustrated like using a predefined stylesheet like descriped in this question: Print: How to stick footer on every page to the bottom?
If you want to search for features in electron and you do not know where they could be hidden, all you have to do is to go to "all" docs and use your search function: https://electron.atom.io/docs/all/
regards,
Megajin
Comment: Your question was to "silently" print a PDF. In electron you have to load your content to print it. Since you want it to be "silent" you have to load it into a invisible window and instantly print it with the given commands I've provided to you.
Comment: And how do I load my pdf into an invisible window?
Comment: As noted from be in my answer you can see everything in the [electron docs for hide window](https://electron.atom.io/docs/all/#winhide). The usage is as follows: `win.hide()`. That's it. Consider accepting my answer if it was helpful to you
Comment: I guess the question is more about the pdf loading, not about the invisible window, sorry
Comment: Right, everything is clear for me, I just wonder how the content of a PDF-file can be loaded into a `BrowserWindow`
Comment: You can try it with [loadURL](https://electron.atom.io/docs/api/web-contents/#contentsloadurlurl-options) just use this prefix `file://` and then the link to your pdf like: `loadURL('file://path/to/my/pdf/myDoc.pdf')`
Comment: I've added some code for you so you have a good starting point. See my edited answer.
Comment: `contents.getPrinters()` is not a function is it deprecated ?
Comment: @Jeevan what makes you think that `contents.getPrinters();` is deprecated? According to the docs it is not deprecated: https://electron.atom.io/docs/all/#contentsgetprinters . All deprecated functions are listed in the docs as well with the necessary information how to replace it.
Comment: @Megajin I have updated electron its working fine now...Its available in electron > 1.7 version
Comment: @Jeevan I'm glad it worked out for you =). They should add a Tag saying on which version the function was added, like in nodejs...
Comment: @Megajin : How do i check the printer status, whether it's on,idle,busy or unavailbale. The status in the json returned is always 3 and  'printer-is-accepting-jobs' is 'true'
Comment: @hablema it depends, please keep in mind that printers may behave differently. For the best results you have to look up the `status-codes` of the given printer. A printer is accepting jobs even if there are errors sometimes. That is what I meant by 'printers behave differently'. Google for your printer and the given codes, that will make things clearer in your case. BTW, updating electron is also a good idea, new features might help as well.
Comment: @Megajin this appears to be broken/not working, [here's a similar question](https://stackoverflow.com/q/49650784/1768303). Am I missing something?
Comment: @Noseratio I will answer that question, it is not really broken but unnecessarily complex. PDFs work differently on different APPs... I did run into this problem twice. However give me some time and I will answer the question linked by you.
Comment: @Megajin, thank you, take your time. I'd be happy to reward your answer with another bounty here. For now, [PDF.js](https://mozilla.github.io/pdf.js/) solves the problem with rendering/previewing individual pages, but as to printing itself, it appears Electron (at the time of this posting) just lacks the proper printing APIs. E.g., you can't set paper size/landscape portrait mode etc. Moreover, both PDF.js and Electron when printing produce rasterized print-outs, unlike Chrome PDF Viewer. That can be seen if you print to "Microsoft Print to PDF" and the view/scale the output.
Comment: So for now I think it'll be a combination of PDF.js (for UI in the Electron's Renderer process) and PDFium (for actual printing from the Main process).
Comment: How do I print from a specific printer?
Comment: @toni Just use `contents.getPrinters()`. That will return a `PrinterInfo[]` object. You can then search for your desired printer in there. Once you have found your printer name, you can use this method: `webContents.print({silent: false, printBackground: false, deviceName: '_YOUR_PRINTER_NAME_'})` just replace `_YOUR_PRINTER_NAME_` with your actual printer name.
Answer: I recently published NPM package to print PDF files from Node.js and Electron. You can send a PDF file to the default printer or to a specific one. Works fine on Windows and Unix-like operating systems: https://github.com/artiebits/pdf-to-printer.
It's easy to install, just (if using yarn):
yarn add pdf-to-printer

or (if using npm):
npm install --save pdf-to-printer

Then, to silently print the file to the default printer you do:
import { print } from "pdf-to-printer";

print("assets/pdf-sample.pdf")
  .then(console.log)
  .catch(console.error);

Answer: To my knowledge there is currently no way to do this directly using Electron because while using contents.print([]) does allow for 'silently' printing HTML files, it isn't able to print PDF views. This is currently an open feature request: https://github.com/electron/electron/issues/9029
Edit: I managed to work around this by converting the PDF to a PNG and then using Electron's print functionality (which is able to print PNGs) to print the image based view. One of the major downsides to this is that all of the PDF to PNG/JPEG conversion libraries for NodeJS have a number of dependencies, meaning I had to implement them in an Express server and then have my Electron app send all PDFs to the server for conversion. It's not a great option, but it does work.
Comment: can you show your code. i have same task. need to print image from electron/express.

Silent printing in electron


Google Cloud Platform Logging: How to search wildcard strings in all logs

Question: How does one do a simple wildcard search in all the logs? I hate GCP's query language and their documentation is just confusing.
I tried:
text:*MY_STRING_TO_SEARCH_FOR*

Doesn't work.
Answer: Use regex instead: text=~".*MY_STRING_TO_SEARCH_FOR.*"
Answer: Use : character followed by the string:
text:"MY_STRING_TO_SEARCH_FOR"

This seems to do the trick without using regex syntax and needing to escape characters. According to the docs:

:           "has" matches any substring in the log entry field

Bonus: If you want to exclude the text, put a - minus sign before the key, eg:
-text:"EXCLUDE_THIS..."

Answer: Commonly used matching operator in GCP:

=: equals
!=: not equal
=~: regex match
!~: regex unmatch
:: contains

Examples:

textPayload = 'foo': check if textPayload is foo
textPayload != 'foo': check if textPayload is not foo
textPayload =~ '.*foo.*': check if textPayload contains foo somewhere
textPayload !~ '.*foo.*': check if textPayload does not contain foo somewhere
textPayload:'foo': check if textPayload contains foo somewhere

For a definitive guide on log query language, check the official doc here: https://cloud.google.com/logging/docs/view/logging-query-language


Using Crypto-JS (commonjs) in titanium

Question: I am not familiar with commonjs conception, so my strategy might be basically wrong..
I want to use CryptoJS.HMAC() and CryptoJS.SHA256 in titanium
I have downloaded CryptoJS v3.1.2.zip from here.
then copy all files under Resources/CryptJS/ .
then I add this last line in core.js
    return C;
}(Math));

module.export = CryptoJS;  //add this line

now in my app.js
var CryptoJS = require('./CryptoJS/components/core');

CryptoJS.HMAC(CryptoJS.SHA256, dateStamp,  testKey, { asBytes: true});

however it shows

undefined is not a function  error when I call CryptoJS.HMAC()
Can I have help?
Answer: You find a commonJS version of Crypto Js on npm: https://www.npmjs.com/package/browserify-cryptojs
Maybe you got more luck with that!
Answer: Try adding an s to export, so it becomes:
module.exports = CryptoJS;  //add this line

Using Crypto-JS (commonjs) in titanium


Easiest way to implement Watson Language translation to Watson Assistant?

Question: I'd like to know the easiest way to integrate IBM Language Translation to my current IBM Watson Assistant. I think I can do it through Cloud Functions, but I'm not sure how.
I already read the GitHub Sample Watson app, but it wasn't clear to me how ti implement it.
Comment: I would recommend asking on Slack as it is more of a discussion: http://wdc-slack-inviter.mybluemix.net/
Answer: Hi you can indeed use a Webhook for your use case.
You can put the URL of the Language Translator-Service (e.g. https://gateway.watsonplatform.net/language-translator/api/v3/translate?version=2018-05-01) as URL of your Webhook within watson assistant.
You can find an example in the docs here:


Heapreplace and ordering

Question: I have a list (or heap) of elements and I want to replace the element with the lowest value with a new element of higher value. However if there are multiple elements in the heap with this lowest value, I expect to replace the last element.
Example 1 (works as expected):
input:
n = 7
new_element = 1
hlist = [0 for x in range(n)]
hp.heapreplace(hlist,new_element)
hlist

output:
[0, 0, 0, 0, 0, 0, 1]

Example 2 (doesn't work as expected):
input:
n = 10
new_element = 1
hlist = [0 for x in range(n)]
hp.heapreplace(hlist,new_element)
hlist

output:
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0]

The expected output is:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1]

With n in [1,2,...,9,10] it works when n in [1, 2, 3, 6, 7].
Comment: The "last element" isn't a meaningful location in a heap.  *Any* leaf node of the tree is a perfectly valid place to put the new, larger value.
Answer: The order you see inside a heap, is not necessarily ascending or descending inside the list that stores the values. So you need to sort it out before printing. According to the documentation, you can define a function named heapsort to sort the heap.
from heapq import *

def heapsort(iterable):
    h = []
    for value in iterable:
        heappush(h, value)
    return [heappop(h) for i in range(len(h))]

n = 7
new_element = 1
hlist = [0 for x in range(n)]
heapify(hlist)
heapreplace(hlist,new_element)
print(heapsort(hlist))

and the output will be :
[0, 0, 0, 0, 0, 0, 1]

Also you can solve this problem using lists.
n = 7
new_element = 1
hlist = [0 for x in range(n)]
min_value = min(hlist)
for i in range(n-1,-1,-1):
    if hlist[i]==min_value:
        hlist[i] = new_element
        break

and the output will be :
[0, 0, 0, 0, 0, 0, 1]

Heapreplace and ordering


Find Data Patterns from Database automatically

Question: We want to Extract Data Patterns from Data smartly and automatically.
We have the following Phone Database Struture (Few Fields noted to give example)-
PhoneName(string), LaunchDate(Date), LaunchPrice(Currency), AmoutOfRam(Number), IsTouchScreen(Bit), IsProximitySensor(Bit), IsCompassSensor(Bit)
We have around 1500 phones in database. We want to derive smart rules like-

If the launchdate is 2016 and LauchPrice is above 200$ then AmountOfRam will be more than 2GB.
If the phone has a TouchScreen than it will definitely have a ProximitySensor.
If the launchdate is 2016 and LauchPrice is above 400$ then it will Definitely have a Compass.

Analyzing the data in the database, we want an algorithm to AUTOMATICALLY find these patterns.
Can someone suggest a framework, reliable technique to do this? Any starting point shall help as well.
Regards,
Swapneel Shah
Answer: Discretize the numerical attributes, and use association rule mining.
For details, see any textbook on data mining. Your question is too brad to be answered in this format - the answer fills a chapter of an introductory book.
Comment: Thank you for your response! I actually expected this to be a common problem and we should by now have a ready App Dev framework that can do most of the work. Something like Business Intelligence does with SQL server.

Yeah, I am anyway reading a Data Mining Book over the weekend. :)
Answer: After spending some time over reading a Data Mining book, and Google search, use BI (Business Intelligence) algorithms with MS SQL server.
Here is the link - https://msdn.microsoft.com/en-us/library/ms175595.aspx
[And there should be parallel solutions with databases as well]
All the basic algorithms are available and can be used with a Quick Configuration Wizard.


css3 and dreamweaver

Question: i have just downloaded dreamweaver cs5.5 and am trying to apply css3 to my page, however although my current css is working fine both in dreamweaver and other coders the new css3 is not being applied.
eg i am trying to apply border-radius, although it is showing up in my css list as i type it out (unlike microsoft expression 4, which is'nt although i believe it should), it is not being applied to the actual page.
i have also tried using box-shadow, and linear-gradient, both unsuccessfully which made me believe that it is a css3 issue.
could it be something like setting up dreamweaver to accept css3, (ticking/unticking something in settings).
i am a beginner, any help would be appreciated and also i have looked it up before submitting q, but it seems not much info on css3 and especially css3 with dreamweaver.
thanks in advance
Comment: Which browser are you testing in?
Comment: IE9 doesn't support gradients without the use of [`filter`](http://msdn.microsoft.com/en-us/library/ms532997(v=vs.85).aspx).
Answer: Did you make sure to include properties for all browsers? also, can we see your css?
Cross compatible linear gradient needs to look like this:
<code>linear-gradient(bottom, rgb(48,54,48) 0%, rgb(54,61,54) 100%);
-o-linear-gradient(bottom, rgb(48,54,48) 0%, rgb(54,61,54) 100%); /*opera*/
-moz-linear-gradient(bottom, rgb(48,54,48) 0%, rgb(54,61,54) 100%);/*mozilla*/
    -webkit-linear-gradient(bottom, rgb(48,54,48) 0%, rgb(54,61,54) 100%);/*chrome*/
-ms-linear-gradient(bottom, rgb(48,54,48) 0%, rgb(54,61,54) 100%);/*IE*/
</code>
Comment: #box {
  border: 1px solid #696;
  padding: 60px 0;
  text-align: center; width: 200px;
  border-radius: 8px;
  box-shadow: #666 0px 2px 3px;
  background: #EEFF99;
  background: linear-gradient(#EEFF99, #66EE33);
  font-family:Tahoma, Geneva, sans-serif
  }
Comment: i tried ur methods using moz and webkit also didnt work, the prob is i cant view any implementations in dreamweaver in the first place let alone browser.
Comment: Probably is a Dreamweaver menu item in need of ticking, then.  My only other concern is that maybe dreamweaver isn't smart enough to recognize linear-gradient in its current context and needs to see the gradient explicitly under the background-image attribute.
Answer: Please see what browser you are using Internet explorer 8 and below may not support the css3 newly introduced styles.check it in a browser like chrome. Also refer to the answer from @rfinz you can see how he does it for different browsers. You probably have to work along the same lines

css3 and dreamweaver


Undefined columns selected when performing TukeyHSD

Question: I am very new to R and coding in general, so I apologize in advance for anything that may seem silly.
I performed an ANOVA and wanted to do a TukeyHSD on my data. At first, it worked fine. Then I created two data sets. In each one, I sorted my data to include just one of the two dose types. I then go on to perform the ANOVA (which works), but the Tukey yields this error

-[.data.frame`(mf, mf.cols[[i]]) : undefined columns selected.

What does that mean? I search the names of the columns in my newly created data set and they are all present.
Thank you so much!!
Here is the dataset I created and the error I received.
df1 <- Flor_Group_1_2019_EC[Flor_Group_1_2019_EC$Dose=="IM", ]
df2 <- Flor_Group_1_2019_EC[Flor_Group_1_2019_EC$Dose=="SC", ]
aov1 = aov(`CFU/g`~Treatment+`Time Point`, data=df1)
    summary(aov1)
              Df    Sum Sq   Mean Sq F value   Pr(>F)
Treatment      3 3.068e+15 1.023e+15   7.774 7.98e-05 ***
`Time Point`  16 2.065e+16 1.291e+15   9.810 7.20e-16 ***
Residuals    134 1.763e+16 1.316e+14
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
1 observation deleted due to missingness
TukeyHSD(aov1)

Error in [.data.frame(mf, mf.cols[[i]]) : undefined columns selected

colnames(df1)
[1] "Steer"      "Dose"       "Time Point" "Treatment"  "Average"
[6] "CFU/g"      "Log"

Answer: After going through some old source code, I figured this had to do with the naming in my data set.
This is because for my data,like in the data in this post, the naming convention is not very friendly. While we can add "backticks"(``) to names, it is sometimes difficult to use those when programming with base R based functions. The solution then is to rename as follows:
# base
names(df1) <- gsub("CFU\\/g","CFU",names(df1))
names(df1) <- gsub("Time Point","time",names(df1))
# tidyverse
dplyr::rename(df1, CFU = `CFU/g`,
time = `Time Point`)

You can then rebuild your models and redo the TukeyHSD:
df1 <- Flor_Group_1_2019_EC[Flor_Group_1_2019_EC$Dose=="IM", ]
df2 <- Flor_Group_1_2019_EC[Flor_Group_1_2019_EC$Dose=="SC", ]
aov1 = aov(CFU~Treatment+ time , data=df1)
TukeyHSD(aov1)

NOTE: I cannot provide a reproducible example because I cannot readily create an example dataset. I however did solve this issue as stated in this answer.


LaTeX Optional Arguments

Question: How do you create a command with optional arguments in LaTeX?
Something like:
\newcommand{\sec}[2][]{
    \section*{#1
        \ifsecondargument
            and #2
        \fi}
    }
}

Then, I can call it like
\sec{Hello}
%Output: Hello
\sec{Hello}{Hi}
%Output: Hello and Hi

Comment: Relevant question: [Different command definitions with and without optional argument](http://tex.stackexchange.com/q/308/1347).
Answer: Example from the guide:
\newcommand{\example}[2][YYY]{Mandatory arg: #2;
                                 Optional arg: #1.}

This defines \example to be a command with two arguments,
referred to as #1 and #2 in the {<definition>}--nothing new so far.
But by adding a second optional argument to this \newcommand
(the [YYY]) the first argument (#1) of the newly defined
command \example is made optional with its default value being YYY.

Thus the usage of \example is either:

   \example{BBB}
which prints:
Mandatory arg: BBB; Optional arg: YYY.
or:
   \example[XXX]{AAA}
which prints:
Mandatory arg: AAA; Optional arg: XXX.

Comment: Although that's true, I found this question while looking for a way to provide a default argument, so this answer was the most useful one for me.
Comment: I think the question was about how to determine *whether* an optional argument was given, not providing a default.
Answer: All of the above show hard it can be to make a nice, flexible (or forbid an overloaded) function in LaTeX!!!  (that TeX code looks like greek to me)
well, just to add my recent (albeit not as flexible) development, here's what I've recently used in my thesis doc, with
\usepackage{ifthen}  % provides conditonals...

Start the command, with the "optional" command set blank by default:
\newcommand {\figHoriz} [4] []  {

I then have the macro set a temporary variable, \temp{}, differently depending on whether or not the optional argument is blank.  This could be extended to any passed argument.
\ifthenelse { \equal {#1} {} }  %if short caption not specified, use long caption (no slant)
    { \def\temp {\caption[#4]{\textsl{#4}}} }   % if #1 == blank
    { \def\temp {\caption[#1]{\textsl{#4}}} }   % else (not blank)

Then I run the macro using the \temp{} variable for the two cases.  (Here it just sets the short-caption to equal the long caption if it wasn't specified by the user).
\begin{figure}[!]
    \begin{center}
        \includegraphics[width=350 pt]{#3}
        \temp   %see above for caption etc.
        \label{#2}
    \end{center}
\end{figure}
}

In this case I only check for the single, "optional" argument that \newcommand{} provides.  If you were to set it up for, say, 3 "optional" args, you'd still have to send the 3 blank args...  eg.
\MyCommand {first arg} {} {} {}

which is pretty silly, I know, but that's about as far as I'm going to go with LaTeX - it's just not that sensical once I start looking at TeX code...  I do like Mr. Robertson's xparse method though, perhaps I'll try it...
Comment: I like this approach. Is more "programming-like" and therefore easier to read. Good job!
Answer: The general idea behind creating "optional arguments" is to first define an intermediate command that scans ahead to detect what characters are coming up next in the token stream and then inserts the relevant macros to process the argument(s) coming up as appropriate. This can be quite tedious (although not difficult) using generic TeX programming. LaTeX's \@ifnextchar is quite useful for such things.
The best answer for your question is to use the new xparse package. It is part of the LaTeX3 programming suite and contains extensive features for defining commands with quite arbitrary optional arguments.
In your example you have a \sec macro that either takes one or two braced arguments. This would be implemented using xparse with the following:

\documentclass{article}
\usepackage{xparse}
\begin{document}
\DeclareDocumentCommand\sec{ m g }{%
    {#1%
        \IfNoValueF {#2} { and #2}%
    }%
}
(\sec{Hello})
(\sec{Hello}{Hi})
\end{document}

The argument { m g } defines the arguments of \sec; m means "mandatory argument" and g is "optional braced argument". \IfNoValue(T)(F) can then be used to check whether the second argument was indeed present or not. See the documentation for the other types of optional arguments that are allowed.
Comment: Will! It does not work. Output: `(Hello and ) (Hello and Hi)`
Comment: Thanks for the feedback, Alexey. I suspect you're using an older version of xparse; there's been a lot of work done on it recently. TeX Live 2009 has just been released :)
Comment: The `g` option is not documented in the latest `xparse` manual. In section 1.8 its usage is not recommended. https://mirrors.mit.edu/CTAN/macros/latex/contrib/l3packages/xparse.pdf
Answer: I had a similar problem, when I wanted to create a command, \dx, to abbreviate \;\mathrm{d}x (i.e. put an extra space before the differential of the integral and have the "d" upright as well). But then I also wanted to make it flexible enough to include the variable of integration as an optional argument. I put the following code in the preamble.
\usepackage{ifthen}

\newcommand{\dx}[1][]{%
   \ifthenelse{ \equal{#1}{} }
      {\ensuremath{\;\mathrm{d}x}}
      {\ensuremath{\;\mathrm{d}#1}}
}

Then
\begin{document}
   $$\int x\dx$$
   $$\int t\dx[t]$$
\end{document}

gives \dx with optional argument
Answer: All you need is the following:
\makeatletter
\def\sec#1{\def\tempa{#1}\futurelet\next\sec@i}% Save first argument
\def\sec@i{\ifx\next\bgroup\expandafter\sec@ii\else\expandafter\sec@end\fi}%Check brace
\def\sec@ii#1{\section*{\tempa\ and #1}}%Two args
\def\sec@end{\section*{\tempa}}%Single args
\makeatother

\sec{Hello}
%Output: Hello
\sec{Hello}{Hi}
%Output: Hello and Hi

Comment: I thought TeX understands as parameters appropriate count of first 'boxes' after command. this 'box' is written in curly braces or it's one symbol. Ie. `x^2+1` or `x^{2+1}`
So I have question, does your command test presence of braces?

Is it possible to create LaTeX command `\sec` producing:
"A, b,c and d" for command `\sec{A}[b,c,d]`,
"A and b" for `\sec{A}[b] and
"A" for `\sec{A}`?
Comment: You have two questions. 1) Yes, my command test presence of braces. 2) Yes, it is possible to create macro for `\sec{A}[b,c,d]` or `\sec{A}[b]` or `\sec{A}`.
Answer: Use the xargs package. See the guide here.
Example definition:
\usepackage{xargs}

\newcommandx{\foo}[3][1=1, 3=n]{...}

Example usage:
\foo[1][2]
\foo[1][2][3]

Answer: Here's my attempt, it doesn't follow your specs exactly though. Not fully tested, so be cautious.
\newcount\seccount

\def\sec{%
    \seccount0%
    \let\go\secnext\go
}

\def\secnext#1{%
    \def\last{#1}%
    \futurelet\next\secparse
}

\def\secparse{%
    \ifx\next\bgroup
        \let\go\secparseii
    \else
        \let\go\seclast
    \fi
    \go
}

\def\secparseii#1{%
    \ifnum\seccount>0, \fi
    \advance\seccount1\relax
    \last
    \def\last{#1}%
    \futurelet\next\secparse
}

\def\seclast{\ifnum\seccount>0{} and \fi\last}%

\sec{a}{b}{c}{d}{e}
% outputs "a, b, c, d and e"

\sec{a}
% outputs "a"

\sec{a}{b}
% outputs "a and b"

LaTeX Optional Arguments


Can you visit this place in Deponia?

Question: In the bonus material of Deponia, I found the following screenshot:

I can't remember visiting this place.
Is it in the game actually? Or did it never make it to the finished version?
Comment: Oh, I think it might have been the file "concept art" instead.
Comment: I just looked through the bonus material, and didn't see this.  Where did you find this?
Comment: @Blueraja-DannyPflughoeft: In the file "24 artworks" from the [version on gog.com](https://secure.gog.com/gamecard/deponia).
Answer: I don't remember this from the game either.  However, Goal gets locked up a similar machine in the sequel, Chaos on Deponia:

I bet this was an old prototype of Doc's workshop that got cut from the first game and altered for the second.

Can you visit this place in Deponia?


A frustum is made by removing a small cone from a large cone as shown in the diagram.

Question: this the question
can someone give me a step by step answer and explanation on how to do this question
Comment: hint: use substraction and similarity
Comment: What Jorge means is 1) calculate the radius of the small cone 2) The volume of the frustum is equal to the volume of the big cone minus the volume of the small cone. 3) Transform volume to mass using density
Answer: Calculate the mass of the big cone first.
It is $m=\frac{6^2\cdot\pi\cdot 15\cdot2.5}{3}$.
The proportion between the big cone and small one is $\frac{1}{3}$ so the mass of the small cone is $m\cdot (\frac{1}{3})^3$
Finally, your answer is $m(1-(\frac{1}{3})^3)$
Comment: The similarity ratio is $1/3$
Comment: Right, thanks.${}$
Comment: why do they say this on the mark scheme then?  (Highlighted is answer) http://imgur.com/a/MQtk9
Comment: If you multiply the acual terms you get approximately $1361.35681656$


Can we change the html or body height using jquery?

Question: I am trying to run this statement: $('body').height(100); but when I check the height again, I find it unchanged!
Is there any way to change the height of the ?
Answer: document body is a magical element and does not behave the way other HTML elements do. Your code:
$('body').height(100);

Is correct and it is same as:
$('body').css({height: 100});
$('body').css({height: '100px'});
$('body').attr({style: 'height: 100px'});

All result in this:

However, setting the height will not hide the area outside the 100px height invisible. You should wrap the body content inside a div and set its height instead:

jQuery solution would be:
$("body").wrapInner($('
').css({
    height: 100,
    overflow: "hidden"
}));

Comment: I have tried it as well, when I set the height of the wrapper, its height got changes but the body was remaining the same, and to ensure, body was already wrapped in a wrapper
Comment: See edited answer. Set `height: 100px; overflow: hidden;` on the wrapper. I believe this is what you want. overflow can also be set to scroll.
Comment: Just a note for the last code: if you want to set back the original state use this: `$('#height-helper').contents().unwrap();`
Answer: You should actually use
$('body').css('height', '100'); and it will work.
Comment: Use this instead $('body').css('height', '100px');
Comment: It is working in firefox but when I tried using it in iOS browser, it is not working :-/
Answer: Try using $('body').addClass('your class name'); or $('body').attr('style', 'height: 100px');
Comment: $('body').attr('style', 'height: 100px'); It is not working as well
 see
>>> $('body').height();
416
>>> $('body').attr('style', 'height: 100px');
[body]
>>> $('body').height();
416
Comment: What I have seen in many browsers is that you add the following in css style `` which will always show the height as 100%, so if you change it with jquery you should run it in a $(document).ready to ensure that the DOM has created before changing the size. Also if there are css style involved they might override your inline style (shouldn't but possible). So try `height: 100px !important`
Answer: It should be
$('body').css('height', '100px');

Or
$('body').height(100);

Comment: see $('body').height(100); is not working in browser itself and $('body').css('height', '100px'); is working in browser but not in iOS browser, I want it to be working in both


How do I correctly count the number of clicks in a usability test?

Question: I'm unsure how I should count the number of clicks in a usability test conducted with mockups.
Say, for example, a user must complete the task of creating a new post. In this task the user will start on the homepage, so he needs to click the "Create New Post" button then he will go to a form to insert a title, select a category through a select menu, and complete other fields.
How should the number of clicks be counted?
The "Create New Post" should be a click, but then when the user is redirected to the create post page, in order for the user to write the title he needs to click in the input or use Tab. Is that a click?
Also for the user to select a category through a select menu he needs to select a category. That's also another click?
Does each input that the user needs to fill in count as a click in my usability test?
Comment: **Brace yourself:** everyone is going to really enjoy telling you to [stop counting clicks](https://www.google.com/search?q=stop+counting+clicks) as a primary usability metric.
Comment: I guess I did also ;)
Answer: For the sake of illustration, let's create a new unit of measurement:

Active Focus Unit—An Active Focus Unit (AFU) is defined to be the amount of focus that it takes a user to perform a simple, common task. For example, finding, pointing to, and clicking an arbitrary site's logo to navigate to the homepage = ~1 AFU.
Navigating to the root of a site is a very common function, and the vast majority of successful sites provide this function in the same general area: the top of the site, normally at the left.

Let's also define our goal to be the following:

Minimize the user's cumulative AFU output for any given task.

Now for an example:
Clothing Inc.

Alice is navigating Clothing Inc.'s site for the first time. The homepage shows categories of products. She notices immediately three large headers: "Men", "Women", and "Children". She clicks on "Women". = .8 AFUs
She now sees that she's viewing only "Women's Clothing", as the page header tells her. She sees several categories highlighting a few popular products in each: "Jeans", "Dresses", "Tops"... She clicks "Dresses". = 1.1 AFUs
She finds a dress that she likes, and selects her size, then adds it to her cart. = 1.2 AFUs

She has spent 3.1 AFUs performing basic navigation through a series of common steps. Not too bad.
She still has more shopping to do, so she visits another clothing site.
We Sell Stuff

Alice visits We Sell Stuff's site next. Their homepage shows 100 products per page. She tries to figure out if there's any organization to the madness to make this more manageable and to find what she's looking for. = 2.4 AFUs
Alice finds a "Search" button and clicks it. It takes her to a new page where she can type her search request. She types "Purses" and clicks "Search". = 1.3 AFUs
Alice sees another button called "Sort". It again takes her to another page to let her pick what property to sort by. She sees "Price", but can't figure out if that's low-to-high or high-to-low. She clicks it anyways. = 2.1 AFUs.
Alice finds out that this was not low-to-high like she wanted. She goes back to sort by "Rating" instead. = 1.7 AFUs

At this point on We Sell Stuff's site, Alice has already spent 7.5 AFUs and hasn't even found a the products she wants to look at yet.

Sure, this is a hugely contrived example, but the points remain: Don't focus on minimizing clicks; focus on providing an intuitive experience that removes as much friction from the user's experience as possible.


Joints between paving stones - A breeding ground for weeds. Sustainable control?

Question: I'm looking for a solution to control weed growth on a patio out of paving stone. The weeds are growing the the joints between the stones as can be seen in the picture.
Two methods have been proposed:

Jointing the gaps with mortar.
Remove the stones and ad a fleece under the paving stones.

Method 1. is much cheaper than method 2. So I'm inclined to use method 1.
What are the pros and cons of each method?
Are there any other alternatives which suppress weed growth sustainably and in the long term?
Comment: Jointing with mortar will be some considerable effort, will alter the appearance, and probably won't work well enough to justify the effort. Pulling up the stones and putting down fabric will be way, way too much effort. Just pull the weeds while you ponder the matter further.
Comment: @JimStewart I found this mortar and the videos demonstrate that it seems to be quite easy to do..https://www.youtube.com/watch?v=vIO7dYHpCk4
Comment: OK then, but that is the absolute most I would ever do. Personally a few weeds (or even more than few) wouldn't upset me. And those "simple, nifty solutions can sometimes go awry.
Answer: From the picture you already have your patio installed.
To implement the polymetric sand solution or the mortar solution requires that you

Pull up the pavers
Clean out the sand/dirt between the cracks
Reinstall the pavers
Apply polymetric sand/mortar

I've been working on the same issue but I am trying to not pull up the pavers.
The Problem:

Dirt gets into the cracks between the pavers
Seeds blow onto the patio and get into the dirt
Seeds grow and send roots down between the pavers

So, polymetric sand/mortar provides less opportunity for dirt which reduces the chance for seeds to sprout.
Putting weed blocker under the patio fails to address the root cause.
My Solution
I know I'm going to catch some heat for this but here goes.
I have a large paver patio and I hate pulling weeds so I decided to try salt to prevent weeds. Salt gets down into the cracks and makes an unfavorable environment for seeds to sprout.

Bought a 20 pound bag of table salt for $7 (not rock salt, table salt is super ground super fine)
Poured about 3 pounds of it onto the patio
Used a push broom to work the salt into the cracks. Since it was table salt it is very fine and broomed into the cracks nicely.
Using my water hose I wetted down the salt so that it washed into the cracks. Not a major hose down, just enough to get the salt wet and further into the cracks.

The patio looked a little salty for a few days. A rain or two brought the patio back to it's normal color.
The result

Weed free patio all summer
No salt damage to the pavers

If weeds start to grow again I'll broom in more salt. I'm one year into my experiment - so far, so good.
Comment: According to [wiskeychief's answer](https://diy.stackexchange.com/a/159659/34147), the polymetric sand goes between the pavers (putting it underneath probably doesn't hurt, but isn't required). Therefore, it's a great "after market" addition. However, I'm on board with your "salted earth" technique, as well. Depending on your climate, salting in the late fall _may_ also help prevent freezing, which may help prolong the life of the pavers and the general levelness of the patio.
Comment: Salting will work, but you need to be careful of what is around your patio, some excess salt will wash out and can kill vegetation downstream, i.e. your lawn or other plants you want to grow, and it will be persist in the soil making it difficult to grow anything there in the future.
Comment: I worried about what would happen to the plants around the patio. I had no issues wanted plants dying. I'm always amazed how much salt is on the road and how few roadside plants die. You are correct, it is important to be aware of where you are salting.
Comment: I like this answer, too.    I dub this the "Brawndo has electrolytes!" method and it sounds very promising.  But yes, @JoshKing, better watch out for collateral crop damage.
Answer: You're right that weed-block fabric underneath the paver bricks is a good idea.  You didn't say if you put these pavers in yourself, but it might already be under there.
Weeds don't need deep roots (all the way through the bricks). They can take root in the gaps between the bricks (the same can happen in a concrete sidewalk.)
A quality install of pavers will generally finish with a layer of polymeric sand ("paver sand") that's brushed into the cracks.  The sand acts like mortar by filling the cracks, and it may have some acidity to make it more difficult for weeds to grow. (Then they sweep up the excess).   A 50-pound bag of polymeric sand costs only about $4.
This is also recommended as annual maintenance by some installers I've talked to.  Clean the cracks as best you can, then sweep some paver-sand into the cracks to make a more inhospitable environment for weeds to take root.
Comment: Mortar will break and crumble from movement of pavers.
Answer: That looks like grass rather than weeds and could be coming from "runners" following the cracks in the pavers from the yard.
Carefully dig out and inspect the transition from grass to pavers and see if there are any runners growing into the pavers.  If there are, then installing a strip of metal or plastic edging against the grass could be the best solution.


Adding Software Repositories

Question: I can't add a repository because when I click Unbuntu Software I do not have a selection for "Software and Updates", just "Updates".  If I click on "Updates" I get a window that says I'm up to date and no other choices.  I assume I am not going to the correct window or?  Please point me in the correct direction, thank you.
Comment: Are you using Ubuntu? Which release? What kind of repository are you trying to add? Please [edit] your question. "Software & Updates" is a program not an option anywhere.
Comment: -1 The title seems misleading. This is a question about how to locate software on the system, not about how to add a repository.
Answer: Use your Desktop Search to find Software & Updates. There are three easy ways to reach Desktop Search in Gnome:

Click on "activities" in the top bar, or
Click on the nine-box-grid at the bottom of the Shortcut Bar, or
Press your [super] key

Don't use Ubuntu Software to look for Software & Updates. They are separate applications.
Comment: Thanks for your help.  I am new and have a lot to learn about using Linux.

Adding Software Repositories


How do I adjust touchpad scroll sensitivity in Wayland/Gnome?

Question: Touchpad scrolling is extremely sensitive in Wayland/libinput. The touchpad controls in system settings are very limited. Does anyone know how to adjust this?
My thinkpad has a clickpad (the worst invention ever) and I'd also like to get two finger clicks working with it instead of the location and time dependent clicks that it currently has. Judging by the documentation for libinput, this may not happen.
Comment: Same issue here on the Macbook Air (2013 model) in Ubuntu 17.10 when using Wayland. When I use X, the scroll sensitivity is good.
Comment: The scroll sensitivity has been fixed in 17.10 on my thinkpad, but it has created another strange problem where waking from sleep only allows scrolling with 3 fingers. I will dig into this a bit more in the next couple of days to see if I can figure out how to configure this in the backend.
Comment: Same issue here (Asus Zenbook), any updates?
Comment: The most recent updates seem to have taken care of all my problems. Best of luck to you folks with MacBooks. I suggest filing a bug report on launchpad if it still doesn't work
Answer: Go to a terminal and type:
synclient PalmDetect=1
synclient HorizHysteresis=10
synclient VertHysteresis=10

then keep adding zeroes to the following 2 parameters:
synclient HorizHysteresis=100
synclient VertHysteresis=100

until it becomes not responsive enough.  E.g.:
synclient HorizHysteresis=1000
synclient VertHysteresis=1000

Then halve that number and keep halving it until it's just right.  E.g.:
synclient HorizHysteresis=500
synclient VertHysteresis=500

synclient HorizHysteresis=250
synclient VertHysteresis=250

When that works, leave a comment with the value you have and I'll edit this answer to give you the perfect answer.  If it doesn't, I'll delete...
Comment: This answer is accepted but wrong. Wayland does not use the synaptics driver and executing synclient should tell you that there is no driver loaded.
Comment: I guess "you can't do it atm" is not a very useful answer. Just added my comment so people don't get confused by this not working.
Comment: Even though updates fixed most of the problem, this did help me fine tune touchpad sensitivity. Thanks!
Comment: @kjyv Post your own answer and ask the OP to change the acceptance...


Extension Methods - How to return the correct type in inheritance?

Question: I'm trying to create a generic methods from my Repository classes. The idea is a method that do something and return the instance of the class who called it.
public class BaseRepository { }

public class FooRepository : BaseRepository { }

public class BarRepository : BaseRepository { }

public static class ExtensionRepository
{
    public static BaseRepository AddParameter(this BaseRepository self, string parameterValue)
    {
        //...
        return self;
    }
}

// Calling the test:
FooRepository fooRepository = new FooRepository();
BaseRepository fooWrongInstance = fooRepository.AddParameter("foo");

BarRepository barRepository = new BarRepository();
BaseRepository barWrongInstance = barRepository.AddParameter("bar");

Well, this way I can get BaseRepository instance. But I need to get FooRepository and BarRepository instances, who called this method. Any idea? Thank you so much!!!
Comment: Do you realize that a `class` type variable is just a _reference_ to the object? What's the purpose of returning _the same_ reference back to the caller of the method? He already has that reference. There may be a valid reason (which is why I ask). Addition: In your usage example above, the `=` sign simply assigns _the same_ reference to the new variable. It's not a "wrong instance". The method doesn't create new instances; it's the same instance.
Comment: The purpose of returning the same reference, Jeppe, is to realize a lot of method calls on a row. "Wrong instance" was a way to say that I want the children instances like returning, but not the base class, you know?
Comment: Now I understand. The correct term is "wrong (unwanted) compile-time type" or "type of the variable", I guess.
Answer: You can try using generics
public static class ExtensionRepository
{
    public static T AddParameter<T>(this T self, string parameterValue) where T:BaseRepository
    {
        //...
        return self;
    }
}

Comment: +1, but we can improve this by using `where T : BaseRepository`
Comment: @Kiwanax, You don't need to specify the type in `<>` , it will be infered by compiler. Your code will look like `fooRepository.AddParameter("value")`
Comment: Thanks, Alex. I've already thought this solution, but I want to create an elegant code. Something like: "fooRepository.AddParameter("value")" instead "fooRepository.AddParameter("value")", you know?
Answer: Why do you want to return self in the first place? As far as I can see (don't know what's inside your method body) you don't assign a new object to self. So it's the same instance you're returning as the caller already has.
Maybe you could make it return void:
public static void AddParameter(this BaseRepository self, string parameterValue)
{
    //...
}

Usage:
FooRepository fooRepository = new FooRepository();
fooRepository.AddParameter("foo");
// fooRepository is still fooRepository after the call

BarRepository barRepository = new BarRepository();
barRepository.AddParameter("bar");
// barRepository is still barRepository after the call

Comment: The purpose of returning the same instance is to call a lot of methods in a row, you know? Like: "fooRepository.AddParameter("").AddSomeStuff("", "").AddAnotherStuff("").List();". Something like this.
Comment: @Kiwanax Alright, then you could use the solution from the other answer.
Comment: Yeah, @Jeppe, the another solution solved my problem. Thank you for your answers!


distinct permutations using all objects with repeated objects

Question: I thought my question was identical to Number of permutations with repeated objects. but it is not. They were looking for permutations of size $0\leq ... \leq N$ but I would not call a permutation of size less than $N$  a "permutation".
I'm looking for the number of distinguishable distinct permutations of N objects where some of the objects are indistinguishable copies. Suppose there are $k$ total types of objects. To use that questions terminology: "In general, suppose we have objects $\underbrace{X_1, \dotsc, X_1}_{n_1}, \underbrace{X_2, \dotsc, X_2}_{n_2}, \dotsc,\dotsc, \dotsc, \underbrace{X_k, \dotsc, X_k}_{n_k}$. Then what is the number of ways we can choose and order $N=n_1 +\dotsb + n_k$?
E.g., if the objects are "AAB" so N=3, then "AAB" and "AAB" are indistinguishable so the answer is 3 (AAB,ABA,BAA).
Is it a simple modification of the answer there?
Answer: Assume they were distinguishable, total would be $N!$.
Assuming they we not distinguishable as you state, each of the $N!$ can be mapped to $n_1! n_2! \dots n_k!$ permutations without the distinguishing factor (permuting the kinds among themselves)
Thus the answer is $$\frac{N!}{n_1! n_2! \dots n_k!}$$


How to ngShow a div when filtered search bar returns nothing?

Question: first I'll provide background info then show some code snippets.

I have an ng-repeat that is repeating box-like widgets with data/information inside.
I have a search bar that filters the data in the widgets and only shows widgets that contain the string in the search bar.
With number 2 in mind, when a string is entered that is not in any of the widgets, it leaves the page blank with no widgets. (it makes widgets without that string disappear)

What I want: is to show a div when no result is returned instead of having a blank page.
For the sake of examples, I have:
<input type = "text" data-ng-model = "searchWidgets" />

No Results Found

        (this is where all the widgets get displayed)

Thank you in advance for your time and input!
Answer: You can have a few options, one of the easiest is to save the filteredWidgets as its own object, and just use ng-show:

No Results Found

        (this is where all the widgets get displayed)

Related SO Question
Comment: I changed the ng-show a little. I have ``. Now it shows the div whenever i search anything or search incorrectly.
Comment: @Kepler my first guess would be "!searchWidgets.length == 0". I believe the ! is extra (and the cause of this issue)
Comment: Correct again, you genius! However, when I backspace the string the search bar now, the div stays. Thanks for letting me bug you with this :)
Comment: That probably because searchWidgets.length is 0 then. I guess, my next question would be, "Why do you have that as part of the ng-show?". In my mind, this div should only depend on the results.
Comment: If it is not there, the div appears whenever there is something in the searchbar.


How to hide audio source in viewpage source just like spotify or soundcloud does?

Question: I am making a music player using javascript but want to hide the music source in the view page source code. How do I make sure that no one is able to download the EXCLUSIVE music?
Thanks !
Comment: Research HLS it's as close as you can get to having protected media. Please read [ask].
Answer: The short answer: You simply cannot! On the internet everything is freely accessible.
The long answer: All you can do is make it pretty hard for someone to get to that information. This can be done by code obfuscation (Try https://obfuscator.io/) and hiding the information, so it is not obviously visible. (Some websites add enough whitespace at the top of their source code, so if the source code view is opened by a non expert, it looks like it is empty.) But any expert with enough time and effort will find the content in the end.
If someone uses the network tab in the browsers developer tools (CTRL + SHIFT + I), the incoming and outgoing requests are visible. There are even more sophisticated network sniffers, like Fiddler or Wireshark, which offer to save packages to the harddisk.
Some modern streaming websites provide the content with streaming servers, which makes it a little bit harder to get the streamed content, but even that is possible, by downloading all the chunks and combining them. (Even content poisened with DRM can be downloaded, by just playing it and recording the screen.)


How can I make the combobox add items faster?

Question: I used a ComboBox to load all the font on the computer and preview it.
Here is the XAML:
<Window x:Class="Sample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Sample"
        mc:Ignorable="d"
        Title="Demo" Height="450" Width="800" WindowStartupLocation="CenterScreen" WindowStyle="None" Loaded="Window_Loaded" Background="White">
    <Window.Resources>
        <local:FontFamilyConverter x:Key="FontFamilyConverter"></local:FontFamilyConverter>
    </Window.Resources>
    <Grid>
        <ComboBox  Margin="10,10,0,10" HorizontalContentAlignment="Stretch" Name="FontFaimlyCB" Height="50" Width="250" ItemsSource="{Binding Source={x:Static Fonts.SystemFontFamilies}}">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}" FontFamily="{Binding Converter={StaticResource FontFamilyConverter}}" FontSize="20"></TextBlock>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
    </Grid>
</Window>

And here is code-behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;
using System.Globalization;

namespace Sample
{

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
        }
    }
    public class FontFamilyConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return new FontFamily(value.ToString());
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

When the first time I click the ComboBox, it always takes a long time to add the items(There are almost one thousand fonts on my computer and it will takes 3-4 seconds to finish it). But any other software such as word/photoshop and so on won't like this.
How can I make it add faster? Please help me, thank you.
Comment: Base on this [answer by Tim Lloyd](https://stackoverflow.com/a/4805466/880990) to question [WPF: How to filter out non-Roman fonts from Fonts.SystemFontFamilies?](https://stackoverflow.com/questions/4798370/wpf-how-to-filter-out-non-roman-fonts-from-fonts-systemfontfamilies), you could filter out all symbol fonts, hidden fonts and composite fonts to reduce the number of fonts displayed.
Comment: @OlivierJacot-Descombes Thank you sir.
Answer: You could try to use a VirtualizingStackPanel as the ItemsPanel and set the MaxDropDownHeight to a fairly small value in order not to render all containers immediately. And you shouldn't have to use a converter:
<ComboBox  Margin="10,10,0,10" HorizontalContentAlignment="Stretch" Name="FontFaimlyCB" Height="50" Width="250"
           ItemsSource="{Binding Source={x:Static Fonts.SystemFontFamilies}}"
            MaxDropDownHeight="50">
    <ComboBox.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel />
        </ItemsPanelTemplate>
    </ComboBox.ItemsPanel>
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}" FontFamily="{Binding}" FontSize="20" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

Comment: Well, it works and maybe it is the easiest way. Thank you for helping me a lot sir.
Answer: Create your own observable collection that allows you to suspend notifications when adding items. E.g.:
static void Main(string[] args)
{
    var fonts = new ObservableCollectionEx<string>();
    using (fonts.DeferCollectionChanged())
    {
        for (int i = 0; i < 100000; i++)
        {
            fonts.Add(Guid.NewGuid().ToString());
        }
    }
}

public class ObservableCollectionEx<T> : ObservableCollection<T>
{
    private int deferLevel;
    private bool collectionUpdateNeeded;

    public ObservableCollectionEx()
    {
    }

    public ObservableCollectionEx(IEnumerable<T> collection)
        : base(collection)
    {
    }

    public ObservableCollectionEx(List<T> collection)
        : base(collection)
    {
    }

    public override event NotifyCollectionChangedEventHandler CollectionChanged;

    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        if (deferLevel == 0)
        {
            CollectionChanged?.Invoke(this, e);
            collectionUpdateNeeded = false;
        }
        else
        {
            collectionUpdateNeeded = true;
        }
    }

    public IDisposable DeferCollectionChanged()
    {
        ++deferLevel;
        return new DeferHelper(this);
    }

    private void EndDefer()
    {
        --deferLevel;

        if (deferLevel == 0 && collectionUpdateNeeded)
        {
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        }
    }

    private class DeferHelper : IDisposable
    {
        private ObservableCollectionEx<T> collection;

        public DeferHelper(ObservableCollectionEx<T> collection)
        {
            this.collection = collection;
        }

        public void Dispose()
        {
            if (collection != null)
            {
                collection.EndDefer();
                collection = null;
            }
        }
    }
}


mysql insert can't with select into outfile?

Question: mysql> insert into helpme set user=(select 0x616361 into outfile 'c://windows//temp//test.ini');
Database changed

mysql> select * from helpme;
+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+
| user                                                                                | id    |
+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+
| a                                                                                |     1 |                                                                                | 37833 |
| aca                                                                                | 37834 |
+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+
2 rows in set

why user is aca?and can't find the file (c://windows//temp//test.ini)?
Comment: 1) What do you think `0x616361` contains? 2) What happens if you run `select 0x616361 into outfile 'c://windows//temp//test.ini'` separately?
Comment: What do you want to put with 0x616361 as value? Will you have permission to write in 'C:' from database without explicitly granting so?
Comment: 1) 0x616361 unhex --> aca  2)I know select 0x616361 into outfile 'c://windows//temp//test.ini' will write a file in c:/windows/temp/test.ini; but insert into helpme set user=(select 0x616361 into outfile 'c://windows//temp//test.ini') as a statment, mysql should run select 0x616361 into outfile 'c://windows//temp//test.ini (start from right regulation ) first,if success,user=1 and write a file in c:/windows/temp,if failed,user=0 and can't write a file.
Answer: SELECT … INTO … can't be used in a sub-query:

An INTO clause should not be used in a nested SELECT because such a SELECT must return its result to the outer context.

That's why MySQL chose to return the value instead of writing it into file.


Injecting list of strings in Guice

Question: I am trying to inject one arraylist of Strings in Guice. For that I am trying to construct list as following in module, which I can inject later into any class:
Multibinder<String> myList =
            Multibinder.newSetBinder(binder(), String.class);

myList.addBinding().to("Test1");
myList.addBinding().to("Test2");

In the above line I am getting following error:
The method to(Class<? extends String>) in the type LinkedBindingBuilder<String> is not applicable for the arguments (String)

In this context, I have found this: Guice : Inject an ArrayList of Strings, but I think given solution does not fit my use case.
Comment: Where's your arraylist? What are you trying to inject it into?
Answer: Use .toInstance()
myList.addBinding().toInstance("Test1");
myList.addBinding().toInstance("Test2");`

Answer: I realize this is an older post, but I've been unsuccessful at finding a solution until today.  I've wanted to inject a list of comma-delimited strings defined in a property file in a generic way without having to explicitly create @Named providers for every property that needed to be represented as a list of Strings.
Today I found this post (Injecting a List of Strings From a Properties File Using Guice).  The relevant part for me was this line in my configure method:
 @Override
 protected void configure() {
    ...

    binder().convertToTypes(Matchers.only(new TypeLiteral<List<String>>() {
    }), (String value, TypeLiteral<?> toType) -> Arrays.asList(value.split(",")));

    ...
 }

I didn't use DefaultListDelimiterHandler as the original solution did, but instead just did a standard string split converted to a List.  Now from a property file, I can have something like:
testList=one,two,three

And I can inject it using:
@Inject
@Named("testList")
List<String> testList;

Injecting list of strings in Guice


Creating a UIbutton from an already defined Bezier Path?

Question: I have a range of defined Bezier Paths within one View Controller (the default). However specifically, I want to make one of them a UIButton (It doesn't have to lead anywhere yet but it would be great if it could print something on touch).
By looking at some similar questions, I have been able to define the Bezier Path I want and the UIButton separately on the simulator, but haven't been able to splice them together.
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

    let circlePath = UIBezierPath(arcCenter: CGPoint(x: 200, y: 350), radius: CGFloat(150), startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true)

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = circlePath.cgPath

    //change the fill color
    shapeLayer.fillColor = UIColor.clear.cgColor
    //you can change the stroke color
    shapeLayer.strokeColor = UIColor.gray.cgColor
    //you can change the line width
    shapeLayer.lineWidth = 7.5

    view.layer.addSublayer(shapeLayer)

  let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
        button.backgroundColor = .green
        button.setTitle("Test Button", for: .normal)
        button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

        self.view.addSubview(button)
    }

    @objc func buttonAction(sender: UIButton!) {
        print("Button tapped")
    }

}

How can I pass circlePath as a UIButton?.
Answer: A UIButton is a UIView so you can add the layer you created to the button in just the same way as you did the view:
button.layer.addSublayer(shapeLayer)

Note that this layer will then cover the label of the UIButton, but an easy way to solve this is to change the z-position of the layer:
shapeLayer.zPosition = -1

E.g. if you want to add a circular layer to a button:
let circlePath = UIBezierPath(ovalIn: button.bounds)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
shapeLayer.zPosition = -1
button.layer.addSublayer(shapeLayer)

Or, matching the circle in your example but creating the button before the shape:
// define circle parameters
let radius: CGFloat = 150
let center = CGPoint(x: 200, y: 350)

// create the button
let button = UIButton(frame: CGRect(origin: center.applying(CGAffineTransform(translationX: -radius, y: -radius)),
                                        size: CGSize(width: 2 * radius, height: 2 * radius)))

// create the circle layer
let circlePath = UIBezierPath(ovalIn: button.bounds)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
shapeLayer.zPosition = -1

// add the circle layer to the button
button.layer.addSublayer(shapeLayer)

view.addSubview(button)

Comment: Thanks for the answer. I had to switch around the position of the button and the path  to allow it to run. However, I'm only getting the 'button pressed' message whenever I tap on the position where the original button used to be, and not the circular layer. I'm trying to make the circular layer the only button on the view - sorry if I'm being unclear!
Comment: Yes, the frame of the button and that of the layer might be different. UIBezierPath(ovalIn: button.bounds) creates a path that, when assigned to the button, is inside the button. Do you have a particular reason why you want to declare a path first and then a button, and not the other way around?
Comment: It's has come out that way because I don't know so much. I'm more focused (probably unnecessarily) on the Path because I only want the stroke of the path to respond to touch, not the whole Circle. I'm also hoping to set up so that I can later apply an animated gradient to the stroke of the path
Comment: Ah, so you want a path that responds to touch? UIButton is really not suitable for that and that is probably what lead to the confusion. You should look for questions asking "How to detect touches on a CGPath" or create one yourself.
Comment: Exactly that - my bad for being vague. I'll do just that. Thanks Priebe


Integral of a complex gaussian + inverse gaussian integral

Question: Why does this identity holds ?
$$
I(a, b) := \int_0^\infty dx e^{-ia^2x^2 -i b^2/x^2} = \frac{1}{2|a|} \sqrt{\frac{\pi}{i}} e^{-2i |a| |b|}
$$
It is given in the book Quantum Field theory by T. Padmanabhan, eq. 1.82 page 22.
I am not sure how to tackle this integral. I know that the prefactor can be found by looking at the value of $I(a, b=0)$. Furthermore, looking at the function $J(a, b) = |a| I(a, b)$, it can be found to only depend on $|ab|$, that is $J(a, b) = \int_0^\infty dx \exp(-ix^2 -i|ab|^2/x^2)$.
Answer: Use the fact that the function is even to get
$$\int_{0}^\infty e^{-ia^2x^2-i\frac{b^2}{x^2}}\:dx = \frac{1}{2}\int_{-\infty}^\infty e^{-ia^2x^2-i\frac{b^2}{x^2}}\:dx$$
Then use the Glasser Master Theorem
$$\int_{-\infty}^\infty f\left(x-\frac{k}{x}\right)dx = \int_{-\infty}^\infty f(x)dx$$
for $k>0$ after completing the square. Can you take it from here?
Answer: So to start, we need to clarify that your result is only valid in the case where $a$ and $b $ are real numbers, and not complex.  It is possible to work this out that this is out from the context, but it took me a few minutes.
 I'm going to make the further restriction that $a$ and $b$ are positive. I think it should be relatively straightforward to reinstate the absolute value signs to extend to $a$ and $b$ on the whole real line if you need to do that afterwards.
Then let's consider
 $$
I(a, b) := \int_0^\infty dx e^{-ia^2x^2 -i b^2/x^2}
$$
As you suggest, first look at the case where $b = 0$. Then this is a standard Gaussian integral with a purely imaginary argument, and we can get the result from an integral table, or using contour integration, that
$$
I(a, 0) = \frac{1}{2a} \sqrt{\frac{\pi}{i}}
$$.
Now we'll proceed to differentiate under the integral sign with respect to $b$, and construct a differential equation for $I$ which we can solve. So:
 $$
\partial_b I(a, b) = -2ib \int_0^\infty \frac{dx}{x^2} e^{-ia^2x^2 -i b^2/x^2}
$$
Change variables to $y = \frac{b}{a x}$, noting that this gives $dy = -\frac{b}{ax^2}dx$, and interchanges the $0$ and the $\infty$ in the limits. Then we see that
 $$
\partial_b I(a, b) = 2ia \int_\infty^0 dy e^{-ib^2/y^2 -i b^2 y^2}
$$
Swapping the limits of the integral and introducing a minus sign, we recognise that this is just the original function, $I(a,b)$. Hence we see that $I$ satisfies the equation
 $$
\partial_b I(a, b) = -2ia I(a,b)
$$
We also calculated the initial condition when $b=0$ already, so we can integrate this equation using that $f'(x) = c f(x), f(0) =A$ gives $f(x) = A e^{c x}$, and  we arrive at
 $$
I(a, b) := \int_0^\infty dx e^{-ia^2x^2 -i b^2/x^2} = \frac{1}{2a} \sqrt{\frac{\pi}{i}} e^{-2i a b}
$$
as required.


Minimization of a summation and a norm

Question: I have been trying to figure out how to minimize
$$\|y-x\|_2^2 +\mu\sum_{i=1}^{n-1} (y_{i+1}-y_i)^2$$
where $y$ is a vector and $x$ is a noisy data set vector by putting it into the form of
$$\|Ay-b\|_2^2$$
and minimizing from there. I understand how to deal with the left half of the equation but the summation is what's throwing me off.
Comment: Are you trying to find a value of $\mu$ that minimizes this with $x$ and $y$ fixed? Or maybe a value of $y$ that minimizes this with $x$ and $\mu$ fixed?
Comment: I want to solve for y essentially, I have x as a noisy function and then depending on a set mu value, I would like to find the values of y that show a smoother function
Answer: The objective function can be written as
$$
f(y) = \| y - x\|_2^2 + \mu \| Dy \|_2^2
$$
where
$$
D = \begin{bmatrix} -1 & 1 & 0 & 0 & \cdots & 0 & 0\\
0 & -1 & 1 & 0 & \cdots & 0 & 0\\
\vdots & & \ddots & \ddots& & \vdots & \vdots \\
0 & 0 & 0 & 0 & \cdots & -1 & 1
\end{bmatrix}.
$$
The gradient of $f$ is
$$
\nabla f(y) = 2(y - x) + 2\mu D^T Dy.
$$
To minimize $f$, you can set the gradient equal to $0$ and solve for $y$.
Comment: what if I do not know what the D matrix is? say I only know mu and x, I see that solving for y gives $$y=\frac{x}{\mu D^T D}$$
Comment: @PineRun But you do know $D$. I edited the answer to write $D$ explicitly.
Answer: $A$ is the shift operator (where $a_{i, i+1} = 0,$ and $a_{i,j}=0$ otherwise.)

Minimization of a summation and a norm


What do I look for when buying a used gas cooktop

Question: We're replacing an electric Jenn-air cooktop with a gas cooktop. I see several used ones on fb marketplace but worry about the safety of a used gas cooktop. Am I being paranoid or are there key things to look for when dealing with a used gas-based appliance?
Answer: I would be more worried about the igniter or if electronic how often it fails.
I have been asked several times if I could repair them and the high voltage circuits are usually potted and not repairable.
With potted electronics you are stuck purchasing expensive replacement parts.
And that may be the reason to sell (or a remodel).
I am not aware of any real safety concerns and any alerts could be online using the brand and model.
Comment: Wow this is great information! Thanks so much!


Issue with reading values from Multi-dimensional array

Question: I'm working on a question where in i need to take coordinates entered by the user (separated by spaces) into a Multi-dimensional array. I'm trying to separate the 'x' and 'y' values and store them separately in a single dimension array say x[i] and y[i].
The issue i'm facing here is i'm not able to read the 'y' values from the array. when i'm trying to output the array containing y values, it is just displaying only 0's. kindly help me on this on how do i rectify this issue. please find my code below.
(Note: N = number of rows in the multi-dimensional array, columns is fixed to 2) (Sorry, forget R, used for some other purpose)
public class Read{

public static void main(String[] args) {
    int  N = 1, R=1;
    double AoN=1;
    float d=0 , e=0, s=0, length=0;
    Scanner in = new Scanner(System.in);
    int[] arr = new int[2];
    System.out.println("Enter values of N and R separated by space: ");

    for (int i=0;i<arr.length;i++) {
        arr[i]=in.nextInt();
            if (arr[0]>=1 && arr[0]<=100) {
                N=arr[0]; //storing N
            }
                R=arr[1]; //storing R
    }

    float[ ][ ] arr1 = new float[N][2];
    System.out.println("Enter Coordinates seperated by spaces: ");
    for(int i=0; i<N;i++) {
          for (int j=0;j<2;j++) {
              arr1[i][j]=in.nextFloat();
              //System.out.println(arr1[i][j]);
              }
      }
    float[] x = new float[N];
    float[] y = new float[2]; // I've given 2 here coz the coordinates are always x and y. please correct me if im wrong.

    for(int i=0; i<N;i++) {
              x[i] = arr1[i][0];
              System.out.println(x[i]);
    }
    for (int j=0;j<N;j++) {
              y[j] = arr1[0][j];
          System.out.println(y[j]);

    }

Input:
2 1 (N, R)
0 0 (x1, y1)
1 3 (x2, y2)

Output:
0.0 (x1)
1.0 (x2)
0.0 (y1)
0.0 (y2)

The output of the array containing 'y' values is always 0 (should be 0 and 3). kindly help. thanks.
Comment: I wish you chose better naming for your variables name :)
Comment: What is N? What is R? You are free to choose arbitrary undescriptive names for identifiers that make reading your code very hard, but then please add comments that explain what they are supposed to be. thanks
Comment: N is the number of rows of the multi-dimensional array, and the column is fixed to 2. please find the updated question.
Comment: As far as I can see you store your `y` value in `arr1[i][1]`; Think where you are trying to retrieve it from
Comment: @GermannArlington yes.you are right. it should be arr[ j ][ 1 ]. thanks for the help.
Answer: I think you have a bug here...
    for (int j = 0; j < N; j++) {
        y[j] = arr1[0][j]; // <<< HERE!!
        System.out.println(y[j]);
    }

I think you mean...
    for (int j = 0; j < N; j++) {
        y[j] = arr1[j][1];
        System.out.println(y[j]);
    }

With the parameters you entered, by the time the code gets to the "float[] x =..." bit, the state of the "arr"s is...
arr = [2, 1]
arr1 = [[0.0, 0.0], [1.0, 3.0]]

The second block is always selecting the first element of the 2d array which has "0" for each value of "j"
Comment: Yes. you were right. thank u for pointing it out. its working fine now. Since its a multi dimensional array, we have to take the first element as 'j' and second element as '1'. since the values are 01, 11 and so on. thanks again.


Are second-countable metric spaces $\sigma$-compact?

Question: I was curious about the relations between second-countable, separable, Lindelöf and $\sigma$-compact topologies in the context of metric spaces.
I am aware of the following implications in general topological spaces:

second-countable $\Rightarrow$ separable $\not \Rightarrow$ Lindelöf, $\;$ [thanks bof]
$\sigma$-compact $\Rightarrow$ Lindelöf
second-countable + locally compact $\Rightarrow$ $\sigma$-compact

as well as the reversed implications in the case of metric spaces:

Lindelöf $\Leftrightarrow$ separable $\Leftrightarrow$ second-countable

Since all the proofs I've seen so far require the LC condition I assume it is not true in general that second-countable topological spaces are $\sigma$-compact (although seeing an actual counterexample would be nice).  So what about metrizable topological spaces?

Ideas so far:
If we can proof that every subset of a $\sigma$-compact space is again $\sigma$-compact, then this would follow from the fact, that every separable metric space is homeomorphic to a subset of the Hilbert cube (which is compact). $\;$[debunked by bof]
Comment: The set of irrational numbers is a separable metric space which is not $\sigma$-compact. (Every $\sigma$-compact subset of the irrational numbers is meager.) Hilbert space is another example.
Comment: By the way, separable does **not** imply Lindelöf in general topological spaces. For example, the Sorgenfrey plane is separable but not Lindelöf.
Comment: Every closed subset of a $\sigma$-compact space is again $\sigma$-compact. Not all subspace, as witnessed by the rational and the irrationals assubspaces of the reals.
Comment: @bof I also wanted to disprove local compactness.
Comment: Any infinite-dimensional separable Banach space is a counterexample. This follows from the fact that the unit ball of a Banach space $E$ is compact iff $E$ is finite dimensional, so a compact subset of an infinite dimensional Banach space has empty interior. Then we just apply the Baire category theorem.
Answer: A counterexample is the "Baire space" $\mathcal{N} = \mathbb{N}^{\mathbb{N}}$.  This is one of the main examples of a Polish space: a separable, completely metrizable space.
One fact about this space is that all compact subsets have empty interior, that is, all compact subsets are nowhere dense.  By the Baire Category Theorem, $\mathcal{N}$ is not the countable union of nowhere dense subsets, and so together with the above fact it cannot be $\sigma$-compact.
See also this question and its answer for more details:

Is the Baire space $\sigma$-compact?


Ubuntu server ports refuse connection occasionally

Question: Background
I have Ubuntu 18.04.5 LTS (server) running multiple services, including the usual ssh, samba and then quite a few other things, including home automation, Nextcloud, etc. It serves up my entire digital life, and it did so quite well until a few months ago. I should add that the machine itself has a Xeon CPU, 12GB of ECC RAM and a ZFS filesystem running a mirrored pool. All of this hardware has been faultless, to my knowledge. I also try to keep Ubuntu up-to-date, so it is patched with whatever is the latest from the repo.
Problem
Recently, I have noticed that I get odd connection drops for short periods. Sometimes I noticed that a SSH connection stops working. Other times I notice that I can't access the Samba file share, or maybe Nextcloud refuses a connection. Different things. As soon as it happens, I ping the machine and without fail the ping works fine, but I cannot connect to anything.
Fault finding
Realising that the port connections seem to the problem, I started logging the output from:
    nc -v -w 5 -z 192.168.1.68 22

which produces:
Tue Mar 23 08:18:00 GMT 2021  - Connection to 192.168.1.68 22 port [tcp/ssh] succeeded!
Tue Mar 23 08:18:05 GMT 2021  - nc: connect to 192.168.1.68 port 22 (tcp) failed: Connection refused
Tue Mar 23 08:18:10 GMT 2021  - nc: connect to 192.168.1.68 port 22 (tcp) failed: Connection refused
<---snip--->
Tue Mar 23 08:18:41 GMT 2021  - nc: connect to 192.168.1.68 port 22 (tcp) failed: Connection refused
Tue Mar 23 08:18:46 GMT 2021  - nc: connect to 192.168.1.68 port 22 (tcp) failed: Connection refused
Tue Mar 23 08:18:51 GMT 2021  - Connection to 192.168.1.68 22 port [tcp/ssh] succeeded!
Tue Mar 23 08:18:56 GMT 2021  - Connection to 192.168.1.68 22 port [tcp/ssh] succeeded!

Notice that the duration of the connection problem is slightly less than a minute. I have peered over logs in /var/log, /var/snap/*/log, journalctl, even router logs; tried to shutdown the various services, LXC instances, snap services, anything I could do without. I cannot see any correlation with an event, or indication that something is wrong. For example, I cannot see daemons crashing, logging errors, an increase in system load, or any particular service running at (or just before) a connection drop occurs.
I have also run a similar nc command from the server to a client and in that log I can see that the outbound connections have a similar problem, albeit for shorter periods.
Question to the community
What else can I do to diagnose this problem? Could it be hardware, e.g.: Network interface (which is embedded on the Motherboard), Router, cabling. If so, how would I check? And if not hardware, then this leaves the software but where to start?
Comment: Read `man journalctl `, and use the `--since` and `--until` switches to inspect the logs around those times.
Comment: Thanks @waltinator. Yes, I have done that, and as I said, there was nothing in there that leaps out as a problem. That said, there is obviously a lot being logged in the journal. I'm not a networking expert, or any kind of IT expert to be fair. What I am hoping for is the next step, after merely looking at all the logs. Is there a lower-level where I can go take a look?
Comment: Try `sudo journalctl ...`. Regular users don't have access to all the logs.
Comment: @waltinator yes, I've done that too. Is it possible that a process can block IO in such a way that nothing can get to the network interface, and would there be a warning in a log if this were possible?
Comment: Read `man top`. Use `top` in batch (`-b`) mode to grab repeated (`-n` and -d` options) snapshots of the system state. System "freezes" are often caused by running too many, too large programs and running out of available memory. Use `free` to see if you have swap space, read `man mkswap swapon fstab` to create some. Traditionally, swap space of 1.5 × RAM has been recommended,  but YMMV. Especially since you have 12GB RAM.
Comment: I have not actually done this, but I did look into it... I use `htop` generally, and looked at `ps` for logging. Did not think to use `top`, so will give that a try now. I did log the system load via `cat /proc/loadavg` but since the connection issue was so short, it did not show much: Load average is reported for 1m, 5m and 15m intervals.
Comment: There is no Ubuntu 18. Maybe 18.04?
Comment: I'm no expert in this, but when I last experienced "weird connection losses" before, I focussed my search on the hardware.  So swap in/out cables, router, computer...whatever I could think of.  I guess it could be either hardware or software, but I guess it's easier to rule out hardware (i.e., through swapping devices).
Comment: @Ray you may be right. I moved the router 30cm last night and so far I have not seen any issues. So it may be EMI or a dodgy connection. I'm not getting too excited yet - it has been less than 24 hours, but it feels like progress!
Comment: I once had an intermittent network problem and I realised that software doesn't usually (there are exceptions) terminate network connections suddenly due to settings.  It's either a bug in the software or a loose cable, etc.  Software bugs might be experienced by the wider Ubuntu committee...so I'd start with physical connections first...  Out of frustration/anger, I was tempted to buy a proper network cable tester...  Good luck with your problem!
Answer: I was experiencing the same problem with a server a couple of months ago, turns out it was a routing problem in my case I got two ether nics, both with a default route, so I deleted one and problem solved, check if it's the same problem in your case.
Comment: Good idea. I recall messing around with network settings when setting up lxc, so I checked it using netstat -rn. This produced:

    `Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface`
    `0.0.0.0         192.168.1.1     0.0.0.0         UG        0 0          0 enp2s0`
    `192.168.1.0     0.0.0.0         255.255.255.0   U         0 0          0 enp2s0`


Docker seems to include OS?

Question: I'm just starting docker.
According to some articles, the most significant difference of docker from VM is that it doesn't run on an emulated OS but on the host kernel.
However, when I run the nginx image on my Mac:
<code>$ docker run -d nginx
a88142a23cb4e1900093ee4a27303f7d80adb0305e4008203829a84ae29ca4f2
$ docker exec -it a88142a23cb4e1900093ee4a27303f7d80adb0305e4008203829a84ae29ca4f2 bash
root@a88142a23cb4:/# cat /etc/*release
PRETTY_NAME="Debian GNU/Linux 9 (stretch)"
NAME="Debian GNU/Linux"
VERSION_ID="9"
VERSION="9 (stretch)"
ID=debian
HOME_URL="https://www.debian.org/"
SUPPORT_URL="https://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"
root@a88142a23cb4:/#
</code>
So for me, it seems like this container actually runs Debian, and nginx on top of it.
Now I'm totally confused. Can somebody explain this output?
Comment: Why downvote? Please tell me the reason.
Answer: Docker use a base image to start which generally a OS image(Not actually OS. It does not have a kernel). It provides a file system and necessary library to run  your application.
For more details, see this answer: https://stackoverflow.com/a/53049134/7695859

Docker seems to include OS?


After installing Ubuntu 14.04 Over windows 8.1 i'm unable to boot from my DVD Drive

Question: Fun story, i had Ubuntu and Windows 8.1 both installed on my pc. When attempting to re install it detected Ubuntu and said if i wanted to replace that i was like ooh nice, now i don't have to change partitions and stuff. Instead in installed it over everything on the drive. after that i thought i'd just re install windows 8.1 again and then do the dual boot again.. But now even when i change the boot order it for some reason won't go into the windows installation. Can anyone help me with this? Because i'm really clueless and need windows on my pc for Visual Studio 2013 (school related)...
Comment: @Fabby i did not test the F12 key yet but did just test it and even after getting that menu and selecting the disc, it still did not go to the installation and went to Ubuntu.
Comment: How are you trying to boot?  Do you press a key ([F12] most of the time) and then boot?  Or did you try re-arrange the boot order in BIOS?  If the latter, try the boot key at start-up anyway, because some BIOSes have a timing issue and boot the HD is the DVD doesn't spin up fast enough...
Comment: Can you post the output of `fdisk -l` in your question and put the contents of /boot/grub/grub.cfg in http://paste.ubuntu.com?
Answer: I found the solution myself, the problem was that my bios was set to the new windows 8 UEFI boot mode and i needed to set it to legacy. (UEFI is the new thing with windows 8 i believe)


How to have consistent width in material ui

Question: I have two Goal components and I don't know what is causing their width to behave in this manner

I have tried setting the width of the Paper selector to 100% but it had no effect on each Goal component. How can I responsively set a consistent width on each side of this Goal component? Something perhaps like this... with the black box representing the web page and the red boxes representing the goal components

Current code is listed below for reference:
import React, { useEffect } from "react";
import Moment from "react-moment";
import PropTypes from "prop-types";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import { getGoals } from "../../actions/goal";
import Spinner from "../layout/Spinner";
import Navbar from "../dashboard/Navbar";
import ThumbUpAltIcon from "@material-ui/icons/ThumbUpAlt";
import ThumbDownAltIcon from "@material-ui/icons/ThumbDownAlt";
import ChatIcon from "@material-ui/icons/Chat";
import DeleteIcon from "@material-ui/icons/Delete";
import DoneIcon from "@material-ui/icons/Done";
import {
  Typography,
  Container,
  CssBaseline,
  makeStyles,
  Grid,
  Avatar,
  Paper
} from "@material-ui/core";

const useStyles = makeStyles(theme => ({
  paper: {
    height: "auto"
  },
  actionButtons: {
    marginTop: "3vh"
  },
  profileHeader: {
    textAlign: "center",
    marginBottom: 20
  },
  avatar: {
    width: theme.spacing(7),
    height: theme.spacing(7)
  }
}));

const Goals = ({ getGoals, auth, goal: { goals, user, loading } }) => {
  useEffect(() => {
    getGoals();
  }, [getGoals]);

  const classes = useStyles();

  return loading ? (
    <>
      <Navbar />
      <Container component="main" maxWidth="xs">
        <CssBaseline />

          <Spinner />

      </Container>
    </>
  ) : (
    <>
      <CssBaseline />
      <Navbar />

        <Container>
          <Typography variant="h2" className={classes.profileHeader}>
            Goals
          </Typography>
          {/* parent grid */}
          <Grid container spacing={4}>
            {goals.map(singleGoal => (
              <Paper key={singleGoal._id}>
                <Grid
                  className={classes.paper}
                  spacing={1}
                  container
                  direction="row"
                  alignItems="center"
                >
                  <Grid
                    item
                    container
                    direction="column"
                    justify="center"
                    alignItems="center"
                    xs={3}
                  >
                    <Avatar
                      className={classes.avatar}
                      src={singleGoal.avatar}
                    />
                    <Typography variant="caption">{singleGoal.first_name} {singleGoal.last_name}</Typography>
                    <Typography variant="caption" className={classes.postedOn}>
                      Posted on{" "}
                      <Moment format="MM/DD/YYYY">{singleGoal.date}</Moment>
                    </Typography>
                  </Grid>
                  <Grid container item direction="column" xs={9}>
                    <Typography variant="body1">
                    {singleGoal.text}
                    </Typography>
                    <Grid item className={classes.actionButtons}>
                      <ThumbUpAltIcon />
                      <ThumbDownAltIcon />
                      <ChatIcon />
                      <DoneIcon />
                      <DeleteIcon />
                    </Grid>
                  </Grid>
                </Grid>
              </Paper>
            ))}
          </Grid>
        </Container>

    </>
  );
};

Goals.propTypes = {
  getGoals: PropTypes.func.isRequired,
  goal: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
  goal: state.goal,
  auth: state.auth
});

export default connect(mapStateToProps, { getGoals })(Goals);

Answer: The weird behaviour is because you're wrapping you component in a <Paper>. The Grid container should be filled with Grid items to make it behave as expected. So removing the <Paper key={singleGoal._id}> should improve it a lot. You can then use CSS to make the inner Grid item white or even add component={Paper} to its props.
So something like this
<Grid container spacing={4}>
  {goals.map(singleGoal => (
    <Grid
      className={classes.paper}
      spacing={1}
      container
      direction="row"
      alignItems="center"
      component={Paper}
    >
      <Grid
        item
        container
        direction="column"
        justify="center"
        alignItems="center"
        xs={3}
      >
        <Avatar className={classes.avatar} src={singleGoal.avatar} />
        <Typography variant="caption">
          {singleGoal.first_name} {singleGoal.last_name}
        </Typography>
        <Typography variant="caption" className={classes.postedOn}>
          Posted on <Moment format="MM/DD/YYYY">{singleGoal.date}</Moment>
        </Typography>
      </Grid>
      <Grid container item direction="column" xs={9}>
        <Typography variant="body1">{singleGoal.text}</Typography>
        <Grid item className={classes.actionButtons}>
          <ThumbUpAltIcon />
          <ThumbDownAltIcon />
          <ChatIcon />
          <DoneIcon />
          <DeleteIcon />
        </Grid>
      </Grid>
    </Grid>
  ))}
</Grid>;


What does Resharper have against the commonly-used getRange() in Excel Interop?

Question: Almost all of the example code online for C# Excel interop has stuff like this:
monthlyChartRange = _xlSheetChart.get_Range("A3", "C4");

Yet, Resharper turns up its nose at it and demands: "Use indexed property" If you accede to its wishes (and I love R#, so I always say, "As you wish"), it changes it to:
monthlyChartRange = _xlSheetChart.Range["A3", "B4"];

Why? How is Range better than get_Range? How is the former any more indexed than the latter?
Comment: See [this article](http://blogs.msdn.com/b/kirillosenkov/archive/2009/10/20/indexed-properties-in-c-4-0.aspx). It isn't about OO at all as mentioned in the answer, its just about cleaner syntax.
Answer: Resharper is trained to use properties instead of the underlying Getter because it's easier code to read and more OO-like. The property just calls the getter under the covers.
The COM port of Excel automation just exposed the Getter, even though this is not really all that OO-ish.
BTW, I recommend using Aspose Cells instead of Office automation. It's like ten trillion times faster.
Comment: How is a 'property', a term that applies to a specific implementation of a specific programming language, "more OO-like" than a function which accomplishes the same thing (i.e., encapsulation)?  I think you've been brainwashed into an incorrect view of what object oriented programming really is.  C++ has no properties, would you say that it is less OO than e.g. C# purely based upon that?
Comment: I love the look of hyperbole on a Friday afternoon (Your time of day may vary).
Comment: @EdS., I didn't say that, that's just the motivation behind what Resharper did. It's for c#, not c++, so that's the target language.
Comment: @toddmo Haha no worries.  Thanks for the edit. Down-vote removed.  Have a fine weekend :)
Answer:
Yet, Resharper turns up its nose at it and demands: "Use indexed property"

A bit of an intro - COM goes way back. You must bare in mind that COM is a binary protocol and that some COM-aware languages have no concept of properties.
COM indexed properties are generally defined like so:
[propget, id(DISPID_VALUE), helpstring("blah")]
HRESULT Item([in] long Index, [out, retval] BSTR* Item);

The dispatch ID is DISPID_VALUE which informs clients that this is the default property typically used for indexed properties.  Notice how it is defined as a property get but interestingly it takes a parameter index.  The notion of a property getter that takes an argument can be confusing to some programming languages as we shall see.
Fully COM-compliant Client Languages
A good COM-aware client language (such as VB6; VBA; .NET) will allow you to interact with the object like so:
string thing = myObject.Item[2];

These languages sees that this particular property is a propget however it takes and in parameter.  The fact that it is marked as DISPID_VALUE is rather riveting because that tells COM clients that it is the default property.  Putting two and two together, clients will realise that it must be a dandy indexed property so that they can use groovy square brackets.
It's important to realise that this is just sugar syntax.  It's just a more convenient way to call the default indexed property.  Behind the scenes, it will call the same COM property getter method as per un-compliant languages as shown below.
Not-so-COM-compliant Client Languages
Some programming languages (like Visual Objects 2.6), freak out (then again I freak out when I use VO) when they see a COM property that takes a parameter and so it falls back to the underlying method declaration where it essentially treats it as a method call that takes an index parameter and returns a string:
string thing = myObject.get_Item(2)  //  Boo!

These clients probably also missed the important fact that the property was marked as DISPID_VALUE.
Now with c#, you are arguably free to use the method-style operations to query a property or do as COM was designed and use index property notation.
After all, c# is OO; understands properties; understands indexers so why wouldn't you use them?
Hence why Resharper is prompting you to use the COM-preferred indexed style.  It's no different to how you would use a regular c# class.