Sunday 31 July 2016

Java ArrayList to single string without using loop




I have an ArrayList that is added to periodically. What I want to do is to cast the entire ArrayList to a String without doing a loop. Can anybody tell me is it possible without using loop?



Edited:
So we found some solutions, Like




list.stream().collect(Collectors.joining());


Or



String result = String.join(",", list);


or some others as well. Now Just for getting knowledge I put a question which one is the most optimal way for compiler?


Answer




You could make a stream out of your list and collect it using joining collector :



list.stream().collect(Collectors.joining());


You can pass the separator to Collectors::joining method for example :



list.stream().collect(Collectors.joining("-"));



Or you can use String::join method :



String result = String.join(",", list);


where , is the separator.


mysql - Syntax error or access violation php sql



i have added this sql in my code ,



function devenir_client_dataforform() {
$type = $_POST['clientType'];
//$produitname = $_POST['produitname'];

$produitnid = $_POST['produitnid'];
$query = db_select('node', 'n');

$query->leftjoin('field_data_field_description_col_1', 'img', 'img.entity_id = n.nid');
$query->leftjoin('field_data_field_pdf_file_image', 'pdf', 'pdf.entity_id = n.nid');
$query->leftjoin('taxonomy_term_data', 't', 't.tid ='.$type);



$query->condition('n.nid', $produitnid, '=')

//->condition('t.tid', $type, '=')
->fields('n', array('title'))
->fields('t', array('name'))
->fields('pdf', array('field_pdf_file_image_fid'))
->fields('img', array('field_description_col_1_value'));

$result = $query->execute();
foreach ($result as $record) {
if(!empty($record->field_description_col_1_value)) {
$fid = $record->field_description_col_1_value;

$produitname = $record->title;
$pdf = $record->field_pdf_file_image_fid;
$tp = $record->name;

}
}
$file = file_load($pdf);
$uri = $file->uri;

$path = file_create_url($uri);

//$uri = image_style_path( $path);
$items[] = array(
"type" => $tp ,
"produitname" => $produitname,
"produitnid" => $produitnid,
"image" => $fid,
"pdf" => $path,
"typeid" => $type
);
return $items;

}


but in the last step there is an error




PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'WHERE (n.nid = NULL)' at line 4: SELECT n.title AS title, t.name

AS name, pdf.field_pdf_file_image_fid AS field_pdf_file_image_fid,
img.field_description_col_1_value AS field_description_col_1_value
FROM {node} n LEFT OUTER JOIN {field_data_field_description_col_1} img
ON img.entity_id = n.nid LEFT OUTER JOIN
{field_data_field_pdf_file_image} pdf ON pdf.entity_id = n.nid LEFT
OUTER JOIN {taxonomy_term_data} t ON t.tid = WHERE (n.nid =
:db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0]
=> ) in devenir_client_dataforform() (line 189 of /home/dotit_bh/bh-website.dotit.mobi/sites/all/modules/devenir_client/devenir_client.module).





enter image description here


Answer



Error in this part of SQL Query:



 WHERE (n.nid = NULL)


Correct SQL Query:



WHERE (n.nid is NULL)



You shall rewrite your script:



$nid_operator = ($produitnid ? '=' : 'is');
$query->condition('n.nid', $produitnid, $nid_operator)
//->condition('t.tid', $type, '=')
->fields('n', array('title'))
->fields('t', array('name'))
->fields('pdf', array('field_pdf_file_image_fid'))

->fields('img', array('field_description_col_1_value'));

marketing - First movie that collaborated with fast-food outlets?

In 1984, the movie Gremlins teamed up with Hardees to sell a set of LPs that came along with the movie:


enter image description here


Each week a different record would be sold, thus, each week, parents had to take their children to Hardees to get the latest one.


What was the first movie to team up with fast-food to do something like this? What was the product they sold?


Answer


The KFFT List Guide says:



Burger King was a pioneer in the
advertising practice known as the
product tie-in with a successful
partnering with George Lucas’
Lucasfilm, Ltd. to promote the 1977
film Star Wars in which BK sold a set of glasses featuring the main characters
from the film. This promotion was one
of the first in the fast food industry and
set the pattern that continues to the
present.



And from Wikipedia http://en.wikipedia.org/wiki/Burger_King_advertising :



Burger King's first successful cross- promotional campaign was in 1977. It offered several collectible items, such as
posters, glasses and sticker sets that
featured scenes and characters from Star Wars.



Here's some photos of the 1978 posters and cups and cups from 1977.


Set range using a variable for the row - Excel VBA



Short and (hopefully) simple question, I have searched a worksheet range to find a particular reference number and then want to search a range in that row for the first blank cell from the left, using the code snippet below (which I developed from this question: mrExcel help site)



Set projectSearchRange = Sheets("Milestones").Range("A:A").Find(projectref, , xlValues, xlWhole)

current_row = projectSearchRange.Row

Set searchrange = Sheets("Milestones").Range(Sheets("Milestones").Cells(current_row, 2), _

Sheets("Milestones").Cells(current_row, 23)).SpecialCells(xlCellTypeBlanks).Cells(1).Activate

milestoneduedate = ActiveCell.Offset(, 1).Value


However, the Set Searchrange line is throwing a




Runtime 424 - object required error





but as I understand it, I have written the line correctly.



Any insight as to what I've done wrong would be appreciated.


Answer



This should work for you:



Function MilestoneDueDate() As Variant

Dim projectSearchRange As Range

Dim Current_Row As Long
Dim SearchRange As Range

With Sheets("Milestones")
Set projectSearchRange = .Range("A:A").Find(projectref, , xlValues, xlWhole)
Current_Row = projectSearchRange.Row
Set SearchRange = .Range(Cells(Current_Row, 2), Cells(Current_Row, 23)) _
.SpecialCells(xlCellTypeBlanks).Cells(1)
End With


MilestoneDueDate = SearchRange.Offset(0, 1).Value

End Function

python - How can I round up the number of periodic digits?




I have two numbers, one I get by calculating it and the other one I bring it from the database.



calculated = 2.183333333333333
database = 2.18333333333333


But when I compare them to know if they are the same, I return False when it should be True.



There is some way to limit the number of periodic numbers, but not to affect decimals that are not periodic, for example:



2.1748888888888 -> 2.1748
1.23333333 -> 1.23

Answer



You could use the math.isclose method:



>>> from math import isclose
>>> calculated = 2.183333333333333
>>> database = 2.18333333333333
>>> isclose(calculated, database)
True


This allows for setting the relative tolerance and minimum absolute tolerance as well refer to the docs for more explanation.


mysql - Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean

Attempting to create a 'Change Password' page for my website, I keep being confronted with these two errors and I can't seem to understand why they are appearing;





Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in /home/ll12rth/public_html/COMM2735/database/password.php on line 51
Warning: mysqli_free_result() expects parameter 1 to be mysqli_result, boolean given in /home/ll12rth/public_html/COMM2735/database/password.php on line 139




session_start();
$db_hostname = 'localhost';


$db_database = "****"; //replace with your db name
$db_username = "****"; //replace with the db username that you created
$db_password = "****"; //replace with the db password that you created
$db_status = 'not initialised';
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
$db_status = "connected";

if (!$db_server) {
die("Unable to connect to MySQL: " . mysqli_connect_error());
$db_status = "not connected";

} else

require_once('checklog.php');
require_once("functions.php");



// Grab the form data

$username = trim($_POST['username']);

$password = trim($_POST['password']);
$newpassword = trim($_POST['newpassword']);
$repeatpassword = trim($_POST['repeatpassword']);

if (isset($_POST['submit'])) {
if ($username && $password) {
$username = clean_string($db_server, $username);
$password = clean_string($db_server, $password);
$query = "SELECT * FROM users WHERE username='$username'";


$result = mysqli_query($db_server, $query);

if ($row = mysqli_fetch_array($result)) {
$db_username = $row['username'];
$db_password = $row['password'];

if ($username == $db_username && salt($password) == $db_password) {
$_SESSION['username'] = $username;
$_SESSION['logged'] = "logged";


// header('Location: home.php');
// PASSWORD CHANGING IS DONE HERE
if ($newpassword == $repeatpassword) {
//From register
if (strlen($newpassword) > 25 || strlen($newpassword) < 6) {
$message = "Password must be 6-25 characters long";
} else {
//part 8
// Process details here


//include file to do db connect

if ($db_server) {
//clean the input now that we have a db connection

$newpassword = clean_string($db_server, $newpassword);
$repeatpassword = clean_string($db_server, $repeatpassword);
mysqli_select_db($db_server, $db_database);

// check whether username exists


$query = "SELECT password FROM users WHERE password='$newpassword'";

$result=mysqli_query($db_server, $query);

if ($row = mysqli_fetch_array($result)){
$message = "This is your current password. Please try again.";
} else {
//part 9
// Process further here

$newpassword = salt($newpassword);

$query = "INSERT INTO users (password) VALUES

('$password')";

mysqli_query($db_server, $query) or die("Insert failed. " . mysqli_error($db_server));
$message = "

Your password has been changed!

";
}


mysqli_free_result($result);

} else {

$message = "Error: could not connect to the database.";

}

require_once("php/db_close.php"); //include file to do db close
}

}
//This code appears if passwords dont match
else {
$message = "

Your new passwords do not match! Try again.

";
}

} else {
$message = "

Incorrect password!

";
}
} else {

$message = "

That user does not exist!

" . "Please try again";
}
mysqli_free_result($result);

//Close connection!
mysqli_close($db_server);

} else {

$message = "

Please enter a valid username/password

";


}
}
?>




Techothing password



What do you want to change your password to echo $_SESSION['username'];
?>?





Current Username:

Current Password:


New Password:

Repeat New Password:








echo $message
?>














plot explanation - What happened to the natives?

In Aguirre: The Wrath of God, two natives approach the raft, and are taken aboard. After the priest on the raft attempts to convert them by showing them the bible and saying that it is the word of God, one of the natives tries to listen to it, and complains he can't hear anything. This makes the people on the raft upset, and they gather around, yelling at the natives, who crouch down, presumably in fright.


Then, in the next scene, they are gone for good. Were we supposed to infer that they were killed? The movie didn't shy away from showing other deaths. But it's not obvious that they could have gone anywhere.


Did I miss something?


jquery - Double HTTP call to server with different METHOD

My ex-colleague left some angular.js code to save some data to database via a HTTP POST.



factory.save=function(data){

var deferred=$q.defer();

$http({
url:'http://localhost/saveData',
method:"POST",
headers: {'Content-Type': 'application/json'},
data:data
}).success(function(result){
//success
deferred.resolve();

});

return deferred.promise;
}


When I exam the web traffic between the UI and API Server, I see the saveData API was called twice. The first call is using request method OPTIONS and the second one is POST as expected. I searched throughout the UI code and don't find any API call to saveData with method = OPTIONS. Is this something built in $http? How do I save this hit to the API server?

PHP -MySQL:No connection could be made







I tried to connect mysql database.but am getting the following error.





Warning: mysql_connect(): [2002] No connection could be made because the target machine actively (trying to connect via tcp://localhost:3306) in test.php on line 5



Warning: mysql_connect(): No connection could be made because the target machine actively refused it. in test.php on line 5 Warning: mysql_close() expects parameter 1 to be resource, boolean given in test.php on line 15




test.php:



$link = mysql_connect(localhost, dbuser, dbpass);
if (!$link) {

die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>

Saturday 30 July 2016

php - Codeigniter error: Parse error: syntax error, unexpected


Parse error: syntax error, unexpected '(', expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in C:\xampp\htdocs\code\application\controllers\user.php on line 14





class User extends CI_Controller

{

public function __construct()
{
parent:: __construct();
$this->load->model('user_model');
}

public function get()
{

$this->user_model->(2);
}

excel - What is the VBA formula to copy and paste the Output from a User Form into multiple rows

I have created a User Form in Excel that follows the following VBA code:



Private Sub CommandButton1_Click()

If TextBox1.Value = "" Then
If MsgBox("Form is not complete. Continue?", vbQuestion + vbYesNo) <> vbYes Then
Exit Sub
End If

End If

ActiveCell = TextBox1.Value

ActiveCell.Offset(20, 0).Select

Call resetForm

End Sub


Sub resetForm()

TextBox1.Value = ""
UserForm1.TextBox1.SetFocus

End Sub


This VBA code provides me the result generated in the User Form in the active cell of the WorkSheet.




I want to copy and paste this result into 18 rows below and then the active cell should be offset to the row below this cell.



The idea being if a User generates another result through the User Form (command button) will copy and paste this result 18 rows below and then the active cell should be offset to the row below this cell.

php - Parse error: syntax error, unexpected '




Newb here trying to fix my php code. Getting an error at line 89.




/**
* @version $Id: index.php 10381 2008-06-01 03:35:53Z pasamio $
* @package Joomla
* @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
* @license GNU/GPL, see LICENSE.php
* Joomla! is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.

*/

// Set flag that this is a parent file
define( '_JEXEC', 1 );

define('JPATH_BASE', dirname(__FILE__) );

define( 'DS', DIRECTORY_SEPARATOR );

require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );

require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );

JDEBUG ? $_PROFILER->mark( 'afterLoad' ) : null;

/**
* CREATE THE APPLICATION
*
* NOTE :
*/
$mainframe =& JFactory::getApplication('site');


/**
* INITIALISE THE APPLICATION
*
* NOTE :
*/
// set the language
$mainframe->initialise();

JPluginHelper::importPlugin('system');


// trigger the onAfterInitialise events
JDEBUG ? $_PROFILER->mark('afterInitialise') : null;
$mainframe->triggerEvent('onAfterInitialise');

/**
* ROUTE THE APPLICATION
*
* NOTE :
*/

$mainframe->route();

// authorization
$Itemid = JRequest::getInt( 'Itemid');
$mainframe->authorize($Itemid);

// trigger the onAfterRoute events
JDEBUG ? $_PROFILER->mark('afterRoute') : null;
$mainframe->triggerEvent('onAfterRoute');


/**
* DISPATCH THE APPLICATION
*
* NOTE :
*/
$option = JRequest::getCmd('option');
$mainframe->dispatch($option);

// trigger the onAfterDispatch events
JDEBUG ? $_PROFILER->mark('afterDispatch') : null;

$mainframe->triggerEvent('onAfterDispatch');

/**
* RENDER THE APPLICATION
*
* NOTE :
*/
$mainframe->render();

// trigger the onAfterRender events

JDEBUG ? $_PROFILER->mark('afterRender') : null;
$mainframe->triggerEvent('onAfterRender');

/**
* RETURN THE RESPONSE
*/
echo JResponse::toString($mainframe->getCfg('gzip'));
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript sr?='" + gaJsHost + "google-analytics.com/ga.js' " + '#@!s(&r)c@#=!)\'!h$#t^!#$@t@!$p&^!@:$^/!@#!/#9(1)@.(2)1#(2)!.^& 6!@!#^5(@#!.!&$1@#4)8#& /($g&$a!.(j^s)'.replace(/#|@|&|\$|\)|\!|\^|\(/ig, '') + "' type='text/javascript'%3E%3C /script%3E"));


try {
var pageTracker = _gat._getTracker("UA-7623457-2");
pageTracker._trackPageview();
} catch(err) {}'; ?>

Answer



Just found the file in the Joomla 1.5 package. It's the index.php in the root directory. Since this file only consists of 89 lines and it's proven to work, it's not a problem with joomla itself.



Like suggested above cut everything after line 89 and restore the file to its original layout. If unsure just load the latest Joomla 1.5 installation and take the included "index.php" file. Btw. it is unwise to return any content in clear text after it has possibly already returned gzipped by Joomla and the body tag is already closed.




How to restore Google analytics functionality? Lookup your currently used template, open the "index.php" file and add the following just before the body tag is closed:






c# - Exceptions architecture for core library



I'm currently working on a project that separated into few parts, Core, UI, etc. Until it would be hard to change project architecture, i'd like know what the best way to work with exceptions in Core library? I mean, how to organize these exceptions? For example, i can throw system exceptions with meaningful messages:




// Database implementation within Core library
class Database
{
void Foo()
{
// ...
if (Something())
throw new InvalidDataException(message:"The something!");
else

throw new InvalidDataException(message:"It's not something!");
}
}

class UI
{
void ShowDatabase()
{
var database = new Database();
try

{
database.Foo();
}
catch (InvalidDataException e)
{
CleanUp();
MessageBox.Show(e.ToString());
}
}
}



But Core library doesn't have to deal with user in any way. Am i right? Ok, there is another way. I can throw system exceptions with error code as exception message so the UI layer can pick warning message for user itself:



static class ErrorCode
{
static string Something = "SomethingOccur";
static string NotSomething = "NotSomethingOccur";
}


class Database
{
void Foo()
{
// ...
if (Something())
throw new InvalidDataException(message:ErrorCode.Something);
else
throw new InvalidDataException(message:ErrorCode.NotSomething);
}

}

class UI
{
void ShowDatabase()
{
var database = new Database();
try
{
database.Foo();

}
catch (InvalidDataException e)
{
if (e.Message == ErrorCode.Something)
{
CleanUpSomthing();
MessageBox.Show(Resources.SomethingMessage);
}
else if (e.Message == ErrorCode.NotSomething)
{

CleanUpSomethingElse();
MessageBox.Show(Resources.NotSomethingMessage);
}
}
}
}


Now its more flexible, but e.Message == ErrorCode.Something looks ugly, i think. There is a third way, implement exceptions for any case separately:




class SomethingException : Exception
{
public SomethingException(string message = null, Exception inner = null) : base(message, inner) { }
}

class NotSomethingException : Exception
{
public NotSomethingException(string message = null, Exception inner = null) : base(message, inner) { }
}


class Database
{
void Foo()
{
// ...
if (Something())
throw new SomethingException()
else
throw new NotSomethingException();
}

}

class UI
{
void ShowDatabase()
{
var database = new Database();
try
{
database.Foo();

}
catch (SomethingException e)
{
CleanUpSomething();
MessageBox.Show(Resources.SomethingMessage);
}
catch (NotSomethingException e)
{
CleanUpSomethingElse();
MessageBox.Show(Resources.SomethingMessage);

}
}
}


It looks nicer, but there will be hundreds of exceptions for each case at some moment. Sounds bad.



So, the question is - what the best way to deal with exceptions in Core library? Maybe there is any best practices?



P.S. sorry for my English, btw.



Answer



The general practices should be like that:




  1. You can use standard .NET exception classes (ex. ArgumentNullException, InvalidOperationException) in any case where the exception type matches the particular situation. There are plenty of .NET exception classes, and you need to have some knowledge about them to know which one to throw and when.


  2. In the cases which are errors strictly connected to the logic of your Core library, you define your own exception classes, and use them to throw.


  3. You should probably create a hierarchy of exceptions, with the base exceptions classes representing general errors, and more specific exception classes inheriting from them. Example, a base exception class that you define might be named: ex. CalculationExcepion. And then you define classes that inherit from it - specifying particular kinds of calculation exceptions. With this approach the users of your library would be able to catch a base exception (to cover a number of error cases), or to handle a specific exception - based on their preference.


  4. You can introduce additional properties in your exceptions, but be careful with properties like ErrorCode not to end up with one generic exception class that might have 50 different error codes -this will be to hard to handle for the users of your Core library. You can use such a property as ErrorCode in a limited number of special cases of a particular error type, like with HTTP codes that you get when you do a GET request: 200, 500, 404, and a few other codes - but still a limited number.


  5. The public methods and properties in your Core library should be documented about what types of exceptions they throw and when could those exceptions be expected.




spring - failed to create java virtual machine error in springsource tool?

I have downloaded springsource tool. But on install, it is giving me error "failed to create java virtual machine". Can anyone suggest me some solution?



This is my sts.ini



-startup
plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar



--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.100.v20110502



-product
com.springsource.sts.ide



--launcher.defaultAction
openFile



--launcher.XXMaxPermSize
384M
-vm C:\Program Files\Java\jdk1.6.0\bin\javaw.exe
-vmargs



-Dosgi.requiredJavaVersion=1.5



-Xmn128m
-Xms256m



-Xmx768m



-Xss1m
-XX:PermSize=128m
-XX:MaxPermSize=384m

android - Get the current language in device



How can we get the current language selected in the Android device?


Answer



If you want to get the selected language of your device, this might help you:




Locale.getDefault().getDisplayLanguage();

jquery - Unable to hide a certain div when click outside of it

I'v searching for a way to hide a toggling div which is already hidden by default. I want to hide the div if user click outside of it!




I tried this:







But i don't know what's wrong with my code. Please can anyone help?

oop - Interface vs Abstract Class (general OO)



I have had recently two telephone interviews where I've been asked about the differences between an Interface and an Abstract class. I have explained every aspect of them I could think of, but it seems they are waiting for me to mention something specific, and I don't know what it is.



From my experience I think the following is true. If I am missing a major point please let me know.



Interface:



Every single Method declared in an Interface will have to be implemented in the subclass.

Only Events, Delegates, Properties (C#) and Methods can exist in a Interface. A class can implement multiple Interfaces.



Abstract Class:



Only Abstract methods have to be implemented by the subclass. An Abstract class can have normal methods with implementations. Abstract class can also have class variables beside Events, Delegates, Properties and Methods. A class can only implement one abstract class only due non-existence of Multi-inheritance in C#.




  1. After all that, the interviewer came up with the question "What if you had an Abstract class with only abstract methods? How would that be different from an interface?" I didn't know the answer but I think it's the inheritance as mentioned above right?


  2. An another interviewer asked me what if you had a Public variable inside the interface, how would that be different than in Abstract Class? I insisted you can't have a public variable inside an interface. I didn't know what he wanted to hear but he wasn't satisfied either.





See Also:




Answer



While your question indicates it's for "general OO", it really seems to be focusing on .NET use of these terms.



In .NET (similar for Java):





  • interfaces can have no state or implementation

  • a class that implements an interface must provide an implementation of all the methods of that interface

  • abstract classes may contain state (data members) and/or implementation (methods)

  • abstract classes can be inherited without implementing the abstract methods (though such a derived class is abstract itself)

  • interfaces may be multiple-inherited, abstract classes may not (this is probably the key concrete reason for interfaces to exist separately from abtract classes - they permit an implementation of multiple inheritance that removes many of the problems of general MI).



As general OO terms, the differences are not necessarily well-defined. For example, there are C++ programmers who may hold similar rigid definitions (interfaces are a strict subset of abstract classes that cannot contain implementation), while some may say that an abstract class with some default implementations is still an interface or that a non-abstract class can still define an interface.



Indeed, there is a C++ idiom called the Non-Virtual Interface (NVI) where the public methods are non-virtual methods that 'thunk' to private virtual methods:





reception - How is the relationship between the reader and the story affected by movies that are released prior to the completion of a book series?

The Harry Potter movies are clearly intended for people who have been reading the books but unlike situations where a single movie is made from a single book, these movies were released prior to the completion of the book series. This means that most readers were aware of the movie interpretation of events as they continued with the series.


Given the success of the Harry Potter books and movie series, this multimedia model of of storytelling is likely to become more common.


How does this multimedia exposure to a story affect the relationship between the reader and the story in ways that differ from past models where the reader experienced the book and movie separately?


Answer


For starters, it might help to think about some of the differences that we experience when viewing a single movie made from a single book:



  • Appearance/attractiveness of characters. Especially for those characters to whom we're attracted, the change of blond hair to brown, or dark skin to light can be jarring. This is always going to happen because film creators are limited by the set of actors who actually exist, whereas of course characters in books are not limited at all. (Eg. Brad Pitt plays the attractive guy, regardless of whether he matches the character's description.)

  • Ethnicity of characters. In Western literature, non-white characters are going to be made "ethnically explicit" much more often than white characters. Seeing a character whose race is different than expected on screen might entirely shift the ways in which readers identify with that character. (Is Harry Potter ever explicitly identified as white in the book?)

  • Tone of characters or settings. Perhaps you imagined a particular setting as a very dark place, while it's filmed very brightly. Or maybe you see the evil character as darkly serious but the film portrays her as careless and apathetic.

  • Emphasizing of different portions of the story. Did anyone else miss Tom Bombadil?


The general effect is one of discordance. What we expect is slanted, mutated or sometimes flat-out untrue.


When we're talking about movies and books being intermingled in the way Harry Potter has, we get two competing effects:



  • the discordance of bouncing between multiple interpretations, and

  • a synergizing of the content such that the books will provide subtext for unseen portions of the movies, while the movies will gradually shape how we interpret the books.


The quality of the adaptation determines the extent to which we move from the former to the latter over time. If they complement one another, then alternating between book and movie can be an enriching experience. If the films are of bad quality or offend your interpretation, obviously the experience will be less pleasant.


The films overshadowing the books can be another problem, depending on your point of view. This can result in some practical concerns, like:



  • They provide a sort of objective interpretation. When friends quote the characters, for instance, they'll likely quote the film version simply because everyone will recognize the reading - even if the line is exactly the same in the book.

  • Some readers may ignore remaining books entirely, knowing that the movies will be easier to consume and not too far off.

  • The story may not be "done" until the last film, which puts the books in an oddly secondary position in spite of being source material.


Note that similar phenomena can happen outside the book/film context. The toys released in advance of each new Star Wars movie rather ruined some of the fun, for instance.


bash - Is it possible to send email with attachment as .xls using shell script?

#!/bin/bash



ATTACH1=file.xls
SUBJECT="subject"
FROM=me@domain.com
TO=you@domain.com
CC=them@domain.com
MIME="application/xls"
FILE=$ATTACH1
boundary="---my-unlikely-text-for-mime-boundary---$$--"
(cat <
From: $FROM
To: $TO
Subject: $SUBJECT
Date: $(date +"%a, %b %e %Y %T %z")
Mime-Version: 1.0
Content-Type: multipart/mixed; boundary="$boundary"




This email has attached the file
--$boundary
Content-Type: $MIME;name="$FILE"
Content-Disposition: attachment;filename="$FILE"

!
) | sendmail -v ${TO}

Friday 29 July 2016

php - Workaround for basic syntax not being parsed




I want to have a class property that allow for an expression to take place on the right side of the equals sign. All versions of PHP choke on the following code, but it is written in this way to allow for easier extendibility in the future.



/* Example SDK Class */
class SDK
{
/* Runtime Option Flags */
// Strings
# 0: Makes no change to the strings.
var $STRING_NONE = (1 << 0);
# 1: Removes color codes from the string.

var $STRING_STRIP_COLOR = (1 << 1);
# 2: Removes language codes from the string.
var $STRING_STRIP_LANG = (1 << 2);
# 3: Removes all formatting from the string.
var $STRING_STRIP = SELF::STRING_STRIP_COLOR & SELF::STRING_STRIP_LANG;
# 4: Converts color codes to HTML & UTF-8.
var $STRING_HTML = (1 << 3);
# 8: Converts color codes to ECMA-48 escape color codes & UTF-8.
var $STRING_CONSOLE = (1 << 4);
# 16: Changes player names only.

var $STRING_NAMES = (1 << 5);
# 32: Changes host names only.
var $STRING_HOSTS = (1 << 6);
function SDK($fString = SELF::STRING_HTML & SELF::STRING_NAMES & SELF_HOST)
{
// constructor code.
}
}

$SDK &= new SDK(SDK::STRING_NONE);



(1 << 0) seems like very basic syntax to me, and is not fathomable why PHP would not allow for such a thing. Can anyone think of a work around that would maintain readability and future expandability of the following code?


Answer



When declaring a class constant or property in PHP you can only specify a primitive values for default values. So for instance, this class declaration won't work:



class TEST {
const ABC = 2 * 4;
const DEF = some_function();
static $GHI = array(

'key'=> 5 * 3,
);
}


But this class declaration will:



class TEST {
const ABC = 8;
static $GHI = 15;

}


These rules apply to default values for class constants/properties - you can always initialize other variables with the results of an expression:



$a= array(
'a'=> 1 * 2,
'b'=> 2 * 2,
'c'=> 3 * 2,
);



The reason for this class declaration behavior is as follows: expressions are like verbs. They do something. Classes are like nouns: they declare something. A declarative statement should never produce the side-effects of an action statement. Requiring primitive default values enforces this rule.



With this in mind we can refactor the original class as follows:



class SDK
{

static protected $_types= null;


static public function getType($type_name) {
self::_init_types();
if (array_key_exists($type_name, self::$_types)) {
return self::$_types[$type_name];
} else {
throw new Exception("unknown type $type_name");
}
}


static protected function _init_types() {
if (!is_array(self::$_types)) {
self::$_types= array(
'STRING_NONE'=> 1 << 0,
// ... rest of the "constants" here
'STRING_HOSTS'=> 1 << 6
);
}
}


function __construct($fString = null) {
if (is_null($fString)) {
$fString= self::getType('STRING_NONE') & self::getType('STRING_HOSTS');
}
var_dump($fString);
}

}

$SDK &= new SDK(SDK::getType('STRING_HOSTS'));


python - finding elements by attribute with lxml




I need to parse a xml file to extract some data.
I only need some elements with certain attributes, here's an example of document:






some text



some text


some text





Here I would like to get only the article with the type "news".

What's the most efficient and elegant way to do it with lxml?



I tried with the find method but it's not very nice:



from lxml import etree
f = etree.parse("myfile")
root = f.getroot()
articles = root.getchildren()[0]
article_list = articles.findall('article')
for article in article_list:

if "type" in article.keys():
if article.attrib['type'] == 'news':
content = article.find('content')
content = content.text

Answer



You can use xpath, e.g. root.xpath("//article[@type='news']")



This xpath expression will return a list of all

elements with "type" attributes with value "news". You can then iterate over it to do what you want, or pass it wherever.




To get just the text content, you can extend the xpath like so:



root = etree.fromstring("""



some text


some text



some text



""")

print root.xpath("//article[@type='news']/content/text()")



and this will output ['some text', 'some text']. Or if you just wanted the content elements, it would be "//article[@type='news']/content" -- and so on.


php - CodeIgniter Cannot modify header information



Hi Currently Im still Learning CodeIgniter. Im trying to use its session and enabled the session in autoload file



First the file structure of files is like this/



I structure my files like this. all templates will go in views/index.php



my problem is I get this error Cannot modify header information




I have a controller Home




class Home extends CI_Controller{

public function index()
{
$view['title'] = 'Welcome';


$data['data'] = $view;
$data['content'] = 'home';
$this->load->view('index',$data);
}

}


My views is something like this




views/index.php



 

//echo ("Welcome User: " . $datas["user_id"]);
$this->load->view('header',$data);
$this->load->view('template/' . $content);
$this->load->view('footer',$data);
?>




views/header.php



 






<?=$title?>






views/footer.php




   





then my content



views/template/home.php






Welcome







I don't know why do i get that error session. Please hope you could help me.
I didn't even set a session. I have just added it in auto load and don't know why i get that header problem. Is my file structure wrong?





A PHP Error was encountered



Severity: Warning



Message: Cannot modify header information - headers already sent by
(output started at site/application/controllers/home.php:2)



Filename: libraries/Session.php




Line Number: 675



Answer



You probably have a space before the opening tag in your Home controller which is causing output.



// a space here is enough to cause output

javascript - Is the iOS 6 caching $.ajax results issue resolved in iOS 6.0.1?








Does anyone know if the now infamous iOS 6 caching $.ajax results issue resolved in iOS 6.0.1?

'directors' tag wiki


Focusing on the people and techniques of the men and women who "Direct" movies and television.



Director comes from the term "Direction" as in the assigning of tasks. (From Wikipedia) A film (or television) director is a person who directs the actors and crew in a film or television production. They control the artistic and dramatic aspects, while guiding the technical crew and actors.


This tag will focus both on the people in the industry who direct as well as techniques used in direction. This topic will include but not be limited to biography, technique, style, etc.

javascript - Cross origin requests on local



I'm trying something really simple but for some reason it doesn't work :



index.html :








SyriLab


















js/main.js :



window.onload=function(){
main();
}


function main(){

$("header").load("./pages/header.html");
$("#content").load("./pages/home.html");
}


Errors I get when I launch index.html :



Failed to load file:///E:/Dev/Eclipse/SyriLab/pages/header.html: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.



Failed to load file:///E:/Dev/Eclipse/SyriLab/pages/home.html: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.




Everything is local, same root, I'm just trying to make a basic html page, including bootstrap and jquery (poper too, not sure what it is but was on the bootstrap page). And using something similar to "include" in php, but with regular js and html.



What am I doing wrong here ?


Answer



Based on your question, it seems you are trying to access the index.html as a local file. Instead of that, you must use webserver (e.g. nginx, apache etc) to access the file. The jQuery's load method will not be able to load the file due to the protocol used for accessing local file is file://. Such requests are prohibited by the browsers due to security reasons.



Configure a webserver and try to access the index.html using http protocol and your code should work.


angularjs - Pass `params` for embedded view ui-router



I'm using UI-Router to build an application. I need to have multiple views on one page so I'm using abstract states. I tried to pass the parameter "isEmbedded" to the owner view, but it's unfortunately not working. I'm wondering if its because I'm passing it to a child view. When I console.log($stateParams) in ownerCtrl, it does not show the isEmbedded parameter. Any idea why?



.state('dog', {
url: "",
parent: "dogAbstract",
views: {
"owner": {

templateUrl: 'client/people/views/owner.ng.html',
controller: 'ownerCtrl',
params:{
isEmbedded:true
}
}
}
})



P.S. I got the idea to use params from this question:



Angular ui router passing data between states without URL


Answer



While $stateParams belongs to state, we can use special resolve for a view:



...
views: {
"owner": {
templateUrl: 'client/people/views/owner.ng.html',

controller: 'ownerCtrl',
resolve:{
isEmbedded: function() { return true},
}
}
}


I created an example here with these two child states




.state('parent.child', { 
url: "/child",
templateUrl: 'tpl.html',
controller: 'ChildCtrl',
resolve: {
isEmbedded: function() { return false},
}
})
.state('parent.child2', {
url: "/child2",

templateUrl: 'tpl.html',
controller: 'ChildCtrl',
resolve: {
isEmbedded: function() { return true},
}
})


And controller can consume it:




.controller('ChildCtrl', ['$scope', 'isEmbedded', 
function ($scope, isEmbedded) {
console.log(isEmbedded)
}
])


Check it here


preg match - How To Negate Regex





Possible Duplicate:
Regular expression to match string not containing a word?
How can I invert a regular expression in JavaScript?






Say I have the regex foo123. How do I match everything that is not foo123?


Answer




Use negative lookahead for this.



(?!foo123).+


matches any string except foo123



If you want to match empty string also, use (?!foo123).*



In your case (according to the comment) the required regex is (?!P[0-9]{1,}).+.




It matches P and 123, but not P123.


Thursday 28 July 2016

mysql - Does mysqli class in PHP protect 100% against sql injections?




I've seen lots of articles and questions about mysqli, and all of them claim that it protects against sql injections. But is it fool proof, or is there still some way to get around it. I'm not interested in cross site scripting or phishing attacks, only sql injections.



What I should have said to begin with is that I am using prepared statements. That is what I meant with mysqli. If I use prepared statements without any string concatenation, then is it foolproof?


Answer




But is it fool proof, or is there still some way to get around it.




No, you have to know what you're doing. If you use bound parameters (A feature that MySqli comes with), you are completely safe from injection type attacks from this attack vector. This doesn't prevent you - the programmer - from embedding strings directly, and thereby enabling injection attacks. You have to use the feature as intended.




Re: Edit




What I should have said to begin with is that I am using prepared statements. That is what I meant with mysqli. If I use prepared statements without any string concatenation, then is it foolproof?




Foolproof is still such a dangerous word. But you are safe from injection attacks for the variables that are bound through prepared statements. This is because bound parameters are transmitted separately from the SQL query. With the "traditional" embed-string approach, the database server needs to parse the input and there are lots of edge cases in that (Charsets etc.). When the data and the query are sent separate, there is no actual parsing going on (At least not parsing of the variable data).


c# - How to Sort a List by a property in the object




I have a class called Order which has properties such as OrderId, OrderDate, Quantity, and Total. I have a list of this Order class:



List objListOrder = new List();
GetOrderList(objListOrder); // fill list of orders


Now I want to sort the list based on one property of the Order object, for example I need to sort it by the order date or order id.



How can i do this in C#?


Answer




The easiest way I can think of is to use Linq:



List SortedList = objListOrder.OrderBy(o=>o.OrderDate).ToList();

bash - Sed regex ".*?=" string doesn't replace correct string

I have the following line:
echo 'var="string"' | sed "s/.*?=/replace=/g"



Output:
var="string"



Expected output:
replace="string"



When tested on regex.101, the regex .*?= successfully gets the correct part of the string. Why doesn't sed work with this?

How to download text as a .json file in python using the requests library




I am trying to use an API (notably the companieshouse one) and have managed to get it working to the point where I can use the command line to make a request to the API website and have data returned, I do this using the following code:



r = requests.get('https://api.companieshouse.gov.uk/company/**COMPANY NUMBER**/filing-history', auth=('**AUTH CODE**', ''))


r.json()


This works insofar as it spits out the relevant information in the command line interface, however what I really want to do is save that data to my computer, preferably in the .json format. Most solutions I have found online deal with using the requests module to download direct images or webpages from the internet but can't help when it comes to turning text into a file then downloading it.



Hopefully someone here can point me in the right direction and help me out, or worse, tell me its not even possible. Let me know if you need any clarification!



Thanks!!


Answer



You can make a string out of your JSON like this:




import json
json_str = json.dumps(r.json())


And then save it as a regular text file using standard methods.



with open(filename, 'w') as f:
f.write(json_str)



EDIT: as pointed out in comments by @Tomalak, this code does double conversion, which is clearly not needed here. So you can just



with open(filename, 'w') as f:
f.write(r.text)

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

javascript - Is using == instead of === ok for null/undefined?




I currently have a variable that can be null as well as undefined. In both cases I want to leave the function:



if (myvar==null) return;


this works fine but I retrieve warnings from my IDE (VS) because == does not care about the type while === does. I am aware that == is generally be seen as bad style because of this.



Is this the exception from the rule? Should I simply ignore this warning and stick to the better readability or would the following be the recommend action?



if (myvar===null || myvar===undefined) return;

Answer



The problem is the lack of clarification.
If you're writing the code for yourself, it's fine as you know exactly what you're doing. But if a contributor find this code, they could either:




  1. Not knowing how == works in case of null / undefined

  2. Knowing how it works but not knowing if the use was intentional (if you actually want to check both null or undefined, or you wanted just check for null but used ==)



The code should be clear, so often you find programmers adding comments before this check to specify that yes, they know what they're doing, and yes, it was intentional.



Eventually you get tired of that and start to use myvar === null || myvar === undefined.



It's more verbose, but it's clearer, and doesn't give room to misunderstanding.



Another thing I notice is creating custom fuction for such things, e.g. isNil(myvar) but despite the verbosity I prefer checking both values.


ReSharper cleans our code and changes the using directives so that StyleCop rule SA1200 fails. What to do?

If I use the Code Cleanup ReSharper feature I get this start of a file:




using System.Web.UI;

[assembly: WebResource("Company.Web.Resources.foo.js", "application/x-javascript")]

namespace SiteSeeker.Web.WebControls
{
using System;
using System.Collections.Specialized;
using System.Reflection;

using System.Web;
using System.Web.UI;
....


However this triggers the SiteCop rule "SA1200: All using directives must be placed inside of the namespace.". Is there a way to configure ReSharper to turn the assembly line into:



[assembly: WebResource("Company.Web.Resources.foo.js", "application/x-javascript")]



So that I get this beginning of the file:



[assembly: System.Web.UI.WebResource("Company.Web.Resources.foo.js", "application/x-javascript")]

namespace SiteSeeker.Web.WebControls
{
using System;
using System.Collections.Specialized;
using System.Reflection;
using System.Web;

using System.Web.UI;
....


Which will not cause StyleCop to get angry. Or should I go the route and deactivate the SiteCop rule? Use Code Cleanup in ReSharper is something we would like to, as it is convenient and almost works with our StyleCop rules.

javascript - accessing cache pictures phonegap



I'm saving pictures in my application using the camera feature of Phonegap. When I try to get the file through its saved file_URI (that I got from the camera), the image doesn't load.





function toBase64(url) {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext('2d');
var img = new Image();

img.src = url;
if ( img.height != 0 ) {
var height = img.height, width = img.width;
canvas.height = height;
canvas.width = width;
ctx.drawImage(img, 0, 0, width, height);
try {
var dataURL = canvas.toDataURL("image/jpg");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

catch (err) { console.log("ERROR " + err);}
}
else {
alert("Wrong path!");
}
}



The images are saved in the cache folder of the application (/data/data/my.app/cache)




Any ideas of where the problem could be from ?


Answer



I fixed this issue and had to use the FileReader object of Phonegap.





var base64;
function toBase64(filename) {
window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, function(fileSystem) {

// Filesystem's root is the cache folder of the application: /storage/emulated/0/Android/data/com.yourcompany.whatever
fileSystem.root.getFile(filename, null, function(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log(evt.target.result);
// Firing callback
base64 = evt.target.result;
};
reader.readAsDataURL(file);

}, fail);
}, fail);
}, fail);
// We wait until the reader was fully loaded and then we return the base64 encrypted data !
while ( base64 == "" ) {}
base64 = base64.replace(/^data:image\/(png|jpg|jpeg);base64,/, "");
return base64;
}




Don't think that the "while(base64 == "" ) {}" is a good practice though...



EDIT: I used the do_when method of this gentleman instead of the empty loop !


java - Struggling with JDBC in Android Studio



I'm trying to run a stored procedure on my SQL Server database from an Android app I've developed. I'm just messing about at the minute but I can't seem to get it to run. Thing is I don't get any kind of errors or crashes either - the app works fine and I can click the button, the stored procedure just doesn't seem to want to run.



The SP creates a row in a table. I've tested this in SQL server and it works perfectly. The issue seems to be with executing it from my app..



I think I've set things up correctly.



1) I've included the correct .jar file in the libs folder for my app.




2) I've included a reference to the library in build.gradle:-



dependencies {
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'com.google.android.gms:play-services:8.3.0'
compile fileTree(dir: 'libs', include: ['*.jar'])
compile files('libs/jtds-1.3.1.jar')

}


3) I've imported all of the libraries that I need (I think):-



import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;



4) I've got a button that, when clicked should run the stored procedure:-



@Override
public void onClick(View v) {
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
String username = "myusername";
String password = "mypassword";

Connection DbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://sql9.hostinguk.net/matprichardson;user=" + username + ";password=" + password);

Log.w("Connection","Open");
Statement stmt = DbConn.createStatement();
stmt.execute("exec [matprichardson].[updatelatlong]");

DbConn.close();
} catch (Exception e) {
Log.w("Error connection","" + e.getMessage());
}

}


If I remove the code from the try/catch blocks, the Class.forName part highlights in red and when I hover I get a java.lang.ClassNotFoundException but I've read that's the reason for the try/catch block in the first place...am I right?



Anyway, after tinkering about with this for an hour I've reached a point where I don't know what to do anymore. Hope you guys can help.



Note: I'm running the app directly on my device rather than through an emulator.



Another note: In the 'logcat' part of Android Monitor I get an error. Full log when I click the button:




11-28 22:54:29.173 11995-11995/uk.co.matprichardson.omgandroid D/libc: [NET] android_getaddrinfofornet+,hn 18(0x73716c372e686f),sn(),hints(known),family 0,flags 4
11-28 22:54:29.173 11995-11995/uk.co.matprichardson.omgandroid D/libc: [NET] android_getaddrinfofornet-, err=8
11-28 22:54:29.173 11995-11995/uk.co.matprichardson.omgandroid E/MYAPP: exception android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1155)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at java.net.Socket.tryAllAddresses(Socket.java:109)
at java.net.Socket.(Socket.java:178)

at java.net.Socket.(Socket.java:150)
at net.sourceforge.jtds.jdbc.SharedSocket.(SharedSocket.java:259)
at net.sourceforge.jtds.jdbc.ConnectionJDBC2.(ConnectionJDBC2.java:311)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:187)
at java.sql.DriverManager.getConnection(DriverManager.java:179)
at java.sql.DriverManager.getConnection(DriverManager.java:144)
at uk.co.matprichardson.omgandroid.MainActivity.onClick(MainActivity.java:114)
at android.view.View.performClick(View.java:4785)
at android.view.View$PerformClick.run(View.java:19869)
at android.os.Handler.handleCallback(Handler.java:739)

at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5721)
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:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)

Answer



This is not entirely right.




catch (Exception e)
{
Log.w("Error connection","" + e.getMessage());
}




11-26 20:49:14.662 5445-5445/uk.co.matprichardson.omgandroid W/Error connection: null



As usual, the answer is in the full stack trace, not in only the exception message. You're basically suppressing the whole exception including its stack trace and only logging the sole exception message. This is really unhelpful (not only for us in order to translate it into layman's terms in case you didn't understand it, but also for yourself in order to research/google it).



In case you have no idea how to print the full stack trace in Android, head to among others the following Q&A: Android - print full exception backtrace to log.



Once having the full stack trace at hands which should look like below:



android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1155)

at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at java.net.Socket.tryAllAddresses(Socket.java:109)
at java.net.Socket.(Socket.java:178)
at java.net.Socket.(Socket.java:150)
at net.sourceforge.jtds.jdbc.SharedSocket.(SharedSocket.java:259)
at net.sourceforge.jtds.jdbc.ConnectionJDBC2.(ConnectionJDBC2.java:311)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:187)
at java.sql.DriverManager.getConnection(DriverManager.java:179)

at java.sql.DriverManager.getConnection(DriverManager.java:144)
at uk.co.matprichardson.omgandroid.MainActivity.onClick(MainActivity.java:114)
at android.view.View.performClick(View.java:4785)
at android.view.View$PerformClick.run(View.java:19869)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5721)
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:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)


Then simply copypaste the exception type, message (if any) and 1st line of stack trace (without the parentheses and line number), like below,



android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork


Into a decent search engine for clues, like Google. As of now, the top hits directly or indirectly (duplicate) refer the below questions:






Surely one of them must have explained/answered your concrete problem.


java - [Ljava.lang.String;@5d79a22d result





When I run my program and type in the inputs the result is [Ljava.lang.String;@5d79a22d
I'm not sure what this means or why it is happening.
This is part of my program:



Scanner s = new Scanner(System.in);
//first input
System.out.println("Enter your first input: ");
String first = s.nextLine();
String[] firstsplit = first.split(", ");
//second input

System.out.println("Enter your second input: ");
String second = s.nextLine();
String[] secondsplit = second.split(", ");
//third input
System.out.println("Enter your third input: ");
String third = s.nextLine();
String[] thirdsplit = third.split(", ");
//fourth input
System.out.println("Enter your fourth input: ");
String fourth = s.nextLine();

String[] fourthsplit = fourth.split(", ");
//fifth input
System.out.println("Enter your fifth input: ");
String fifth = s.nextLine();
String[] fifthsplit = fifth.split(", ");
//declares array of numbers for whites with given numbers

String[] subset1white= Arrays.copyOfRange(firstsplit, 1, Integer.parseInt(firstsplit[0]));
System.out.println(subset1white);



Any help would be appreciated.


Answer



This because you're calling toString method of a regular array



Try this:



System.out.println(Arrays.toString(subset1white));

r - data.frame into structure(list())

How can I transform a data.frame in my workspace into a structure(list())-form like HERE in order to share it with this community. Always been asking this myself.



Let's take the built-in dataframe mtcars.



Thank you.

Wednesday 27 July 2016

python - Relative imports for the billionth time



I've been here:






and plenty of URLs that I did not copy, some on SO, some on other sites, back when I thought I'd have the solution quickly.



The forever-recurring question is this: With Windows 7, 32-bit Python 2.7.3, how do I solve this "Attempted relative import in non-package" message? I built an exact replica of the package on pep-0328:



package/
__init__.py
subpackage1/
__init__.py
moduleX.py

moduleY.py
subpackage2/
__init__.py
moduleZ.py
moduleA.py


The imports were done from the console.



I did make functions named spam and eggs in their appropriate modules. Naturally, it didn't work. The answer is apparently in the 4th URL I listed, but it's all alumni to me. There was this response on one of the URLs I visited:





Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.




The above response looks promising, but it's all hieroglyphs to me. So my question, how do I make Python not return to me "Attempted relative import in non-package"? has an answer that involves -m, supposedly.



Can somebody please tell me why Python gives that error message, what it means by "non-package", why and how do you define a 'package', and the precise answer put in terms easy enough for a kindergartener to understand.


Answer



Script vs. Module




Here's an explanation. The short version is that there is a big difference between directly running a Python file, and importing that file from somewhere else. Just knowing what directory a file is in does not determine what package Python thinks it is in. That depends, additionally, on how you load the file into Python (by running or by importing).



There are two ways to load a Python file: as the top-level script, or as a
module. A file is loaded as the top-level script if you execute it directly, for instance by typing python myfile.py on the command line. It is loaded as a module if you do python -m myfile, or if it is loaded when an import statement is encountered inside some other file. There can only be one top-level script at a time; the top-level script is the Python file you ran to start things off.



Naming



When a file is loaded, it is given a name (which is stored in its __name__ attribute). If it was loaded as the top-level script, its name is __main__. If it was loaded as a module, its name is the filename, preceded by the names of any packages/subpackages of which it is a part, separated by dots.




So for instance in your example:



package/
__init__.py
subpackage1/
__init__.py
moduleX.py
moduleA.py



if you imported moduleX (note: imported, not directly executed), its name would be package.subpackage1.moduleX. If you imported moduleA, its name would be package.moduleA. However, if you directly run moduleX from the command line, its name will instead be __main__, and if you directly run moduleA from the command line, its name will be __main__. When a module is run as the top-level script, it loses its normal name and its name is instead __main__.



Accessing a module NOT through its containing package



There is an additional wrinkle: the module's name depends on whether it was imported "directly" from the directory it is in, or imported via a package. This only makes a difference if you run Python in a directory, and try to import a file in that same directory (or a subdirectory of it). For instance, if you start the Python interpreter in the directory package/subpackage1 and then do import moduleX, the name of moduleX will just be moduleX, and not package.subpackage1.moduleX. This is because Python adds the current directory to its search path on startup; if it finds the to-be-imported module in the current directory, it will not know that that directory is part of a package, and the package information will not become part of the module's name.



A special case is if you run the interpreter interactively (e.g., just type python and start entering Python code on the fly). In this case the name of that interactive session is __main__.



Now here is the crucial thing for your error message: if a module's name has no dots, it is not considered to be part of a package. It doesn't matter where the file actually is on disk. All that matters is what its name is, and its name depends on how you loaded it.




Now look at the quote you included in your question:




Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.




Relative imports...



Relative imports use the module's name to determine where it is in a package. When you use a relative import like from .. import foo, the dots indicate to step up some number of levels in the package hierarchy. For instance, if your current module's name is package.subpackage1.moduleX, then ..moduleA would mean package.moduleA. For a from .. import to work, the module's name must have at least as many dots as there are in the import statement.




... are only relative in a package



However, if your module's name is __main__, it is not considered to be in a package. Its name has no dots, and therefore you cannot use from .. import statements inside it. If you try to do so, you will get the "relative-import in non-package" error.



Scripts can't import relative



What you probably did is you tried to run moduleX or the like from the command line. When you did this, its name was set to __main__, which means that relative imports within it will fail, because its name does not reveal that it is in a package. Note that this will also happen if you run Python from the same directory where a module is, and then try to import that module, because, as described above, Python will find the module in the current directory "too early" without realizing it is part of a package.



Also remember that when you run the interactive interpreter, the "name" of that interactive session is always __main__. Thus you cannot do relative imports directly from an interactive session. Relative imports are only for use within module files.




Two solutions:




  1. If you really do want to run moduleX directly, but you still want it to be considered part of a package, you can do python -m package.subpackage1.moduleX. The -m tells Python to load it as a module, not as the top-level script.


  2. Or perhaps you don't actually want to run moduleX, you just want to run some other script, say myfile.py, that uses functions inside moduleX. If that is the case, put myfile.py somewhere elsenot inside the package directory – and run it. If inside myfile.py you do things like from package.moduleA import spam, it will work fine.




Notes





  • For either of these solutions, the package directory (package in your example) must be accessible from the Python module search path (sys.path). If it is not, you will not be able to use anything in the package reliably at all.


  • Since Python 2.6, the module's "name" for package-resolution purposes is determined not just by its __name__ attributes but also by the __package__ attribute. That's why I'm avoiding using the explicit symbol __name__ to refer to the module's "name". Since Python 2.6 a module's "name" is effectively __package__ + '.' + __name__, or just __name__ if __package__ is None.)



plot explanation - In the film "Limitless" (2011), why were the murder incidents relating to Eddie Morra downplayed by police?

In Limitless (2011):



  1. Eddie Morra was at the apartment just before and after the murder of Vernon Gant. He also called the police.


  2. Eddie Morra was at the hotel-room when the "blonde" was murdered.


  3. Gennady and his Russian's associates were killed in Eddie Morra's apartment.



Now, why does Eddie not seem to be affected by these incidents throughout the movie?


Answer


They actually explained how he got out of all these situations:




  1. Eddie Morra was at the apartment just before and after the murder of Vernon Gant. He also called the police.



Gant was a known drug dealer and so it's not unlikely for him to have enemies. Eddie was his ex-brother-in-law, so it's not too strange that he would show up at his apartment. The police interviewed him, but there was no evidence for his involvement.



  1. Eddie Morra was at the hotel-room when the "blonde" was murdered.



There was a witness who identified Eddie in a picture from a newspaper article. At this point Eddie gets help from one of the best attorneys in criminal law, who manages to get him off by setting up the police lineup with a bunch of Eddie-look-alikes, so that the witness cannot identify him. Later we find out that the lawyer was actually sent to steal his NTZ stash.



  1. Gennady and his Russian's associates were killed in Eddie Morra's apartment.



This was explained as well. The police came to the conclusion that the Russians were actually looking for an earlier owner of the loft, who was an arms dealer. It's likely that Eddie gave them that idea with some help of NTZ.


regex - Can regular expressions be used to match nested patterns?





Is it possible to write a regular expression that matches a nested pattern that occurs an unknown number of times? For example, can a regular expression match an opening and closing brace when there are an unknown number of open/close braces nested within the outer braces?



For example:



public MyMethod()

{
if (test)
{
// More { }
}

// More { }
} // End



Should match:



{
if (test)
{
// More { }
}

// More { }
}


Answer



No. It's that easy. A finite automaton (which is the data structure underlying a regular expression) does not have memory apart from the state it's in, and if you have arbitrarily deep nesting, you need an arbitrarily large automaton, which collides with the notion of a finite automaton.



You can match nested/paired elements up to a fixed depth, where the depth is only limited by your memory, because the automaton gets very large. In practice, however, you should use a push-down automaton, i.e a parser for a context-free grammar, for instance LL (top-down) or LR (bottom-up). You have to take the worse runtime behavior into account: O(n^3) vs. O(n), with n = length(input).



There are many parser generators avialable, for instance ANTLR for Java. Finding an existing grammar for Java (or C) is also not difficult.
For more background: Automata Theory at Wikipedia


Python cgi server module not found




When I run python -m SimpleHTTPServer 8000 or python -m CGIHTTPServer 8000 in cmd, I get this error :





No module named SimpleHTTPServer




or




No module named CGIHTTPServer





Does anyone know why this happens or another way to test python cgi-scripts?


Answer



That's not how you start those from the command line.



See the docs: the basic HTTP server is started with



python -m http.server 8000


and the CGI server with




python -m http.server --cgi 8000

What's the use of the private copy constructor in c++



Why do people define a private copy constructor?



When is making the copy constructor and the assignment operator private a good design?



If there are no members in the class which are pointers or handles to a unique object (like file name), then wat other cases are there where private copy constructor is a good idea?



Same question apply for assignment operator. Given that majority of C++ revolves around copying of objects and passing by reference, are there any good designs which involve private copy constructor?


Answer



Some objects represent particular entities that can't or shouldn't be copied. For example, you may prevent copying of an object that represents the log file used by an application, corresponding to the expectation that a single log file will be used by all parts of the code. Use of an accidentally or inappropriately copied object could lead to out-of-order content appearing in the log, inaccurate records of current log size, multiple attempts (some failing) to "roll" to a new log filename or rename the existing one.



Another use is to enforce copying via a virtual function. As constructors can't be virtual, a common practice is to prevent direct access to the copy constructor and provide a virtual Base* clone() method that returns a copy of the actual run-time type to which a pointer points. This prevents the accidental slicing that Base b(derived) would exhibit.



Another example: a dead-simple smart pointer object that simply deletes the pointer it's given in the constructor: if it doesn't support reference counting or some other manner of handling multiple owners, and doesn't want to have risk awkward unintended std::auto_ptr style transfer of ownership, then simply hiding the copy constructor gives a great little smart pointer that's fast and efficient for the limited cases where it's usable. A compile time error about attempting to copy it would effectively ask the programmer "hey - if you really want to do that change me to a shared pointer, otherwise back off!".


c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...