Unable to install or remove MySQL

Question: So today I installed MariaDB so I can login through phpmyadmin, apparently it didn't work so I removed it, tried again like four times and I failed. Decided to go with MySQL Server instead. I couldn't install it after removing MariaDB.
Here's what I'm trying to do and the outputs:
shavit@dedi:~$ sudo apt-get install mysql-server
[sudo] password for shavit:
Reading package lists... Done
Building dependency tree
Reading state information... Done
mysql-server is already the newest version (5.7.12-0ubuntu1).
0 to upgrade, 0 to newly install, 0 to remove and 0 not to upgrade.
2 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Do you want to continue? [Y/n] y
Setting up mysql-server-5.7 (5.7.12-0ubuntu1) ...
mysql_upgrade: Got error: 1524: Plugin 'unix_socket' is not loaded while connect                                                                                ing to the MySQL server
Upgrade process encountered error and will not continue.
mysql_upgrade failed with exit status 11
dpkg: error processing package mysql-server-5.7 (--configure):
 subprocess installed post-installation script returned error exit status 1
dpkg: dependency problems prevent configuration of mysql-server:
 mysql-server depends on mysql-server-5.7; however:
  Package mysql-server-5.7 is not configured yet.

dpkg: error processing package mysql-server (--configure):
 dependency problems - leaving unconfigured
No apport report written because the error message indicates it's a follow-up er                                                                                ror from a previous failure.
                            Errors were encountered while processing:
 mysql-server-5.7
 mysql-server
E: Sub-process /usr/bin/dpkg returned an error code (1)

shavit@dedi:~$ sudo apt-get remove mysql-server
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
  libaio1 mysql-client-5.7 mysql-client-core-5.7 mysql-common mysql-server-5.7
  mysql-server-core-5.7
Use 'sudo apt autoremove' to remove them.
The following packages will be REMOVED
  mysql-server
0 to upgrade, 0 to newly install, 1 to remove and 0 not to upgrade.
2 not fully installed or removed.
After this operation, 159 kB disk space will be freed.
Do you want to continue? [Y/n] y
(Reading database ... 35749 files and directories currently installed.)
Removing mysql-server (5.7.12-0ubuntu1) ...
Setting up mysql-server-5.7 (5.7.12-0ubuntu1) ...
mysql_upgrade: Got error: 1524: Plugin 'unix_socket' is not loaded while connecting to the MySQL server
Upgrade process encountered error and will not continue.
mysql_upgrade failed with exit status 11
dpkg: error processing package mysql-server-5.7 (--configure):
 subprocess installed post-installation script returned error exit status 1
Errors were encountered while processing:
 mysql-server-5.7
E: Sub-process /usr/bin/dpkg returned an error code (1)

I'm really lost right now.. Googling told me I should run apt-get install -f but that's what I get:
shavit@dedi:~$ sudo apt-get install -f
Reading package lists... Done
Building dependency tree
Reading state information... Done
0 to upgrade, 0 to newly install, 0 to remove and 0 not to upgrade.
2 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Setting up mysql-server-5.7 (5.7.12-0ubuntu1) ...
mysql_upgrade: Got error: 1524: Plugin 'unix_socket' is not loaded while connecting to the MySQL server
Upgrade process encountered error and will not continue.
mysql_upgrade failed with exit status 11
No apport report written because the error message indicates it's a follow-up error from a previous failure.
                                                                                dpkg: error processing package mysql-server-5.7 (--configure):
 subprocess installed post-installation script returned error exit status 1
dpkg: dependency problems prevent configuration of mysql-server:
 mysql-server depends on mysql-server-5.7; however:
  Package mysql-server-5.7 is not configured yet.

dpkg: error processing package mysql-server (--configure):
 dependency problems - leaving unconfigured
Errors were encountered while processing:
 mysql-server-5.7
 mysql-server
E: Sub-process /usr/bin/dpkg returned an error code (1)

So I ran sudo apt-get autoremove and proceed to install again:
dpkg: error processing package mysql-server (--configure):
 dependency problems - leaving unconfigured
Processing triggers for libc-bin (2.23-0ubuntu3) ...
No apport report written because the error message indicates it's a follow-up error from a previous failure.
                            Errors were encountered while processing:
 mysql-server-5.7
 mysql-server
E: Sub-process /usr/bin/dpkg returned an error code (1)

I'm a newbie with anything related to Linux and especially Ubuntu.
Could anyone lend their hand and help me? Much appreciated!
Comment: Maybe try [this](http://stackoverflow.com/a/11869352/4700944)
Comment: @Alex I actually did try it, Kaz Wolfe's solution worked though
Comment: Glad that we could help.
Answer: I think the fact that you had MariaDB installed caused this problem. The configs that MariaDB set up do not exactly play nice with vanilla MySQL. If you were to purge all of the old configs and set everything up from scratch, it should work. Note though that this will delete your current DBs! Back up any important data.
Try running the following command to reset and purge all MySQL related things:
sudo apt purge mysql-client-5.7 mysql-client-core-5.7 mysql-common mysql-server-5.7 mysql-server-core-5.7 mysql-server

Once this is done, run the below to update your system and "clean up" your package cache.
sudo apt update && sudo apt dist-upgrade && sudo apt autoremove && sudo apt -f install

Then, try re-installing MySQL Server:
sudo apt install mysql-server

Comment: While running the first command, I've got this output: `dpkg: warning: while removing mysql-common, directory '/etc/mysql' not empty so not removed` - should I remove `/etc/mysql`?
Comment: @shavit Yeah, it's probably a good idea to remove those files.
Comment: Thank you, I've installed MySQL Server successfully! One last thing as it seems you're experienced: the brand new MySQL server I installed doesn't let me access it via `sudo mysql_secure_installation`, it worked when I had MariaDB. Do you have any idea about what might be wrong?
Comment: @shavit You should ask this in a new question. Link it here, and I'll see what I can do. Please be sure to include any error messages you get.
Comment: Thank You! I was trying to fix the issue from hours.  :)
Answer: This error can occur when you install mariadb-server before mysql-server. To resolve this error, you must delete directories /var/lib/mysql* and /etc/mysql* to remove all configurations and dependencies files, before trying to install MySQL again.
sudo apt purge mysql-client-5.7 mysql-client-core-5.7 mysql-common mysql-server-5.7 mysql-server-core-5.7 mysql-server
sudo apt update && sudo apt dist-upgrade && sudo apt autoremove && sudo apt -f install
sudo apt install mysql-server

Comment: this finally worked for me. Thanks.

Unable to install or remove MySQL


Searching a prefix in list of dictionaries in python

Question: I have currently a list of dictionaries
list_of_dicts = [{"name": 'stfdahbancssc',"status":'running'},
                 {"name": 'stfdahbancssc',"status":'running'}]

I want to check how can i match the prefix 'stf' and print stf exists otherwise stf does not exist .
Answer: Iterate the dictionaries, get the "name" value, check for prefix, print message:
list_of_dicts = [{"name": 'stfdahbancssc',"status":'running'},
                {"name": 'stfdahbancssc',"status":'running'},
                {"name": 'none'}]

for idx,d in enumerate(list_of_dicts):
    if d.get("name","").startswith("stf"):
        v = d["name"]
        s = d["status"]
        print(f"The {idx} dictionary has {v} as {s}")
        print("a")
    else:
        print(f"The {idx}. dictionary has no name starting with 'stf'.")

Output:
Comment: In case i want to also check whether the status is running or not how do i proceed to changes here . lets say another dictionary has status of error
Comment: @kshi  I suggest following https://docs.python.org/3/tutorial/ as a starting point and learn how to work with pythons list / dict / etc instead of moving the goal posts of your question...


SQLAlchemy connection hangs on AWS MySQL RDS reboot with failover

Question: We have a Python server which uses SQLAlchemy to read/write data from an AWS MySQL MultiAZ RDS instance.
We're experiencing a behavior we'd like to avoid where whenever we trigger a failover reboot, a connection which was open already and then issues a statement hangs indefinitely. While this is something to expect according to AWS documentation, we would expect the Python MySQL connector would be able to cope with this situation.
The closest case we've found on the web is this google groups thread which talks about the issue and offers a solution regarding a Postgres RDS.
For example, the below script will hang indefinitely when initiating a failover reboot (adopted from the above mention google groups thread).
<code>from datetime import datetime
from time import time, sleep
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.scoping import scoped_session
from sqlalchemy.ext.declarative import declarative_base

import logging

current_milli_time = lambda: int(round(time() * 1000))
Base = declarative_base()

logging.basicConfig(format='%(asctime)s %(filename)s %(lineno)s %(process)d %(levelname)s: %(message)s', level="INFO")

class Message(Base):
    __tablename__ = 'message'
    id = Column(Integer, primary_key=True)
    body = Column(String(450), nullable=False)

engine = create_engine('mysql://<username>:<password>@<db_host>/<db_name>',echo=False, pool_recycle=1800,)
session_maker = scoped_session(sessionmaker(bind=engine, autocommit=False, autoflush=False))
session = session_maker()

while True:
    try:
        ids = ''
        start = current_milli_time()
        for msg in session.query(Message).order_by(Message.id.desc()).limit(5):
            ids += str(msg.id) + ', '
            logging.info('({!s}) (took {!s} ms) fetched ids: {!s}'.format(datetime.now().time().isoformat(), current_milli_time() - start, ids))

        start = current_milli_time()
        m = Message()
        m.body = 'some text'
        session.add(m)
        session.commit()
        logging.info('({!s}) (took {!s} ms) inserted new message'.format(datetime.now().time().isoformat(), current_milli_time() - start))

    except Exception, e:
        logging.exception(e)
        session.rollback()
    finally:
        session_maker.remove()

    sleep(0.25)
</code>
We've tried playing with the connection timeouts but it seems the issue is related to an already opened connection which simply hangs once AWS switches to the failover instance.
Our question is - has anyone encountered this issue or has possible directions worthwhile checking?
Comment: It is definitely not supposed to be seamless to the clients. From the [docs](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_RebootInstance.html): "When you force a failover of your DB instance, Amazon RDS automatically switches to a standby replica in another Availability Zone and updates the DNS record for the DB instance to point to the standby DB instance. As a result, you will need to clean up and re-establish any existing connections to your DB instance."
Comment: You're totally correct, I'm wondering if the Python DB connector has a way of sensing this situation
Comment: How are you setting connection timeouts? If the problem is with existing connections, it sounds like the remote host isn't sending a FIN packet when it's shutting down, which is worrying. Normally, when you gracefully shut down a host, applications will close open socket connections gracefully. A connection should not hang unless some router in the middle is dropping TCP RST packets.
Comment: First of all, I've edited the question to reflect your comment about AWS documentation. About timeouts, that seems to have no effect if the failover happens after the connection opened. I've tried searching for ways to effect socket timeouts specifically through SQLAlchemy but come out short
Comment: Can you show the specific code for how you are setting the timeout?
Comment: sure:

`engine = create_engine('mysql://:@/', echo=False, pool_recycle=1800, connect_args = {'connect_timeout': })`

or

`engine = create_engine('mysql://:@/?connect_timeout=', echo=False, pool_recycle=1800)`
Comment: Bare in mind that, there is many MySQL connector for SQLAlchemy, you never know which one actually work for the timeout switch over conditions
http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#module-sqlalchemy.dialects.mysql.mysqldb
Comment: Thanks for pointing that out, for now I'm leaving this as the effort seems to great for the return. Thanks!
Answer: IMHO, using SQL connector timeout to handle switchcover is like black magic. Each connector always act differently and difficult to diagnose.
If you read @univerio comment again, AWS will reassign a new IP address for the SAME RDS endpoint name.  While doing the switching, your RDS endpoint name and old IP adderss is still inside your server instance DNS cache. So this is a DNS caching issues, and that's why AWS ask you to "clean up....".
Unless you restart SQLAlchemy to read the DNS again, there is no way that the session know something happens and switch it dynamically. And worst, the issue can be happens in connector that used by SQLAlchemy.
IMHO, it doesn't worth the effort to deal with switch over inside the code. I will just subscribe to AWS service like lambda that can act upon switch over events, trigger the app server to restart the connection, which suppose to reflect the new IP address.


How to serialize a form into an object with jQuery?

Question: $('form').serialize() will generate something like a=1&b=2,but what I want to get is {a:1,b:2}.
How to do this?
Further more,is it possible to do this kind of job to arbitrary container like div?
Comment: 35 questions / 25% AR is pretty grim.
Comment: possible duplicate of [Serializing to JSON in jQuery](http://stackoverflow.com/questions/191881/serializing-to-json-in-jquery)
Answer: jQuery doesn't support this. You'll have to use JSON.stringify, which is supported in some modern browsers, but for support in older browsers, you have to include the json2 library as a


How to get the duration length of an mp3 file from a URL

Question: I have a requirement to get the length in seconds from an audio file. All I am given is the URL of the file. I have tried with the NAudio library but when I try using a URL as source I get the error-

The given path's format is not supported

Below is the code-
 Mp3FileReader reader = new Mp3FileReader(RecordingURL);
 Result = reader.TotalTime

Comment: Why don't you download the file first?
Answer: Mp3FileReader cannot open files from a URL, but MediaFoundationReader can, so you should try that instead.


How to print the contents of an OSX textclipping file from terminal?

Question: In OSX (I'm on 10.7.x, Lion), you can grab some text from most any app and drag it to the desktop to get a "snippet.textClipping" file.  The file is not just raw text, though -- the text is hidden away, somewhere (in a resource?)  I've tried poking around with DeRez, but haven't been able to bend it to my will.  What I'm looking for is the ability to get what one might think would be the output from
cat mysnippet.textClipping
NOTE: These clippings were made under an older version of OSX.  Maybe Leopard.  Maybe older, it's been a while.  :)
Thanks!
P.S. I've got a folder with 1600+ of them, that's why I'm looking to script this, not just manually copy/pasting them into a text file.
P.P.S.  Yes, if I just select-all then drag into an open, empty text document, it does as you'd expect.  But I still want to do it via script, so I can put the name of the clipping first and a blank line ahead of each, etc.
Comment: Another option, besides DeRez, is to use AppleScript (or Automator, or Python+ScriptingBridge, or whatever you prefer) to script TextEdit to do what you want. That will automatically handle cases like converting the best option of RTFD, RTF, HTML, or plain text to RTFD, getting the charset right, etc.
Comment: You can use `strings < filename.textClipping/rsrc` or just `cat filename.textClipping/rsrc` to get the file contents, but I'm not sure how you'd go about cleaning it up from there. Perhaps there's a better way.
Comment: `filename.textClipping/rsrc: Not a directory.`  The DeRez command in the accepted answer did the trick.  Not a directory may have to do with the age of the clippings -- I don't really know if the formats changed.  (That makes sense though, as many suggestions here and elsewhere on the web that others said work did not work for me.)
Comment: I do like the idea of using AppleScript, as I think it is probably the best way to do this. I just can't write AppleScript code to save my life.
Comment: A late comment on the above `rsrc` access, but it might be useful to someone coming here from Google like me. The right command would be `strings filename.textClipping/..namedfork/rsrc`. It would reveal rtf formatted data.
Answer: Here's something ugly that could work:
DeRez -only TEXT foo.textClipping | perl -ne 'm|/\* (.*) \*/| && print $1; END {print "\n"}'

Basically, it extracts the text from the C-style comments in the DeRez output and prints it all on one line. I got the idea from another Stack Overflow question (which I cannot find now).
Comment: This doesn't work correctly with nonprintable and control characters, which get shown as `.` by DeRez.
Comment: +1. But you probably want the utf8, not the TEXT, because otherwise you have to pass it through iconv or something to convert from MacRoman. (And that's assuming you want the plain text, not the RTF or HTML…)
Comment: Oddly, utf8 and UTF8 both returned nothing, but TEXT did what I want (modulo the transition.)  Could be because of the age of the clippings.  Either way, I'm going to take this answer as exactly doing what I want -- thanks!
Answer: Unfortunately, chepner's answer didn't do the trick because nonprintable and control characters are crucial to me, and neither did reading rsrc because the output was too challenging to clean. Equally unfortunate is that I have a bunch of important text stuck in .textClippings. ♂
Inspired by chepner's solution, this ended up doing the trick:
#!/usr/bin/env bash

input="${1:?missing argument}"
derezed="$(DeRez -only utf8 "$input")"
n_lines="$(wc -l <<<"$derezed")"

tail -n $((n_lines-1)) <<<"$derezed" \
    | head -n $((n_lines-2)) \
    | cut -d \" -f 2 \
    | xxd -p -r

The script takes the hexadecimal UTF-8 output from DeRez and passes it through xxd. In my case, the script's output is plain text without any style tags. file identifies the output as Unicode text, UTF-8 text.
I ran the script on macOS 12.6.7.
Comment: The `wc` and `head` + `tail` combo could be reduced; the entire script then becomes a one-liner `DeRez -only utf8 "${1?Missing argument}" | sed -e '1d' -e '$d' | cut -d \" -f 2 | xxd -p -r` which should be a fair bit more efficient, too. (The last mile optimization woud fold the `cut` into the `sed` script, too - `-e 's/^[^"]*"\([^"]*\).*/\1/'` - but this hampers legibility a bit, especially if you aren't very good with regex.)


how is the size of every pointer variable being 8 bytes on a 64-bit machine justified?

Question: I went through pointer arithmetic and the fact that you can't assign pointer of one data type to another data type. for example, below declaration is incorrect.
  double x = 10;
  int *ptrInt = &x;

We've assigned the address of double variable to a "pointer to integer". Double takes 8 bytes as compared to an integer, that takes 4 bytes and therefore an integer pointer will truncate those extra 4 bytes.
But how come, the size of any pointer variable is 8 bytes and that also means it will not truncate those extra 4 bytes and should work correctly(even though it doesn't).
I have this doubt. Can anybody help me with the clarification?
Comment: The size of a pointer has nothing to do with the size of the object it points to.  A 64-bit pointer supports a 64-bit address space.  For instance, suppose you had an array of 2**34 character variables.  You would need a minimum of 34 address bits to address every element of the array, even though the elements themselves are only 1 byte each.
Comment: The pointer is the address. The variable (x) is what lives at that address. If you assign the address of a double to an int pointer and dereference the int pointer, you're going to get sizeof(int) bytes out. It's a strange workflow, so you have to jump through some hoops to say "yes, I really want to do this". And you probably don't
Comment: https://stackoverflow.com/a/17260931/2850543
Comment: Think about `printf ("pointer size: %lu-bytes\n", sizeof (void*));`
Answer: how come, the size of any pointer variable is 8 bytes ? pointer variable contains address & size of address is 8 byte on 64-bit system irrespective of whether pointer variable points to int or char or float objects as 64-bit pointer supports 8 byte address space.
Comment: OK, but if the pointer only supports `8-byte` address space, why do tools like `objdump -x` report address with 16 bytes?


Return an array with element in specific position

Question: I've been trying to figure this out for a good while now, and I can't solve it.
This function receives an array of names and should return an array containing the middle names. If someone does not have a middle name the array should contain the value null at this index.
I know my code isn't complete, but cannot make work even half of it. The splice method doesn't work whatever I do, and now I'm very lost.
This is my code so far:
function getMiddleNames (names) {
let solution =[];
let separated = [];
for(let i=0; i<names.length; i++){
  separated.push(names[i].split(' '));
}
 return separated.splice(1);
}

And the tests:
describe('getMiddleNames', function () {
  it('returns [] when passed []', function () {
    expect(getMiddleNames([])).to.eql([]);
  });
  it('returns ["Hannah"] when passed ["Caroline Hannah Jamieson"]', function () {
    expect(getMiddleNames(['Caroline Hannah Jamieson'])).to.eql(['Hannah']);
  });
  it('returns ["Reuben", "Keith", "Clara"] when passed ["Steven Reuben Williams", "Carl Keith Morelli", "Sissel Clara Blomqvist"]', function () {
    expect(getMiddleNames(['Steven Reuben Williams', 'Carl Keith Morelli', 'Sissel Clara Blomqvist'])).to.eql(['Reuben', 'Keith', 'Clara']);
  });
  it('returns ["Reuben", null, "Clara"] when passed ["Steven Reuben Williams", "Carl Morelli", "Sissel Clara Blomqvist"]', function () {
    expect(getMiddleNames(['Steven Reuben Williams', 'Carl Morelli', 'Sissel Clara Blomqvist'])).to.eql(['Reuben', null, 'Clara']);
  });
  it('returns ["Reuben", null, null] when passed ["Steven Reuben Williams", "Carl Morelli", "Sissel"]', function () {
    expect(getMiddleNames(['Steven Reuben Williams', 'Carl Morelli', 'Sissel'])).to.eql(['Reuben', null, null]);
  });
});

Could anyone give me a hand? Thank you
Comment: hint: check length of split array
Answer: Your pushing the whole name into your separated array and then splicing that. Which doesn't really work. You need to separate the names and split each one individually:

function getMiddleNames (names) {
    let solution =[];
    for(let i=0; i<names.length; i++){
    let separated = names[i].split(' ')
      solution.push(separated.length == 3 ? separated[1] : null);
    }
     return solution
    }

let names = ['Steven Reuben Williams', 'Carl Morelli', 'Sissel Clara Blomqvist']

console.log(getMiddleNames(names))

This of course assumes there will always be a middle name. It will fail and deliver the last name without it.
You can be a bit more succinct with map and test for name length at the same time. Still there will be edge cases (people with four names, etc):

let names = ['Steven Reuben Williams', 'Carl Keith Morelli', 'Sissel Clara Blomqvist']

let middles= names.map(n => {
    s = n.split(' ')
    // s should be an array [first, middle, last]
    // if no middle name it will be [first, last]  and length 2
    return s.length == 3 ? s[1] : null
})
console.log(middles)
Comment: It works partially, as returns this error:AssertionError: expected [ [ 'Hannah' ] ] to deeply equal [ 'Hannah' ]
      + expected - actual

       [
      -  [
      -    "Hannah"
      -  ]
      +  "Hannah"
       ]
Comment: @VisualXZ Right, that's because `slice` returns an array. I edited to just return the value. The map version should take care of nulls. Also edited the first to check for no middle name.
Comment: I see it now, thanks for your help. The map version is still a bit far from what I'm able to do at the moment, but trying to get used to it. Cheers.
Answer: try this:
function getMiddleNames(names) {
  return names.map(x => getMiddleNameOf(x));
}
function getMiddleNameOf(name) {
  let split = name.split(' ');
  return split.length == 3 ? split[1] : null;
}

Comment: Where does `x.getMiddleName` come from when `x` is a string? Answer doesn't appear to have anything to do with code in the question


How to use JKAutoShrinkView or GTScrollNavigationBar with storyboard

Question: I am trying to use JKAutoShrinkView but I am using storyboard and I am not sure how to translate the following notion:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

    UINavigationController *navigationController = [[UINavigationController alloc] initWithNavigationBarClass:[JKAutoShrinkNavigationBar class] toolbarClass:[JKAutoShrinkToolbar class]];
    [navigationController setToolbarHidden:NO animated:NO];
    [navigationController setAutoNavigationBarShirnkEnabled:YES];
    [navigationController setAutoToolbarShirnkEnabled:YES];

    JKViewController *viewController = [[JKViewController alloc] init];
    [navigationController pushViewController:viewController animated:NO];

    self.window.rootViewController = navigationController;

    return YES;
}

The same approach is taken by GTScrollNavigationBar. Basically, what is the storyboard equivalent? I am supposing the problem piece to be initWithNavigationBarClass. But someone who knows should be able to tell me how the translation goes.
Answer: Just change the class of Navigation Bar to GTScrollNavigationBar from storyboard in your Navigation Controller Scene
Comment: This works. Don't know why He didn't accept the answer.


Completion of $C_c(X)$ with respect to $\|\cdot\|_\infty$

Question: Notation:
All functions here are from $X$ to $\mathbb R$.
$C_c(X)$ = compactly supported continuous functions.
$C_b(X)$ = bounded continuous functions.
$B(X)$ = bounded functions.
$C_0(X)$ = continuous functions that tend to zero (so $X$ has to be locally compact and Hausdorff)

Today I proved that $C_c(\mathbb R)$ is not complete with respect to $\|\cdot\|_\infty$. One can do this by taking $g_n$ to be the function that is zero on $(-\infty,-n]$, linear on $[-n, -n+1]$, $1$ on $[-n+1, n-1]$ and symmetric with respect to the $y$-axis. For $f(x) = e^{-x^2}$ one can show that $\|fg_n - f\|_\infty \to 0$ but $f \notin C_c(\mathbb R)$.
Then I read about completions and wanted to work out the completion of $C_c$(X). (I did this all for $X = \mathbb R$). In any case, my thoughts were as follows: $C_c(X)$ is contained in $B(X)$. But it is a proper subset because the uniform limit of continuous functions is continuous but there are discontinuous bounded functions. The next candidate then seems to be $C_b(X)$ but $f(x) = 1$ is in there and not the uniform limit of $f_n$ in $C_c$. (cannot be because if $f_n$ is zero outside a compact set then $\|f_n - 1\|_\infty = 1$ for all $n$ so this doesn't converge in norm).
The next candidate then is $C_0(X)$ and I'm quite sure that that's the completion of $C_c$ with respect to $\|\cdot\|_\infty$ in $B(X)$. But now I need to show this by showing that $C_0(X)$ is isomorphic to the space of Cauchy sequences in $C_c(X)$ quotient Cauchy sequences that tend to the zero function and I don't really know how to think about this. Can someone please show me how to prove this? Thank you. I want to see this quotient construction and an isomorphism but if there are other ways to show that $C_0$ is the completion of $C_c$ then go ahead and post it, I will upvote it.
Comment: Is [this link](http://www.proofwiki.org/wiki/Completion_Theorem_(Metric_Spaces)) good enough? ProofWiki is usually not very good but this entry looks reasonable (I haven't read it).
Comment: If $f \in C_0(X)$ find a compact set $K$ such that $|f(x)| \lt \varepsilon$ whenever $x \notin K$. Consider the restriction $f|_K and remember Tietze (again :)).
Comment: Yes, that's right. Note that the completion is unique up to unique isometry, so you only have to find a complete space in which $C_c(X)$ is dense with respect to $\|\cdot\|$ and I suggested how to show that $C_c$ is dense in $C_0$. And yes, we've convinced ourselves at various points over the last half-a-year that $B(X) = \ell^\infty(X)$ is complete...
Comment: Of course you can use Tietze. Take an open set $U$ with compact closure containing $K$ (you can do that by local compactness of $X$). Define a function $g$ on $K \cup (X \smallsetminus U)$ by $g = f|_K$ on $K$ and $g = 0$ on $X \smallsetminus U$. Observe that $g$ is continuous. Now extend.
Comment: My suggestion works on any locally compact Hausdorff space. But on $\mathbb{R}$, you can use those $g_n$'s, yes.
Comment: @t.b. It's good. It's what is shown in the notes linked to in the comments to ncmathsadist's answer.
Comment: Addendum: I started to think about this because there is an exercise in my notes that asks me to find a Banach space $B$ containing $(C_c, \|\cdot\|_\infty)$ such that the norm on $B$ restricted to $C_c$ is the same as $\|\cdot\|_\infty$. I think $B(X)$ is such a space (easy to show that it's complete), right?
Comment: @t.b. I upvoted your comments (as mentioned in my question). But I still want to see the quotient construction with the isomorphism!
Comment: @t.b. How can I use Tietze here? If I continuously extend $f\mid_K$ to $\mathbb R$, I get a continuous function which is what I had to begin with. Tietze doesn't give me compact support. OTOH, if I take the (usual) $g_n$ (same as I used in my question) then I get a sequence $fg_n$ in $C_c$ converging to $f \in C_0$ in $\|\cdot\|_\infty$.
Comment: @t.b. But I could also just use $fg_n$, no?
Comment: @t.b. Great! Thanks for these comments! Now for maximum awesome you could write an answer that shows the quotient construction with an iso from the quotient thingie to $C_0$ : )
Comment: @t.b. I was hoping to learn something from seeing it done with the concrete example at hand. For example, next time in the same situation how to see the completion. I can do that if I "see" what the quotient space of sequences looks like.
Comment: @t.b. But at the moment I can still only *guess* that Cauchy sequences in $C_c$ modulo Cauchy sequences converging to zero (in $\|\cdot\|_\infty$) look like $C_0$. And then tomorrow when I'll replace the sup norm with $\|\cdot\|_p$ I might be stuck (=*head asplode*) again.
Comment: @t.b. [Or not.](http://chat.stackexchange.com/transcript/message/2918479#2918479) Now I need to come up with an example to which I don't know the answer!
Answer: In a locally compact space, the $C_0$ functions are complete in the $\|\cdot\|_\infty$ norm; they constitute a Banach Space in this norm.    The space $C_c(X)$ is dense in $C_0$ if $X$ is locally compact and Hausdorff.  This is sufficient to tell you that $C_0(X)$ is the completion of $C_c(X)$ in a locally compact Hausdorff space.
Comment: Look at pp. 17 ff in this:  http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=21&ved=0CE0QFjAAOBQ&url=http%3A%2F%2Fwww.ima.umn.edu%2F~miller%2Fwaveletsnotes.pdf&ei=FtH9T-CUIIex0AG928SCBw&usg=AFQjCNHRzbXC2p-_AlFcKFHY4TxwnoexTg&sig2=wXLHa62la_4OZY2xvVrxxg
Comment: Yes. +1 I still would like to see the construction with the quotient space and an isomorphism. : )
Comment: Mainly because I have not proved that completions are unique up to unique isometry so I don't understand properly why it's enough to show that it's dense in a complete space. But I have a good idea of what the quotient construction looks like (like the construction of the reals from $\mathbb Q$).
Comment: They seem to skip the proof of isometry of any two completions. But they do it in the proof linked to in the comments to the question.


android maps not showing map

Question: I got api key properly . even map does not show on emulator or device.
Comment: have you added uses-library in manifest file??
Comment: Check the Log cat. Whats the stack trace?
Answer: Internet connection permission missing?
<code><uses-permission android:name="android.permission.INTERNET"/>
</code>

android maps not showing map


Call a function when a child process finishes

Question: In my c++ program several child processes are started using fork and execv. I don't wait for them so they run in the background. When they finish running, I want to run a certain function. How can this be done?
Answer: Listen for the SIGCHLD signal and call your function in the handler. Be careful what you call in the handler, you should only call async-signal-safe functions.
Comment: How do you know what those functions are?
Comment: @z-buffer: There is a list at the end of this page: http://linux.die.net/man/2/signal
Answer: I'm guessing that you do want to wait for the processes to finish, but you want to run the processes in parallel rather than sequentially. If so, start each process as you do now, then use the waitpid() system call on each child pid. When every process has exited, every waitpid will have returned.
Comment: Not if you want to wait for the subprocesses to finish.
Comment: I don't want the parent process to wait for the child.


How to identify where in a list a certain letter is?

Question: I'm new to python, and trying to create hangman. I have created a list, but I can not figure out how to identify where in the list the users guess is. For instance, if the word is "yes", and the user guesses "y", the output is "correct". What I am striving for is "Y _ _".
Answer: Just do a for loop with enumerate() to notate the indeces of the correct letters guessed to match with the user's guesses.
user_guesses = ['_', '_', '_']
answer = ['Y', 'e', 's']
while '_' in user_guesses:
    user_guess = input('Guess a letter: ')
    correct = False
    for i, letter in enumerate(answer):
        if letter == user_guess:
            correct = True
            user_guesses[i] = letter
    if correct:
        print('correct')
    else:
        print('incorrect')
    print(*user_guesses)

Comment: Why not just `while '_' in user_guesses:` rather than `while (user_guesses.__contains__("_")):`?
Comment: Yes, much more readable.


Find which IP address was used by manage.py while the Django dev server was started

Question: In Django dev environment, we start our Django server in various way, like:-
python3 manage.py runserver which auto starts development server at http://127.0.0.1:8000/
OR
python3 manage.py runserver 192.168.1.1:8005 which auto starts development server at http://192.168.1.1:8005/
How or in what ways, can I find the IP address that the development server was started using which IP address and which port number?
I want to write a python script within this Django project (in an app), which could tell me that the dev server is accessible on <this_specific_ip_address> (ex: 127.0.0.1 or 192.168.1.1) and then on <this_specific_port_number> (ex: 8000 or 8005).
Is there a way this can be achieved?
Comment: Find out the process ID and then use `psutil.Process(pid=xxx).cmdline()` to get the command and find if there's an IP different from 127.0.0.1 or not.
Comment: ok -- I can manually find the PID, but i am not sure how to have the script within Django Project app auto-find the PID -- could you give pointers please @Daviid
Comment: Here is a [dirty trick](https://stackoverflow.com/a/10119663/11517893). You could improve it by adding a condition: `sys.argv[-1] if sys.argv[-1] != 'runserver' else '127.0.0.1:8000'`
Answer: Django runs with the following py file:
C:[...]\Django\venv\Lib\site-packages\django\core\management\commands\runserver.py
You could edit the def inner_run(self, *args, **options): method and add any code that will run only when the server starts.
With the following addition, you can save the last IP address and port that the server runs on to a file.
        with open('C:\\file.txt', 'w') as f:
            f.write(
            (
                "Django version %(version)s, using settings %(settings)r\n"
                "Starting development server at %(protocol)s://%(addr)s:%(port)s/\n"

            )
            % {
                "version": self.get_version(),
                "settings": settings.SETTINGS_MODULE,
                "protocol": self.protocol,
                "addr": "[%s]" % self.addr if self._raw_ipv6 else self.addr,
                "port": self.port
            }
        )

result: file.txt
Django version 4.0.4, using settings 'app.settings'
Starting development server at http://127.0.0.1:8000/

You could also write a log to a database.
Comment: What if we update Django ? We lose the custom code…


How to clone a structure between dimensions?

Question: The /clone command is used to clone structures from one location to another.
The /execute in command is used to change the dimension the command is executed in.
Say I want to clone a block from the Overworld coordinates (0, 0, 0) to the Nether coordinates (12, 23, 34).
/execute in minecraft:overworld run clone 0 0 0 0 0 0 12 23 34

uses both coordinates in the Overworld.
/execute in minecraft:the_nether run clone 0 0 0 0 0 0 12 23 34

uses both coordinates in the Nether.
I need the (0, 0, 0) to be in the Overworld, and the (12, 23, 34) to be in the Nether.
How do I clone a structure between dimensions?
Structure blocks can probably accomplish this, but I would prefer an answer without one.
Answer: What i could see from the wiki the /clone command cannot send structures from one dimension to another.
Theoretically you could scan through all the blocks in the structure. and send the scan results in falling sand blocks to the other dimension (just make sure to place a block they can fall on) but this is far from instant and i'd use structure blocks.
You can save the structure to minecraft:autoclone (can be any namespace)
/setblock ~ ~ ~ minecraft:structure_block{mode:"SAVE",posY:1,name:"minecraft:autoclone",sizeY:10,sizeX:10,sizeZ:10,author:"<yourname>",showboundingbox:1b} destroy

and load it from there with almost the same command just switch it to "LOAD" mode
/setblock ~ ~ ~ minecraft:structure_block{mode:"LOAD",posY:1,name:"minecraft:autoclone",sizeY:10,sizeX:10,sizeZ:10,author:"<yourname>",showboundingbox:1b} destroy

and after each step you need to set a redstone block next to it
the redstone block needs to be set twice for the structure to actually load
/setblock ~ ~ ~1 minecraft:redstone_block destroy

now just run these with the execute command in the dimension you need
/execute in minecraft:overworld run (setblock ..."SAVE"...)
/execute in minecraft:the_nether run (setblock ..."LOAD"...)

if the area isn't loaded you can use /forceload ~ ~ to force a chunk's loading
proof of concept
commands used in the video can be found from the video description
Comment: How would someone go about doing this?
Comment: i've updated it to contain the commands
Comment: Very good answer! I knew structure blocks would be our saviour here. I'll accept this one I've verified its validity in Minecraft.
Comment: muh bounty's gon expire lol
Comment: I'm waiting for validation.  You got 22 hours left anyways.
Comment: i made a proof of concept video to show it in action :)
Answer: 1.19.4 update
As of 1.19.4, the /clone command has been supplemented with additional options to choose separate dimensions for source and destination.
These options can be exercised by adding from <dimension name> or to <dimension name> before entering the respective coordinates.
For example:
clone from minecraft:overworld 0 0 0 0 0 0 to minecraft:nether 12 23 34


Apache beam, FileBasedSink.CompressionType.GZIP is deprecated?

Question: I have code in my apache beam 2.2.0 pipeline which is responsible for writing a json file to Google Cloud Storage. The code is as follows:
results.apply(ParDo.of(new TableRowToString()))
        .apply("WriteProfile", TextIO.write().to(outputBucket)
            .withWritableByteChannelFactory(FileBasedSink.CompressionType.GZIP)
            .withNumShards(numChunks));

While looking at the code in Eclipse, I noticed it was giving me a warning over the text FileBasedSink.CompressionType.GZIP:

The field FileBasedSink.CompressionType.GZIP is deprecated

What is the recommended way of writing gzipped files to GCS, and if this is documented elsewhere (apache beam docs, SO) what is the link to that documentation?
Answer: With beam 2.2.0 I am not aware of an alternative way to write compressed data to Google Cloud Storage.
In beam 2.3.0+ they recommend using the newer FileIO API.
FileIO 2.4.0 Docs
With the new FileIO API it is as simple as appending the withCompression call to your FileIO chain.
FileIO.write().to("gs://bucket/path").withCompression(Compression.GZIP);

If you cannot update and really want to avoid the deprecation you can implement the factory yourself, but that is exactly what FileBasedSink.CompressionType.GZIP already does.
TextIO.write().to("gs://bucket/path").withWritableByteChannelFactory(new FileBasedSink.WritableByteChannelFactory() {
    @Override
    public WritableByteChannel create(final WritableByteChannel channel) throws IOException {
        return Compression.GZIP.writeCompressed(channel);
    }

    @Nullable
    @Override
    public String getMimeType() {
        return MimeTypes.BINARY;
    }

    @Nullable
    @Override
    public String getSuggestedFilenameSuffix() {
        return Compression.GZIP.getSuggestedSuffix();
    }
});


CS0246 error on first part of name in using clause

Question: In a simple console app used to test a couple of API's, I am getting a "CS0246 The type or namespace name 'IFS' could not be found." error.

The strange thing is that the errors are on the 'using` clauses

and is about not finding the first part of the name in that clause.
The assembly, with the same name as in the first using clause, is referenced. And it's root name space is set to `IFS.EOI.ETL'

AFAICT with all this the console project is set up as it should be. So what could be causing the compiler to barf at it like this?
Answer: The error seems to have been caused by a mismatch in the targeted frameworks. The console project was targeting .Net 4.5.2, while the library was targeting .Net 4.6.1.
After changing the properties of the console project to target .Net 4.6.1 as well, the compiler stopped complaining.


How do you stop learned behavior when testing very similar scenarios?

Question: I am running some usability tests in the coming days. I have three options of one feature for a pretty simple and quick test.
My concern is that because each of the options are very similar to each other, once the user understands how the first one works the other two would be easy to figure out.
I will be rotating the options so as to not start with the same test each time.
My goal is to find out which option makes the most sense and is easiest for them to complete a particular task.
Any advice would be appreciated.
Comment: The short answer: you don't stop it. That's why it is a problem.
Comment: You've made a good choice to rotate the options to avoid learnability between options. I think this is the quickest and cheapest way to get it done.
Answer: When I run into these, I go back to "What am I trying to learn?"
In this case, I'd revisit how I'm going to measure what "Makes the most sense" and what is "easiest".
If you have the users self-rate (i.e. How easy was this on a scale from 1-5), you may run into users always thinking the last option was best/easiest ("recency bias") and users wanting to say what they think the researcher wants to hear.
If you're able to use something like Time on Task or Number of Taps, it might help bridge the Say->Do gap as you'll be measuring how long it actually takes them instead of how long they felt it took them. Often very different things. =)
Something else coming to mind is showing three separate groups of user testers only a single version of your design and compare stats between the three so you completely remove the "figuring out the other two" issue.
Once I worked with the team who handles the live website and had them target real users coming into the site. They were able to put a banner for certain visitors which linked to our User Test. We had to tread carefully as management people were rightly very wary of sending users into an area with an incomplete experience, but we were able to quickly get fast data from real people visiting the website (we were testing who would try to do something online through self-service instead of calling or emailing the company).
I always find it helpful to have someone outside my UX team do a "Dry run" of the test, as well as someone inside the UX team as they will likely be able to give really pointed feedback.
I hope some of this helps!
At the end of the day, you'll be learning something no matter what and the fact you're doing any User Testing is great news. Keep it up!
Answer: Evil Closet Monkey alludes to this but it's an effect that every research plan has to contend with. If you have enough people in there and are rotating the question order, it should mitigate that familiarity effect enough that it's a wash across all the participants.
It's also worth asking (I think Jason makes this point also maybe) whether or not you even need the two very similar tasks in the same usability experiment. Can you get your research answered question without employing 2 distinct but very similar options?
Answer: Only do one task per user. That way there can't be any interference of prior knowledge.
If you can't get enough users for that, definitely rotate the oder of the tests. You could also have the users only do 2 tests out of 3, each a different combination to further reduce the influence.
Answer: This is the classic Within-subjects vs. Between-subjects conundrum. Sounds like you're leaning toward doing a within-subjects testing approach. If you're concerned about knowledge transfer or "interference" as it is called in most HCI literature, what you could try instead is a between-subjects approach, which means each user is tested under one condition only. Only real disadvantage of between-subjects is you're going to require a larger number of participants to get useful data.
You could also try the counterbalancing/Latin squares technique for within-subjects, which is about presenting all options to each user but in different orders to essentially cancel out any interference. You're "rotating" options, so sounds like you're doing something similar but perhaps apply that rotation to a proper Latin Square Analysis of Variance to make it more sound.


Flashlight error

Question: I have a bit of a problem with the code in my flash demo application, currently I have tried the application on samsung phone and have turned it on or off.
But the flashlight is only on when the phone screen is still on, and vice versa when the phone screen goes off, the flashlight application is also turned off. While the flashlight application is still on.
This is my entire code
File manifest

 <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.demo.flashlight">

        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.CAMERA" />
        <uses-feature android:name="android.hardware.camera" />

        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">

            <activity
                android:name=".MainActivity"
                android:label="@string/app_name" android:screenOrientation="portrait">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>

        </application>

    </manifest>

File Activity_main
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/background_dark"
    tools:context="com.demo.flashlight.MainActivity">

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        ads:srcCompat="@drawable/on"
        android:id="@+id/imageButton"
        android:background="@android:color/background_dark"
        android:clickable="false"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="145dp" />

</RelativeLayout>

File MainActivity

package com.demo.flashlight;

import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;

public class MainActivity extends AppCompatActivity {

    private ImageButton imageButton;
    private Camera camera;
    private boolean isFlashOn;
    private boolean hasFlash;
    private Camera.Parameters params;
    private MediaPlayer mp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

         imageButton = (ImageButton) findViewById(R.id.imageButton);

        /*
   * First check if device is supporting flashlight or not
   */
        hasFlash = getApplicationContext().getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

        Context context = this;
        PackageManager pm = context.getPackageManager();

        // if device support camera?
        if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            Log.e("err", "Device has no camera!");
            return;
        }
        // get the camera
        getCamera();

        // displaying button image
        toggleButtonImage();

  /*
   * Switch button click event to toggle flash on/off
   */
        imageButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (isFlashOn) {
                    // turn off flash
                    turnOffFlash();
                } else {
                    // turn on flash
                    turnOnFlash();
                }

          }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /*
//         * Get the camera
//         */
    private void getCamera() {
        if (camera == null) {
            try {
                camera = Camera.open();
                params = camera.getParameters();
            } catch (RuntimeException e) {
                Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
            }
        }
    }

    /*
     * Turning On flash
     */
    private void turnOnFlash() {
        if (!isFlashOn) {
            if (camera == null || params == null) {
                return;
            }

            params = camera.getParameters();
            params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
            camera.setParameters(params);
            camera.startPreview();
            isFlashOn = true;
            toggleButtonImage();
        }

    }

    /*
     * Turning Off flash
     */
    private void turnOffFlash() {
        if (isFlashOn) {
            if (camera == null || params == null) {
                return;
            }

            params = camera.getParameters();
            params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
            camera.setParameters(params);
            camera.stopPreview();
            isFlashOn = false;
            toggleButtonImage();
        }
    }
    /*
     * Toggle switch button images changing image states to on / off
     */
    private void toggleButtonImage() {
        if (isFlashOn) {
            imageButton.setImageResource(R.drawable.on);
        } else {
            imageButton.setImageResource(R.drawable.off);
        }
    }

    @Override
 protected void onDestroy() {
  super.onDestroy();
 }

 @Override
 protected void onPause() {
  super.onPause();

  // on pause turn off the flash
  turnOffFlash();
 }

 @Override
 protected void onRestart() {
  super.onRestart();
 }

 @Override
 protected void onResume() {
  super.onResume();

  // on resume turn on the flash
  if (hasFlash)
   turnOnFlash();
 }

 @Override
 protected void onStart() {
  super.onStart();

  // on starting the app get the camera params
  getCamera();
 }

 @Override
 protected void onStop() {
  super.onStop();

  // on stop release the camera
  if (camera != null) {
   camera.release();
   camera = null;
  }
 }
}

I do not know how to fix it. Can you fix or guide me?
Thank you
Answer: When the screen turn off, the activity call onPause and onStop.
Try to remove turnOffFlash(); in your onPause.
If it doesn't work, try to see your onStop.
Good Luck
Comment: I also checked and try the functions onDestroy ..... onStop the such not no change
Comment: you have remove/commented all the `turnOffFlash();` and the flash still turnoff when screen turnoff ?
Comment: Yes. I also tried removing turnOffFlash (); There are in all functions from onDestroy ..... onStop but it is still off screen so.

And when I delete all the code from onDestroy ..... onStop, the flashlight works even when the phone screen is off but an error occurred when I pressed the Pack to go back to the screen before it. Do not turn it off yourself and when you re-open the flashlight application to turn it off, it also can not turn off the flashlight.
I have to power off the phone and restart
Comment: If you have deleted your `onDestroy` and `onStop` ect, are you sure to havn't deleted the super call ? I mean that if you have deleted the complete override its good, but if you have an `override` of the `onStop` for exemple, and you havn't the `super.onStop();` in your function, it's the reason of the crash.
Comment: Thank you. I'm still struggling with my first app but have not found a way to fix this problem.
How can I fix the above error so that the flashlight in androidn can work as intended.
I tried removing or adding the code but it still does not change anything.
You or someone can help me.

Flashlight error


Is there an adapter to raise the tank on a toilet

Question: A long standing complaint with low flow toilets is they often don't flush well (even if it had a high MaP rating).
I've tried most of the tricks on mine of adjusting the float, the flusher,  etc.
It came to me that one of the things an older high flow toilet would have (besides volume) is more hydronic head (the tanks were often taller).
Is there a modern way to raise the tank off the base (like the old timey water closets)?
Comment: The 1.25 and 1.6 GPF recent era toilets (at least the ones I've replaced old 5's with) have tanks as tall or taller than the 5 gallon ones, but much narrower. My 1.25 sometimes needs a second flush, as did the 5 - that's 7.5 gallons saved right there. Most of the time it does just fine on one. If you have a 3.5-2 GPF that does not work well, IMHO you'd be better off scrapping it and replacing with a modern unit.
Comment: How old, or what model is this toilet? Early "low flush" were not done well - recent ones are very much better (amazing what actual hydraulic design, rather than just shrinking the flush volume without changing anything else, can do) while using even less water than those early ones that flush poorly.
Comment: @Ecnerwal what I have is about 12y old and at the time had a MaP of 1000+

I looked into MaP at the time we had it installed. It was the best I could find in the price range we could aford.

I guess my constitutionals regularly exceed the max for the MaP standard :-(
Comment: Your assumption is faulty. Tank height is a design/aesthetic thing. You'd have to put the tank near the ceiling to see any difference. Get a new toilet.
Answer: I will take a WAG and say this sounds like an older installation. I believe you are measuring the hydraulic head from the floor. It should be measured to the top of the water in the bowl to the top of the water in the tank. In either case your idea would help. The problem being as you know is finding an extension. In lieu of finding a bigger tank, you could make one from plastic pipe but mounting the tank would be a problem as they are supported on the bottom by the stool portion of the toilet. That weight would also need to be supported by the wall.
I would recommend you seriously consider getting a new toilet. Please consider getting one at least "comfort height" in size.
Comment: A *good* new 1.6GPF toilet flushes far better than any old 5GPF one ever did even when new.
Answer: Around here (France) the old style is still being sold.

It is quite uncommon, so you'd have to dig a little, but it's available.
One of the advantages is the pipe can be hidden inside the drywall, which makes the toilet shorter. That's useful if you don't have a lot of space.
These really flush, no questions asked.
You don't get the water-saving "small flush/big flush" knob though.
Comment: Also used in England. Gave rise to the colourful language « who pulled your chain » when someone interrupts a conversation.
Comment: Also used in The Godfather (set in 1940s New York): "They've got an old-fashioned toilet. You know, the box and the chain thing." Interesting how the earliest designs are sometimes the best.


Is there a way to collapse global variables?

Question: I have an Android project with more that 50 global variables and I would like to collapse them so that the project is cleaner.
Is there a way to do that?
This:
public class MainActivity extends Activity {

    private TextView texView1;
    private int value1;
    ...
    x50

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }
}

to this:
public class MainActivity extends Activity {

    globalVariables();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    private void globalVariables() {
        private TextView texView1;
        private int value1;
        ...
        x50
    }
}

Comment: Short answer no. Why on earth do you have 50?
Comment: I need to have them for my project.
Comment: You can create a 'Constants' class where you make the global variables static and reference them ```Constants.globalVar1```. It would be cleaner, but you should really limit the scope of each variable as much as possible if you can. Having that many global variables can make code very hard to read.
Comment: It depends on what do you mean by `collapse`. If you mean to *group* tem, then the answer is **YES**, you can: use **enum**s.
Comment: maybe this source will help you: http://stackoverflow.com/questions/2344524/java-equivalent-to-region-in-c-sharp
Answer: You can make something like this:
public class MyClass extends AppCompatActivity {

    private MyVariables variables;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        variables = new MyVariables();
        variables.texView1 = (TextView) findViewById(R.id.my_text_view);
        variables.value1 = 10;
    }

    private static class MyVariables {
        TextView texView1;
        int value1;
    }
}

However, if you have more than 50 global variables, something is wrong with your code.
Answer: Step 1 Define region in any java class as follows:
//region GLOBAL_VARIABLES

put your 50 global variables inside this region
//endregion

Step 2 Auto fold/collapse regions using:
Go to File -> Settings -> Editor -> General -> Code Folding and then Check 'Custom Folding regions'
Cheers.
Comment: Thank you, this is what I needed!


Apply onChange effect on a select option

Question: I have a DatePicker that has todayButton = Vandaag shown in the code and image below. I wanted to see if I can activate the todayButton by clicking on any of my select option instead of clicking Vandaag. I need some idea where to start. I appreciate any insight on this.
<code>```<div className="status">
<select name="status" id="status">
<option selected>1</option>
<option>2</option>
</select></div>```

```DatePicker
  todayButton="Vandaag"
  selected={startDate}
  onChange={(date) => setStartDate(date)}
/>```

</code>
Answer: I am not 100% sure but from what i understand you want to change the date to today's date from the select. Instead of going in a round about manner of selecting today button  you can update startDate using setStartTime when you select corresponding option in select.
<code>const onSelectChange = (e) => {
 if (e.target.value === "Today") {
    setStartDate(new Date())
 }
}
</code>
Comment: Its not working, it doesn't change the date in the datepicker to today. I don't know what I'm missing I tried different approach similar to that one but It never  taken effect to the date picker date.
Comment: Did you check if the state is update properly. Console log startDate and see if the update is happening due to the select option change
Comment:  setStartDate(date)}
    />
Comment:
Submitted
First Interview
Additional Interview
Final Interview
Offer
Placement
Rejected
No Update
Comment: I am trying to see I I can apply this one instead: https://stackoverflow.com/questions/21662734/click-on-an-element-triggers-the-click-on-another-element-jquery


How can I protect laminated floor from casters on office chairs?

Question: How can I protect laminated floor from office chairs?
An acrylic mat looks ugly.  Can a rug end up damaging the floor too?
Comment: If dirt gets under the carpet the flooring can be damaged but I think it would be less than grit being ground in by the wheels.
Answer: Replace the casters on your chairs with "hardwood floor" casters.

These have a rubberized edge instead of typical hard plastic. Should cost in the order of USD$20-40 per chair, and takes only a few minutes at most to replace.
It's cheaper than those acrylic mats, works everywhere (not just a 4x6' area), and doesn't look stupid (in fact you probably don't notice at all, especially if you get all black). They also make moving your chair a bit quieter.


How can I find which games are available in the Microsoft PC Game Pass?

Question: Microsoft is offering its PC game subscription service for $1.  Cool!  But, how can I determine which games are available on it?

I found this list, but it doesn't tell you anything about any of the games, and it won't be kept up-to-date.
On the "Microsoft Store" Windows 10 app, you can click Games --> Browse all games, then filter by "Subscription Type: Game Pass".  However for some reason a lot of the games shown are console games, and not all of the PC Game Pass games are shown (ex. Into The Breach)
The "XBox Console Companion" Windows 10 app has a Store --> Xbox Game Pass list, but it only shows the console Game Pass games, not the PC ones.

Is there any way to view all the games on the PC Game Pass?
Comment: Note: Game Pass is only $1 for the first month. Afterwards it's $5 a month.
Comment: @Nolonar: Well if you already own XBox Gold it's actually [$1 for up to 3 years](https://www.cnet.com/how-to/get-xbox-game-pass-for-up-to-3-years-at-no-extra-charge/), but that didn't seem important to mention in the question.
Answer: At least on xbox.com, you can filter the games by Xbox Game Pass and then click PC games as shown in this screenshot below (marked the filter with yellow)

The whole thing is in beta anyway so expect the Windows Store and all related apps to be gradually updated. Till then you can use the site to check what games are available.
Answer: I came across the same issue when i got the Ultimate GamePass recently.
The thing to do is download the new Xbox(beta) app on your pc from the windows store.
Within the App you can see and download all the games for your pc.
Side Note: the App requires you to patch to the latest Win10 build, which forced me to install the Windows update before beieng able to use it.


Can I plug dust collector into NEMA 6-50?

Question: I've searched what feels like the whole internet for an answer to this seeming easy question, but cannot find a definitive answer:
I'm looking to purchase a 220v dust collector (Shop Fox W1666) to run in conjunction with a 110v table saw in the garage.
In addition to a single 110v 20a circuit, there's an unused NEMA 6-50 outlet in the garage, and I thought it made sense to purchase a dust collector that could plug into the unused 220v outlet, giving it a dedicated circuit to avoid overloading the regular 20a circuit that already runs the table saw. However, from what I've read on other threads in this forum it looks like the 6-50 outlet may have too much overhead amperage for the 12a dust collector to run safely (the breaker won't trip if there's a problem).
Is this true, and is there any way I can easily convert the NEMA 6-50 into a useful outlet for lower amperage 220v machines like the dust collector, perhaps using something like this adapter/breaker?
I appreciate any advice. Thank you!
Comment: Can you change the 50A circuit for the NEMA 6-50 over to a smaller circuit? (this should just be a breaker and receptacle swap + a bit of pigtailing)
Comment: Once again, breakers are used to protect wiring not devices. Your dust collector most likely has internal controls to keep it protected.  But let's face it, a dust collector is a simple continuous predictable load, not subject to varying demands.  A table saw however is a completely different kettle of fish. Push that 2" maple thru too fast and you'll either trip the breaker or the internal thermal overload of the motor.  (don't ask me how I know that!)
Answer: In theory, the device you linked is just what you need to safely connect your dust collector to that outlet. My suspicion would be that it's Chinese junk that is not properly certified, except that it's sold by Home Depot! More than that, the manufacturer, acworks.com, seems to be an American company.
I'd say: go for it.
Comment: It also includes a 20A overcurrent protection built in. So the worry about the breaker not tripping isn't an issue.
Comment: @ratchetfreak If it didn't, I wouldn't have approved it.
Comment: I figured I should mention it explicitly
Answer: That adaptor looks ideally suited to your task allowing you to connect loads like your dust collector with 6-20 0r 6-15 plugs.
It may be cheaper to instead downgrade to a 20A breaker at the supply end of the wire and fit a 6-20 socket,  but when you get an electric car you'll probably be glad to have the 50A outlet available.


How to install Idea 3GNet Setter in Linux

Question: I've bought an Idea 3G Net Setter and they have provided "Linux driver" and these are the  installation details:

2   Driver installation
2.1 Launch command line
By using "ALT+F2", input" gnome-terminal",click "run" button to launch command line. Shown with below screen shot:
2.2 ROOT right needed
Root right is needed during the driver installation process. End user can start with root right from PC power on or switch to root right by command of "su root"(switch user)before installation start. Shown with below screen shot:
2.3 Get driver tool
Get the "driver-tool" folder ( from website or copy from datacard's cdrom by plugin data card to Windows/MAC PC first. Eg, driver-tool got, copy to Fedora PC and put inside folder of "alcatel".
2.4 Start installation
Enter catalog of "driver-tool" , change file attribute by command of "chmod 777 *". Then, execute "./tcl_instal.sh" to start the installation.
2.5 Reboot computer
After install script executed, PC will prompt to reboot the computer. After PC reboot. Installation finished.
Plug data card to verify.
After PC reboot, plug in alcatel data card, enter "dev" folder, execute command of "ls ttyu" to list the USB device information. If the driver installation succeed, you should get information below:
If you don't get result above, please re-install driver with above steps, then, plug in data card to query.
3 Internet connection
3.1 Configure script
By execute command of "vi /etc/wvdial.conf" to configure the file of "wvdial.conf " before start the internet connection. The APN/Dial number / password/user name need to be set. You can get above information from operator. Shown with below screen shot:
3.2 PIN management
If PIN code is enabled, after you insert the data card to PC, please input pin code first. It will take据some time to unlock the PIN, please wait with patience. Shown with below screen shot:
3.3 Dial up
After configure with right configuration and PIN unlocked, by executing script of "alcatel_pppd_on" to launch the internet connection. Shown with below screen shot:
3.4 Connection succeed
Once connection succeed, will be shown with below screen shot:
3.5 Disconnect
Run script of "alcatel_pppd_off" to disconnect the internet connection, shown with below screen shot:

Can anyone explain me the step 3.1 and further?
Answer: It's asking you to edit /etc/wvdial.conf to provide the APN, Dial number, username and password. You haven't provided the screenshot it mentions so I can't suggest a format.
In Ubuntu, you'll want to run sudoedit /etc/wvdial.conf instead though so you're editing it as root. A normal account shouldn't have permission to edit files in /etc/.


convergence of $\{\sin(1/n)\}$ sequence using limit definition?

Question: how to prove convergence of  $\{\sin(1/n)\}$ sequence when $n$ goes infinity, using limit definition?
I proved that $\{\sin(n)\}$ is divergent but i can not do this with that method.
Comment: The proof should resemble a demonstration that $\sin(x)$ is continuous at $x=0$.
Comment: *Hint:* For all positive integers $n$,

$$|\sin (1/n) - 0| \  \leq \  |1/n - 0|$$
Comment: oh goodness! thanks man. I think it will help
Answer: Hint: Notice that if this sequence is convergent, then it has to be Cauchy. If sequence $\{\sin\frac{1}{n}\}$ does not converge, then there exists an $\epsilon>0$ such that for all $N\in \mathbb{N}$, $m,n>N$ implies $|\sin\frac{1}{n}-\sin\frac{1}{m}|\ge \epsilon.$ What if we let $\epsilon=\frac{1}{2}$ ?
Comment: If 'there exists an $\epsilon$', we may not know its value, and can't proceed to let $\epsilon=\frac12$.
Comment: @paw88789 When we actually write down the proof, we would let $\epsilon=\frac{1}{2}$ then I would be able to show you that as we go furthur, we can always find two terms that are $\frac{1}{2}$ apart, which implies the sequence cannot be convergent. As long as you choose $\epsilon$ as something less than $1$.
Comment: I agree that always being able to find terms at least $\frac12$ apart is sufficient for the sequence to diverge, it is not necessary.
Comment: @paw88789 I'm sorry but you lost me. Are you saying this proof is wrong? Or are you saying that there is simpler way of doing it?
Comment: I'm saying that being able to show that all the terms beyond some point are within $\frac12$ of each other is not enough to show that the sequence is converging.  Or equivalently, the sequence diverging doesn't necessarily mean that we will find terms that are more than $\frac12$ apart.
Comment: @paw88789 Yes you are right.
Answer: Let $\epsilon>0$.
$\sin(x)$ is continueous at $x=0$ and $\sin(0)=0$.
As a result there exists $a>0$ such that $\forall x\in[-a,a],|\sin(x)|<\epsilon$.
What is more since $\lim_\infty\frac{1}n=0$ we have $N>0$ such that $\forall n\ge N,\left|\frac{1}n\right|<a$.
As a result $\forall n>N,|\sin(\frac{1}n)|<\epsilon$.
Conclusion : $\boxed{\lim_{n\to\infty}\sin(\frac{1}n)=0}$
Answer: Hint: Here is the proof that $\sin x$ is continuous at $0$. Can you see how to use this?
Recall $|\sin x|\le|x|$. Now, for every $\epsilon>0$, there exists a $\delta=\epsilon$ such that whenever $\left|x-0\right|<\delta$ then $|\sin x-0|\le |x|<\delta=\epsilon$. Hence $\sin x$ is continuous at $0$.


colorbox Jquery plugin, trying to open second popup

Question: I'm usinc colorbox to open popup #1:

<a href="<?php bloginfo ('template_directory'); ?>/get-quote.php?productID=<?php echo $post->ID; ?>">Get Quote

and jquery:
$('.getquotebtn a').colorbox();

This works fine. But I've another button inside the content of get-quite.php that I'd like to open another popup...
<form name="getquotedata" action="" method="post">
        <input type="text" name="nameandsurname" id="popupnamefield" onblur="this.value=!this.value?'<?php _e('Name and Surname','medishop'); ?>':this.value;" onfocus="this.select()" onclick="if (this.value=='<?php _e('Name and Surname','medishop'); ?>'){this.value='';}" value="<?php _e('Name and Surname','medishop'); ?>">
        <input type="text" name="email" id="popupemailfield" onblur="email@example.com':this.value;" onfocus="this.select()" onclick="if (email@example.com'){this.value='';}" value="email@example.com">
        <input type="hidden" name="prod_ID" value="<?php echo $productID_from_url; ?>">
        <input type="hidden" name="prod_name" value="<?php echo get_the_title($productID_from_url); ?>">
        <input type="hidden" name="prod_url" value="<?php echo get_permalink($productID_from_url); ?>">
            <input type="submit" value="Get Quote" id="popupsbmt" onclick="$.colorbox({href:'<?php bloginfo('template_directory'); ?>/get-quote-sendmail.php'}); return false;">
    </form>

This is where the problems start!
I get error: This content failed to load.
Any ideas how to solve this problem?
Thanks!
Comment: Let me see if I understood this correctly, you want to open a colorbox inside a colorbox?
Comment: @Trufa Yes, or simply open another colorbox and close previous one.
Comment: I think that the later is easier, I'm a little confused about your particular situation, would if help if I made you an example situation that isn't exactly like your code? Otherwise I would need more explanation as to what is you are doing...
Answer: Everything seems to work fine when you put a colorbox inside another, see live example here.
Inline HTML

        open second

hi second

js:
$(".inline").colorbox({inline:true, width:"50%"});
$(".inline2").colorbox({inline:true, width:"50%"});

Comment: I'm loading content from separate files. Both pop-ups are php files.could this be a problem?
Comment: @SandroDzneladze does the first colobox calll the form you are showing? If so, is the submit supposed to bring up the second one? If so what is the new content you are trying to bring?
Comment: First color box calls get-quote.php that contains the form. Submit is subbosted to bring up second colorbox correct. New pop-up is simply a php script that grabs variables from POST and puts them into wp_mail function. Also does checks and displays alerts. Like mail successfully sent etc.
Comment: @SandroDzneladze are you working locally or can you link me to a live example?
Comment: locally unfortunately... I cannot put it on jsfiddle :(


How can I prevent other users from changing wifi settings?

Question: How to make Ubuntu ask for a password every time a user tries to access system settings?
I need this specifically for the wifi settings, so that no one can change, turn on, or off wifi on my machine without putting the root password in the prompt.
Any help is appreciated.
Comment: Does this answer your question? [How do I set the policy for users to modify the network state and connections?](https://askubuntu.com/questions/708261/how-do-i-set-the-policy-for-users-to-modify-the-network-state-and-connections)
Comment: Does [this solution answer your question?](https://askubuntu.com/a/708262/1222991)
Comment: @matigo Yes. Absolutely. I posted this question on Reddit and got the same result. It worked out exactly the way I wanted. Thank you for answering. Though The user can turn on airplane mode to turn off the wifi. Otherwise, it works wonderfully.
Answer: I reached the target with as follow:
sudo mv /usr/bin/gnome-tweaks /usr/bin/gnome-tweaks.real
sudo mv /usr/bin/gnome-control-center /usr/bin/gnome-control-center.real
sudo nano /usr/bin/gnome-tweaks

Added the line
user=$USER ; disp=$DISPLAY ; pkexec sudo -u $user DISPLAY=$disp gnome-tweaks.real

sudo nano /usr/bin/gnome-control-center

Added the line
user=$USER ; disp=$DISPLAY ; pkexec sudo -u $user DISPLAY=$disp gnome-control-center.real

sudo chmod 755 /usr/bin/gnome-tweaks
sudo chmod 755 /usr/bin/gnome-control-center

Answer: To revert back to default settings,
sudo rm /usr/bin/gnome-tweaks
sudo rm /usr/bin/gnome-control-center

sudo mv /usr/bin/gnome-tweaks.real /usr/bin/gnome-tweaks
sudo mv /usr/bin/gnome-control-center.real /usr/bin/gnome-control-center


Meaning of =~ in Ruby

Question: I came across an example in the Ruby documentation and am confused about it's exact meaning. I am referring to =~. The sample below uses it, but I'm not sure what it's purpose over say == is.
a = %w{ a b c d e f }
a.select {|v| v =~ /[aeiou]/}   #=> ["a", "e"]

Comment: You might want to bookmark some documentation: http://ruby-doc.org/core-1.9.3/String.html#method-i-3D-7E
Comment: @Mohamad: symbolhound.com is your friend: http://symbolhound.com/?q=ruby+%3D%7E
Comment: @muistooshort thank you. Here's Ruby 2.1.0 docs. I looked for 20 minutes on Google to find this without any luck.
Answer: if v =~ /[aeiou]/ # if this value matches this regex
if v == /[aeiou]/ # if this value IS this regex

See the difference?
Comment: Thanks. I had a hunch it might be because of the regex.
Answer: It matches to a regular expression.

Meaning of =~ in Ruby


Fail msbuild when gulp task fails

Question: I just started to learn gulp tasks for checking javascript files. I am using ASP.NET Core Web Application(.NET Framework) project type.
I am trying to fails msbuild when the gulp task fails. Here is the task:
gulp.task('jshint', function () {
    return gulp.src('./wwwroot/lib/test/js/**/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter('default'))
        .pipe(jshint.reporter("fail"));
});

Here is the only one javascript file with code:
LHG^(&^%(*&^%(*&)))

When I build the project(I binded to run task before build in the Task Runner Explorer), the task generates errors in the Error List tab. But I am getting:

========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ==========

in the Output window. i came across this question Cancel Build if Task Runner Explorer Task Fails where it suggests to run the task from pre-build event, but the problem is this project type doesn't seem to have build tab in its Properties window. I suspect that it can be done via some json configuration file, but I can not find any related information.
Answer: XPROJ files do not have traditional CSPROJ pre-build/post-build events. You can specify them in project.json. I would highly recommend migrating away from XPROJ back to CSPROJ, in line with what Microsoft are doing.

Fail msbuild when gulp task fails


Can't delete Minecraft files

Question: Ok, so I wanted to download a mod. But the mod has nothing to do with the problem... Anyway, I went to delete the META-INF file in the Minecraft .jar (or Minecraft) and it did not delete, due to the file is being used by a program. I then tried to delete the Bin folder since that worked in the past with different problems. So I went to delete the BIN, and it said cannot delete, because Minecraft is being used in Java(tm)SE-BINARY. I opened Java and it closed instantly.
What can I do to get my mod on the game because the folder wont delete ANYTHING? Unless I can find out what program is currently using Minecraft?
Comment: Try rebooting? That should make sure nothing's using those files. If it still gives you the error, then you have a bigger problem.
Comment: Run task manager and check for javaw.exe if Minecraft doesn't show up in the task bar. You can definitely delete these files, but you definitely cannot if they are being used.
Comment: Are you sure you are not running Minecraft?
Comment: I wanst running it Ive been modding for a while and know not to have it open at the same time im doing work
Comment: Why down voted? I had the same question! (upvoted) Found this on google
Answer: The easy way is to restart your computer and try again. If this doesn't work try to close all apps in Task Manager manually.
Answer: Type this command into command prompt, this should fix your problem. You can launch command prompt by doing Start Menu -> Run, then type in CMD.
taskkill /f /im javaw.exe

Once you do this you should be able to delete the file.
What this does is tell Windows you want to close the Java application that is currently using Minecraft. Once this happens it will free up the file and allow you to delete the file.
The other options is open up your task manager and if you see any instance of javaw.exe to end task the program.
Answer: Exit ALL of Minecraft, and all Minecraft-related applications.  If this doesn't work, delete each folder individually.
Answer: I recommend quitting all applications that could possibly be related to minecraft. That should work as I've had similar problem not specifically with minecraft, but once all applications related to it were quitted I could remove any of its files.
Answer: OK, this will work; I just did it:

Go to minecraft but don't log in.
Go to options and it should say "force update".
Click that and then login.

It will refresh everything but you will have to redownload all of your mods.
Answer: Go to the task manager (Ctrl + Alt + Delete).
Go to Processes and find javaw.exe, then click End Process.
Then try to delete the file.
If that doesn't work try to restart your PC and try again.
Comment: It is javaw.exe, not Java.exe
Answer: There could be a program running inside of META-INF. Go into Task Manager and if you find the program there, end the process. After that, try deleting META-INF and it may work. You cannot delete a file if a program is running inside it, or if you are trying to run the program itself, it can't be running.

Can't delete Minecraft files


Dense subset of $Q$

Question: Does there exist any dense subset of the set of rationals $Q$? In fact $Q$ is a (countable) dense subset of $R$ (hence $R$ is separable). If there exist any dense subset of $Q$ then $Q$ is also separable. But the problem is that if we assume $Q$ subset $Q$ then closure of $Q$ is not $Q$ (it is $R$)!
Answer: Pick $N \in \mathbb{N}$.  Then $S = \{p/q \in \mathbb{Q} : \gcd(p,q) = 1, q \geq N\}$ is a dense subset of $\mathbb{Q}$.  (If we pick $N = 1$, we get the other answers.)
The closure of $S$ in $\mathbb{Q}$ is $\mathbb{Q}$.  (That the closure of $S$ in $\mathbb{R}$ is $\mathbb{R}$ does not change that $S$ is dense in $\mathbb{Q}$.)
Answer: Closure is something you do to a subset, not to a space (that would be (sequential) completion). So "the closure of $\Bbb Q$" is really an uncomplete phrase since it's missing a reeference to the ambient space.
"The closure of $\Bbb Q$ in $\Bbb R$" is $\Bbb R$, while "the closure of $\Bbb Q$ in $\Bbb Q$" is $\Bbb Q$.
Answer: You are wrong. $\mathbb{Q}$ is dense in itself, as every topological space is equal to its own closure.

Dense subset of $Q$


How do I logout users that have been afk for 10 minutes?

Question: I wrote this script but it doesnt seem to work. even tho mysqli_num_rows is > 1, no user get logged out.
online=0 = user is offline.
<code><?php

include_once 'db.php';

$res = mysqli_query($con, "SELECT username FROM users WHERE last_active<= NOW() - INTERVAL 10 MINUTE");

$row=mysqli_fetch_array($res);
$user = $row['username'];

mysqli_query($con, "UPDATE users SET online=0 WHERE username='$user'");
?>
</code>
Comment: Does it set `online` correctly?
Comment: where is your session management code?
Answer: You could just run a query like this:

"UPDATE users SET online = 0 WHERE last_active<= NOW() - INTERVAL 10
  MINUTE"

oh, assuming you have code somewhere else that will actually put them "offline" if their online field = 0...


Demonic War Axe or Light's Bane, which is best against the Eater of Worlds?

Question: I am going to attempt to kill the Eater of Worlds, but I lost the weapon (Muramasa) that I killed it with last time. So this time around I still have full silver armor, but should I use the Demonic War Axe or Light's Bane?
I have 15 hearts, Hermes boots, and Mana Flower and I am playing on my Ipad.
Comment: You might find some good info [here](http://gaming.stackexchange.com/questions/124684/what-equipment-do-i-need-to-kill-the-eater-of-worlds)
Comment: Suggestion wise i would use the Light's bane since it has a way higher attackspeed and only a bit lower damage. If you have some sort of piercing weapon though i would defenitly take that.
Comment: Thx a lot Marco I'm gonna go fight that thing! :D
Comment: Oh great i looked at franks thing now I need a tie breaker
Comment: Ok I defeated it with the War Axe and Ball O Hurt that I got from an orb, thank you for your help
Comment: Fought him loads of times. Most items work ^^
Answer: I use a Thorn Chakram. Here's my setup:

■ = Solid Block
  0 = Air/You
  ■■■■■■
  ■■■■■■
  ■■ 0  0 ■■
  ■■ 0  0 ■■
  ■■ 0  0 ■■
  ■■■■■■
  ■■■■■■

Note: This strategy works best on Mobile only.

Enclose yourself in a 2x3 space.
(Make sure the walls are 2 thick, otherwise the Thorn Chakram will go outside the wall.)
Summon the Eater of Worlds.
Aim the Thorn Chakram at the wall, doesn't matter which side.
Hold the fire button the entire length of the battle.
Just sit there until it's dead.
Collect the lovely loot.


itext7.pdfHTML library how to fix it to support multiple languages

Question: I have a created sample project for try to test the itext7.pdfHTML library. I think this library supports the English language only, But I think it's impossible to remember only one language support. Please help me to fix it to support multiple language. I will convert html to pdf only and I use itext7.pdfhtml 3.0.4
Controller
public IActionResult TestPDFHtml()
        {
            string html = @"<meta http-equiv=""content-type"" content=""text/html""; charset=""UTF-8"">สวัสดี";
            TestPDF test = new TestPDF();
            byte[] vs = test.creatPDFByte(html);
            return File(vs, "application/pdf");
        }

Code method creatPDFByte
public byte[] creatPDFByte(string pdfHTML)
        {
            byte[] buffer;
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    using (PdfWriter pw = new PdfWriter(ms))
                    {
                        pw.SetCloseStream(true);
                        using (PdfDocument pdfDoc = new PdfDocument(pw))
                        {
                            ConverterProperties cProps = new ConverterProperties();
                            cProps.SetCharset("UTF-8");
                            pdfDoc.SetDefaultPageSize(PageSize.A4);
                            pdfDoc.SetCloseWriter(true);
                            pdfDoc.SetCloseReader(true);
                            pdfDoc.SetFlushUnusedObjects(true);
                            HtmlConverter.ConvertToPdf(pdfHTML, pdfDoc, cProps);
                        }
                    }

                    buffer = ms.ToArray();
                }
            }
            catch ...

Comment: I'm voting to close this question because it's an X-Y question.
Comment: *"I think this library supports the English language only"* - why do you think so?
Answer: why do you think so? Have you tried adding fonts in css because the default font may not support your language.


CUDA function call from other .cpp file that contains the same header file

Question: I have two files utilCUDA.cu and util.cpp. They both include util.h. "add" is declared in util.h and defined in util.cpp. "add" calls "addCUDA" to add the two vectors. Please don't mind the approach, it's just meant as a test project.
The error is:
util.cpp: In function 'void add(double*, double*, double*, int)':
util.cpp:5:20: error: 'addCUDA' was not declared in this scope

Is there anyway I can call "addCUDA" in "add"?

util.h:
#ifndef __UTIL_H__
#define __UTIL_H__

#include <stdio.h>
void add(double *a, double *b, double *c, int size);
void printVec(double *v, int size);

#endif

util.cpp:
#include "util.h"

void add(double *a, double *b, double * c, int N)
{
    addCUDA(a,b,c,N);
}
void printVec(double *v, int size)
{
    int i;
    for(i = 0; i < size; i++)
        printf("%f ", v[i]);
    printf("\n");
}

utilCUDA.h:
#ifndef __UTILCUDA_H__
#define __UTILCUDA_H__
#include <cuda.h>
#include <cuda_runtime.h>
#include <cuda_runtime_api.h>
#include "util.h"

__global__ void myAdd(double *a, double *b, double *c, int size);
void addCUDA (double *a, double *b, double *c, int size);
#endif

utilCUDA.cu:
#include <stdio.h>
#include <stdlib.h>
#include "utilCUDA.h"
#define THREAD_PER_BLOCK 128
__global__ void myAdd( double *a, double *b, double *c, int size ) {
    int tid = threadIdx.x + blockIdx.x * blockDim.x;//blockIdx.x;    // this thread handles the data at its thread id
    if (tid < size)
        c[tid] = a[tid] + b[tid];
}

void addCUDA(double *a, double *b, double *c, int size)
{
    printf("CUDA called\n");
    double *dev_a, *dev_b, *dev_c;
    cudaMalloc( (void**)&dev_a, size * sizeof(double) );
    cudaMalloc( (void**)&dev_b, size * sizeof(double) );
    cudaMalloc( (void**)&dev_c, size * sizeof(double) );

    cudaMemcpy( dev_a, a, size * sizeof(double),
                cudaMemcpyHostToDevice );
    cudaMemcpy( dev_b, b, size * sizeof(double),
                cudaMemcpyHostToDevice );
    myAdd<<<(size - 1)/THREAD_PER_BLOCK + 1,THREAD_PER_BLOCK>>>( dev_a, dev_b, dev_c,size );

    cudaMemcpy( c, dev_c, size * sizeof(double),
                  cudaMemcpyDeviceToHost );
    cudaFree( dev_a );
    cudaFree( dev_b );
    cudaFree( dev_c );
}

test.cpp:
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include "util.h"

#ifdef USE_CUDA
    #include "utilCUDA.h"
#endif

using namespace std;

int main(int argc, char** argv)
{
    int size = atoi(argv[1]);

    double *a, *b, *c;// *cBase;
    int j;
    a = (double*)malloc(size*sizeof(double));
    b = (double*)malloc(size*sizeof(double));
    c = (double*)malloc(size*sizeof(double));

    srand(time(NULL));
        for(j = 0; j < size; j++)
        {
            a[j] = rand() % 10;
            b[j] = rand() % 10;
        }

    printVec(a,size);
    printVec(b,size);
#ifdef USE_CUDA
    addCUDA(a,b,c,size);

#endif

#ifdef NO_CUDA
    add(a,b,c,size);
#endif
    printVec(c,size);
    free(a);
    free(b);
    free(c);
    return 0;
}

Makefile:
NVCC_RESULT := $(shell which nvcc 2> NULL)
NVCC_TEST := $(notdir $(NVCC_RESULT))
CFLAGS=-c -Wall

CUDAFLAGS=-c

CUDA_INCLUDE =
OBJ=test.o util.o
ifeq ($(NVCC_TEST),nvcc)
    CUDACC := nvcc
    CC := g++
    OBJ+=utilCUDA.o
    CUDA_INCLUDE += -I /usr/local/cuda-5.5/include
    CCFLAGS := -DUSE_CUDA
else
    CUDACC := g++
    CC := g++
    CCFLAGS := -DNO_CUDA

endif

all: test

test: $(OBJ)
    $(CUDACC) $(CCFLAGS) $(OBJ) -o test

ifeq ($(NVCC_TEST),nvcc)
utilCUDA.o: utilCUDA.cu utilCUDA.h
    $(CUDACC) $(CCFLAGS) $(CUDAFLAGS) utilCUDA.cu
endif

.cpp.o:
    $(CC) $(CCFLAGS) $(CFLAGS) $*.cpp $(CUDA_INCLUDE)
clean:
    rm -rf *.o test

Comment: You question isn't clear (to me at least). Can you provide a minimal self-contained example code that others can compile, along with a description of expected vs. actual behavior? Are you getting compilation errors, run-time errors, crashes?
Comment: Try adding the function headers to the .h file. (a function header is just the function declaration without the body - ie void func(int a, int b);)
Comment: Did you define both functions in the ".h file"?
Comment: No, the functions are defined in their corresponding files.
Comment: @njuffa: I just editted the question. Thanks.
Answer: util.cpp calls addCUDA but you haven't indicated where to find it. (i.e. you've provided no "declaration" of the function in that scope.)
move this line:
void addCUDA (double *a, double *b, double *c, int size);

from utilCUDA.h to util.h
this really has nothing to do with CUDA.


C++: weird error "expected initializer before extern" in library SDL_image.h

Question: I'm currently trying to make a simple game with SDL and Box2D. Unfortunately, the code I added to make the character shoot proyectiles is so buggy I can't even begin to count the errors. To deal with this I added some code to show some debug info in the game. Unfortunately, after dealing with all the errors a weird error that didn't appear before popped up:
<code>/usr/include/SDL/SDL_image.h|34|error: expected initializer before 'extern'|
||=== Build finished: 1 errors, 0 warnings ===|
</code>
The code in SDL_image.h that causes this is:
<code>/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
</code>
I have no idea what causes this error message to appear, or how to solve this. There are no error messages on my code. I don't think there's anything wrong with the library because other game I did compiles just file. This is the only error that pops up.
Comment: The error message say "before extern" -- the ifdef is *not* what is before, so you need to show us the line of code before that
Answer: Have a look at the end of the header files that are included before this one. My guess is that there's a missing <code>;</code> after a class definition.
Comment: Yup, there was a missing semi-colon after a function. Thanks!
Comment: OMG MAN. I LOVE YOU! I was for more than an hour looking for my error and finally you saved me. There was a missing ; on the last function of my header file. Thanks a lot!
Comment: +1, but I'm guessing it's a global variable declaration, not a class declaration.  With g++ 4.3.4, the code `int x extern int y;` gives the same error, whereas `class X{} extern int y;` gives a different error.
Comment: there it is, missing ; !!


Central logging solution for enterprise application & on-prem only

Question: I'm looking after a number of applications that I inherited when I joined my company. These app had no tiers and no logging mechanism. New apps that I developed are using log4net. I have two web servers behind F5 load balancer and there are at least 6 such pairs on which my applications are distributed. It is a nightmare to go out and look at log files. Not to mention each application has tiers and each tier writes it own log. I now need a central log management. I'm developing primarily on .Net and I have started to develop core level modules using Serilog.
End result would be replacing log4net with Serilog but the main issue still remain. I can arrange a SQL Server database dedicated to collect all the logs from all the applications but reading about it on the net, it seems like a bad idea. Other services are out there but they are cloud based and subscription based and I work at a government organization and cloud is a big no-go. Extra funding is also not an option. We are premier partners of Microsoft. If there is an offering for MS, I might be able to make that work but not cloud and App-Insights.
Is there an application available that I can install in-house on a server and get things going?
Comment: Opinion based questions are not suitable for Stack Overflow.
Comment: I understand. Where should I ask, if not stack?
Answer: You could check out something like Elasticsearch which is a pretty good way to store/search log files. There's also a Log4Net adapter for ElasticSearch.