store object's name and reference it in the code

Question: I have two lists, after find which one has the highest value I store the other one's name into a string variable, like this:
iterateList = "lstDrives"; //lstDrives

So, I want to use that stored name in the next lines:
for(Integer currentElement : iterateList){
    if((mostExpensiveValue + currentElement) > b){
        result = -1;
    }
}

right now I obtained an error because I'm trying to iterate the String var and I want to refer to its content, my question is: how can I achieve this?
This is the entire piece of code:
if(mostExpensiveKb > mostExpensiveDv ){
    iterateList = "lstDrives"; //lstDrives
    mostExpensiveValue = lstKb.get(keyboards.length-1);
} else{
    iterateList = "lstKb"; //listKb
    mostExpensiveValue = lstDrives.get(keyboards.length-1);
}

for(Integer currentElement : iterateList){
    if((mostExpensiveValue + currentElement) > b){
        result = -1;
    }

}

Comment: Why store the name of the variable referencing the `List` instead of the `List` itself?
Answer: That's not how java works. Object do not have names; variable names do not survive the compilation process.
Object o = new Object();

This does not mean that your object's name is 'o'. After all:
Object o = new Object();
Object v = o;

There is only one object here (to make an object, new must be invoked; it is only invoked once here, therefore, there cannot possibly be 2 objects). You have 2 variables that are both referring to the same object. It's like having 2 post-it notes with the same house address written on each. That doesn't mean you have 2 houses.
So, does that mean this one object's name is both o and v?
Object o = new Object();
Object v = o;
o = null;
v = null;

Does that mean that the name of the object used to be o, but then it became both o and v, and then it became just v, and then it became nameless?
Hopefully this gives you the insight as to why objects do not have names and java is not now and not ever going to let you do something like obj.getName().
Java compiles code to an intermediate step (.class files) before you run them. In this intermediate step, local variable names disappear; they can remain for debug purposes but the actual act of running class files ignores this, and you can see this in class files: The local var names don't need to be there in the first place (depends on whether you're using -g when compiling or not to save debug vars), and if they are there, it's in a separate attachment to a method which the JVM just skips completely when reading a class file.
As a consequence, something like getVar("varName") does not now and will never exist in java either. Let alone that java is strongly typed and getVar wouldn't let you type it, given that "varName" could as far as you know, be supplied by the user on the fly.
In other words, you're not 'thinking in java' here. What you're trying to do doesn't work, never has, and never will.
What you can instead do is simply make another variable. After all, all non-primitive variables are merely references (postit notes that contain an address to an object, NOT the object itself). Postit notes are cheap. Here:
List<String> someList = readTheCollectedWorksOfShakespeare();

Let's assume here that this method makes a humongous list with all the lines of everything shakespeare ever wrote. That's a sizable list! Let's say 100MB's worth, so your VM's memory load spikes considerably after this line. Then you do:
List<String> list2 = someList;
List<String> list3 = someList;
List<String> list4 = someList;
List<String> list5 = someList;

and check memory load again: No effect. These are 4 references (pointers). The above 4 lines execute pretty much instantaneously, and cost no memory. It's just that you now have 5 post it notes, all with the address to some ginormous castle on it. The computer did not have to painstakingly copy the castle brick by brick. You can do the same thing in your code:
List<Integer> iterateList;
if (mostExpensiveKb > mostExpensiveDv) {
    iterateList = lstDrives;
    mostExpensiveValue = lstKb.get(keyboards.length-1);
} else {
    iterateList = lstKb;
    mostExpensiveValue = lstDrives.get(keyboards.length-1);
}

for (Integer currentElement : iterateList) {
    if ((mostExpensiveValue + currentElement) > b) {
        result = -1;
    }
}

Answer: You can use an hashMap to store the list name like key and the list object like value:
Map<String, List<Integer>> namesAndLists= new HashMap<String, List<Integer>>();
namesAndLists.put("lstDrives",lstDrives);
namesAndLists.put("lstKb",lstKb);


Setting daily backups on laptop with cron/anacron on 16.10

Question: I have similar questions to confusion about cron and anacron (setting up backup schedule for rsnapshot), but there weren't answered either.
Problem
My problem is to have a backup routine on daily basis on a laptop. So, my first idea was to set it in a crontab like
$ crontab -e
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# I guess as user I have no access to /var/log from this crontab, do I?
@daily ~/my-backups.sh >> ~/.log/my-backup.log

and then the script my-backups.sh should run everyday at midnight (0 0 * * *), right?
Ok, and after reading the documentation I found out about anacron. But then the problem arises as the script is not run. From the documentation I understand that if the computer was off when the daily routine was supposed to be executed by cron then anacron should fire it up on start up. But that is not happening either.
Do I need to do another setup? (From the documentation I assumed it was not needed and that it should work out of the box, but is not happening.)
Question
How can I set up cron/anacron to execute a daily script, and in case the computer was off at the time of execution, it should run the script on startup or after some time after startup.
Version using cron.daily
I modified my backup script changing to cron.daily as suggested. My test script is:
#!/bin/bash

date +%Y-%m-%d >> /var/log/backup.log

Then add it to /etc/cron.daily as a symbolic link
sudo ln -s ~/bin/my-backup /etc/cron.daily/backup

I checked, and the script and the symlink both have execute permissions.
Then, today, I started my machine around 9, and the first entries on /var/log/syslog are around that time, but there is no sign of cron.daily there.
$ cat /var/log/syslog | grep cron
Feb 16 09:05:15 box cron[981]: (CRON) INFO (pidfile fd = 3)
Feb 16 09:05:15 box cron[981]: (CRON) INFO (Running @reboot jobs)
Feb 16 09:17:01 box CRON[4574]: (root) CMD (   cd / && run-parts --report /etc/cron.hourly)
Feb 16 10:17:01 box CRON[6453]: (root) CMD (   cd / && run-parts --report /etc/cron.hourly)
Feb 16 11:17:01 box CRON[6878]: (root) CMD (   cd / && run-parts --report /etc/cron.hourly)
Feb 16 12:17:01 box CRON[7310]: (root) CMD (   cd / && run-parts --report /etc/cron.hourly)
Feb 16 13:14:01 box CRON[7582]: (root) CMD (   test -x /etc/cron.daily/popularity-contest && /etc/cron.daily/popularity-contest --crond)
Feb 16 13:17:01 box CRON[7595]: (root) CMD (   cd / && run-parts --report /etc/cron.hourly)
Feb 16 14:17:02 box CRON[8134]: (root) CMD (   cd / && run-parts --report /etc/cron.hourly)

Also, the last time of the anacron executed was yesterday
$ sudo cat /var/spool/anacron/cron.daily
20170215

And I check, and my script is listed in the cron.daily
$ run-parts --test --report /etc/cron.daily
/etc/cron.daily/0anacron
/etc/cron.daily/apport
/etc/cron.daily/apt-compat
/etc/cron.daily/backup
/etc/cron.daily/bsdmainutils
/etc/cron.daily/cracklib-runtime
/etc/cron.daily/dpkg
/etc/cron.daily/google-chrome
/etc/cron.daily/google-talkplugin
/etc/cron.daily/logrotate
/etc/cron.daily/man-db
/etc/cron.daily/mlocate
/etc/cron.daily/passwd
/etc/cron.daily/popularity-contest
/etc/cron.daily/update-notifier-common
/etc/cron.daily/upstart

Comment: I setup cron to create a `.tar` backup file of my laptop every morning and email it to myself in the cloud: https://askubuntu.com/questions/917562/backup-linux-configuration-scripts-and-documents-to-gmail/922493#922493
Answer: Place you script to /etc/cron.daily and you will get exactly what you wanted.
Comment: Will it run as `root` there? Or as my user?
Comment: It will run as root.
Comment: I move the script to the `/etc/cron.daily`, and run it manually and worked. However, today after startup (after the daily hour of `cron`) the anacron job was not executed. I checked, and the script has no extension, but there is not info about anacron.
Comment: Can you post the script to your question? You can't use path like `~/` there. You need to add full path like `/home/xxxxx/....`.
Comment: The script right now is a test one, just to see if it is executed. See my changes.
Comment: Did you ever end up resolving this?


How change the name of an object with a for loop vba?

Question: I would like to import multiple pictures with a for loop using a table in vba, but I have a problem with the named object. I don't konw how to deal with it (lake of experience):

Public Table_glob(1) As Variant

Sub Table_glob()
    table(0) = "toto"
    table(1) = "tata"

End Sub

Sub Insert()

    Call Table_glob

    For i = LBound(table) To UBound(table)
       Set shp_ & table(i) & = ActivePage.Import("C:\Users\antho\Documents\" & table(i) &".png")
    Next i

End Sub

I have an error message : "expected: =" on the first "&"
Comment: You can't "create" a variable like this. What is your end goal?
Comment: I have python habits and I just got into vba so it's a shock lol...I need to import specific pictures with specific coordinates (X, Y) in MS Visio
Comment: You could possibly add each picture to a `Collection`, creating a unique key for each similar to what you're currently attempting.
Answer: Sub Insert()
Dim table(0 To 1) As Variant
Dim shp_table(0 To 1) As Variant

table(0) = "toto"
table(1) = "tata"

For i = LBound(table) To UBound(table)
Set shp_table(i) = ActivePage.Import("C:\Users\antho\Documents\" & table(i) & ".png")
Next i

End Sub


Beginner:What do several parts of my code mean?

Question: Because I'm an absolute beginner I have a really simple question but I can't help myself.Maybe they are too simple because I can't find the answer in forums, books or other internet paged. I do not get the meaning of some parts of my java code because i just knew the ''normal'' eclipse, and android is so different to that.
    import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Button;

import android.widget.Toast;

public class Spritkostenactivity extends Activity
implements View.OnClickListener{

    private TextView textcosts;
    private TextView textcostsperson;

    private Button buttonnew;
    private Button buttonstop;

Are these elements (Button and TextView) objects, variables, attributes? How can I call them?
        buttonnew= (Button)     findViewById(R.id.buttonerneuteberechnung);
        buttonnew.setOnClickListener(this);
        buttonstop= (Button) findViewById(R.id.buttonschliessen);
        buttonstop.setOnClickListener(this);

Now I put the element of the xml file in the "buttons". If they are objects, why don't I have to write something like "Button buttonnew=new ..." Because after that the Buttons start a Method, so do they need to be an object?
And what does the "this" mean. I read that it means the actual object, but what does the actual object mean?
  Double.parseDouble(liters)

My last question is about the method Double.parsedouble().
Can you say me for what the Double(.parsedouble) stands? Is it the classname that starts the method?
I'm really sorry that there are several questions in one post, but I think this is basic knowledge, and it wouldn't be necessary to post it in more questions.
I hope you can help me. Thank You!
Comment: @Juned Ahsan I read 3 books about android apps.. I just want to understand the most simple things that aren't explained in my books so well that I could understand it. I'm really sorry if this sounds dumb to you but I would be really grateful if you helped me.
Comment: @Vivian If you're having problems with the basics, you should start with the [tutorials from Oracle](http://docs.oracle.com/javase/tutorial/).  Start with **Trails Covering the Basics**.
Comment: You are right. Most of your questions are about basic things. About *VERY* basic things. And that's exactly why you should read some java tutorials.
Comment: @Vivian There is no shame of asking basic questions ;) Everybody needs to start some time ! But I recon reading books and stuff isn't that...fun to do. I followed this course by Coursera. https://class.coursera.org/android-001/lecture. The lectures are free !! The bloke begins at the very start of Android programming :) Hope it helps ya out !
Answer: Button and TextView are class names. When I type:
private Button myButton;

I create a reference to an object of type button that points to an empty address location.
If I then instantiate an object as follows:
myButton = new Button();

myButton will refer to a newly created Button object in the program's memory.
For android, or any Java Swing, Button objects simply mean buttons in your GUI interface. While TextView is a text field that displays.. you guessed it.. text.

In your case, the Button is something you already have in your XML file describing your GUI, so you point to that button in your object by using findViewById(..).
Regarding this, it refers to an object of the class that you are in. So whenever I instantiate an object of type Spritkostenactivity, there will be a button listening to clicks on this object (any instance of Spritkostenactivity) due to the statement buttonstop.setOnClickListener(this).

Double is the class name of the data type that holds a double-precision floating point number, parseDouble is a function that takes a string and formats it into a double number.
Comment: Thank you, this post was really helpful for me!


How often is 2 a principal root of unity modulo a prime $p$?

Question: We know, from Bertand's postulate that there is always a prime number between $n$ and $2n$, for $n > 3$.  I'm wondering if there is a similar conjecture for the number $2$ being a principal root of unity modulo a prime $p$, with maximum multiplicative order.
To make this more clear, I'm wondering if we can say something like $2$ is a principal root of unity, with maximum multiplicative order, modulo some prime $p$, with $n \le p \le \alpha \cdot n$, for all $n$ and some constant $\alpha$ that is preferably small.  Does this $\alpha << \infty$ exist?
Comment: That condition is just called being a primitive root. It is a wide open problem whether there are even infinitely many primes $p$ for which this is true.
Comment: What do you mean a "principal root of unity modulo a prime $p$"?  Did you mean a primitive root?
Comment: @lulu:  Sorry, thinking about things, I may need $2$ to be both, if that is possible.  I'm really looking for a principal root of unity that also has maximum multiplicative order, if it's possible.
Comment: Well, I don't understand what the first condition is. if $k$ is the order of $2\pmod p$ then isn't $2$ a primitive $k^{th}$ root of unity $\pmod p$?
Comment: @lulu:  I'm looking for how often it occurs that $k=(p-1)$.  Additionally, $2$ must be a principal root of unity.
Comment: @QiaochuYuan:  That's what I was afraid of.  I wonder if there are any conditional results, such as assuming the generalized Riemann hypothesis.  Is there any situation in which $2$ or, really, any constant integer such as $100000$ occurs in this way?
Comment: As I say, I don't understand what the "principal" condition means in this context.  I think you are just looking for a primitive root.  And, as others have remarked, it's unknown whether there are infinitely many such $p$.
Comment: @lulu:  Just to be brief:  According to Wikipedia, the primitive roots are always principal roots (of unity) in an integral domain, and I know that I need a principal root, so I believe now that we are ok.
Answer: According to Artin's conjecture on primitive roots, there are infinitely many primes for
which $2$ is a primitive root, and the asymptotic density of these in the primes is
Artin's constant, approximately 0.3739558136.  However,
 the conjecture is still open.
See also OEIS sequence A001122.
Comment: I see that Pieter Moree writes that assuming GRH, it is essentially proven.  Anyways thanks for adding the OEIS entry, and of course thanks for the answer.


Need help writing query for Mongo DB for string does not contain

Question: I'm a total beginner to querying Mongo DB, and need some help! This should be an easy one! I'm trying to write a query to show only opportunities that are not from an event. So, I'm trying to query my database for when my lead source does NOT contain the string "show" or "event". These phrases could be anywhere in the string, for example "Miami Show - 2022" or "Orlando 2021 Event".
So far, my query below is not working because (1) it does not include event and (2) does not account for other text being before or after "show" or "event".
Any ideas?
{leadsource:{ "$not":/show/i}}
Answer: Maybe something like this:
db.collection.find({
$and: [
{
  key: {
    $not: {
      "$regex": "event",
      "$options": "i"
      }
    }
  },
 {
  key: {
    $not: {
      "$regex": "show",
      "$options": "i"
      }
    }
  }
]
})

Explained:
Match sentences that do not cotain at least one "event" or at least one "show".
Playground


How can I apply a filter using Softlayer's ticket API?

Question: I tried to receive a full list of tickets with the following code snipped:
client = SoftLayer.create_client_from_env(username="xxx", api_key="xxx")
client['Account'].getTickets(mask='id')

Even so I mask the output to only return 'id' it fails in one of my Softlayer accounts with SoftLayerAPIError: SoftLayerAPIError(SOAP-ENV:Server): Internal Error. I have over 1.4 millions tickets (including closed) in that account.
Next I tried to apply a filter:
tickets = client.call('Account', 'getTickets',
                      filter={'id': { 'operation': 48076123 }}
# or
tickets = client.call('Account', 'getTickets',
                      filter={'id': { 'operation': '>48076123' }}

But it always returns the complete list of tickets and fails the same way on the accounts with a high number of tickets. I need to create a history of all tickets.
Is there are way to limit the query or create a window over the results?
Any help is appreciated.
Answer: your objectMask should be

client['Account'].getTickets(mask="mask[id]")

your fitler should be:

tickets = client.call('Account', 'getTickets',
                        filter={"tickets":{"id":{"operation":48076123}}}

and also you can limmit the result using the pagination
client.call('Account', 'getTickets', limit=10, offset=0)

see https://github.com/softlayer/softlayer-python/blob/master/docs/api/client.rst for more information
Comment: I think the pagination is the solution I was looking for. Thank you.


Basics of using MongoDB on remote server with SSH

Question: I'm having trouble getting started with MongoDB via SSH on a VPS.  Note that MongoDB was installed by admins with the VPS service, not me.  I have to presume they installed it correctly.  Unfortunately, they provide zero support documentation and I can't figure it out after reading countless official MongoDB docs and even more found elsewhere.
I am able to SSH into the remote server just fine.  I can check the MongoDB version, and mongosh is there, too.  But I cannot figure out how to get to the point where I can create a new collection, or even start MongoDB, if that's what I need to do.
Here are some of the things I've tried in the shell for the VPS.  The closest I've gotten is by running mongosh -nodb which seems to get me inside of MongoDB, but I know that option means "no database," so it's not what I need to do.
$ ssh firstname.lastname@example.com
Last login: Thu Dec 29 11:56:53 2022 from 22.214.171.124
firstname.lastname@example.com [~]# mongod -version
db version v6.0.3
Build Info: {
    "version": "6.0.3",
    "gitVersion": "f803681c3ae19817d31958965850193de067c516",
    "openSSLVersion": "OpenSSL 1.0.1e-fips 11 Feb 2013",
    "modules": [],
    "allocator": "tcmalloc",
    "environment": {
        "distmod": "rhel70",
        "distarch": "x86_64",
        "target_arch": "x86_64"
    }
}
email@example.com [~]# mongosh --version
1.6.1
email@example.com [~]# mongosh -nodb
Current Mongosh Log ID: 63abf66ca872ab436a8040c8
Using Mongosh:      1.6.1

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

> use test-db
MongoshInvalidInputError: [SHAPI-10004] No connected database
> exit
firstname.lastname@example.com [~]# mongosh --username customusername
Enter password: ********************************
Current Mongosh Log ID: 63abf8c15a47f0e078be3d76
Connecting to:      mongodb://<credentials>@127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.1
MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017
email@example.com [~]#

I am able to pull up "help" files.  And I've tried multiple variations of # mongod mongodb://firstname.lastname@example.com:27017/ which fail.
email@example.com [~]# mongod help

firstname.lastname@example.com [~]# mongosh -h

firstname.lastname@example.com [~]# mongod mongodb://email@example.com:27017/

That last command returns a few lines which indicate it might be working, then it fails with message: "Invalid command: mongodb://firstname.lastname@example.com:27017/" And then it displays a number of "General options" such as "-h [ --help ]".  I can't make sense of most of them.
Note that I cannot install MongoDB/mongosh locally because my machine is too old, so I have to be able to log in through SSH and handle it that way.  If I can figure it out via SSH, maybe I'll try something like MongoDB Compass next, which I am able to install locally.
Thank you for your time and assistance.

UPDATE: I think I've made progress, but am still not there yet.
I think I got MongoDB running with this, after creating a directory called "mongodb" to hold data files:
# mongod --port 28015 --dbpath ./mongodb/
A string of messages come up in my terminal, with the last being related to listening ("ctx":"listener","msg":"Waiting for connections"), and the process appears to continue running.
I then open a new terminal window, SSH in, and run this:
# mongosh --port 28015
Which appears to land me in a mongo shell in which I'm able to create a new collection:
test> use test-db
switched to db test-db
test-db>

Also, I notice that the original terminal window with the open process outputs connection-related messages as I interact with the second window (e.g. "ctx":"listener","msg":"Connection accepted").
I looked inside of the /mongodb/ directory and there are a number of mongo-related files in there now, "collection-0-5001736531146682033.wt", "index-1-5001736531146682033.wt", "storage.bson", and so forth.  So, I think the db creation is working.

UPDATE TWO
Was struggling with why the show command was throwing an error, since use was already working, then figured out I needed to insert a document first:
test> db.tours.insertOne({name: "Some Name", price: 19, rating: 3.5})
The full command is show dbs and then the "test" database appears.
Comment: This is a really broad question.  You might start with https://www.mongodb.com/docs/manual/tutorial/manage-mongodb-processes, and then ask more specific question if you get into trouble.
Comment: First of all, you need to start the `mongod` database service (see https://www.mongodb.com/docs/manual/reference/program/mongod/). Once the service is up an running, you can use the `mongosh` to connect to the database.
Comment: `--nodb` means "no database", i.e. you just open the mongo shell but you don't connect to any database.
Comment: It is all correct what you have done. You started the database and you connected your shell to it. Now, what do you like to do? There is nothing you stated in your question.
Comment: Yes, I think I'm getting there.  Thanks.  But why is the `show` command throwing an error?  Once I feel like `use` and `show` are working, I'll move on to more regular mongo tasks like manipulating data, or accessing it via Compass.  So, I guess this is resolved if I can get `show` to work properly.
Comment: Ah, I just needed to insert a document (`db.tours.insertOne({...})` before `show` worked, and the actual command is `show dbs`.  So, it's working and I'm good to go I think with very basic SSH mongodb.  Thanks for checking this out
Answer: So, you can check out my two updates above.  I was able to access and do very basic operations with MongoDB on a VPS with SSH.
Also, here are some helpful links, if you struggle with similar issues.
Mongo Shell basics:
https://www.mongodb.com/basics/get-started#get-started-with-mongodb
(skip down to the "Get Started with MongoDB" subsection, since the top of the page is about the Atlas interface)
Setting up admin and user accounts via command line:
https://medium.com/@haxzie/getting-started-with-mongodb-setting-up-admin-and-user-accounts-4fdd33687741
Good luck!


How to connect to a wireless network that has a two word name with a space?

Question: Ok, I have searched for some time in earnest for an answer to this question.  I have a Beagleboard which has Ubuntu 10.10 Minimal install for Arm running on it.
With the default install, minimal tools, no GUI, I am unable to connect to my wireless network.  The name of my network is "MYNAME NETWORK".  Using a text editor to edit /etc/network/interfaces I can not seem to connect at all.
As an experiment, I connected to a friends network, which has a one word name "dystek",and was able to connect with Zero issues, and update and install a full GUI for ubuntu Arm.
The problem is that I don't want a full blown gui on the beagleboard, just a minimal install of ubuntu with CLI is all I need or want.
Is there anyway to connect to my wireless network via editing the /etc/network/interfaces file.  Surely there is... I just don't know how.
Right now my interfaces file looks like this:
auto lo
iface lo inet loopback

auto wlan0
iface wlan0 inet static
address 192.168.1.200
netmask 255.255.255.0
gateway 192.168.1.1
wireless-essid BARRETT NETWORK
wireless-key 46456xxxxxxxx

Any help would be appreciated.
Comment: did James' suggestion in the comment to my answer help?
Answer: From here:

Add the name (ssid) for the network you want to create/join. Use single quotes if there is a space in the name.

So you could try:
wireless-essid 'BARRETT NETWORK'

Another alternative is to specify the MAC address of the router/gateway, instead of the name. This is called the bssid.
wireless-bssid FFFFFFFFFFFF

You would replace the essid line with a bssid line containing the MAC address of the router (it should be printed on the bottom of it, or can be found with sudo iwlist scanning under 'Address').

Edit: From James' comments below, try replacing the wireless-essid and wireless-key lines with the following, as you are using WPA. Your passphrase also needs to be in hex. There are online tools for converting your passphrase to hex.
wpa-ssid 'BARRETT NETWORK'
wpa-psk 46456xxxxxxxx

Comment: Now trying the mac address as bssid, no quotes, does not work either.
Comment: The configuration you've quoted is for a network protected by WEP, which is a bit uncommon these days.  If the network is instead using WPA, then that is more likely to be the reason you can't connect rather than an incorrect network name.  If that's the case then you should probably be using the `wpa-ssid` and `wpa-psk` options instead of `wireless-essid` and `wireless-key`.
Comment: as a follow up to this, I am definitely on a wep connection, but the main problem was using a passphrase instead of a hex key.  Once I corrected this, today, finally got it working correctly.
Comment: I had tried the single quotes, thinking that I had it right, but I had left the slash in, (\) not sure where i heard that it needed that. 'Barrett Network' does not work.
Comment: @grinan James makes a good point, are you sure your network is using WEP? If not, try the wpa commands he listed.
Comment: @grinan: since it seems this answer was the right one to solve your problem or at least it gave you hints, you should check it as the right one. Thanks!
Comment: @igi no actually this answer is incorrect.  The linked page regarding using single quotes is talking about at the command line, not the file syntax.  From my own test in Ubuntu 16.04.2, the rest of the line following the wpa-essid and the first space is taken literally, so no quotes or escaping is required.
Answer: From my own test in Ubuntu 16.04.2, the rest of the line following the wpa-essid prefix is taken literally, so no quotes or escaping is required.  From your comments in this thread, it looks like the issue was actually due to using a passphrase instead of a hex key.


AND-ing shorts in c++

Question: How would i write a piece of code that ANDs the first byte of a short, but not the second part?
Eaxmple:
I have a short called inputShort, and I want this short to delete all values in the second byte. So I want to AND this with a logic operator.
Well, I tried, and I failed. so can someone give me an example how to do this ?
My goal is to keep the left part of the short, and empty out the right part of the short.
Answer: I don't know if you mean the most or least significant when you say "second byte", but here is an example that might help.
short second = 0xFF00;
short first = 0x00FF;
short number = 0x1234;
short tmp;

tmp = number & first; //tmp is set to 0x1234&0x00FF -> 0x0034
tmp = number & second; //tmp is set to 0x1234&0xFF00 -> 0x1200

Answer: "First" and "second" are ambiguous. They tend to refer to the storage, so endian-ness comes into play, and I assume you don't mean that. Also the number of bytes in a short is implementation-defined.
I assume you want to zero out the least significant ("right") bits, and retain all other bits:
#include <limits>

...

inputShort & ~std::numeric_limits<unsigned char>::max();

Or if you're feeling brave, and you want to assume 8-bit bytes:
inputShort & ~0xFF;

(It doesn't take very much bravery to assume 8-bit bytes).
Comment: +1 for realizing that the question was tagged C++, not C. I don't know what is happening to my eyesight ;-)
Comment: Heh, I got to the point where I was about to type UCHAR_MAX, before I thought to myself "are we in C here, or C++?"
Comment: +1 for pointing out that bytes aren't (well, weren't) always 8 bit.
Comment: Still aren't: the usual examples of non-8-bit platforms include some modern DSPs with chars of 16 or 32 bits. POSIX and Windows both specify 8 bits, though, and network protocols are all about octets, which does cut down the chances of encountering anything else. There's not much point building a CPU with any other byte size if you plan to put an OS on it...
Answer: It's easy:  res = inputShort & 0xff00
If you want you can also shift the second byte to the lower order one by using >>:
unsigned short res = (inputShort & 0xff00) >> 8

Answer: Assuming 16-bit shorts:
#include<stdio.h>

int main(void) {
    unsigned short val = 0xbaba;
    unsigned short mask = 0xff00;
    unsigned short result = val & mask;
    printf("%04x\n", result);
    return 0;
}

Output:

E:\tmp> t
ba00
Comment: thanks all of you, i guess &-ing with 0xffffffff00000000 didn't quite give the same result.
Answer: Ok, I wrote this method:
short Game::swapShort(short inputShort)
{
    short tempA;
    short tempB;

    tempA = ((inputShort & 0xff00) >> 8);
    tempB = ((inputShort & 0x00ff) << 8);

    short total = tempA + tempB;
    return total;
}

which i think should work correctly.
However, my inputShort will be a pointer in my program. Can someone also explain to me how i would adapt my method to work with short pointers? :$
Answer: In response to Krunk's comment above:
First of all, you probably want to do this:
short total = tempA | tempB;

You're logically trying to OR them, not add them. If you wanted to do this with inputShort being a pointer, that'd be pretty easy, but you might as well use a reference instead, so you don't have to mess with dereferencing a pointer. Also, you have to be careful with automatic sign extension when you're dealing with signed types. If you're doing a right-shift of a value that has the most significant bit set, you're dealing with a shift of a negative number.. Well, let me just show you an example:
short foo = -5;

Let's assume 16 bit shorts for now.
In two's complement binary that's
1111 1111 1111 1011

If we right-shifted that by 1, we'd get:
1111 1111 1111 1101

That extra 1 on the left hand side is there because of sign extension.
So let's walk through byte-swapping our -5 using your code:
tempA = ((1111 1111 1111 1011) & 0xff00) >> 8
so, the and operation first gives us:
1111 1111 0000 0000

Then right-shift gives us:
1111 1111 1111 1111

That's obviously not what you wanted.
One way you can do this is just use a reinterpret cast. I'm assuming there's a reason your input to swapShort is a short instead of an unsigned short? In any case, I'll leave it as a short:
//I went ahead and modified this to take a short pointer, like Krunk asked.
//Also note we're assuming 16-bit shorts. This'll break on platforms where this isn't the case.
void Game::swapShort(short *inputShort)
{
    //Once we start treating it as unsigned, don't have to worry about sign extension.
    unsigned short* tmp = (reinterpret_cast<unsigned short*>(inputShort);

    unsigned short highByte = ((*tmp & 0xff00) >> 8)
    *tmp = highByte | ((*tmp & 0x00ff) << 8);

}

Or if what you're REALLY trying to do is just get this in network byte order, there's an easier way, you can use htons and ntohs:
An example would be:
unsigned short foo = 300;
//htons = host to network short
unsigned short foo_net_byte_order = htons(foo);

The good thing about using htons and its equivalents is, if you're running the code on a big-endian system, htons & ntohl are basically no-ops, but it'll actually swap them on a little endian system. That is, you don't have to figure out the endianness of the system you're running on before figuring out if you need to swap or not. htons knows what network byte order means and what your host byte order is, and it will just handle it for you. There are equivalents for longs as well. See http://msdn.microsoft.com/en-us/library/ms738557%28VS.85%29.aspx
The same function exists on POSIX type operating systems as well, but you'll have to include a different set of headers.

AND-ing shorts in c++


gnuplot gives extraordinary large error estimates

Question: Today I tried to fit experimental data with a given theoretical model. Although the fit was fairly good, gnuplot returned extremely high errors:
Final set of parameters            Asymptotic Standard Error
=======================            ==========================

A               = 1.76654e-11      +/- 2.589e-06    (1.465e+07%)
g               = 0.000929911      +/- 1.006e-05    (1.082%)
offset          = 0.831727         +/- 0.005273     (0.634%)
x0              = 25.7152          +/- 3768         (1.465e+04%)

Especially, the error on x0 is an important measure for my following calculations. Obviously, this value is absolutely nonsense, as can be seen in the figure below.
What do I have to do to get a meaningful error?

MWE:
f(x,x0,g) = -16.0*A*(g*(g**2.0-12.0*(x-x0)**2))/(pi*(g**2.0+4.0*(x-x0)**2.0)**3.0) + offset
FIT_LIMIT = 1e-16

A=-1e-3
g=1e-3
offset=0.8
x0 = 25.71514200

fit f(x,x0,g) "data" via A,g,offset,x0

plot "data", f(x,x0,g)

Data: Link (pastebin)
Comment: If you want to try building gnuplot from the sources, there is a patch [#655 fit: alternative minimization packages](http://sourceforge.net/p/gnuplot/patches/655/) which allows you to select between different fitting libraries. I haven't tested it.
Comment: I can reproduce what you see, curious to learn what is going on actually.
Comment: Did you try to evaluate df/dA, df/dx0 etc? It gives you an idea about error propagation, and might teach you something.
Comment: Yes, I did error propagation analysis but that showed nothing unusual... In the end I concluded that it is somehow not possible using gnuplot although the fit itself was relatively fine. I chose to use (for the first time in my life) a commercial software with which it worked nicely.
Answer: I guess there are two aspects to this case.
0. I exclude the presence of a bug, but that could still be the case.

Check the actual definition of the Asymptotic st. error, and the other parameters of the fit, which in this case seem reasonable.
Please check also the other details of the fitting:
"degrees of freedom    (FIT_NDF)                        : 97
rms of residuals      (FIT_STDFIT) = sqrt(WSSR/ndf)    : 0.0420015
variance of residuals (reduced chisquare) = WSSR/ndf   : 0.00176412
"

From Gnuplot manual:

the asymptotic standard errors are generally over-optimistic and should not be used for determining confidence levels, but are useful for qualitative purposes.

It may be that the fit is actual correct, but since you have many dof, and a complex function that's the best you can rigorously achieve.

There is an intrinsic limit into fitting. For example it depends on the starting values and sometimes you fall into some pits.

As a test I run the fitting starting with different starting values for the parameters.
(I renamed variables) and I created a second function with different parameters just to be sure we are all the time starting with new parameters.
f(x) = -16.0*A*(g*(g**2.0-12.0*(x-y)**2))/(pi*(g**2.0+4.0*(x-y)**2.0)**3.0)+B
g(x) = -16.0*AA*(gg*(gg**2.0-12.0*(x-yy)**2))/(pi*(gg**2.0+4.0*(x-yy)**2.0)**3.0)+BB
gnuplot> A=1e-3 ; g=1e-3; B =0.8 ; y = 25.71514200
gnuplot> AA=-1e-3 ; gg=1e-3; BB =0.8 ; yy = 25.71514200

(Basically I did a second fitting changing the sign of A)
Results of fitting f(x)

gnuplot> fit f(x) "data.dat" u 1:2 via A,B,g,y
iter      chisq       delta/lim  lambda   A             B             g             y
[CUT]

After 2 iterations the fit converged.
final sum of squares of residuals : 487.102
rel. change during last iteration : -4.02829e-07

degrees of freedom    (FIT_NDF)                        : 97
rms of residuals      (FIT_STDFIT) = sqrt(WSSR/ndf)    : 2.24091
variance of residuals (reduced chisquare) = WSSR/ndf   : 5.02167

Final set of parameters            Asymptotic Standard Error
=======================            ==========================
A               = 0.000999999      +/- 585.1        (5.851e+07%)
B               = 0.8              +/- 2124         (2.655e+05%)
g               = 0.001            +/- 535.8        (5.358e+07%)
y               = 25.7408          +/- 1362         (5292%)

correlation matrix of the fit parameters:
                A      B      g      y
A               1.000
B              -0.999  1.000
g              -1.000  0.999  1.000
y               1.000 -1.000 -1.000  1.000

Result of fitting g(x)
gnuplot> fit g(x) "data.dat" u 1:2 via AA,BB,gg,yy
iter      chisq       delta/lim  lambda   AA            BB            gg            yy
   0 5.0258343096e+02   0.00e+00  1.03e+03   -1.000000e-03   8.000000e-01   [CUT]
iter      chisq       delta/lim  lambda   AA            BB            gg            yy

After 6 iterations the fit converged.
final sum of squares of residuals : 0.171225
rel. change during last iteration : -3.85774e-08

degrees of freedom    (FIT_NDF)                        : 97
rms of residuals      (FIT_STDFIT) = sqrt(WSSR/ndf)    : 0.0420144
variance of residuals (reduced chisquare) = WSSR/ndf   : 0.00176521

Final set of parameters            Asymptotic Standard Error
=======================            ==========================
AA              = -0.000999968     +/- 9.454e+07    (9.454e+12%)
BB              = 0.828332         +/- 240.8        (2.908e+04%)
gg              = 0.000999968      +/- 9.453e+07    (9.454e+12%)
yy              = 26.1206          +/- 3.798e+06    (1.454e+07%)

correlation matrix of the fit parameters:
                AA     BB     gg     yy
AA              1.000
BB             -0.040  1.000
gg              1.000 -0.040  1.000
yy             -0.110  0.998 -0.109  1.000
gnuplot>

Not only the fitting are different, but in my case they are completely off (I have a different version of gnuplot).
Looking at the graphic I also notice that the graphic has 3 areas, two almost linear and one that looks like a well.
I am not surprised is not easy to find the proper function that matches all.
Have you tried to proceed fitting one parameter at the time, starting from X0, since it seems the most univocal one? ( you might as well assign it by eye, or use a parabolic approach to a subset of the data).
This is practically equivalent to do fitting with respect to derivates.
In this way you are reducing the number of constrain and you might land in a better fit.
Answer: I think that problem is in using 3-parameter function. From the first line it seems that x0 and g are variables. But in fit it's used as mixture of parameters (because of via...) and variables (because of f(x,x0,g)).
How many columns have got file "data"? It looks like that 2 is right answer.
Try this:
f(x) = -16.0*A*(g*(g**2.0-12.0*(x-x0)**2))/(pi*(g**2.0+4.0*(x-x0)**2.0)**3.0) + offset
FIT_LIMIT = 1e-16

A=-1e-3
g=1e-3
offset=0.8
x0 = 25.71514200

fit f(x) "data" via A,g,offset,x0

plot "data", f(x)

Comment: That gives identical results to the OP's results. In fact it is completely irrelevant how the values are given to the function which is to be evaluated.
Comment: Well, I am not convinced from this argument.
Variable and parameters are intrinsically different and usually people proceed to calculate them iteratively to avoid to find a bad solution.
Comment: @Cippo1987 Maybe people proceed differently, but not gnuplot. My point was, that both cases are evaluated identically by gnuplot
Comment: Oh, yes, sorry, you are totally right. As far as Gnuplot cares, there is no difference.
I infact suspect that here the problem is more on the side of theory rather than gnuplot.


Kill All the Things or Rush Missions?

Question: Which is better for progressing as quickly as possible in diablo 3, killing everything you can with a +xp gem in a helmet, or completing missions as fast as possible, while just killing monsters that you encounter along the way?
Comment: it used to be repeating missions was the best, but then they nerfed the repeat rewards for all the missions, so I'd imagine a mix of both is probably the way to go.
Answer: It depends :)
If it's your first character, you should probably take the 'Kill ALL the things!' approach, or you could find yourself starting Hell/I with lousy gear and no money to upgrade it with, and have to go back and kill all the things anyway.
For subsequent characters, I definitely prefer to rip through the quests as fast as possible. Success in Normal and Nightmare in particular are far more dependent on gear, and you'll get enough XP from just doing the quests and only killing the stuff that's in your way to keep from getting too far ahead of the curve. I've done this three times, and the only real speedbump I've hit is only being in the late 40's at the end of Nightmare/IV, and having to grind out XP until level 50.
Comment: Wow... I guess that answers the difference in effectiveness then, as I "killed all the things" for my second character, and hit 60 part way through act 2 hell. This will be my third so I think I'll slow up a bit now that I'm in nightmare.

Kill All the Things or Rush Missions?


Authenticating with Exchange Web Services from server after setting up impersonation context

Question: I have the following setup for an app I want to use on the local network:
Silverlight Client App -> Web Server (data objects etc) | -> Exchange
                                                        | -> SQL Database

Everything else works fine, I can get data from the DB, etc (might be worth noting I'm using SQL auth for SQL not windows auth), but when I try to get calendar entries for the current user from exchange using Exchange Web Services it gives me a 401 unauthorised error.
This is all running on my local dev server (on my machine) which is running under a classic ASP.NET 4 app pool using the default ApplicationPoolIdentity. I'm not coming in via SSL, just over port 81
I can connect to get my own calendar entries, but for other users I get the error
If I try it without the impersonation code, I get a Connection did not succeed. Please try again later error since I assume that EWS will be using ApplicationPoolIdentity which doesn't have a domain logon.
I've used the following code to impersonate (ignore any potentially unhandled exceptions/security holes for now I just want to get it working!):
var impersonationContext = ((System.Security.Principal.WindowsIdentity)System.Threading.Thread.CurrentPrincipal.Identity).Impersonate();

// Use default credentials
service.UseDefaultCredentials = true;

// Get the target folder ID using the email address
var folder = new FolderId(WellKnownFolderName.Calendar, new Mailbox(emailAddress));

// Get the appointments
var response = service.FindAppointments(folder, view);

impersonationContext.Undo();

// Return list of appointment entities
return response.Items;

Looking at System.Security.Principal.GetCurrent() shows that the user changes to the identity of the user I want to impersonate after the Impersonate method is called. The AuthenticationType is Kerberos and the ImpersonationLevel is Impersonate. As far as I can see this should work but it looks like my web server doesn't want to successfully auth with exchange.
Am I missing something in my setup or in exchange?
Comment: AFAIK because of the "server hop" this will only work if you have Kerberos delegation enabled for your servers.
Answer: This ended up working in the end - it ended up being some exchange settings and using the current threads principal instead of the system principal
Comment: What exchange settings? Having the same issue.
Comment: Well that's the problem - I have no idea :) at the time the CTO wouldn't let me near the servers - it was a case of "try now...... try now.... try now...", sorry :(


How To Combine/Pull corresponding Columns

Question: I have the following table in SQL

I would like to create a new table that combines the values of FemaleID and MaleID into one column FemaleMale, while bringing in the corresponding columns as well.
Here would be the final output.

How can this be done? I am using snowflake.
Comment: If you are using Snowflake, then tag Snowflake, instead of completely different database products, MySQL & SQL Server - which are totally not relevant.
Comment: As per the question guide, please do not post images of code, data, error messages, etc. - copy or type the text into the question. Please reserve the use of images for diagrams or demonstrating rendering bugs, things that are impossible to describe accurately via text.
Comment: What have you tried? Where did you get stuck?
Answer: Without answers to questions asked in comments, this might need changing, but general SQL, this is simple UNION:
<code>SELECT FemaleId AS FemaleMale, Stage, Season
FROM YourTable

UNION ALL

SELECT MaleId AS FemaleMale, Stage, Season
FROM YourTable
</code>
Comment: I tried this and have values from Stage in season and season to Stage


Query with Foreach inside

Question: I would like Wordpress query to have a foreach in it.
$aid=0;
    foreach ($QA as $key => $value) {
    AND wp_postmeta.post_id IN (
        SELECT wp_postmeta.post_id
        FROM wp_postmeta, wp_posts
        WHERE wp_posts.ID = wp_postmeta.post_id
        AND wp_posts.post_status = 'publish'
        AND wp_posts.post_type = 'post'
        AND wp_postmeta.meta_key = '$key'
        AND wp_postmeta.meta_value = '$value'
    )
    $aid++;
}

But it's not working that way, so I'm asking for help -
How I can put foreach in sql query?
Full example of code below.
<?php
 function query_products($QA) {

global $wpdb;
global $post;
global $pageposts;

$querystr = "

SELECT wp_posts.*, wp_postmeta.*
FROM wp_postmeta, wp_posts
WHERE wp_posts.ID = wp_postmeta.post_id
AND wp_posts.post_status = 'publish'
AND wp_posts.post_type = 'post'
AND wp_postmeta.meta_key = 'country'
AND wp_postmeta.meta_value = 'Denmark'

$aid=0;
    foreach ($QA as $key => $value) {
    AND wp_postmeta.post_id IN (
        SELECT wp_postmeta.post_id
        FROM wp_postmeta, wp_posts
        WHERE wp_posts.ID = wp_postmeta.post_id
        AND wp_posts.post_status = 'publish'
        AND wp_posts.post_type = 'post'
        AND wp_postmeta.meta_key = '$key'
        AND wp_postmeta.meta_value = '$value'
    )
    $aid++;
}

ORDER BY wp_postmeta.meta_value ASC
    ";

$pageposts = $wpdb->get_results($querystr, OBJECT);

}

$QA = array (
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3',
);
query_products($QA);
?>

Comment: Can you explain what would be the purpose of such a thing?
Comment: Yes. That would loop over Wordpress posts, dynamically filtering them by multiple meta values.
Answer: $querystr = "
SELECT wp_posts.*, wp_postmeta.*
FROM wp_postmeta, wp_posts
WHERE wp_posts.ID = wp_postmeta.post_id
AND wp_posts.post_status = 'publish'
AND wp_posts.post_type = 'post'
AND wp_postmeta.meta_key = 'country'
AND wp_postmeta.meta_value = 'Denmark'
";

$aid=0;
    foreach ($QA as $key => $value) {
       $querystr .= "
    AND wp_postmeta.post_id IN (
        SELECT wp_postmeta.post_id
        FROM wp_postmeta, wp_posts
        WHERE wp_posts.ID = wp_postmeta.post_id
        AND wp_posts.post_status = 'publish'
        AND wp_posts.post_type = 'post'
        AND wp_postmeta.meta_key = '$key'
        AND wp_postmeta.meta_value = '$value'";
    )
    $aid++;
}
$querystr .=" ORDER BY wp_postmeta.meta_value ASC";

Comment: `.=` operator for string concatenation.
Answer: Without knowing what the query is supposed to accomplish, I can only suggest something like this:
<?php

$querystr = "
SELECT wp_posts.*, wp_postmeta.*
FROM wp_postmeta, wp_posts
WHERE wp_posts.ID = wp_postmeta.post_id
AND wp_posts.post_status = 'publish'
AND wp_posts.post_type = 'post'
AND wp_postmeta.meta_key = 'country'
AND wp_postmeta.meta_value = 'Denmark'
AND wp_postmeta.post_id IN (
    SELECT wp_postmeta.post_id
    FROM wp_postmeta, wp_posts
    WHERE wp_posts.ID = wp_postmeta.post_id
    AND wp_posts.post_status = 'publish'
    AND wp_posts.post_type = 'post'
";
if (count($QA) >= 1) {
    $querystr .= " AND ( ";
    foreach($QA as $key => $value) {
        $querystr .= "(wp_postmeta.meta_key = '{$key}' AND wp_postmeta.meta_value = '{$value}') OR ";
    }
    // get rid of the last "OR" in the string
    $querystr = substr($querystr,0,strrpos($querystr,"OR"));
    $querystr .= " ) ";
}
$querystr .= " ORDER BY wp_postmeta.meta_value ASC ";

?>

Note I used "OR" above because you'll never get any results when checking a single field for multiple values using an "AND" clause.
Answer: You need to pass all the keys in as an array or issue the full query iteratively (including the select).  I would not recommend the latter, because performance will be poor (excessive database round trips are bad).  So, I'd do something like this as long as $QA is not too huge.  I believe it to be a little bit simpler than the full subquery originally submitted by using an EXISTS clause, but this may be more a matter of taste than one truly being better than the other.
<?php
 function query_products($QA) {

global $wpdb;
global $post;
global $pageposts;

    $querystr = "
    SELECT wp_posts.*, wp_postmeta_a.*
    FROM wp_postmeta AS wp_postmeta_a, wp_posts, wp_postmeta AS wp_postmeta_b
    WHERE wp_posts.ID = wp_postmeta_a.post_id
    AND wp_posts.post_status = 'publish'
    AND wp_posts.post_type = 'post'
    AND wp_postmeta_a.meta_key = 'country'
    AND wp_postmeta_a.meta_value = 'Denmark'
    ";

    $aid=0;
    foreach ($QA as $key => $value) {
        $querystr .= "
            AND EXISTS (SELECT 1
                    FROM wp_postmeta AS wp_postmeta_b
                    WHERE wp_posts.ID = wp_postmeta_b.post_id
                    AND wp_postmeta_b.meta_key = '$key'
                    AND wp_postmeta_b.meta_value = '$value')
        ";

        $aid++;
    }

    $querystr .= " ORDER BY wp_postmeta_a.meta_value ASC ";

    $pageposts = $wpdb->get_results($querystr, OBJECT);

}

$QA = array (
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3',
);
query_products($QA);
?>

Query with Foreach inside


How to set Attributes in Firebase?

Question: I need to set the "People" attribute in firebase. I don't know how to set dictionary attribute using SWIFT.
 I have added my code below which I have tried .
<code>let key = snapshot.key

        let upload = ["id":key,
                  "status":status,] as [String : Any]

        databaseRef.child("location").child(key).setValue(upload)
</code>
This image is firebase data
Answer: Try this:
<code>  let key = snapshot.key

  let updates: [String: Any] = [
     "/id": key,
     "/people/name1": <yourValue>,
     "/people/name2": <yourValue>,
     "/status": status
  ]

  databaseRef.child("location").child(key).updateChildValues(updates)
</code>
Hope it helps

How to set Attributes in Firebase?


Use table from existing external database in my project

Question: I have a database created out of my android  project.
There are some static informations as for example contact informations.
Instead of creating a new table and inserting those informations in my local project database, I would like to use the existing table and add it to my project.
Is this possible and if possible, how can i do this?
Thank you very much.
Answer: For this, you may copy your already created database file in Assets or Raw folder and load it by copying it in a cache directory. Doing so will actually include your database file in your .apk file and you may access it when ever you want without any fear of loosing records in case if user clears the cache
Comment: Thank you Waqas, I will try this, but how to load this database from Assets folder?
Comment: this will help you to deal with your own databases: http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/


Hashlib, Trouble Debugging

Question: I am trying to play with a hashcracker to use in a secure sandbox account for ethical purposes. I believe my code is correct and I cannot find a reason why it is not executing. Well the code is clearly not correct unless it would run LOL however, I cannot find the bug
<code>from urllib.request import urlopen, hashlib

sha1hash = input("Please input the hash to crack.\n>")      #puts user input on new line in prompt

LIST_OF_COMMON_PASSWORDS = str(urlopen('https://raw.githubusercontent.com/danielmiessler/SecLists/master/Passwords/Common-Credentials/10-million-password-list-top-10000.txt').read(), 'utf-8')

for guess in LIST_OF_COMMON_PASSWORDS.split('\n'): # starts the process of looping through all passwords from the above URL until the correct one is matched.(\n) is used to specifiy/split each individual password from list
    hashedguess = hashlib.sha1(bytes(guess, 'utf-8')).hexigest()  #turns the 'guess' into bytes from string and then turns it into a SHA1 hash// hexigest() prints the current value of the SHA-1 hash
    if hashedguess == sha1hash:
        print('The password is', str(guess))
        quit()
    elif hashedguess != sha1hash:
        print('Password guess ', str(guess),' does not match, trying next....')
print('Password not in database, better luck next time.')

</code>
HERE IS MY ERROR TRACEBACK
Traceback (most recent call last):
  File "hashcracker.py", line 5, in
    LIST_OF_COMMON_PASSWORDS = str(urlopen('https://raw.githubusercontent.com/danielmiessler/SecLists/master/Passwords/Common-Credentials/10-million-password-list-top-10000.txt').read(), 'utf-8')
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 222, in urlopen
    return opener.open(url, data, timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 525, in open
    response = self._open(req, data)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 542, in _open
    result = self._call_chain(self.handle_open, protocol, protocol +
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 502, in _call_chain
    result = func(*args)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 1360, in https_open
    return self.do_open(http.client.HTTPSConnection, req,
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 1320, in do_open
    raise URLError(err)
urllib.error.URLError:
MBP-00704:SHA1cracker andrewroe$ python3 hashcracker.py
Please input the hash to crack.

cbfdac6008f9cab4083784cbd1874f76618d2a97
  Traceback (most recent call last):
    File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 1317, in do_open
      h.request(req.get_method(), req.selector, req.data, headers,
    File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1230, in request
      self._send_request(method, url, body, headers, encode_chunked)
    File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1276, in _send_request
      self.endheaders(body, encode_chunked=encode_chunked)
    File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1225, in endheaders
      self._send_output(message_body, encode_chunked=encode_chunked)
    File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1004, in _send_output
      self.send(msg)
    File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 944, in send
      self.connect()
    File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1399, in connect
      self.sock = self._context.wrap_socket(self.sock,
    File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ssl.py", line 500, in wrap_socket
      return self.sslsocket_class._create(
    File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ssl.py", line 1040, in _create
      self.do_handshake()
    File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ssl.py", line 1309, in do_handshake
      self._sslobj.do_handshake()
  ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)

During handling of the above exception, another exception occurred:
Comment: This looks like an issue trusting GitHub's SSL certificate. How did you install Python?
Comment: I am using a MAC, python was preinstalled. However, I did install Python3 using brew.
Comment: (It's just Mac, not "MAC".) Are you running this code with the preinstalled Python, or with the one you installed yourself? It looks like the latter. Whatever you did, your Python doesn't trust the certificate.
Comment: But seriously, thank you. You turned my attention to the SSL certificate which was the issue!
Answer: I found the answer. I went to Python3.8 folder and installed something called, Install Certificates Command. This fixed my SSL error. Thank you.

Hashlib, Trouble Debugging


Which units are most effective at destroying buildings?

Question: In Halo Wars (1) I use to enjoy a good hit&run tactic on an enemy base early in the game to destroy their generator(s) with cyclops's.
In Halo Wars 2, cyclops's are more anti-tank units then building destroyers.
Which units are the best to take down buildings for both UNSC and Banished?
Answer: For the Banished, the Locust unit is specifically for destroying buildings.  A bunch of these against a building should take it down pretty fast.
As for the USMC, I don't think there is an actual unit specifically for targeting buildings.  However, Scorpions are probably the best at taking out buildings, or Grizzly Tanks if playing as Sgt. Forge.  Upgrading the Scorpion tanks to have their Canister Shell ability makes them pretty devastating against buildings, especially when you have multiple tanks fire all at one time at a building.  Marines when upgraded to have rocket launchers make them pretty effective at this as well, but you need a lot of them focused on a building at a time.
The Vulture unit is very strong as well, but due to the amount of man power it takes to create one, it makes it difficult to get multiples of them.
Comment: +1 but none of those units are available early game. Best I have so far is ODST drops with demo charges
Comment: @Vahx Wasn't sure if you were looking in general or for early on in the game.  I'm not sure what would be best for early game.  Perhaps marines if you upgrade them fast enough.


Reconciling different definitions of orthogonality

Question: I want to establish about orthogonality in my mind.
I knew the orthogonality of two functions $f$ and $g$ in interval $T$ like the following:
$$
\int_{\langle T\rangle}f(t)g^*(t)~dt=0 \tag{1}
$$
where
$$
g^*(t) \mbox{ is a conjugate of } g(t)
$$
However, in some textbooks, if
$$
\text{E}\left[f(t)g(t)\right]=0 \tag{2}\ ,
$$
then two functions $f$ and $g$ are orthogonal.
I want to know the relationship between two equations.
Answer: The notation $E(f)$ is most commonly used in probability theory and this means simply just $\int_{X}fd\mu$ where $(X,\mu)$ is your measure space (it is called expectation). Therefore the only difference between those two relations is the fact that the second uses real scalar product. In other words $g$ is real if and only if $\overline{g(t)}=g(t)$ for all $t$ and in this situation these two notions coincide.
Comment: Thank you, you mean the equations are same?? f and g are real signal.
Comment: I mean that if $f,g$ are real then both notions of orthogonality are the same.


Error in loading a data from the txt file to oracle table using sqlldr

Question: my .ctl file is :
LOAD DATA
  INFILE "C:\Users\nkb1\Desktop\fnames.txt"
  INTO TABLE MDB.TEACHERS
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  (first_name,last_name)

i am executing this from the windows command prompt as
sqlldr system@mdb/mdb control=C:\Users\nkb1\Desktop\load.ctl

and i am getting error like this.
 C:\Users\nkb1>sqlldr system@mdb/mdb control=C:\Users\nkb1\Desktop\load.ctl
 SQL*Loader: Release 10.2.0.1.0 - Production on Wed May 4 14:44:22 2011

 Copyright (c) 1982, 2005, Oracle.  All rights reserved.

 SQL*Loader-704: Internal error: ulconnect: OCIEnvCreate [-1]

and i have set the ORACLE_HOME variable as C:\oracle\product\10.2.0\db_2 where the db stores
Answer: Bad news, this is a bug in 10.2.0.1.
Check Metalink document 361325.1 (hope you have access)!
Maybe you'll just have to grant additional privileges but it is possible that you'll need to apply the 10.2.0.3 patch set
Comment: I suspect if @Navin had a Support account they wouldn't still be running the base release of 10g.  Oracle used to host the stable 10.2.0.4 release on OTN, but it looks like they now only make 11gR2 available from that place.
Answer: I hit the same issue. Closed the command prompt.Opened one with Administrator Rights - Open CMD as Administrator.
That's it. This solved all the issues I had been facing.
If you have saved the SQLLOADER/SQLPLUS scripts as a batch file, then submit/open the batch file as administrator .
Hope this helps.


How do I replace Unity?

Question: I wanted to use Ubuntu 12.04 for its long term support. But I cannot stand Unity. I cannot find a way to replace it with compizconfig, so I tried replacing it with Lubuntu.
When I restarted my computer started to load lubuntu, then just went right on with ubuntu as if nothing had happened. Likewise, it shows lubuntu when it shuts down. What is the deal?
I'm confused here, is ubuntu 12.04 supposed to be an operating system or a desktop interface? Can I even run ubuntu with a Lubuntu interface?
Is there a way to do this in compizconfig that I should be doing instead?
Thanks everyone. Now how do I mark this question as solved?
Comment: If you want the gnome classic desktop see this question [How to revert to GNOME Classic Desktop?](http://askubuntu.com/q/58172/107450) or take a look at one other the other members of the family. [Lubuntu](http://www.lubuntu.net/), [Xubuntu](http://xubuntu.org/getxubuntu/), [Kubuntu](http://www.kubuntu.org/getkubuntu/download) or [Ubuntu Gnome](http://ubuntugnome.org/download/).  These are all fully supported here and don't have the Unity desktop.
Answer: Run the command
sudo apt-get install lubuntu-desktop
then at login click the little ubuntu icon next to your name.
It'll take you to a menu like this:
Click LXDE.
Answer: The Lubuntu components for version 12.04 have reached end-of-life so you will, from now onward, not get updates to the components specific to Lubuntu:

Lubuntu 12.04 is not an LTS (5 years support), but a standard release
  that is supported for 18 months (if you would like to change this
  please feel free to contact the developers to offer assistance in this
  area).

Source.
Look here for the possibility of Lubuntu 14.04 being a long-term support version.

How do I replace Unity?


A vector is defined to have a magnitude and *a* direction, but the zero vector has no *single* direction. So, how is the zero vector a vector?

Question: The popular definition of a vector is

A vector is an object that has both a magnitude and a direction.

We know that zero vector has no specific single direction.
Then how can it be a vector?
Comment: What is a direction?
Comment: Because its magnitude is $0$ and it can have any direction.
Comment: Umm... the zero vector has magnitude $0$ *AND IS IN THE DIRECTION (1,0,0)*...  or in the direction $(a,b,c)$... or in the direction ...  All of these are vectors that happen to have zero magnitude.  Each of these have "*a*" direction.  Nobody said it had to be unique.
Comment: Note that there is a completely different way to define a vector that does not use the concept of direction at all. In this alternative view, a *vector space* is defined first as a set with operations that have certain properties, and then any element of that set is called a *vector*. It's possible some of what you've read about the zero vector or zero vectors has this or another definition of *vector* in mind.
Comment: Relevant: https://math.stackexchange.com/questions/1896784/do-all-vectors-must-have-a-direction-and-magnitude
Comment: But vector has **a** direction! @DavidG.Stork
Comment: Nice. I didn't notice this. In this case, "a direction" then is "at least 1 direction" rather than "exactly 1 direction". Or you can say "exactly 1 direction" and then define the zero vector to be in whatever direction you want.
Comment: A snake has one head, but in the rare occasions when it has two, it is nevertheless a snake.
Comment: @Micah The direction of a vector is the measure of the angle it makes with a horizontal line .
Comment: @hanugm: So vectors are all 2-dimensional?
Answer: You are right to question this definition. It suggests that every vector is associated with a unique direction. This is almost true, with the sole exception of the zero vector, which cannot sensibly be said to have any direction. Unfortunately, a more accurate definition
"a vector is an object that has both a magnitude and a direction, with the sole exception of the zero vector, which cannot sensibly be said to have any direction"
is considerably less snappy. When you get to more advanced treatment of vectors, the lack of a direction for the zero vector is made quite explicit.
Comment: @Allawonder Neither has to be correct. Direction is not a canonically defined object, just a useful way of thinking. Consider two possible definitions: (1) The direction of a vector $x\in\mathbb R^n$ is a vector $v\in S^{n-1}$ so that $x=tv$ for some $t\in\mathbb R$. (2) The direction of $x$ is the unit vector $x/|x|$. They only disagree on the zero vector, and both definitions are reasonable.
Comment: Actually, the zero vector has *infinitely* many directions. The problem is with assuming that the definition claims uniqueness of directions, which it doesn't. One should train oneself not to read much more than is stated in mathematics.
Comment: @Allawonder What I'm saying is that there need not be right and wrong here. To me "What is the direction of the zero vector?" is like "What is the best flavor of ice cream?" in that even if we can list all possibilities there is no natural way to decide what is the correct answer. You seemed to assume that there is a single correct answer. I disagree on that. This is not not a matter of logic but of ways of thinking. I have no preferred choice myself (except with ice cream). I wrote something in a separate answer.
Comment: *"It suggests that every vector is associated with a unique direction."* It absolutely does not. In mathematics, "X has a Y" does not imply "X has an unique Y". If we want to say the latter, we say the latter. Otherwise you couldn't say things like "any integer $>1$ has a prime factor", and it would be ridiculous.
Comment: @Allawonder : Clearly we disagree. But I agree with the last, general, point in your comment.
Comment: Clearly. But the question is, which is correct (at least we'll agree that one must be correct, no?)? Is it the case that it simply makes no sense to talk about directions for points, or simply that we can't talk about *definite* directions for them? I think it's the latter -- imagine a working ceiling fan.
Comment: @JoonasIlmavirta Are you then saying that there is another possibility from *The idea of direction makes no sense for the zero vector* and *The idea of direction makes sense for the zero vector, but the direction cannot be definite* and *The idea of direction makes sense for the zero vector and it is definite,* the latter of which (hopefully) everyone agrees is out of the game? If you have other such possibilities, it would be interesting to see. Otherwise, the two possibilities on ground are obviously mutually exclusive.
Comment: @JoonasIlmavirta If there need not be right or wrong, then we're talking opinion, not mathematics. But this is mathematics. Furthermore, the question is not *What is the direction of the zero vector?* The question is whether it makes sense to talk about direction or it doesn't. One of these possibilities *must* be the case -- either it makes sense or not. I'm afraid you've completely misunderstood me -- I don't assume such a thing as you think I do. Indeed, on the contrary, I made an answer below where I stated my points more elaborately (which see please). Clearly, it's a matter of logic.
Comment: @Allawonder I have to add that opinion is very important in mathematics, and so is debating what definitions are useful. Whether something makes sense or not is a good question but often not a binary and fully logical one. As a professional mathematician I have started to see things **very** differently from puristic "math is all about true and false statements" point of view. We appear to disagree, but I will end the discussion on my part here. I might answer if there is a separate question on the topic.
Comment: @JoonasIlmavirta Opinion is important of course, but my point was that the question of whether *It doesn't make sense to talk about directions for zero vectors* or *It makes sense, just that the directions are indefinite* is right is *not* a matter of opinion, but of logic since they both exclude each other. The question between you and me is thus not of what makes sense, but of the fact that one of the statements *has to be* true.
Comment: @fkraiem : In English, it is paradoxical, if it makes sense at all, to say that one thing is pointing in two directions: the word *direction* implies uniqueness. As you say, there is no such implication in the idea of having a prime factor.
Comment: @JohnBentin It depends on the thing you're talking about. What's the unique direction in which a spinning fan points, eh? ;)
Comment: @Allawonder : Forwards (downstream of the airflow) along its axis of spin—so (normally) downwards in the case of a ceiling fan—whether it is spinning or not.
Comment: @JohnBentin Curious. I'm talking of a spinning fan. The object here is not a *fan,* but a *spinning fan.*
Comment: The simple definition of a vector as an object with size and direction is a very simple one which does not transfer to higher levels of understanding.
Answer: What you quote is a reminder, not a definition.
If you are asked to calculate a vector, you know the answer shouldn't be a single number.
The zero vector disagrees with that reminder, and that is a useful caveat to learn.
When vectors are first introduced, they might be treated as arrows and explained with pictures in a way that emphasizes that direction matters.
But if you actually get to give a definition of a vector in linear algebra (an element of a vector space), it looks different.
The direction is of a vector is not a canonically defined object, just a useful way of thinking.
Consider two possible definitions in $\mathbb R^n$:

The direction of a vector $x\in\mathbb R^n$ is a vector $v\in S^{n-1}$ so that $x=tv$ for some $t\in\mathbb R$, $t\geq0$.
The direction of $x$ is the unit vector $x/|x|$.

They only disagree on the zero vector, and both definitions are reasonable.
Whether the zero vector has any or no direction is an irrelevant choice.
If you are on a space without a norm, you can define a direction as an equivalence class.
Sometimes it can be useful to think that $v$ and $-v$ have the same direction, sometimes not.
Going from a vector space to the corresponding space of directions is essentially projectivization.
How you should define a direction depends on what you want to do with it.
At a general level with no application in sight I would say that there simply is no canonical definition.
Sometimes it's useful to say $1/0=\infty$, sometimes it's better to leave $1/0$ undefined.
If these concepts are unfamiliar or weird to you, the message is even clearer:
The concept of direction is a tricky one to define.
I think it's often best left as a heuristic term instead of a technical one.
Answer: Yes, it should have a direction, but I see no place in the quoted definition where it's stated that it should have only a direction.
The idea is simple. This indefiniteness in direction happens only for the trivial (zero) vector. It is a vector that does nothing. And a point can be oriented indefinitely, unlike a line segment. Furthermore, we have to include it to make our computation with vectors become very like normal arithmetic (where although we can't divide by $0,$ we still have to include it). If we do not include it, we inconvenient ourselves, so we include it.
Later, you'll learn that mathematicians define vector differently. In that case, the zero vector automatically becomes a vector without questions of definiteness.
Comment: Re: "I see no place in the quoted definition where it's stated that it should have **only a** direction": So then, do you also believe that a *nonzero* vector can have multiple definitions?
Comment: @ruakh I don't understand your question. But before your reply, perhaps let me reiterate my point. The definition given by OP does not say anything about uniqueness of directions, so it does not *exclude* a vector which might have indefinitely many directions.
Answer: $0 \cdot (a,b,c)$ (for arbitrary $a$, $b$, and $c$) has a magnitude ($0$) and a direction $(a,b,c)$.  It is a vector.
$0 \cdot (d,e,f)$ (for arbitrary $d$, $e$ and $f$) has a magnitude ($0$) and a direction $(d,e,f$).  It is a vector.
These happen to be the same vector.
So what?


var flip = Math.floor(Math.random() * (1 - 0 + 1)) + 0;?

Question: I found some code snippets and I'm not sure what it means:
var flip = Math.floor(Math.random() * (1 - 0 + 1)) + 0;

and
Math.floor(Math.random() * (max - min + 1)) + min

I'm still getting familiar with Javascript... could someone give me a reader's digest condensed version?
Comment: Read this, it is exactly what you are looking for http://www.w3schools.com/jsref/jsref_random.asp
Comment: See [Generating random numbers in Javascript in a specific range?](http://stackoverflow.com/q/1527803/1529630)
Answer: Math.floor() Round a number downward to its nearest integer
For example: if you have 2.7 it will round down to 2.
Math.random() Return a random number between 0 and 1
For example:  .693


How can I undo ending a flight accidentally?

Question: So I had this awesome station orbiting Tylo with a lander and crew there already so that I could (hopefully) perform the landing the next time I played.  So having had enough for the day, I proceed to get myself back to the title screen, but in the process, accidentally hit the end flight button instead of the space station button.  "Oh no, what have!?!" and I frantically try holding F9 to reload the quicksave I had just made, try putting another rocket on the pad and doing the same thing, all with no luck.
If I accidentally end a flight, and I know prior to ending the flight I have a good save, is there any way to recover it?  Assume any persistence and quicksave file backups aren't recent enough.
Answer: While you can't undo an end flight (well, at least not without a stringent backup policy), you can prevent yourself from accidentally clicking the end flight button (and then confirming said action) with this mod.  Of course, even this isn't fool-safe, as you have to enable the option to begin with.  Also, there is the possibility that it will get disabled if you start undocking parts.  With my brief testing, it looks like if one piece of a station was set to block end flight, the entire station will block as well.

Previous answer kept for posterity.  The game mechanics for ending a flight were drastically changed in version 0.21 such that it's much harder to do accidentally.  Yes, it's possible to revert the state of a flight to an earlier point (a quick-save, the launch, or the VAB/SPH), but this is much less destructive compared to ending a flight.
You can still end a flight from the tracking station (by "recovering" vessels that have landed on Kerbin or "terminating" others), but since this is a much more deliberate action, it's less likely that you'll end a critical flight accidentally.
Answer: Reloading a quicksave works perfectly fine in that situation. If it does not bring you back to your lost ship, you should be able to select it in the tracking station.
Comment: Nope, did not work.


Lost power cell during game play

Question: On Horizon Zero Dawn I have gone back for the 1st power cell and it's not there. I believe I have picked it up but mistakenly dropped it during game play when my items were full, and I wanted to pick up other items.
How can I find the lost power cell?
Comment: If I recall correctly, the power cells are key items and cannot be dropped or sold
Comment: First off, welcome to Arqade! If it's not in the first location, then you must have already acquired the power cell from this location. Have you checked the other locations outlined in the linked question?
Comment: I have gone back for the 1st power cell and it is not there. I have tried several times restarted and nothing works.
Comment: I am at level 40 and thought I should go back for the armor but no luck.
Comment: On the quest it shows I have zero power cells so what makes you sure I have acquired a power cell??
Answer: The power cells cannot be dropped, sold, or "lost". Following the Ancient Armory questline, all power cells can be obtained, but they must all be obtained before you can unlock the armor; which only becomes available in the end-game.
Note: one is "missable"; this is part of a main quest line and while it is hard to miss, if you don't grab it when you are there, the area is inaccessible afterwards.

Third Cell
The third cell is in the Maker's End ruin, which you will visit as part of the Maker's End main quest. Climb all the way to the very top of the ruins to Ted Faro's office. Once there, instead of following the quest objective and examining the data storage system, turn around and find the yellow handholds leading up the ruined sky scraper. Follow these all the way to the top and find the Power Cell there. Use the rappel point to return to Ted Faro's office and continue the quest.

The rest of the cells can be collected at any point; you just need to progress the story line to unlock the areas they can be found if first.
Comment: It is possible to get the back up to the top of Maker's End after the mission, in fact a faster path is made available. I missed it on the first playthrough and got it later.
Comment: So if I don't obtain the power cell at the time of the mission and when I go back and its not there what could I do to obtain it again?  I have no way of obtaining the armor anymore?
Comment: That power cell in particular can only be accessed during that mission, because the area becomes inaccessible afterwards. The item doesn't disappear
Comment: If you're sure you did get the power cell, and it's not in your inventory anymore, then it's a glitch

Lost power cell during game play


How do you prevent other players from using commands?

Question: I want to de-op players in Minecraft so they can't use any commands to go into creative mode and grief my map. I want to block them from using commands). How do you do that?
Comment: You don't normally *need* to de-op players. If other players on your server or LAN game have op powers, you did something to give them op powers. How you de-op them depends on how you gave them op powers in the first place. What kind of server/world is this, and how are other players getting into it?
Comment: possible duplicate of [What are all the gamerule commands in Minecraft?](http://gaming.stackexchange.com/questions/97883/what-are-all-the-gamerule-commands-in-minecraft)
Answer: On a vanilla server, the command is <code>/deop playername</code>.


Where should I put "Check for updates" functionality?

Question: Our application (running on Windows, but not a traditional application with menus and toolbars) has a feature that it can check for updates of the application, or of the firmware of the attached (medical) device that the application is controlling. We're having a difficult time deciding where to put this functionality.
In other applications that have a traditional menu bar, we often see the function under the Help menu. We don't have such a menu bar, but we do have a side menu with some buttons with icons that represent the main actions, some of which fold out into a menu with several options. There is a help menu among these. However, we feel that the Check for Updates it out of place with the About... option and the actual Help option there.
We also have a settings dialog, where you can tune all kinds of preferences. However, again, checking for updates is not a preference, so it does not really belong between there either.
Last, we have a status-bar like area where we display things like the currently logged on user name with a logout button, and a status display of the devive (connected/disconnected). Perhaps it could find a place there? Or, perhaps we should check for updates automatically, and only display something in that status area if there if an update has been found?
I would love to get some other suggestions of where auto-update functionality belongs in an application.
Comment: Check for updates automatically, I mean, why would it need user control? I'd be curious how many people actually click on the Check for Updates menu versus the number of people who update after they get a notificaion. However, beware that industrial users might not want to update / want to know what is in the update. After all, a medical device, even if just diagnostical, is a matter of life and death... a wrong diagnosis because of an outdated firmware or a new buggy one is more responsibility than "adium crashed, let's update"..
Comment: *is* there a reason to update manually? Sometimes there is
Comment: I would promote Aadaam comment to an answer.
Answer: How about application startup? You can make a background check from the application to see if a new version is available and then prompt the user to upgrade.
If a dialog prompt is intrusive, you can passively display the "update available" information in some part of your app.
Answer: Check for updates automatically, I mean, why would it need user control?
I'd be curious how many people actually click on the Check for Updates menu versus the number of people who update after they get a notificaion.
However, beware that industrial users might not want to update / want to know what is in the update.
After all, a medical device, even if just diagnostical, is a matter of life and death... a wrong diagnosis because of an outdated firmware or a new buggy one is more responsibility than "adium crashed, let's update"..
Comment: I'm accepting this as an answer. We're discussing if indeed an automatic update check (not install!) is acceptable. It seems like the most logical solution.
Answer: I agree with the comment from Aadaam re: medical device.  Approach this one with caution.  Perhaps get input from your expected userbase, too?
What I personally would suggest is on startup, offer the OPTION to enable automatic update checking and a checkbox to "never ask this again".  This way you put the choice in the hands of the end user (or their IT department), while still offering the automatic update functionality.  You could also in the same dialog offer some simple options to choose update check frequency, and/or action to take on update available.  (Possibly even a short sentence explaining where to find these options again if they want to update/change them in future.)
Answer: I agree both with Aadaam and Ben Brocka.
Check for updates automatically. Don't present a dialog, but display availability of the update in an unobtrusive way. I really like the way Beyond Compare does it a clickable link at the far right of the main menu bar (yes, they had to jump through some hoops to do it, but there you go). I am sure there are other ways, similar to the notification bar in web apps, that can be dreamt up for a desktop that are both noticeable and unobtrusive.
That said, also provide a manual check for updates. As Ben Brocka says sometimes there are reasons for a manual update. Internet access isn't always available at start up and I'd really hate to have to exit ands start the app again when internet is available.
In answer to your question about where it should go: on the help menu of the application. That's where most applications put it and that is where people now expect it.