Saturday 30 September 2017

python - A version of str.isdigit that returns True for decimal fractions?




I want to test raw_input to make sure that the string contains only numbers and at maximum a single decimal point. str.isdigit() looked promising but it will not return True if there is a decimal point in the string.



Ideally, the code would look like this:




def enter_number():
number = raw_input("Enter a number: ") # I enter 3.5
if number.SOMETHING: # SOMETHING is what I am looking for
float_1 = float(number)
return float_1
else
sys.exit()

half = enter_number() / 2 # = 1.75
double = enter_number() * 2 # = 7


Answer



I suggest the EAFP approach.



float raises the ValueError exception if its argument is not a valid float:



In [6]: float('bad value')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
in ()

----> 1 float('bad value')

ValueError: could not convert string to float: 'bad value'


You could catch it:



number = raw_input("Enter a number: ")
try:
return float(number)

except ValueError:
sys.exit()

Extracting XML data to php

I'm trying to extract data from XML file (http://freegeoip.net/xml/google.com). You can see the content of the file looks something like:




74.125.235.3
US
United States
CA
California

Mountain View
94043
37.4192
-122.0574
807
650



I want to take the information stored in the and tags, and store them in separate variables. The problem is, I've little idea how to do this, and was wondering if anyone could show me how to parse XML files with php?

c - Creating a binary search tree in C99



I've got a programming class assignment due tonight at 8 PM CDT that I'm having trouble with. We are to take a list of the following numbers via reading a file:



9
30
20
40
35
22
48
36
37
38



place them in an array (easy enough), and then read these into a binary search tree using C. The first number in the list is the number of elements in the tree. The rest are placed into the following struct:



typedef struct node_struct {
int data;
struct node_struct* left;
struct node_struct* right;
} Node;


I think I've got the first part down pat. Take the stuff in using fscanf (I didn't choose to use this method, I like fgets better), call an insertion function on each member of the array, then call a "createNode" function inside the insertion function.



Problem is, I'm only getting one member into the BST. Furthermore, the BST must satisfy the condition node->left->data <= node->data < node->right->data... in other words, the nodes must be in order in the tree.



Here's what I have so far:



#include 
#include
#include

// def BST node struct
typedef struct node_struct {
int data;
struct node_struct* left;
struct node_struct* right;
} Node;

// prototypes
Node* createNode(int data);
Node* bstInsert(Node* root, int data);
// helper function prototypes
void padding(char ch, int n);
void displayTree(Node* root, int depth);

int main(int argc, char **argv)
{
FILE *in = NULL;
int num_read, count=0, array_size = 0;

if(argc != 2){
printf("hw3 \n");
return 1;
}

in = fopen(argv[1], "r");

if(in == NULL){
printf("File can not be opened.\n");
return 2;
}

// read in the first line to get the array size
fscanf(in, "%d", &array_size);

// declare the array
int array[array_size];

// read from the second line to get each element of the array
while(!feof(in)){
fscanf(in, "%d", &num_read);
array[count] = num_read;
count++;
}
fclose(in);

if (array_size != count) {
printf("data error. Make sure the first line specifies the correct number of elements.");
return 3;
}

Node *root1 = NULL, *root2 = NULL, *root3 = NULL;

int i;
// task1: construct a bst from the unsorted array
printf("=== task1: construct a bst from the unsorted array ===\n");
for (i = 0; i < array_size; i++) {
root1 = bstInsert(root1, array[i]);
}
displayTree(root1, 0);
return 0;
}

Node* bstInsert(Node* root, int data) {
if(root == NULL){
root = createNode(data);

if(root != NULL){
root= createNode(data);
}

else{
printf("%d not inserted, no memory available.\n", data);
}
}

Node* current, previous, right;
current = root;
previous = root->left;
next = root->right;
else{
if(previous->data <= current->data){

}


}
return root;
}

Node* createNode(int data) {
// TODO
Node* aRoot;
if(!data)
return NULL;

aRoot = malloc(sizeof(Node));
if(!aRoot){
printf("Unable to allocate memory for node.\n");
return NULL;
}
aRoot->data = data;
aRoot->left = NULL;
aRoot->right = NULL;
return aRoot;
}

/* helper functions to print a bst; You just need to call displayTree when visualizing a bst */
void padding(char ch, int n)
{
int i;
for (i = 0; i < n; i++)
printf("%c%c%c%c", ch, ch ,ch, ch);
}

void displayTree(Node* root, int depth){
if (root == NULL) {
padding (' ', depth);
printf("-\n");
}
else {
displayTree(root->right, depth+1);
padding(' ', depth);
printf ( "%d\n", root->data);
displayTree(root->left, depth+1);
}
}


main, createNode, displayTree, and padding are okay, I believe. It's bstInsert where I'm having trouble. I'm just not sure how to order things to create a valid tree.



EDIT:



I've edited bstInsert and injected some more logic. It should be printing out more leaves on the tree, but alas, it's only printing out the number "30". Here's the new function.



Node* bstInsert(Node* root, int data) {


if(root == NULL){
root = createNode(data);

if(root != NULL){
root= createNode(data);
}

else{
printf("%d not inserted, no memory available.\n", data);
}
}
else{
if(data < root->data){
bstInsert(root->left, data);
}
else if(data > root->data || data == root->data){
bstInsert(root->right, data);
}
}
return root;
}

Answer



You have to assign the newly created node pointer to the correct part of the tree. This code does that. The key change is using the return value from bstInsert() correctly. The other changes are cosmetic. Note that I checked the input array by printing it out; also, it is sensible to print out the BST as you build it.



Don't use feof() as a loop control condition. It is almost invariably wrong when used as a loop control, but at least you have to also check the input operation that follows. I've written a lot of programs in my time; I've hardly ever used feof() (I found two places in my own code with it; in both, it was correctly used to distinguish between EOF and an error after an input had failed.)



#include 
#include
#include

// def BST node struct
typedef struct node_struct
{
int data;
struct node_struct* left;
struct node_struct* right;
} Node;

// prototypes
Node *createNode(int data);
Node *bstInsert(Node *root, int data);
// helper function prototypes
void padding(char ch, int n);
void displayTree(Node *root, int depth);

int main(int argc, char **argv)
{
FILE *in = NULL;
int num_read, count=0, array_size = 0;

if (argc != 2)
{
printf("hw3 \n");
return 1;
}

in = fopen(argv[1], "r");

if (in == NULL)
{
printf("File can not be opened.\n");
return 2;
}

// read in the first line to get the array size
fscanf(in, "%d", &array_size);

// declare the array
int array[array_size];

// read from the second line to get each element of the array
while (count < array_size && fscanf(in, "%d", &num_read) == 1)
array[count++] = num_read;
fclose(in);

if (array_size != count)
{
printf("data error. Make sure the first line specifies the correct number of elements.");
return 3;
}

for (int i = 0; i < array_size; i++)
printf("%d: %d\n", i, array[i]);

Node *root1 = NULL;

// task1: construct a bst from the unsorted array
printf("=== task1: construct a bst from the unsorted array ===\n");

for (int i = 0; i < array_size; i++)
{
root1 = bstInsert(root1, array[i]);
displayTree(root1, 0);
}

displayTree(root1, 0);
return 0;
}

Node *bstInsert(Node *root, int data)
{
if (root == NULL)
{
root = createNode(data);
if (root == NULL)
printf("%d not inserted, no memory available.\n", data);
}
else if (data < root->data)
root->left = bstInsert(root->left, data);
else
root->right = bstInsert(root->right, data);
return root;
}

Node *createNode(int data)
{
Node *aRoot;

aRoot = malloc(sizeof(Node));
if (!aRoot)
{
printf("Unable to allocate memory for node.\n");
return NULL;
}
aRoot->data = data;
aRoot->left = NULL;
aRoot->right = NULL;
return aRoot;
}

/* helper functions to print a bst; You just need to call displayTree when visualizing a bst */
void padding(char ch, int n)
{
for (int i = 0; i < n; i++)
printf("%c%c%c%c", ch, ch, ch, ch);
}

void displayTree(Node *root, int depth)
{
if (root == NULL) {
padding (' ', depth);
printf("-\n");
}
else {
displayTree(root->right, depth+1);
padding(' ', depth);
printf ( "%d\n", root->data);
displayTree(root->left, depth+1);
}
}

c# - How do I remedy the "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?



C# desktop application on express edition. Worked then didn't work 5 seconds later.



I tried the following.





  • Ensure debug configuration, debug flag, and full debug info are set on all assemblies.

  • Delete all bin and obj folders and all DLLs related to the project from my entire machine.

  • Recreate projects causing the problem from scratch.

  • Reboot.



I have two WinForms projects in the solution. One of them loads the debug info, one doesn't. They both refer to the assembly I'm trying to get debug info on in exactly the same way in the project file. Any ideas?







I want to add in here, mostly for myself when I come back to review this question, that symbols are not loaded until the assembly is loaded, and the assembly is not loaded until it is needed. If the breakpoint is in a library that is only used in one function in your main assembly, the symbols will not be loaded (and it will show the breakpoint as not being hit) until that function is called.


Answer



Start debugging, as soon as you've arrived at a breakpoint or used Debug > Break All, use Debug > Windows > Modules. You'll see a list of all the assemblies that are loaded into the process. Locate the one you want to get debug info for. Right-click it and select Symbol Load Information. You'll get a dialog that lists all the directories where it looked for the .pdb file for the assembly. Verify that list against the actual .pdb location. Make sure it doesn't find an old one.



In normal projects, the assembly and its .pdb file should always have been copied by the IDE into the same folder as your .exe. The bin\Debug folder of your project. Make sure you remove one from the GAC if you've been playing with it.


data structures - How do you implement a Stack and a Queue in JavaScript?



What is the best way to implement a Stack and a Queue in JavaScript?



I'm looking to do the shunting-yard algorithm and I'm going to need these data-structures.


Answer




var stack = [];
stack.push(2); // stack is now [2]
stack.push(5); // stack is now [2, 5]
var i = stack.pop(); // stack is now [2]
alert(i); // displays 5

var queue = [];
queue.push(2); // queue is now [2]
queue.push(5); // queue is now [2, 5]
var i = queue.shift(); // queue is now [5]

alert(i); // displays 2


taken from "9 javascript tips you may not know"


javascript - How can I access and process nested objects, arrays or JSON?



I have a nested data structure containing objects and arrays. How can I extract the information, i.e. access a specific or multiple values (or keys)?



For example:



var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};


How could I access the name of the second item in items?


Answer



Preliminaries



JavaScript has only one data type which can contain multiple values: Object. An Array is a special form of object.



(Plain) Objects have the form



{key: value, key: value, ...}


Arrays have the form



[value, value, ...]


Both arrays and objects expose a key -> value structure. Keys in an array must be numeric, whereas any string can be used as key in objects. The key-value pairs are also called the "properties".



Properties can be accessed either using dot notation



const value = obj.someProperty;


or bracket notation, if the property name would not be a valid JavaScript identifier name [spec], or the name is the value of a variable:



// the space is not a valid character in identifier names
const value = obj["some Property"];

// property name as variable
const name = "some Property";
const value = obj[name];


For that reason, array elements can only be accessed using bracket notation:



const value = arr[5]; // arr.5 would be a syntax error

// property name / index as variable
const x = 5;
const value = arr[x];


Wait... what about JSON?



JSON is a textual representation of data, just like XML, YAML, CSV, and others. To work with such data, it first has to be converted to JavaScript data types, i.e. arrays and objects (and how to work with those was just explained). How to parse JSON is explained in the question Parse JSON in JavaScript? .



Further reading material



How to access arrays and objects is fundamental JavaScript knowledge and therefore it is advisable to read the MDN JavaScript Guide, especially the sections











Accessing nested data structures



A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation.



Here is an example:



const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};


Let's assume we want to access the name of the second item.



Here is how we can do it step-by-step:



As we can see data is an object, hence we can access its properties using dot notation. The items property is accessed as follows:



data.items


The value is an array, to access its second element, we have to use bracket notation:



data.items[1]


This value is an object and we use dot notation again to access the name property. So we eventually get:



const item_name = data.items[1].name;


Alternatively, we could have used bracket notation for any of the properties, especially if the name contained characters that would have made it invalid for dot notation usage:



const item_name = data['items'][1]['name'];





I'm trying to access a property but I get only undefined back?



Most of the time when you are getting undefined, the object/array simply doesn't have a property with that name.



const foo = {bar: {baz: 42}};
console.log(foo.baz); // undefined


Use console.log or console.dir and inspect the structure of object / array. The property you are trying to access might be actually defined on a nested object / array.



console.log(foo.bar.baz); // 42





What if the property names are dynamic and I don't know them beforehand?



If the property names are unknown or we want to access all properties of an object / elements of an array, we can use the for...in [MDN] loop for objects and the for [MDN] loop for arrays to iterate over all properties / elements.



Objects



To iterate over all properties of data, we can iterate over the object like so:



for (const prop in data) {
// `prop` contains the name of each property, i.e. `'code'` or `'items'`
// consequently, `data[prop]` refers to the value of each property, i.e.
// either `42` or the array
}


Depending on where the object comes from (and what you want to do), you might have to test in each iteration whether the property is really a property of the object, or it is an inherited property. You can do this with Object#hasOwnProperty [MDN].



As alternative to for...in with hasOwnProperty, you can use Object.keys [MDN] to get an array of property names:



Object.keys(data).forEach(function(prop) {
// `prop` is the property name
// `data[prop]` is the property value
});


Arrays



To iterate over all elements of the data.items array, we use a for loop:



for(let i = 0, l = data.items.length; i < l; i++) {
// `i` will take on the values `0`, `1`, `2`,..., i.e. in each iteration
// we can access the next element in the array with `data.items[i]`, example:
//
// var obj = data.items[i];
//
// Since each element is an object (in our example),
// we can now access the objects properties with `obj.id` and `obj.name`.
// We could also use `data.items[i].id`.
}


One could also use for...in to iterate over arrays, but there are reasons why this should be avoided: Why is 'for(var item in list)' with arrays considered bad practice in JavaScript?.



With the increasing browser support of ECMAScript 5, the array method forEach [MDN] becomes an interesting alternative as well:



data.items.forEach(function(value, index, array) {
// The callback is executed for each element in the array.
// `value` is the element itself (equivalent to `array[index]`)
// `index` will be the index of the element in the array
// `array` is a reference to the array itself (i.e. `data.items` in this case)
});


In environments supporting ES2015 (ES6), you can also use the for...of [MDN] loop, which not only works for arrays, but for any iterable:



for (const item of data.items) {
// `item` is the array element, **not** the index
}


In each iteration, for...of directly gives us the next element of the iterable, there is no "index" to access or use.






What if the "depth" of the data structure is unknown to me?



In addition to unknown keys, the "depth" of the data structure (i.e. how many nested objects) it has, might be unknown as well. How to access deeply nested properties usually depends on the exact data structure.



But if the data structure contains repeating patterns, e.g. the representation of a binary tree, the solution typically includes to recursively [Wikipedia] access each level of the data structure.



Here is an example to get the first leaf node of a binary tree:



function getLeaf(node) {
if (node.leftChild) {
return getLeaf(node.leftChild); // <- recursive call
}
else if (node.rightChild) {
return getLeaf(node.rightChild); // <- recursive call
}
else { // node must be a leaf node
return node;
}
}

const first_leaf = getLeaf(root);




const root = {
leftChild: {
leftChild: {
leftChild: null,
rightChild: null,
data: 42
},
rightChild: {
leftChild: null,
rightChild: null,
data: 5
}
},
rightChild: {
leftChild: {
leftChild: null,
rightChild: null,
data: 6
},
rightChild: {
leftChild: null,
rightChild: null,
data: 7
}
}
};
function getLeaf(node) {
if (node.leftChild) {
return getLeaf(node.leftChild);
} else if (node.rightChild) {
return getLeaf(node.rightChild);
} else { // node must be a leaf node
return node;
}
}

console.log(getLeaf(root).data);





A more generic way to access a nested data structure with unknown keys and depth is to test the type of the value and act accordingly.



Here is an example which adds all primitive values inside a nested data structure into an array (assuming it does not contain any functions). If we encounter an object (or array) we simply call toArray again on that value (recursive call).



function toArray(obj) {
const result = [];
for (const prop in obj) {
const value = obj[prop];
if (typeof value === 'object') {
result.push(toArray(value)); // <- recursive call
}
else {
result.push(value);
}
}
return result;
}




const data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};


function toArray(obj) {
const result = [];
for (const prop in obj) {
const value = obj[prop];
if (typeof value === 'object') {
result.push(toArray(value));
} else {
result.push(value);
}
}
return result;
}

console.log(toArray(data));











Helpers



Since the structure of a complex object or array is not necessarily obvious, we can inspect the value at each step to decide how to move further. console.log [MDN] and console.dir [MDN] help us doing this. For example (output of the Chrome console):



> console.log(data.items)
[ Object, Object ]


Here we see that that data.items is an array with two elements which are both objects. In Chrome console the objects can even be expanded and inspected immediately.



> console.log(data.items[1])
Object
id: 2
name: "bar"
__proto__: Object


This tells us that data.items[1] is an object, and after expanding it we see that it has three properties, id, name and __proto__. The latter is an internal property used for the prototype chain of the object. The prototype chain and inheritance is out of scope for this answer, though.


c - "static const" vs "#define" vs "enum"



Which one is better to use among the below statements in C?




static const int var = 5;


or



#define var 5


or




enum { var = 5 };

Answer



Generally speaking:



static const


Because it respects scope and is type-safe.




The only caveat I could see: if you want the variable to be possibly defined on the command line. There is still an alternative:



#ifdef VAR // Very bad name, not long enough, too general, etc..
static int const var = VAR;
#else
static int const var = 5; // default value
#endif



Whenever possible, instead of macros / ellipsis, use a type-safe alternative.



If you really NEED to go with a macro (for example, you want __FILE__ or __LINE__), then you'd better name your macro VERY carefully: in its naming convention Boost recommends all upper-case, beginning by the name of the project (here BOOST_), while perusing the library you will notice this is (generally) followed by the name of the particular area (library) then with a meaningful name.



It generally makes for lengthy names :)


c++11 - Is effective C++ still effective?



From what I saw in this post I decided to start reading the book Effective C++.




But now that there are many new features because of C++11 and that a few of the good practices changed, I'm not sure whether or not it is actually a good idea. Has the advent of C++11 deprecated any of the advice contained in Effective C++? If so, which topics should I avoid?


Answer



This what Scott Meyers himself had to say about it on his own blog




Which may lead you to wonder whether the information and advice in
this pre-C++0x edition of Effective C++ remains relevant. I'm pleased
to report that it does. Surprisingly so, in fact. Having spent nearly
two years steeped in the details of C++0x, I expected to groan a bit
as I reviewed this book's table of contents with C++0x in mind. Surely

some Items would be inappropriate. But the advice I found proved
sound. Should C++0x developers prefer consts, enums, and inlines to
#defines (Item 2)? They should. Should they prevent exceptions from
leaving destructors (Item 8)? Certainly. Should they use objects to
manage resources? Declare data members private? Consider alternatives
to virtual functions? Factor parameter-independent code out of
templates? (Items 13, 22, 35, and 44.) Yes, yes, yes, yes! My goal has
always been for Effective C++'s table of contents to summarize the
advice in the book, and that summary remains just as applicable to
C++0x development as to “traditional” C++ development. C++0x is a

bigger language, and in some ways it's a different one, but the core
techniques for making effective use of “old” C++ are core for the
effective use of C++0x, too.



This doesn't mean that this Effective C++ is a perfect match for
C++0x. The book doesn't discuss features new to C++0x, so Items about
making effective use of those features are missing. A C++0xified
Effective C++ would certainly have Items devoted to move operations,
to uniform initialization, and to lambda expressions, and it'd probably have an entire chapter on making effective use of the concurrency API. Such a book would also contain different examples, e.g., ones making use of auto variables, range-based for loops, in-class default initializers, as well as the occasional variadic template. To the extent that this book falls short in its support for C++0x, the errors are those of omission, not commission.





UPDATE: the new title Effective Modern C++ has been for sale since November 2014 from O'Reilly and Amazon (and many others that you can google for).


java - Constructor call error message





Any ideas why I may be seeing the following message for this class?



package org.swx.nursing.tools.sqlfinder.gui;

import javax.swing.JPanel;

import java.awt.event.ActionListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class GuiTemplateImpl extends JPanel implements ActionListener {

public void createAndShowGUI(GuiTemplateCriteria guiCriteria) {
super(new BorderLayout());



}
}


Message



Description Resource    Path    Location    Type
Constructor call must be the first statement in a constructor GuiTemplateImpl.java /sqlfinder/src/main/java/org/swx/nursing/tools/sqlfinder/gui line 29 Java Problem



I am not sure why this will not work. The error goes away when i remove the super(), so this seems to be causing some issues.


Answer



super let you call base constructor or base method. It is not clear what exactly you trying to achieve:




  • if you trying to create constructor than its name must match type name. It is the only place where you can call base constructor with super(...), and as error message says it must be first statement:



Code:




public GuiTemplateImpl(GuiTemplateCriteria guiCriteria) {
super(new BorderLayout());
}



  • if you are trying to create method that will call base implementation:



Code (probably not what you looking for based on arguments mismatch):




public GuiTemplateImpl(GuiTemplateCriteria guiCriteria) {
super.GuiTemplateImpl(new BorderLayout());
}

jquery - Get the value in an input text box



What are the ways to get and render an input value using jQuery?




Here is one:








Answer



//Get
var bla = $('#txt_name').val();

//Set
$('#txt_name').val(bla);


math - Why does adding two decimals in Javascript produce a wrong result?








Why does JS screw up this simple math?





console.log(.1 + .2)  // 0.3000000000000004
console.log(.3 + .6) // 0.8999999999999999






The first example is greater than the correct result, while the second is less. ???!! How do you fix this? Do you have to always convert decimals into integers before performing operations? Do I only have to worry about adding (* and / don't appear to have the same problem in my tests)?



I've looked in a lot of places for answers. Some tutorials (like shopping cart forms) pretend the problem doesn't exist and just add values together. Gurus provide complex routines for various math functions or mention JS "does a poor job" in passing, but I have yet to see an explanation.

How to change fontFamily of TextView in Android



So I'd like to change the android:fontFamily in Android but I don't see any pre-defined fonts in Android. How do I select one of the pre-defined ones? I don't really need to define my own TypeFace but all I need is something different from what it shows right now.




android:id="@+id/HeaderText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="52dp"
android:gravity="center"
android:text="CallerBlocker"
android:textSize="40dp"
android:fontFamily="Arial"

/>


It seems what I did up there won't really work! BTW android:fontFamily="Arial" was a stupid attempt!


Answer



From android 4.1 / 4.2 / 5.0, the following Roboto font families are available:



android:fontFamily="sans-serif"           // roboto regular
android:fontFamily="sans-serif-light" // roboto light
android:fontFamily="sans-serif-condensed" // roboto condensed

android:fontFamily="sans-serif-black" // roboto black
android:fontFamily="sans-serif-thin" // roboto thin (android 4.2)
android:fontFamily="sans-serif-medium" // roboto medium (android 5.0)


enter image description here



in combination with



android:textStyle="normal|bold|italic"



this 16 variants are possible:




  • Roboto regular

  • Roboto italic

  • Roboto bold

  • Roboto bold italic

  • Roboto-Light


  • Roboto-Light italic

  • Roboto-Thin

  • Roboto-Thin italic

  • Roboto-Condensed

  • Roboto-Condensed italic

  • Roboto-Condensed bold

  • Roboto-Condensed bold italic

  • Roboto-Black

  • Roboto-Black italic

  • Roboto-Medium


  • Roboto-Medium italic



fonts.xml





sans-serif-light
sans-serif-medium
sans-serif

sans-serif-condensed
sans-serif-black
sans-serif-thin


oop - When should you use a class vs a struct in C++?




In what scenarios is it better to use a struct vs a class in C++?


Answer



Differences between a class and a struct in C++ are that structs have default public members and bases and classes have default private members and bases. Both classes and structs can have a mixture of public, protected and private members, can use inheritance and can have member functions.



I would recommend using structs as plain-old-data structures without any class-like features, and using classes as aggregate data structures with private data and member functions.


Friday 29 September 2017

c++ - How can I use std::maps with user-defined types as key?

I'm wondering why I can't use STL maps with user-defined classes. When I compile the code below, I get the following cryptic error message. What does it mean? Also, why is it only happening with user-defined types? (Primitive types are okay when they are used as key.)




C:\MinGW\bin..\lib\gcc\mingw32\3.4.5........\include\c++\3.4.5\bits\stl_function.h||In
member function `bool

std::less<_Tp>::operator()(const _Tp&,
const _Tp&) const [with _Tp =
Class1]':|



C:\MinGW\bin..\lib\gcc\mingw32\3.4.5........\include\c++\3.4.5\bits\stl_map.h|338|instantiated
from `_Tp& std::map<_Key, _Tp,
_Compare, _Alloc>::operator[](const _Key&) [with _Key = Class1, _Tp = int, _Compare = std::less, _Alloc = std::allocator >]'|



C:\Users\Admin\Documents\dev\sandbox\sandbox\sandbox.cpp|24|instantiated
from here|




C:\MinGW\bin..\lib\gcc\mingw32\3.4.5........\include\c++\3.4.5\bits\stl_function.h|227|error: no match for 'operator<' in '__x <
__y'| ||=== Build finished: 1 errors, 0 warnings ===|




#include 
#include

using namespace std;


class Class1
{
public:
Class1(int id);

private:
int id;
};

Class1::Class1(int id): id(id)

{}

int main()
{
Class1 c1(1);

map< Class1 , int> c2int;
c2int[c1] = 12;

return 0;

}

android - Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference




MainActivity.java has following code:



package com.softjourn.redmineclient.activities;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import com.softjourn.redmineclient.R;
import com.softjourn.redmineclient.models.Issue;
import com.softjourn.redmineclient.models.IssuesResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import butterknife.Bind;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

private final static String URI="https://redmineng.softjourn.if.ua/issues.json?assigned_to_id=me";
@Bind(R.id.list_issues) ListView mListIssues;
Login li;

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

li = new Login();
li.execute(URI);
}

@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();

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

return super.onOptionsItemSelected(item);
}

class Login extends AsyncTask {

@Override
protected String doInBackground(String... strings) {
HttpURLConnection c = null;
try {
c = (HttpURLConnection) new URL(strings[0]).openConnection();
} catch (IOException e) {
e.printStackTrace();
}
c.setUseCaches(false);
try {
c.setRequestMethod("GET");
} catch (ProtocolException e) {
e.printStackTrace();
}
c.setRequestProperty("Accept", "application/json");
c.setRequestProperty("Authorization", "basic " + Base64.encodeToString("osavchak:mhgT7322".getBytes(), 0));
try {
c.connect();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader((c.getInputStream())));
} catch (IOException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String output;
try {
while ((output = br.readLine()) != null) {
sb.append(output);
}
} catch (IOException e) {
e.printStackTrace();
}

return sb.toString();
}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
JsonArray ja = new JsonParser().parse(result).getAsJsonObject().getAsJsonArray("issues");
IssuesResponse ir = new IssuesResponse(ja);

ArrayAdapter adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, ir.getIssues());
mListIssues.setAdapter(adapter);
}
}
}


I've created two model classes.



First, IssuesResponse.java:



package com.softjourn   .redmineclient.models;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.annotations.SerializedName;
import java.util.List;

public class IssuesResponse {
@SerializedName("issues")
private List issues;

public IssuesResponse(JsonArray ja) {
if (issues == null) {

}
for(JsonElement je : ja) {
Issue issue = new Issue(je);
issues.add(issue);
}
}

public List getIssues() {
return issues;
}
}


The second one, Issue.java:



package com.softjourn.redmineclient.models;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.annotations.SerializedName;

public class Issue {
@SerializedName("id")
private int id;

@SerializedName("description")
private String description;

public Issue(JsonElement je) {
Issue issue = new Gson().fromJson(je,Issue.class);
this.id = issue.id;
this.description = issue.description;
}
}


When I run my application an error occurs:




java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
at com.softjourn.redmineclient.models.IssuesResponse.(IssuesResponse.java:26)
at com.softjourn.redmineclient.activities.MainActivity$Login.onPostExecute(MainActivity.java:125)
at com.softjourn.redmineclient.activities.MainActivity$Login.onPostExecute(MainActivity.java:79)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)




I wait for your suggestions how it could be fixed.


Answer



You haven't initialised List in the IssuesResponse class. Try



private List issues = new ArrayList<>();

Windows 7, 64 bit, DLL problems

I have a problem with our executable. I'm running this C++ 32-bit executable on my Windows 7 64-bit development box that also has all those Microsoft applications (Visual Studio 2008 + 2010, TFS, SDK, Microsoft Office)...
And it's still running just fine.



Now I got the client installation of the very same program and was asked to test it with a clean Windows 7 installation. Thus I got one Windows 7 64-bit VMware and updated it to Windows 7 SP 1 (the very same version my developer box is tuning).
But while on my developer box everything is fine the program does not work with the VMware (30 days trial) box.




The x86 Dependency Walker is telling me that the following DLL files are missing:




  • API-MS-WIN-CORE-COM-L1-1-0.DLL

  • API-MS-WIN-CORE-WINRT-ERROR-L1-1-0.DLL

  • API-MS-WIN-CORE-WINRT-L1-1-0.DLL

  • API-MS-WIN-CORE-WINRT-ROBUFFER-L1-1-0.DLL

  • API-MS-WIN-CORE-WINRT-STRING-L1-1-0.DLL

  • API-MS-WIN-SHCORE-SCALING-L1-1-0.DLL


  • DCOMP.DLL

  • GPSVC.DLL

  • IESHIMS.DLL



I googled for those API-MS-WIN-... DLL files and found they should actually already be part of Windows 7 (some sites claiming the belong to Windows 8 and Windows Server 2012 though).



I already tried the suggested fixes I found, which are:





  • running 'sfc /scannow'

  • installing Visual Studio 2008 SP1 runtime executables



But that didn't solve anything. :-(



Side note: My development box does not have them either, and does not seem to need them. For example, the user32.dll on my box does not link against one of those, while the installation on the VMware does.



Any idea on how to fix this issue?
I tried to find a suitable download / fix on the Microsoft pages, but I failed.







After solving my issue I wanted to report what I found out, and I can't post this as an answer because the question has been closed.



Actually all the DLL files reported missing by the Dependency Walker tool, namely those



* API-MS-WIN-CORE-...



type DLL files were not part of the actual problem.



In my case the registration of three OCX files was missing and after that everything was just fine, BUT Dependency Walker tool still listed all the very same DLL files as before even when the program was just running fine now.



The gist of it: As someone elsewhere stated, the tool is a bit dated by now and does not always work properly with a newer OS. Thus keep an eye open and don't get mislead by missing 'API-MS-WIN-CORE-COM-L1-1-0.DLL', ... the problem probably lies entirely elsewhere.

c++ - Choice for class design

Having a different interact-method for each possible other animal will work when you have only three classes, but when you add mice, rabbits, tigers, rats, enchiladas, wombats, dolphins, armadillos and zebras, it will quickly get unwieldy, because whenever you add a new animal you need to edit every existing class to add a new interact-method. This is not how object-oriented programming should be. The purpose of OOP is that you can simply add a new class and all other classes can work with it immediately without requiring any modification.


For that reason you should handle the interactions in a more generalized way. Why does a cat hunt a mouse or a bird, but not a dog? What would happen when I would confront a cat with a smibblat? (A smibblat is a small, fluffy, four-legged, herbivorous mammal about 5 centimeters long which I just made up and wrote a class Smibblat: public Animal for). Even when the cat has never seen a Smibblat before, it would try to hunt it, because it fits into its prey-pattern. Cats are a danger to all animals which are 1. smaller and 2. slower than themself.


When you would add an abstract getSize() and an abstract getSpeed() method to class Animal, you could have a method like this:


void Cat::interact(const Animal & other) {
if (other.getSpeed() < this.getSpeed() &&
other.getSize() < this.getSize()) {
this.eat(other);
}
}

which can be applied to any new animal you create. The Cat class would no longer have a dependency on every other Animal sub-class there is. It only depends on Animal which provides all the methods which matter for making the decision whether or not to eat the other Animal.

PHP/MySQL insert row then get 'id'



The 'id' field of my table auto increases when I insert a row. I want to insert a row and then get that ID.



I would do it just as I said it, but is there a way I can do it without worrying about the time between inserting the row and getting the id?




I know I can query the database for the row that matches the information that was entered, but there is a high change there will be duplicates, with the only difference being the id.


Answer



$link = mysqli_connect('127.0.0.1', 'my_user', 'my_pass', 'my_db');
mysqli_query($link, "INSERT INTO mytable (1, 2, 3, 'blah')");
$id = mysqli_insert_id($link);


See mysqli_insert_id().




Whatever you do, don't insert and then do a "SELECT MAX(id) FROM mytable". Like you say, it's a race condition and there's no need. mysqli_insert_id() already has this functionality.


Explanation of the Muppets/Sesame Street split/merge - Movies & TV

I recently saw the Muppets movie - it's the first time I've ever seen anything on Muppets.



Then I saw the Cookie Monster, but that he was not in the Muppets movie. I found out that only the original Muppets were in the Muppets 2011 movie, and that the rights for the Sesame Street characters are not owned by Disney, who could not then use the characters.




I see a list of complete Sesame Street muppets but no list of exactly which ones are/are not in Sesame Street.



So how did this split/merge happen? Did someone else create Sesame Street?



Was there bad blood here?

How can I join elements of an array in Bash?



If I have an array like this in Bash:



FOO=( a b c )


How do I join the elements with commas? For example, producing a,b,c.


Answer



Rewriting solution by Pascal Pilz as a function in 100% pure Bash (no external commands):




function join_by { local IFS="$1"; shift; echo "$*"; }


For example,



join_by , a "b c" d #a,b c,d
join_by / var local tmp #var/local/tmp
join_by , "${FOO[@]}" #a,b,c



Alternatively, we can use printf to support multi-character delimiters, using the idea by @gniourf_gniourf



function join_by { local d=$1; shift; echo -n "$1"; shift; printf "%s" "${@/#/$d}"; }


For example,



join_by , a b c #a,b,c
join_by ' , ' a b c #a , b , c

join_by ')|(' a b c #a)|(b)|(c
join_by ' %s ' a b c #a %s b %s c
join_by $'\n' a b c #abc
join_by - a b c #a-b-c
join_by '\' a b c #a\b\c

ruby - What does this regex `str.gsub(/#{(.*?)}/)` do?





.* means any character, so why is the .*? needed in the following?



str.gsub(/\#{(.*?)}/) {eval($1)}

Answer



.* is a greedy match, whereas .*? is a non-greedy match. See this link for a quick tutorial on them. Greedy matches will match as much as they can, while non-greedy matches will match as little as they can.



In this example, the greedy variant grabs everything between the first { and the last } (the last closing brace):



'start #{this is a match}{and so is this} end'.match(/\#{(.*)}/)[1]

# => "this is a match}{and so is this"


while the non-greedy variant reads as little as it needs to make the match, so it only reads between the first { and the first successive }.



'start #{this is a match}{and so is this} end'.match(/\#{(.*?)}/)[1]
# => "this is a match"

excel - For Each Loop Deleting Row if Cell = 0

I'm trying to write a macro that will delete a row if a cell = 0 in the range given. The problem I am coming across is when the For Each Loop runs it will find the cell and delete the row but if the row below it also had a 0 it ends up getting skipped by the code since the code has moved onto the next range. I'm looking to have a macro that will find 0 in a range of cells and will loop on that range that had a 0 until the that cell is greater than 0.
I've got this as a work in progress...



Sub Pub_Clean()

Dim IRange As Range
Dim VRange As Range
Set VRange = Range(ActiveSheet.Range("b3"), ActiveSheet.Range("b3").End(xlDown))
For Each IRange In VRange
If IRange = 0 Then
IRange.EntireRow.Delete
End If
Next IRange
End Sub

php - DB class wont load



I'm trying to connect using a simle db class. For some reason it only print out
"Initiate DB class"



test.php



include 'db.class.php';
echo 'Initiate DB class';
$db = new DB();
echo 'DB class did load';


db.class.php




class DB extends mysqli {
private static $instance = null;
private function __construct () {
parent::init();
$host = 'localhost';
$user = 'root';
$pass = 'MY_PASS';
$dbse = 'MY_DB';
parent::real_connect($host, $user, $pass, $dbse);
if (0 !== $this->connect_errno):

die('MySQL Error: '. mysqli_connect_error());
//throw new Exception('MySQL Error: '. mysqli_connect_error());
endif;
}
public function fetch ($sql, $id = null, $one = false) {
$retval = array();
if ($res = $this->query($sql)):
$index = 0;
while ($rs = $res->fetch_assoc()):
if ($one):

$retval = $rs; break;
else:
$retval[$id ? $rs[$id] : $index++] = $rs;
endif;
endwhile;
$res->close();
endif;
return $retval;
}



}



I have tried to search my log files for error but they come out empty.


Answer



Ok got it,



In your call to db your calling new DB(); which mean you're trying to call the constructor of your DB class.



In your DB class it looks like you're trying to create a singleton, but something is missing normally there would be something to assign the instance the database connection, and something that asks the instance if it's empty create a new connection or if it's not use the same instance.




At the end of the day to make this work you can change your constructor to public.


mysql - SQL Injection in my php code


Possible Duplicate:
How to prevent SQL injection in PHP?






I want to know if my code has hacks like SQLI



function insertRow($table,$fields,$values)

{
if(count($fields) != count($values))
{
echo "fields and values must be the same count";
return null;
}
$query = "INSERT INTO ".$table." SET ";
foreach($fields as $key => $field)
{
$query = $query. "" . $field . " = '" . htmlspecialchars($values[$key], ENT_QUOTES) . "', ";

}
$query = substr($query,0,-2);

if (!mysql_query($query, $this->con))
{
echo "Error : " . mysql_error($this->con)."
";
return false;
}
return true;
}



I use htmlspecialchars and I want to know if it is ok



Edit :



$fields = array("a","b","c");
$values = array($_POST["a"],$_POST["b"],$_POST["c"]);
$a = $dbc->insertRow("tbl_synagoge",$fields,$values);

javascript - Check if localStorage is available



I know there has been many questions about checking for localStorage but what if someone manually shuts it off in their browser? Here's the code I'm using to check:



localStorage.setItem('mod', 'mod');

if (localStorage.getItem('mod') != null){
alert ('yes');
localStorage.removeItem('mod');
} else {
alert ('no');
}


Simple function and it works. But if I go into my Chrome settings and choose the option "Don't Save Data" (I don't remember exactly what it's called), when I try to run this function I get nothing but Uncaught Error: SecurityError: DOM Exception 18. So is there a way to check if the person has it turned off completely?




UPDATE: This is the second function I tried and I still get no response (alert).



try {
localStorage.setItem('name', 'Hello World!');
} catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
alert('Quota exceeded!');
}
}


Answer



Use modernizr's approach (you might want to change my function name to something better):



function lsTest(){
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {

return false;
}
}

if(lsTest() === true){
// available
}else{
// unavailable
}



It's not as concise as other methods but that's because it's designed to maximise compatibility.



The original source: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js



Working example: http://jsfiddle.net/6sm54/2/


javascript - How to check whether an object is a date?



I have an annoying bug in on a webpage:




date.GetMonth() is not a function




So, I suppose that I am doing something wrong. The variable date is not an object of type Date. How can I check for a datatype in Javascript? I tried to add a if (date), but it doesn't work.




function getFormatedDate(date) {
if (date) {
var month = date.GetMonth();
}
}


So, if I want to write defensive code and prevent the date (which is not one) to be formatted, how do I do that?




Thanks!



UPDATE: I don't want to check the format of the date, but I want to be sure that the parameter passed to the method getFormatedDate() is of type Date.


Answer



As an alternative to duck typing via



typeof date.getMonth === 'function'


you can use the instanceof operator, i.e. But it will return true for invalid dates too, e.g. new Date('random_string') is also instance of Date




date instanceof Date


This will fail if objects are passed across frame boundaries.



A work-around for this is to check the object's class via



Object.prototype.toString.call(date) === '[object Date]'


c++ - undefined reference to `WinMain@16'

When I try to build a program using Eclipse CDT, I get the following:





/mingw/lib/libmingw32.a(main.o):main.c:(.text+0x106):
undefined reference to `WinMain@16




Why is that? And, how can I solve this issue?

datetime - Convert java.util.Date to java.time.LocalDate



What is the best way to convert a java.util.Date object to the new JDK 8/JSR-310 java.time.LocalDate?



Date input = new Date();
LocalDate date = ???

Answer



Short answer




Date input = new Date();
LocalDate date = input.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();


Explanation



Despite its name, java.util.Date represents an instant on the time-line, not a "date". The actual data stored within the object is a long count of milliseconds since 1970-01-01T00:00Z (midnight at the start of 1970 GMT/UTC).



The equivalent class to java.util.Date in JSR-310 is Instant, thus there is a convenient method toInstant() to provide the conversion:




Date input = new Date();
Instant instant = input.toInstant();


A java.util.Date instance has no concept of time-zone. This might seem strange if you call toString() on a java.util.Date, because the toString is relative to a time-zone. However that method actually uses Java's default time-zone on the fly to provide the string. The time-zone is not part of the actual state of java.util.Date.



An Instant also does not contain any information about the time-zone. Thus, to convert from an Instant to a local date it is necessary to specify a time-zone. This might be the default zone - ZoneId.systemDefault() - or it might be a time-zone that your application controls, such as a time-zone from user preferences. Use the atZone() method to apply the time-zone:



Date input = new Date();

Instant instant = input.toInstant();
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());


A ZonedDateTime contains state consisting of the local date and time, time-zone and the offset from GMT/UTC. As such the date - LocalDate - can be easily extracted using toLocalDate():



Date input = new Date();
Instant instant = input.toInstant();
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
LocalDate date = zdt.toLocalDate();



Java 9 answer



In Java SE 9, a new method has been added that slightly simplifies this task:



Date input = new Date();
LocalDate date = LocalDate.ofInstant(input.toInstant(), ZoneId.systemDefault());



This new alternative is more direct, creating less garbage, and thus should perform better.


Thursday 28 September 2017

c++ - Why is it a bad idea to use 'new'?











Is it really a bad idea to use 'new' in instantiating a class in C++? Found here.



I get that using raw pointers is ill-advised, but why have a 'new' keyword at all when it's such bad practice? Or is it?


Answer



The point is that new, much like a pregnancy, creates a resource that is managed manually (i.e. by you), and as such it comes with responsibility.



C++ is a language for library writing, and any time you see a responsibility, the "C++" approach is to write a library element that handles this, and only this, responsibility. For dynamic memory allocation, those library components already exist and are summarily referred to as "smart pointers"; you'll want to look at std::unique_ptr and std::shared_ptr (or their TR1 or Boost equivalents).




While writing those single-responsibility building blocks, you will indeed need to say new and delete. But you do that once, and you think about it carefully and make sure you provide the correct copy, assignment and destruction semantics. (From the point of exception safety, single responsibility is crucial, since dealing with more than one single resource at a time is horribly unscalable.)



Once you have everything factored into suitable building blocks, you compose those blocks into bigger and bigger systems of code, but at that point you don't need to exercise any manual responsibility any more, since the building blocks already do this for you.



Since the standard library offers resource managing classes for the vast majority of use cases (dynamic arrays, smart pointers, file handles, strings), the point is that a well-factored and crafted C++ project should have very little need for any sort of manual resource management, which includes the use of new. All your handler objects are either automatic (scoped), or members of other classes whose instances are in turn scoped or managed by someone.



With this in mind, the only time you should be saying new is when you create a new resource-managing object; although even then that's not always necessary:



std::unique_ptr p1(new Foo(1, 'a', -2.5));   // unique pointer
std::shared_ptr p2(new Foo(1, 'a', -2.5)); // shared pointer

auto p3 = std::make_shared(1, 'a', -2.5); // equivalent to p2, but better





Update: I think I may have addressed only half the OP's concerns. Many people coming from other languages seem to be under the impression that any object must be instantiated with a new-type expression. This is in itself a very unhelpful mindset when approaching C++:



The crucial distinction in C++ is that of object lifetime, or "storage class". This can be one of: automatic (scoped), static (permanent), or dynamic (manual). Global variables have static lifetime. The vast majority of all variables (which are declared as Foo x; inside a local scope) have automatic lifetime. It is only for dynamic storage that we use a new expression. The most important thing to realize when coming to C++ from another OO language is that most objects only ever need to have automatic lifetime, and thus there is never anything to worry about.



So the first realization should be that "C++ rarely needs dynamic storage". I feel that this may have been part of the OP's question. The question may have been better phrased as "is it a really bad idea to allocate objects dynamically?". It is only after you decide that you really need dynamic storage that we get to the discussion proper of whether you should be saying new and delete a lot, or if there are preferable alternatives, which is the point of my original answer.



plot explanation - Is K unfaithful too his youth love / love interest from MiB in MiB 3? - Movies & TV



In the first Men In Black movie it is made quite clear that K is still in love with the girl he left behind which he had to abandon to be a Man In Black.




But in MiB he flirts heavily with Agent O, even though the incident with the girl he left behind must not have been long ago. J even makes snide remarks about it.



From a narrative point, this plot line makes K look more human in MiB3 and adds a subplot with a love interest, but it completely disregards K's personality from MiB1.



Can it be assumed that the screenwriters just disregarded K's History to have a love interest in MiB3? Is K unfaithful too his youth love / love interest from MiB in MiB 3?


Answer



He could have ended his relationship with the woman from the first movie and joined the MIB.



In working with Agent O they developed a mutual attraction that was never acted upon, however that doesn't mean he no longer had feelings for the woman he left. It could have been his attraction to O was just to help deal with the loss of the other woman.




Having realized that a relationship with a fellow Agent was either not allowed or a bad idea he returned to viewing O as a colleague and eventual superior (i.e. he "Friendzoned" her) this would have allowed his feelings for the woman he left to resurface and since having emotional attachment to her would have little to no impact on his abilities as an Agent he continued to follow her as he did in the first movie.


plot explanation - How did they get to Singapore in Pirates of the Caribbean At World's End?

I imagine it's safe to assume Pirates of the Caribbean is based in the Caribbean.


Do we assume that when they go to Singapore at the beginning of the film that they sailed all the way down around the bottom of South America?


Just wondering as this seems like an awful long way for a pirate ship to travel.


Answer


This is based on the following logical points:



  • The Black Pearl is a fast gallon that sails at 10 knots (historically they sailed around 8 knots, but the Pearl is special and it makes the math easier)


  • Assuming 10% of the trip is spent on re-supply


  • A knot is 1.15MPH


  • They used the common trade route of Caribbean to Portugal around Africa hugging the coast all the way to Singapore (thanks to source)


  • The distance between Cuba and Singapore using the above route (thanks to free map tools for mapping) is roughly 17,000 miles



So the two answers are:



  1. What route did they take? See above for trade route

  2. How long did it take? 10 knots or 11.5MPH * 17,000 miles = 1478 hours plus resupply of 147.8 hours = 1625.8 hours or 67.7 days


java - Background contentPane of a jframe interferes with the jpanel on top of it




I have a jframe with a jpanel on top of it and the panel often has to change its contents with repaint() and revalidate(). I have managed to place the images, texts and buttons just the I way I want them to be on this jpanel. Everything is working, but now I am trying to set a background to the jframe, that does not interfere with the contents above it. For example, if there is a drawing of a tree, it should appear behind the text of the jpanel, without disrupting it. I found that the thing that semi works is to use setContentPane() on the jframe, adding a class, that has extended jpanel and has overrode paintComponent(). Everything appears on the screen, but the text is squashed vertically and the elements are moved towards the top of the frame.



If instead of using setContentPane() I just add the background class to the frame, it doesn't appear, no matter the setOpaque() of the jpanel.
I also tried using jLayeredPane, since the things I read on the internet suggest that this is the right answer. However, I couldn't make it work and the background remained hidden.



private final int WIDTH = 1024;
private final int HEIGHT = 768;

Frame()

{
JFrame frame = new JFrame();
panel = new JPanel();
gbc = new GridBagConstraints();

//Unrelated elements
//font = new Font(Font.MONOSPACED, Font.PLAIN, 20);
//border = BorderFactory.createEmptyBorder();
//imageResizer = new ImageResizer();


frame.setTitle("Shady Path");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH, HEIGHT);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setIconImage(new ImageIcon("res/human.png").getImage());
frame.setContentPane(new DrawPanel());

panel.setLayout(new GridBagLayout());
panel.setOpaque(false);

gbc.anchor = GridBagConstraints.PAGE_START;

frame.add(panel);
frame.setVisible(true);
}

//One of the two methods that change the contents of the jpanel
void appendMain(String mainImage, JTextArea mainText, JButton button)
{
panel.removeAll();


image = new JLabel(imageResizer.resize(200, 200, mainImage));
gbc.insets = new Insets(0, 0, 30, 0);
gbc.gridwidth = GridBagConstraints.REMAINDER;
panel.add(image, gbc);

formatText(mainText);
panel.add(mainText, gbc);

button.setFont(font);

button.setForeground(Color.WHITE);
button.setBackground(Color.BLACK);
button.setBorder(border);
gbc.fill = GridBagConstraints.VERTICAL;
gbc.insets = new Insets(50, 0, 70, 0);
panel.add(button, gbc);

panel.revalidate();
panel.repaint();
}


//This is for the text formating
private void formatText(JTextArea baseText)
{
baseText.setEditable(false);
baseText.setForeground(Color.WHITE);
baseText.setFont(font);
baseText.setLineWrap(true);
baseText.setWrapStyleWord(true);
baseText.setMargin(new Insets(0, 300, 0, 300));

baseText.setOpaque(false);

gbc.insets = new Insets(30, 0, 0, 0);
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
}

//The following code is for the paintComponent() class
//The imageResizer is another class that I made, but it just resizes images and it is unrelated.
public class DrawPanel extends JPanel

{
private Image image;

public DrawPanel()
{
ImageResizer imageResizer = new ImageResizer();
ImageIcon imageIcon = imageResizer.resize(1024, 768, "res/test.png");
image = imageIcon.getImage();
}


public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}

Answer



Well... It looks like @HovercraftFullOfEels was right with his comment. Literally, I just had to set the layout of the DrawPanel to a BorderLayout and everything was fixed.



 public DrawPanel()

{
this.setLayout(new BorderLayout());

ImageResizer imageResizer = new ImageResizer();
ImageIcon imageIcon = imageResizer.resize(1024, 768, "res/test.png");
image = imageIcon.getImage();
}

analysis - Was Alfred in on Bruce's plan in The Dark Knight Rises? - Movies & TV



Near the end of The Dark Knight Rises, Alfred is fed up with Bruce's inability to let go of Batman and quit despite Alfred saying to him




"I've buried enough members of the Wayne family"





so Alfred leaves Bruce.



In the final moments of the film, we see Alfred, sipping his drink in Italy, as he spots Bruce with Selina Kyle-- just as he said he dreamed to one day.



In the interim, Alfred is gone to who-knows-where. His whereabouts are never discussed, never explained or intimated about.



So: was Alfred in on Bruce's plan to 'kill' both Batman and Bruce Wayne, so that Bruce could finally be free? Would they assume the League of Shadows had a way of keeping tabs on their actions, so their fight was just an act?


Answer




The scene at the Wayne graves, Alfred is crying as he feels he has let the Wayne parents down for allowing Bruce to die. He says how he has failed the parents.



I think this clearly indicates that he had no idea of Bruce's plan as you can see he is clearly distraught over the events that unfolded.


How to escape php mysqli query?

I am passing data from AJAX to my PHP. I just run a for loop to make my query. Problem with my data is that it contains single quote.


I am using single quote to enclose my parameters in the query. Query is something like


   INSERT INTO myTable (column1.column2) VALUES('value1', 'value2'),
('value'1', 'value2');

I want to escape like


   INSERT INTO myTable (column1.column2) VALUES('value1', 'value2'),
('value\'1', 'value2');

I just tried mysqli_real_Escape_String. It returns something like


   INSERT INTO myTable (column1.column2) VALUES(\'value1\', \'value2\'),
(\'value\'1\', \'value2\');

So Query execution fails.


I don't think using htmlspeciachars is the right way for this.


Any suggestions?

javascript - Get array value from AJAX request




I have a script that reads a JSON file then populates an array with the name property of each element.



HTML







JSON



[
{"name" : "One"},
{"name" : "Two"},
{"name" : "Three"},
{"name" : "Four"},
{"name" : "Five"}
]


I cant't access a specific index of this array. The console log always returns undefined. I've tried to add .then() after my ajax call, but it doesn't work too.


Answer



You'll wanna do something like this:







Javascript won't wait for all of your code to run line by line, so for asynchronous calls you'll need a seperate function to handle data OR to handle the data within the success callback. Another function would be cleaner though depending on what you want to do with the data.


regex - How do I grep for all non-ASCII characters?



I have several very large XML files and I'm trying to find the lines that contain non-ASCII characters. I've tried the following:



grep -e "[\x{00FF}-\x{FFFF}]" file.xml



But this returns every line in the file, regardless of whether the line contains a character in the range specified.



Do I have the syntax wrong or am I doing something else wrong? I've also tried:



egrep "[\x{00FF}-\x{FFFF}]" file.xml 


(with both single and double quotes surrounding the pattern).



Answer



You can use the command:



grep --color='auto' -P -n "[\x80-\xFF]" file.xml


This will give you the line number, and will highlight non-ascii chars in red.



In some systems, depending on your settings, the above will not work, so you can grep by the inverse




grep --color='auto' -P -n "[^\x00-\x7F]" file.xml


Note also, that the important bit is the -P flag which equates to --perl-regexp: so it will interpret your pattern as a Perl regular expression. It also says that




this is highly experimental and grep -P may warn of unimplemented
features.



How can I use pointers in Java?

I know Java doesn't have pointers, but I heard that Java programs can be created with pointers and that this can be done by the few who are experts in java. Is it true?

java - What is the proper way to navigate between windows?




I am trying to make a simple Customer tracking program.It stars with a window with 4 buttons and you choose a task to do.



I need to navigate between different windows
-Home Menu
-New Customer
-Customer
-Reports




What i do is creating different Jframes for each task but i don't know if it is the right way to do.



So my question is What is the proper way to navigate between windows on Java?


Answer



Please do not create multiple JFrames unless absolutely necessary.



Why?





  • There's multiple icons in the taskbar (on Windows and Linux).

  • Switching windows is an added burden to the user.

  • It raises issues with, e.g., the close button (do they all close if any close? is there one master?), etc.



Instead:



Consider using a JTabbedPane.





To create a tabbed pane, instantiate JTabbedPane, create the components you wish it to display, and then add the components to the tabbed pane using the addTab method.




For example:



JTabbedPane tabbedPane = new JTabbedPane();

JComponent someComponent = ...
tabbedPane.addTab("Tab 1", someComponent);


JComponent anotherComponent = ...
tabbedPane.addTab("Tab 2", anotherComponent);





Alternatively, you could use a CardLayout if you only want your users to see one view at a time.




The CardLayout class manages two or more components (usually JPanel instances) that share the same display space. Conceptually, each component that a CardLayout manages is like a playing card or trading card in a stack, where only the top card is visible at any time.




java - Using Regex to generate Strings rather than match them



I am writing a Java utility which helps me to generate loads of data for performance testing. It would be really cool to be able to specify a regex for Strings so that my generator spits out things which match this. Is there something out there already baked which I can use to do this? Or is there a library which gets me most of the way there?



Thanks


Answer



Edit:



As mentioned in the comments, there is a library available at Google Code to acheive this:
http://code.google.com/p/xeger



See also https://github.com/mifmif/Generex as suggested by Mifmif



Original message:



Firstly, with a complex enough regexp, i believe this can be impossible. But you should be able to put something together for simple regexps.



If you take a look at the source code of the class java.util.regex.Pattern, you'll see that it uses an internal representation of Node instances. Each of the different pattern components have their own implementation of a Node subclass. These Nodes are organised into a tree.



By producing a visitor that traverses this tree, you should be able to call an overloaded generator method or some kind of Builder that cobbles something together.


c++ - Which smart pointer type?




I'm fairly new to smart pointer usage, and want to make sure I'm not introducing bad habits. I have an object A that is being created from a factory, and added to a queue. This queue is then read from another thread, and at this point I think it's perfectly valid to use a unique_ptr.




struct IInterface
{

}

class A : public IInterface
{

}


std::queue> queue;


However, while constructing A I realize I need a Class C. C takes a List of B's that it owns.



class A : public IInterface
{
C c;
}


class B
{
}

class C
{
List> b;
}



To me this still looks okay because we have ownership defined. However, I'm unsure of what pointer needs to be used when Class B now needs a pointer to IInterface, which A happens to implement. Do I make it a shared_ptr?



struct IInterface
{

}

class A : public IInterface
{
C c;

}

std::queue> queue;



class B
{
shared_ptr a;
}


class C
{
List> b;
}


Did I choose the correct smart pointer, and did I analyze this correctly? I know this is super simple for you guys, but figured I would ask before I start doing things incorrectly.


Answer



Leaving aside why C owns its B objects via a pointer, the question is not whether A is used via some base class. Indeed, a shared_ptr can be used to own an object of a derived class even if Base has a non-virtual destructor!




The real question is whether the lifetime of the B objects owned by a C (which is probably the same as the lifetime of the C) is (known to be) shorter than that of the A objects to which they refer. If it is, you can stick to unique_ptr for owning the As and A* (or IInterface*) for using them. If not, you should consider using shared_ptr for both, although you should also consider other possibilities like destroying individual B objects sooner or transferring the ownership of the A to a place where it can outlive the observing references to it.


html - How do I style a dropdown with only CSS?



Is there a CSS-only way to style a form as much as humanly possible, without any JavaScript. What are the properties I can use to do so in CSS?



This code needs to be compatible with all major browsers:





  • Internet Explorer 6, 7, and 8

  • Firefox

  • Safari



I know I can make it with JavaScript: Example.



And I'm not talking about simple styling. I want to know, what the best we can do with CSS only.



I found similar questions on Stack Overflow.




And this one on Doctype.com.


Answer



Here are three solutions:



Solution #1 - appearance: none - with Internet Explorer 10 - 11 workaround (Demo)



--



To hide the default arrow set appearance: none on the select element, then add your own custom arrow with background-image




select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none; /* Remove default arrow */
background-image: url(...); /* Add custom arrow */
}


Browser Support:




appearance: none has very good browser support (caniuse) - except for Internet Explorer 11 (and later) and Firefox 34 (and later).



We can improve this technique and add support for Internet Explorer 10 and Internet Explorer 11 by adding



select::-ms-expand {
display: none; /* Hide the default arrow in Internet Explorer 10 and Internet Explorer 11 */
}



If Internet Explorer 9 is a concern, we have no way of removing the default arrow (which would mean that we would now have two arrows), but, we could use a funky Internet Explorer 9 selector.



To at least undo our custom arrow - leaving the default select arrow intact.



/* Target Internet Explorer 9 to undo the custom arrow */
@media screen and (min-width:0\0) {
select {
background-image:none\9;
padding: 5px\9;
}

}


All together:





select {
margin: 50px;
width: 150px;

padding: 5px 35px 5px 5px;
font-size: 16px;
border: 1px solid #CCC;
height: 34px;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background: url(http://www.stackoverflow.com/favicon.ico) 96% / 15% no-repeat #EEE;
}



/* CAUTION: Internet Explorer hackery ahead */


select::-ms-expand {
display: none; /* Remove default arrow in Internet Explorer 10 and 11 */
}

/* Target Internet Explorer 9 to undo the custom arrow */
@media screen and (min-width:0\0) {

select {
background: none\9;
padding: 5px\9;
}
}






This solution is easy and has good browser support - it should generally suffice.






If browser support for Internet Explorer 9 (and later) and Firefox 34 (and later) is necessary then keep reading...




Solution #2 Truncate the select element to hide the default arrow (demo)



--



(Read more here)



Wrap the select element in a div with a fixed width and overflow:hidden.



Then give the select element a width of about 20 pixels greater than the div.




The result is that the default drop-down arrow of the select element will be hidden (due to the overflow:hidden on the container), and you can place any background image you want on the right-hand-side of the div.



The advantage of this approach is that it is cross-browser (Internet Explorer 8 and later, WebKit, and Gecko). However, the disadvantage of this approach is that the options drop-down juts out on the right-hand-side (by the 20 pixels which we hid... because the option elements take the width of the select element).



Enter image description here



[It should be noted, however, that if the custom select element is necessary only for mobile devices - then the above problem doesn't apply - because of the way each phone natively opens the select element. So for mobile, this may be the best solution.]






.styled select {
background: transparent;
width: 150px;
font-size: 16px;
border: 1px solid #CCC;
height: 34px;
}
.styled {
margin: 50px;

width: 120px;
height: 34px;
border: 1px solid #111;
border-radius: 3px;
overflow: hidden;
background: url(http://www.stackoverflow.com/favicon.ico) 96% / 20% no-repeat #EEE;
}












If the custom arrow is necessary on Firefox - prior to Version 35 - but you don't need to support old versions of Internet Explorer - then keep reading...



Solution #3 - Use the pointer-events property (demo)



--



(Read more here)



The idea here is to overlay an element over the native drop down arrow (to create our custom one) and then disallow pointer events on it.




Advantage: It works well in WebKit and Gecko. It looks good too (no jutting out option elements).



Disadvantage: Internet Explorer (Internet Explorer 10 and down) doesn't support pointer-events, which means you can't click the custom arrow. Also, another (obvious) disadvantage with this method is that you can't target your new arrow image with a hover effect or hand cursor, because we have just disabled pointer events on them!



However, with this method you can use Modernizer or conditional comments to make Internet Explorer revert to the standard built in arrow.



NB: Being that Internet Explorer 10 doesn't support conditional comments anymore: If you want to use this approach, you should probably use Modernizr. However, it is still possible to exclude the pointer-events CSS from Internet Explorer 10 with a CSS hack described here.






.notIE {
position: relative;
display: inline-block;
}
select {
display: inline-block;
height: 30px;
width: 150px;
outline: none;

color: #74646E;
border: 1px solid #C8BFC4;
border-radius: 4px;
box-shadow: inset 1px 1px 2px #DDD8DC;
background: #FFF;
}
/* Select arrow styling */

.notIE .fancyArrow {
width: 23px;

height: 28px;
position: absolute;
display: inline-block;
top: 1px;
right: 3px;
background: url(http://www.stackoverflow.com/favicon.ico) right / 90% no-repeat #FFF;
pointer-events: none;
}
/*target Internet Explorer 9 and Internet Explorer 10:*/


@media screen and (min-width: 0\0) {
.notIE .fancyArrow {
display: none;
}
}













casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...