Monday 31 July 2017

php - mysql_connect() : Access denied for user 'user'@'localhost'



I am trying to connect to mysql and am getting an error.
I put my servers ip address in and used port 3306 whihch post should be used?




$connection = mysql_connect("serer.ip:port", "user", "pass")
or die(mysql_error());


if ($connection) {$msg = "success";}
?>













Here is the error its producing:




Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'user'@'localhost' (using password: YES) in /home/admin/domains/domain.com.au/public_html/db_connect.php on line 3
Access denied for user 'user'@'localhost' (using password: YES)




Answer



Use



$conn = mysql_connect($db_host,$db_user, $db_pass) or die("Error connecting to database");


The port is automatically selected as 3306.



Also double check to make sure your username and password for connecting are correct and allowed access.


jQuery if checkbox is not checked issue











I am having an issue picking up when a checkbox is not checked.



Here is my sample code:



$(".get-the-look ul input").click(function(){
if("this:checked") {
var product = $(this).attr('alt');

$("#bob div").remove('.'+product);
} else {
alert('asdasd');
}
});


But the alert (if the checkbox isn't checked) never fires... The 'else' never kicks in no matter what state the checkbox is in?



I don't see where I am going wrong.



Answer



you can't pass this:checked as a string - it won't work as it will be interpreted as a string and always evaluate to true



use $(this).is(':checked') instead


Get Unique ID of Android Device?

I have htc one b model android phone. I want to know my device ID. I do not know how could I finding out my device ID .

How do I concatenate two lists in Python?



How do I concatenate two lists in Python?



Example:



listone = [1, 2, 3]
listtwo = [4, 5, 6]



Expected outcome:



>>> joinedlist
[1, 2, 3, 4, 5, 6]

Answer



You can use the + operator to combine them:



listone = [1,2,3]
listtwo = [4,5,6]


joinedlist = listone + listtwo


Output:



>>> joinedlist
[1,2,3,4,5,6]

javascript - How to pass data by value into a deferred then handler?

I would like to know how to pass data by value, rather than by reference, into a then handler on a jQuery Deferred object.



I have the following example code to illustrate my question:




var value;
var deferred = new $.Deferred();
var data = ["A", "B", "C", "D"];

// add a separate call to the chain for each piece of data
for (var i = 0; i < data.length; i++) {
value = data[i];
deferred.then(function(response) {
console.log(response+':'+value);

});
}

deferred.resolve("test");


The result I want to get:



test:A
test:B

test:C
test:D


The result I actually get:



test:D
test:D
test:D
test:D



It seems the value of value is evaluated at the time the then handler is executed, whereas I want it to be evaluated at the time the then handler is queued.



I have a JSfiddle, hope someone can help?

c++ - Undefined reference to vtable



When building my C++ program, I'm getting the error message




undefined reference to 'vtable...




What is the cause of this problem? How do I fix it?







It so happens that I'm getting the error for the following code (The class in question is CGameModule.) and I cannot for the life of me understand what the problem is. At first, I thought it was related to forgetting to give a virtual function a body, but as far as I understand, everything is all here. The inheritance chain is a little long, but here is the related source code. I'm not sure what other information I should provide.



Note: The constructor is where this error is happening, it'd seem.



My code:



class CGameModule : public CDasherModule {

public:
CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName)
: CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName)
{
g_pLogger->Log("Inside game module constructor");
m_pInterface = pInterface;
}

virtual ~CGameModule() {};


std::string GetTypedTarget();

std::string GetUntypedTarget();

bool DecorateView(CDasherView *pView) {
//g_pLogger->Log("Decorating the view");
return false;
}

void SetDasherModel(CDasherModel *pModel) { m_pModel = pModel; }



virtual void HandleEvent(Dasher::CEvent *pEvent);

private:



CDasherNode *pLastTypedNode;



CDasherNode *pNextTargetNode;


std::string m_sTargetString;


size_t m_stCurrentStringPos;



CDasherModel *m_pModel;


CDasherInterfaceBase *m_pInterface;
};


Inherits from...



class CDasherModule;

typedef std::vector::size_type ModuleID_t;

/// \ingroup Core
/// @{
class CDasherModule : public Dasher::CDasherComponent {
public:
CDasherModule(Dasher::CEventHandler * pEventHandler, CSettingsStore * pSettingsStore, ModuleID_t iID, int iType, const char *szName);

virtual ModuleID_t GetID();
virtual void SetID(ModuleID_t);

virtual int GetType();
virtual const char *GetName();

virtual bool GetSettings(SModuleSettings **pSettings, int *iCount) {
return false;
};

private:
ModuleID_t m_iID;
int m_iType;

const char *m_szName;
};


Which inherits from....



namespace Dasher {
class CEvent;
class CEventHandler;
class CDasherComponent;

};

/// \ingroup Core
/// @{
class Dasher::CDasherComponent {
public:
CDasherComponent(Dasher::CEventHandler* pEventHandler, CSettingsStore* pSettingsStore);
virtual ~CDasherComponent();

void InsertEvent(Dasher::CEvent * pEvent);

virtual void HandleEvent(Dasher::CEvent * pEvent) {};

bool GetBoolParameter(int iParameter) const;
void SetBoolParameter(int iParameter, bool bValue) const;

long GetLongParameter(int iParameter) const;
void SetLongParameter(int iParameter, long lValue) const;

std::string GetStringParameter(int iParameter) const;
void SetStringParameter(int iParameter, const std::string & sValue) const;


ParameterType GetParameterType(int iParameter) const;
std::string GetParameterName(int iParameter) const;

protected:
Dasher::CEventHandler *m_pEventHandler;
CSettingsStore *m_pSettingsStore;
};
/// @}



#endif

Answer



So, I've figured out the issue and it was a combination of bad logic and not being totally familiar with the automake/autotools world. I was adding the correct files to my Makefile.am template, but I wasn't sure which step in our build process actually created the makefile itself. So, I was compiling with an old makefile that had no idea about my new files whatsoever.



Thanks for the responses and the link to the GCC FAQ. I will be sure to read that to avoid this problem occurring for a real reason.


php - Trying to get property of non-object MySQLi result

Got a bit of PHP code I'm struggling with - had a search around Google etc. and tried everything mentioned, but for some reason I'm having trouble solving it.




The problem is:



I have some code that is querying a database for the presence of a particular user.



The code (it's a method inside a class)



global $mysqli;
// Query specified database for value

$q = 'SELECT id FROM ' . $database . ' WHERE username = \'' . $username . '\'';
$r = $mysqli->query($q);
var_dump($r);
if ($r->num_rows) {
// If row found username exists so return false
return false;
}
...
?>



I've var dumped the result of the query ($r) and got this:



object(mysqli_result)#4 (5) { ["current_field"]=> int(0) ["field_count"]=> int(1) ["lengths"]=> NULL ["num_rows"]=> int(1) ["type"]=> int(0) }


This is correct, there should only be 1 row as above.



I do get this error linking to the line saying if ($r->num_rows) {




Notice: Trying to get property of non-object in FILE on line LINE



but I don't know why since the object is valid (as above) and it should be working fine. From what I can tell it seems to be going through alright, I'm just wondering why there's an error. I'm sure it's something simple but I'd appreciate any help.

jquery - How can I add/remove a class to an element when URL contains a specific string?





I have some tabs:









home

content




And I would like to add a class to the tab, when my URL contains the string ?dir.



So for example: if my URL is www.mypage.com/?dir=something then #contenttab should be active. And if the URL is for example only
www.mypage.com
then #contenttab should not be active but #hometabshould be active.




    


My script is not working. #contenttabis always active and #hometab is never active.


Answer



Try checking with this :




if ( url.indexOf( '?dir' ) !== -1 ) { ... }


Or try with :



var url = location.search; // or location.href;

if ( url.indexOf( '?dir' ) !== -1 ) { ... }

character - What is J.J. LaRoche's dark secret? - Movies & TV



In the season 3 of The Mentalist, Patrick Jane threatens J.J. LaRoche to expose his secret if he doesn't give him his suspect list. LaRoche's secret is something he keeps in a tupperware in his safe. Jane actually bluffs since he knows only of the existence of the tupperware, but has apparently no idea of its actual content.



Later on, Jane says that whatever J.J. LaRoche's dark secret is, it must be horrible.




Is there any clue to what J.J. LaRoche's dark, horrible secret is?


Answer



In Laroche's Tupperware box is the tongue of the man who raped his mother for 2 hours straight, Scott Sanay(sp). The day before his trial, Laroche broke into his apartment while he slept, injected him with a sedative and cut out his tongue. According to the rapists mother Judith Sanay, "they never found his tongue."



Viewers find out in 21st episode of the 5th season (S05E21), "Red and Itchy."


php - Undefined property: CI_Loader::$input

I've just started to learn CodeIgniter and gotten trouble with example below:
My Controller:



class Site extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
function index()
{
$this->load->view('options_view');
}
function create()

{
$data = array (
'title' => $this->load->input->post('title'),
'content' => $this->load->input->post('content')
);
$this->site_model->add_record($data);
$this->index();
}
}


My Model is:

class Site_model extends CI_Model
{
function get_records()
{
$q = $this->db->get('articles');
return $q->result();
}
function add_record($data)

{
$this->db->insert('articles',$data);
return;
}
}


My view is:






















So when I click Submit button I get the error like:

Severity: Notice
Message: Undefined property: CI_Loader::$input

Filename: controllers/site.php
Line Number: 19



Any ideas will be usefull!Thanx!!

Plot two graphs in same plot in R



I would like to plot y1 and y2 in the same plot.




x  <- seq(-2, 2, 0.05)
y1 <- pnorm(x)
y2 <- pnorm(x, 1, 1)
plot(x, y1, type = "l", col = "red")
plot(x, y2, type = "l", col = "green")


But when I do it like this, they are not plotted in the same plot together.




In Matlab one can do hold on, but does anyone know how to do this in R?


Answer



lines() or points() will add to the existing graph, but will not create a new window. So you'd need to do



plot(x,y1,type="l",col="red")
lines(x,y2,col="green")

c++ - Installation of all OpenGL libraries for development in Ubuntu 11.10



I've got a just installed ubuntu 11.10.



I follow the first answer in this question. I installed:
freeglut3
freeglut3-dev



igor@ubuntu:~$ sudo apt-get install freeglut3
[sudo] password for igor:

Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
freeglut3
0 upgraded, 1 newly installed, 0 to remove and 253 not upgraded.
Need to get 77.5 kB of archives.
After this operation, 315 kB of additional disk space will be used.
Get:1 http://us.archive.ubuntu.com/ubuntu/ oneiric/main freeglut3 i386 2.6.0-1ubuntu2 [77.5 kB]
Fetched 77.5 kB in 0s (82.9 kB/s)

Selecting previously deselected package freeglut3.
(Reading database ... 125550 files and directories currently installed.)
Unpacking freeglut3 (from .../freeglut3_2.6.0-1ubuntu2_i386.deb) ...
Setting up freeglut3 (2.6.0-1ubuntu2) ...
Processing triggers for libc-bin ...
ldconfig deferred processing now taking place
igor@ubuntu:~$ sudo apt-get install freeglut3-dev
Reading package lists... Done
Building dependency tree
Reading state information... Done

The following extra packages will be installed:
libdrm-dev libgl1-mesa-dev libglu1-mesa-dev libice-dev libkms1
libpthread-stubs0 libpthread-stubs0-dev libsm-dev libx11-dev libxau-dev
libxcb1-dev libxdmcp-dev libxext-dev libxt-dev mesa-common-dev
x11proto-core-dev x11proto-input-dev x11proto-kb-dev x11proto-xext-dev
xorg-sgml-doctools xtrans-dev
The following NEW packages will be installed:
freeglut3-dev libdrm-dev libgl1-mesa-dev libglu1-mesa-dev libice-dev libkms1
libpthread-stubs0 libpthread-stubs0-dev libsm-dev libx11-dev libxau-dev
libxcb1-dev libxdmcp-dev libxext-dev libxt-dev mesa-common-dev

x11proto-core-dev x11proto-input-dev x11proto-kb-dev x11proto-xext-dev
xorg-sgml-doctools xtrans-dev
0 upgraded, 22 newly installed, 0 to remove and 253 not upgraded.
Need to get 5,673 kB of archives.
After this operation, 23.7 MB of additional disk space will be used.
Do you want to continue [Y/n]? Y
Get:1 http://us.archive.ubuntu.com/ubuntu/ oneiric/main libkms1 i386 2.4.26-1ubuntu1 [9,654 B]
Get:2 http://us.archive.ubuntu.com/ubuntu/ oneiric/main xorg-sgml-doctools i386 1:1.8-2 [10.9 kB]
Get:3 http://us.archive.ubuntu.com/ubuntu/ oneiric/main x11proto-core-dev i386 7.0.22-1 [299 kB]
Get:4 http://us.archive.ubuntu.com/ubuntu/ oneiric/main libxau-dev i386 1:1.0.6-3 [10.2 kB]

Get:5 http://us.archive.ubuntu.com/ubuntu/ oneiric/main libxdmcp-dev i386 1:1.1.0-3 [43.9 kB]
Get:6 http://us.archive.ubuntu.com/ubuntu/ oneiric/main x11proto-input-dev i386 2.0.2-2ubuntu1 [69.0 kB]
Get:7 http://us.archive.ubuntu.com/ubuntu/ oneiric/main x11proto-kb-dev i386 1.0.5-2 [27.6 kB]
Get:8 http://us.archive.ubuntu.com/ubuntu/ oneiric/main xtrans-dev i386 1.2.6-2 [82.9 kB]
Get:9 http://us.archive.ubuntu.com/ubuntu/ oneiric/main libpthread-stubs0 i386 0.3-2.1 [3,270 B]
Get:10 http://us.archive.ubuntu.com/ubuntu/ oneiric/main libpthread-stubs0-dev i386 0.3-2.1 [2,490 B]
Get:11 http://us.archive.ubuntu.com/ubuntu/ oneiric/main libxcb1-dev i386 1.7-3 [77.9 kB]
Get:12 http://us.archive.ubuntu.com/ubuntu/ oneiric/main libx11-dev i386 2:1.4.4-2ubuntu1 [3,252 kB]
Get:13 http://us.archive.ubuntu.com/ubuntu/ oneiric/main libdrm-dev i386 2.4.26-1ubuntu1 [123 kB]
Get:14 http://us.archive.ubuntu.com/ubuntu/ oneiric/main mesa-common-dev i386 7.11-0ubuntu3 [236 kB]

Get:15 http://us.archive.ubuntu.com/ubuntu/ oneiric/main x11proto-xext-dev i386 7.2.0-3 [253 kB]
Get:16 http://us.archive.ubuntu.com/ubuntu/ oneiric/main libxext-dev i386 2:1.3.0-3 [141 kB]
Get:17 http://us.archive.ubuntu.com/ubuntu/ oneiric/main libgl1-mesa-dev i386 7.11-0ubuntu3 [9,248 B]
Get:18 http://us.archive.ubuntu.com/ubuntu/ oneiric/main libglu1-mesa-dev i386 7.11-0ubuntu3 [189 kB]
Get:19 http://us.archive.ubuntu.com/ubuntu/ oneiric/main libice-dev i386 2:1.0.7-2 [128 kB]
Get:20 http://us.archive.ubuntu.com/ubuntu/ oneiric/main libsm-dev i386 2:1.2.0-2 [86.4 kB]
Get:21 http://us.archive.ubuntu.com/ubuntu/ oneiric/main libxt-dev i386 1:1.1.1-2 [472 kB]
Get:22 http://us.archive.ubuntu.com/ubuntu/ oneiric/main freeglut3-dev i386 2.6.0-1ubuntu2 [146 kB]
Fetched 5,673 kB in 16s (336 kB/s)
Selecting previously deselected package libkms1.

(Reading database ... 125555 files and directories currently installed.)
Unpacking libkms1 (from .../libkms1_2.4.26-1ubuntu1_i386.deb) ...
Selecting previously deselected package xorg-sgml-doctools.
Unpacking xorg-sgml-doctools (from .../xorg-sgml-doctools_1%3a1.8-2_i386.deb) ...
Selecting previously deselected package x11proto-core-dev.
Unpacking x11proto-core-dev (from .../x11proto-core-dev_7.0.22-1_i386.deb) ...
Selecting previously deselected package libxau-dev.
Unpacking libxau-dev (from .../libxau-dev_1%3a1.0.6-3_i386.deb) ...
Selecting previously deselected package libxdmcp-dev.
Unpacking libxdmcp-dev (from .../libxdmcp-dev_1%3a1.1.0-3_i386.deb) ...

Selecting previously deselected package x11proto-input-dev.
Unpacking x11proto-input-dev (from .../x11proto-input-dev_2.0.2-2ubuntu1_i386.deb) ...
Selecting previously deselected package x11proto-kb-dev.
Unpacking x11proto-kb-dev (from .../x11proto-kb-dev_1.0.5-2_i386.deb) ...
Selecting previously deselected package xtrans-dev.
Unpacking xtrans-dev (from .../xtrans-dev_1.2.6-2_i386.deb) ...
Selecting previously deselected package libpthread-stubs0.
Unpacking libpthread-stubs0 (from .../libpthread-stubs0_0.3-2.1_i386.deb) ...
Selecting previously deselected package libpthread-stubs0-dev.
Unpacking libpthread-stubs0-dev (from .../libpthread-stubs0-dev_0.3-2.1_i386.deb) ...

Selecting previously deselected package libxcb1-dev.
Unpacking libxcb1-dev (from .../libxcb1-dev_1.7-3_i386.deb) ...
Selecting previously deselected package libx11-dev.
Unpacking libx11-dev (from .../libx11-dev_2%3a1.4.4-2ubuntu1_i386.deb) ...
Selecting previously deselected package libdrm-dev.
Unpacking libdrm-dev (from .../libdrm-dev_2.4.26-1ubuntu1_i386.deb) ...
Selecting previously deselected package mesa-common-dev.
Unpacking mesa-common-dev (from .../mesa-common-dev_7.11-0ubuntu3_i386.deb) ...
Selecting previously deselected package x11proto-xext-dev.
Unpacking x11proto-xext-dev (from .../x11proto-xext-dev_7.2.0-3_i386.deb) ...

Selecting previously deselected package libxext-dev.
Unpacking libxext-dev (from .../libxext-dev_2%3a1.3.0-3_i386.deb) ...
Selecting previously deselected package libgl1-mesa-dev.
Unpacking libgl1-mesa-dev (from .../libgl1-mesa-dev_7.11-0ubuntu3_i386.deb) ...
Selecting previously deselected package libglu1-mesa-dev.
Unpacking libglu1-mesa-dev (from .../libglu1-mesa-dev_7.11-0ubuntu3_i386.deb) ...
Selecting previously deselected package libice-dev.
Unpacking libice-dev (from .../libice-dev_2%3a1.0.7-2_i386.deb) ...
Selecting previously deselected package libsm-dev.
Unpacking libsm-dev (from .../libsm-dev_2%3a1.2.0-2_i386.deb) ...

Selecting previously deselected package libxt-dev.
Unpacking libxt-dev (from .../libxt-dev_1%3a1.1.1-2_i386.deb) ...
Selecting previously deselected package freeglut3-dev.
Unpacking freeglut3-dev (from .../freeglut3-dev_2.6.0-1ubuntu2_i386.deb) ...
Processing triggers for man-db ...
Setting up libkms1 (2.4.26-1ubuntu1) ...
Setting up xorg-sgml-doctools (1:1.8-2) ...
Setting up x11proto-core-dev (7.0.22-1) ...
Setting up libxau-dev (1:1.0.6-3) ...
Setting up libxdmcp-dev (1:1.1.0-3) ...

Setting up x11proto-input-dev (2.0.2-2ubuntu1) ...
Setting up x11proto-kb-dev (1.0.5-2) ...
Setting up xtrans-dev (1.2.6-2) ...
Setting up libpthread-stubs0 (0.3-2.1) ...
Setting up libpthread-stubs0-dev (0.3-2.1) ...
Setting up libxcb1-dev (1.7-3) ...
Setting up libx11-dev (2:1.4.4-2ubuntu1) ...
Setting up libdrm-dev (2.4.26-1ubuntu1) ...
Setting up mesa-common-dev (7.11-0ubuntu3) ...
Setting up x11proto-xext-dev (7.2.0-3) ...

Setting up libxext-dev (2:1.3.0-3) ...
Setting up libgl1-mesa-dev (7.11-0ubuntu3) ...
Setting up libglu1-mesa-dev (7.11-0ubuntu3) ...
Setting up libice-dev (2:1.0.7-2) ...
Setting up libsm-dev (2:1.2.0-2) ...
Setting up libxt-dev (1:1.1.1-2) ...
Setting up freeglut3-dev (2.6.0-1ubuntu2) ...
Processing triggers for libc-bin ...
ldconfig deferred processing now taking place



Now i try to install libglew1.5 and libglew1.5-dev and etc.
but:



$ sudo apt-get install libglew1.5
Reading package lists... Done
Building dependency tree
Reading state information... Done
libglew1.5 is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 251 not upgraded.



I try to compile the example from this answer:



#include < GL/glew.h >
#include < GL/glut.h >
#include < GL/gl.h >
#include < GL/glu.h >
#include < GL/glext.h >


GLenum err = glewInit();
if (GLEW_OK != err)
{
fprintf(stderr, "Error %s\n", glewGetErrorString(err));
exit(1);
}
fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));

if (GLEW_ARB_vertex_program)
fprintf(stdout, "Status: ARB vertex programs available.\n");


if (glewGetExtension("GL_ARB_fragment_program"))
fprintf(stdout, "Status: ARB fragment programs available.\n");

if (glewIsSupported("GL_VERSION_1_4 GL_ARB_point_sprite"))
fprintf(stdout, "Status: ARB point sprites available.\n");


and compile error




$ g++ -lglut -lGL -lGLU -lGLEW example.cpp -o examp
example.cpp:1:23: fatal error: GL/glew.h : No such file or directory
compilation terminated.


enter image description here



Where i can find a normal tutorial for install opengl libs for development? Essential for OpenGL ES...


Answer



Remove the spaces inside the < > and it will compile. So instead of writing < GL/glew.h > write



JSON response parsing in Javascript to get key/value pair







How can I get the name and value of each object in Javascript only?

python - How do you remove duplicates from a list whilst preserving order?



Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:



def uniq(input):
output = []
for x in input:
if x not in output:
output.append(x)
return output



(Thanks to unwind for that code sample.)



But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.



Related question: In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique while preserving order?


Answer



Here you have some alternatives: http://www.peterbe.com/plog/uniqifiers-benchmark




Fastest one:



def f7(seq):
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]


Why assign seen.add to seen_add instead of just calling seen.add? Python is a dynamic language, and resolving seen.add each iteration is more costly than resolving a local variable. seen.add could have changed between iterations, and the runtime isn't smart enough to rule that out. To play it safe, it has to check the object each time.




If you plan on using this function a lot on the same dataset, perhaps you would be better off with an ordered set: http://code.activestate.com/recipes/528878/



O(1) insertion, deletion and member-check per operation.



(Small additional note: seen.add() always returns None, so the or above is there only as a way to attempt a set update, and not as an integral part of the logical test.)


'metalocalypse' tag wiki - Movies & TV



Metalocalypse is an American animated television series, created by Brendon Small and Tommy Blacha, which premiered on August 6, 2006 on Adult Swim. The television program centers around the larger than life death metal band Dethklok, and often portrays dark and macabre content, including such subjects as violence, death, and the drawbacks of fame, with extremely hyperbolic black humor; which accounts for the cartoon's consistent TV-MA rating.






There is no tag wiki for this tag … yet!



Tag wikis help introduce newcomers to the tag. They contain an overview of the topic defined by the tag, along with guidelines on its usage.




All registered users may propose new tag wikis.



(Note that if you have less than 20000 reputation, your tag wiki will be peer reviewed before it is published.)


Can Python be made statically typed?



I know that Python is mainly slower than languages like fortran and c/c++ because it is interpreted rather than compiled.



Another reason I have also read about is that it is quite slow because it is dynamically typed, i.e. you don't have to declare variable types and it does that automatically. This is very nice because it makes the code look much cleaner and you basically don't have to worry too much about variable types.



I know that there won't be a very good reason to do this as you can just wrap eg. fortran code with Python, but is it possible to manually override this dynamicly typed nature of Python and declare all variable types manually, and thus increasing Python's speed?


Answer




If I interpret your question as "Is there a statically-typed mode for Python?", then Cython probably comes closest to offering that functionality.



Cython is a superset of Python syntax - almost any valid Python code is also valid Cython code. The Cython compiler translates the quasi-Python source code to not-for-human-eyes C, which can then be compiled into a shared object and loaded as a Python module.



You can basically take your Python code and add as many or as few static type declarations as you like. Wherever types are undeclared, Cython will add in the necessary boilerplate to correctly infer them, at the cost of worse runtime performance. This essentially allows you to choose a point in the continuum between totally dynamically typed Python code and totally statically typed C code, depending on how much runtime performance you need and how much time you are prepared to spend optimizing. It also allows you to call C functions directly, making it a very convenient way to write Python bindings for external libraries.



To get a better idea of how this works in practice, take a look at the official tutorial.


Sunday 30 July 2017

r - How to concatenate strings in a specified order



Tried to concatenate strings diagonally from this post how to alternatively concatenate 3 strings, but was not successful.



My input is:



a<-c("a1","a2","a3")
b<-c("b1","b2","b3")
c<-c("c1","c2","c3")



My expected output would be



   "a1" "b2" "c3" "a2" "b3" "a3"


How to get the above from



  c(rbind(a,b,c))  


Answer



How about ordering the vector by values derived by the row and columns after setting the lower diagonal to missing



mat <- rbind(a,b,c)

mat[lower.tri(mat)] <- NA
na.omit(mat[order(col(mat) - row(mat))])

sql server - Clustered and non-clustered index

Interviewer asked me the difference between clustered and non-clustered index and than moved further into it and asked one more question - When a table has a clustered index and a non-clustered index, do the non-clustered index still points to the data row in the table? I said yes, and immediately I thought it is wrong. Does it points towards the data row that is ordered by clustered index or the original data rows? Can someone throw some light on this please.

reactjs - React - axios - blocked by CORS policy. How to unblock

I am running a simple API request to return data to a simple API search I've written. I say it's simple API call because there is no authentication needed and I can do it in python very simply.



However, I am having issues when using Axios in React.



Code:



 axios.get('https://www.keyforgegame.com/api/decks/59554ab7-b414-4220-8514-408a0dbf572d')



I've tried looking here and everyone one makes it sound so simple, but I can't seem to do anything. I've tried.



axios.get('https://www.keyforgegame.com/api/decks/59554ab7-b414-4220-8514-408a0dbf572d', { crossDomain: true })


and



axios.get('https://www.keyforgegame.com/api/decks/59554ab7-b414-4220-8514-408a0dbf572d, {
headers: {

'Access-Control-Allow-Origin': true,
},
})


But I keep getting errors like
Access to XMLHttpRequest at 'https://www.keyforgegame.com/api/decks/59554ab7-b414-4220-8514-408a0dbf572d' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.



or




Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.



Do I need to put something in the header to make this work? Or is this some kind of setting I need to make in react.



Help!

apache - How do I redirect domain.com to WWW.domain.com under Django?



How do I go about redirecting all requests for domain.com/... to www.domain.com/... with a 301 in a django site?




Obviously this can't be done in urls.py because you only get the path part of the URL in there.



I can't use mod rewrite in .htaccess, because .htaccess files do nothing under Django (I think).



I'm guessing something in middleware or apache conf?



I'm running Django on a Linux server with Plesk, using mod WSGI


Answer



The WebFaction discussion someone pointed out is correct as far as the configuration, you just have to apply it yourself rather than through a control panel.




RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule (.*) http://www.example.com/$1 [R=301,L]


Put in .htaccess file, or in main Apache configuration in appropriate context. If inside of a VirtualHost in main Apache configuration, your would have ServerName be www.example.com and ServerAlias be example.com to ensure that virtual host handled both requests.



If you don't have access to any Apache configuration, if need be, it can be done using a WSGI wrapper around the Django WSGI application entry point. Something like:




import django.core.handlers.wsgi
_application = django.core.handlers.wsgi.WSGIHandler()

def application(environ, start_response):
if environ['HTTP_HOST'] != 'www.example.com':
start_response('301 Redirect', [('Location', 'http://www.example.com/'),])
return []
return _application(environ, start_response)



Fixing this up to include the URL within the site and dealing with https is left as an exercise for the reader. :-)


in java awt or swing, how can I arrange for keyboard input to go wherever the mouse is?

Answer


Answer




Working on a help system, I'd like each component to offer some help when the the mouse is over it and the "?" key is pressed. Sort of like tooltips, except with much more extensive help - essentially a little web browser is intended to pop up and display text, images or more.



What I'm finding is that no matter where the mouse is, the input always goes to the same KeyListener. Is there only supposed to be one active at a time?



For what it's worth, this is the now-working version - thanks for suggestions!





/**
* Main class JavaHelp wants to support a help function so that when
* the user types F1 above a component, it creates a popup explaining
* the component.
* The full version is intended to be a big brother to tooltips, invoking
* an HTML display with clickable links, embedded images, and the like.
*/


import javax.swing.*;

import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

class Respond2Key extends AbstractAction
{

Component jrp;

// Contract consructor
public Respond2Key( String text)
{
super( text );
}

// Constructor that makes sure it gets done right
public Respond2Key( String text, Component jrpIn)

{
super( text );
System.out.println( "creating Respond2Key with component " + jrpIn
.toString
() );
jrp = jrpIn;
}

public void setJrp( Component j) {
jrp = j;

}


// Functionality: what is the response to a key
public void actionPerformed(ActionEvent e)
{
// use MouseInfo to get position, convert to pane coords, lookup component
Point sloc = MouseInfo.getPointerInfo().getLocation();

SwingUtilities.convertPointFromScreen( sloc, (Component) jrp );


Component c = jrp.getComponentAt( sloc );
System.out.printf( "Mouse at %5.2f,%5.2f Component under mouse is %s\n",
sloc.getX(), sloc.getY(), c.toString() );
}
}


//----------------------------------------------------------------
// The main class

//----------------------------------------------------------------
public class JavaHelp extends JFrame
{
// The object constructor
public JavaHelp()
{
// Start construction
super( "Help System" );
this.setSize( 640, 480 );
Container contents = getContentPane();

contents.setLayout( new FlowLayout() );


JButton b1 = butt( "button1", 64, 48 );
JButton b2 = butt( "button2", 96, 48 );
JButton b3 = butt( "button3", 128, 48 );
JPanel p1 = pane( "hello", 100, 100 );
JPanel p2 = pane( "world", 200, 100 );

contents.add( b1 );

contents.add( p1 );
contents.add( b2 );
contents.add( p2 );
contents.add( b3 );

JRootPane jrp = this.getRootPane();
jrp.getInputMap( jrp.WHEN_IN_FOCUSED_WINDOW)
.put( KeyStroke.getKeyStroke( "F1" ), "helpAction" );
jrp.getActionMap().put( "helpAction",
new Respond2Key("frame",(Component)contents)

);
this.setVisible( true );
this.requestFocus();
this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

}

// Inner classes for instantiating and listening to button, and panel.
class ButtonListener implements ActionListener
{

private String label = null;

public void setLabel(String s) {label = s;}

public void actionPerformed(ActionEvent e)
{
System.out.printf( "Dealing with event labeled %s source %s\n\n",
label,
e.getSource().toString() );
}


}

// def butt( from, name, w, h) = new Jbutton (...)
protected JButton butt( String s, int w, int h)
{
JButton b = new JButton( s );
b.setSize( w, h );
ButtonListener oj = new ButtonListener();
oj.setLabel( s );

b.addActionListener( oj );
return (b);
}

// def pane = new Jpanel(...)
protected JPanel pane(String name, int w, int h)
{
JPanel p = new JPanel();
p.setMinimumSize( new Dimension( w, h ) );
p.add( new Label( name ) );

p.setBackground( Color.black );
p.setForeground( Color.red );
return (p);
}

//--------------------------------
public static void main(String[] args)
{
JavaHelp jh = new JavaHelp();
}




}







Answer




the input always goes to the same KeyListener.




A KeyEvent is always dispatched to the component with focus, the mouse location has nothing to do with how the key event is generated.



Instead of using a KeyListener, you should be using Key Bindings. When you using Key Bindings you can invoke an Action whenever a KeyStroke is generated by adding the binding to the root pane of the JFrame. Read the section from the Swing tutorial on Key Bindings for more information.



Now in the Action that you create to listen for the "?" KeyStroke you can then:





  1. use the MouseInfo class to get the current mouse location.

  2. use the SwingUtilities.convertPointFromScreen(...) to convert the mouse point to be relative to the root pane

  3. then you can use the Conatiner.getComponentAt(...) to get the actual component the mouse is over

  4. once you know the component you can display your help information.


javascript - Passing HTML5 Local Storage Value to PHP error




I am using html5 local storage and I am trying to read it and pass it to a php variable:




This is the code:



$myphpvar = ""; 


When I do this:



echo $myphpvar;



The value looks right (at leave visually)



Upto there all looks good BUT when I add this code:



$sql="INSERT INTO `pending` (`id`, `myfield`) VALUES ('', '$myphpvar')";


I then get this error:




Error: 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 ..



The error points here:



$myphpvar = "";


Any ideas why?


Answer



Updated :




This doesn't Work because :



$myphpvar = ""; 


Now your PHP $myphpvar variable contains :



  



when you echo then this is like :



echo ""


so this will show your Js variable,because it runs on your browser.



but when you do this in SQL : it look something like below :




$sql="INSERT INTO `pending` (`id`, `myfield`) VALUES ('', '')";


For Achieving this, you have to pass your localStorage value to URL,and get it on PHP or use AJAX to post!



window.location.href = window.location.href+"?local="+localStorage.getItem('myjsvar'));

Each line an element in an array when reading text file in Python

When reading the text file, I'm using:



import io

with io.open('MasterList.txt', encoding='latin-1') as myfile:
data=myfile.read().replace('\n', '')


But printing something like data[0] gives me the first character instead of the first line. How can I make data be a list where each element is a line from the text file? Each line ends in \n. Do I have to somehow use that as the marker of where a new line begins?

python - PyPy significantly slower than CPython



I've been testing a cacheing system of my making. Its purpose is to speed up a Django web application. It stores everything in-memory. According to cProfile most of the time in my tests is spent inside QuerySet._clone() which turns out to be terribly inefficient (it's actually not that strange given the implementation).



I was having high hopes for using PyPy to speed things up. I've got a 64-bit machine. However after installing all the required libraries it turns out that PyPy compiled code runs about 2.5x slower than regular Python code, and I don't know what to make out of it. The code is CPU bound (there are absolutely no database queries, so IO-bounding is not an option). A single test runs for about 10 seconds, so I guess it should be enough for JIT to kick in. I'm using PyPy 1.5. One note - I didn't compile the sources myself, just downloaded a 64-bit linux version.



I'd like to know how frequent it is for a CPU intensive code to actually run slower under PyPy. Is there hopefully something wrong I could have done that would prevent PyPy from running at its best.




EDIT



Exact cPython output:



PyPy 1.5:



    3439146 function calls (3218654 primitive calls) in 19.094 seconds

Ordered by: cumulative time


ncalls tottime percall cumtime percall filename:lineno(function)
2/1 0.000 0.000 18.956 18.956 :1()
2/1 0.000 0.000 18.956 18.956 /path/to/my/project/common/integrity/models/transactions.py:200(newfn)
2/1 0.000 0.000 18.956 18.956 /path/to/my/project/common/integrity/models/transactions.py:134(recur)
2/1 0.000 0.000 18.956 18.956 /usr/local/pypy/site-packages/django/db/transaction.py:210(inner)
2/1 0.172 0.086 18.899 18.899 /path/to/my/project/common/integrity/tests/optimization.py:369(func_cached)
9990 0.122 0.000 18.632 0.002 /usr/local/pypy/site-packages/django/db/models/manager.py:131(get)
9990 0.127 0.000 16.638 0.002 /path/to/my/project/common/integrity/models/cache.py:1068(get)
9990 0.073 0.000 12.478 0.001 /usr/local/pypy/site-packages/django/db/models/query.py:547(filter)
9990 0.263 0.000 12.405 0.001 /path/to/my/project/common/integrity/models/cache.py:1047(_filter_or_exclude)

9990 0.226 0.000 12.096 0.001 /usr/local/pypy/site-packages/django/db/models/query.py:561(_filter_or_exclude)
9990 0.187 0.000 8.383 0.001 /path/to/my/project/common/integrity/models/cache.py:765(_clone)
9990 0.212 0.000 7.662 0.001 /usr/local/pypy/site-packages/django/db/models/query.py:772(_clone)
9990 1.025 0.000 7.125 0.001 /usr/local/pypy/site-packages/django/db/models/sql/query.py:226(clone)
129942/49972 1.674 0.000 6.021 0.000 /usr/local/pypy/lib-python/2.7/copy.py:145(deepcopy)
140575/110605 0.120 0.000 4.066 0.000 {len}
9990 0.182 0.000 3.972 0.000 /usr/local/pypy/site-packages/django/db/models/query.py:74(__len__)
19980 0.260 0.000 3.777 0.000 /path/to/my/project/common/integrity/models/cache.py:1062(iterator)
9990 0.255 0.000 3.154 0.000 /usr/local/pypy/site-packages/django/db/models/sql/query.py:1149(add_q)
9990 0.210 0.000 3.073 0.000 /path/to/my/project/common/integrity/models/cache.py:973(_query)

9990 0.371 0.000 2.316 0.000 /usr/local/pypy/site-packages/django/db/models/sql/query.py:997(add_filter)
9990 0.364 0.000 2.168 0.000 /path/to/my/project/common/integrity/models/cache.py:892(_deduct)
29974/9994 0.448 0.000 2.078 0.000 /usr/local/pypy/lib-python/2.7/copy.py:234(_deepcopy_tuple)
19990 0.362 0.000 2.065 0.000 /path/to/my/project/common/integrity/models/cache.py:566(__init__)
10000 0.086 0.000 1.874 0.000 /path/to/my/project/common/integrity/models/cache.py:1090(get_query_set)
19990 0.269 0.000 1.703 0.000 /usr/local/pypy/site-packages/django/db/models/query.py:31(__init__)
9990 0.122 0.000 1.643 0.000 /path/to/my/project/common/integrity/models/cache.py:836(_deduct_recur)
19980 0.274 0.000 1.636 0.000 /usr/local/pypy/site-packages/django/utils/tree.py:55(__deepcopy__)
9990 0.607 0.000 1.458 0.000 /path/to/my/project/common/integrity/models/cache.py:789(_deduct_local)
10020 0.633 0.000 1.437 0.000 /usr/local/pypy/site-packages/django/db/models/sql/query.py:99(__init__)

129942 0.841 0.000 1.191 0.000 /usr/local/pypy/lib-python/2.7/copy.py:267(_keep_alive)
9994/9992 0.201 0.000 1.019 0.000 /usr/local/pypy/lib-python/2.7/copy.py:306(_reconstruct)


Python 2.7:



   3326403 function calls (3206359 primitive calls) in 12.430 CPU seconds

Ordered by: cumulative time


ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 12.457 12.457 :1()
1 0.000 0.000 12.457 12.457 /path/to/my/project/common/integrity/models/transactions.py:200(newfn)
1 0.000 0.000 12.457 12.457 /path/to/my/project/common/integrity/models/transactions.py:134(recur)
1 0.000 0.000 12.457 12.457 /usr/local/lib/python2.7/dist-packages/django/db/transaction.py:210(inner)
1 0.000 0.000 12.457 12.457 /path/to/my/project/common/integrity/models/transactions.py:165(recur2)
1 0.089 0.089 12.450 12.450 /path/to/my/project/common/integrity/tests/optimization.py:369(func_cached)
9990 0.198 0.000 12.269 0.001 /usr/local/lib/python2.7/dist-packages/django/db/models/manager.py:131(get)
9990 0.087 0.000 11.281 0.001 /path/to/my/project/common/integrity/models/cache.py:1068(get)
9990 0.040 0.000 8.161 0.001 /usr/local/lib/python2.7/dist-packages/django/db/models/query.py:547(filter)

9990 0.110 0.000 8.121 0.001 /path/to/my/project/common/integrity/models/cache.py:1047(_filter_or_exclude)
9990 0.127 0.000 7.983 0.001 /usr/local/lib/python2.7/dist-packages/django/db/models/query.py:561(_filter_or_exclude)
9990 0.100 0.000 5.593 0.001 /path/to/my/project/common/integrity/models/cache.py:765(_clone)
9990 0.122 0.000 5.125 0.001 /usr/local/lib/python2.7/dist-packages/django/db/models/query.py:772(_clone)
9990 0.405 0.000 4.899 0.000 /usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py:226(clone)
129942/49972 1.456 0.000 4.505 0.000 /usr/lib/python2.7/copy.py:145(deepcopy)
129899/99929 0.191 0.000 3.117 0.000 {len}
9990 0.111 0.000 2.968 0.000 /usr/local/lib/python2.7/dist-packages/django/db/models/query.py:74(__len__)
19980 0.070 0.000 2.843 0.000 /path/to/my/project/common/integrity/models/cache.py:1062(iterator)
9990 0.208 0.000 2.190 0.000 /path/to/my/project/common/integrity/models/cache.py:973(_query)

9990 0.182 0.000 2.114 0.000 /usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py:1149(add_q)
19984/9994 0.291 0.000 1.644 0.000 /usr/lib/python2.7/copy.py:234(_deepcopy_tuple)
9990 0.288 0.000 1.599 0.000 /usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py:997(add_filter)
9990 0.171 0.000 1.454 0.000 /path/to/my/project/common/integrity/models/cache.py:892(_deduct)
19980 0.177 0.000 1.208 0.000 /usr/local/lib/python2.7/dist-packages/django/utils/tree.py:55(__deepcopy__)
9990 0.099 0.000 1.199 0.000 /path/to/my/project/common/integrity/models/cache.py:836(_deduct_recur)
9990 0.349 0.000 1.040 0.000 /path/to/my/project/common/integrity/models/cache.py:789(_deduct_local)

Answer



Brushing aside the fact that PyPy might really be intrinsically slower for your case, there are some factors that could be making it unnecessarily slower:





  • Profiling is known to slow PyPy a lot more than CPython.

  • Some debugging/logging code can disable optimizations (by, e.g., forcing frames).

  • The server you're using can be a dominant factor in performance (think about how awful classic CGI would be with a JIT: it would never warm up). It can also simply influence results (different WSGI servers have shown various speed-ups).

  • Old-style classes are slower than new-style ones.

  • Even if everything is in memory, you could be hitting e.g. slow paths in PyPy's SQLite.



You can also check the JIT Friendliness wiki page for more hints about what can make PyPy slower. A nightly build will probably be faster too, as there are many improvements relative to 1.5.




A more detailed description of your stack (server, OS, DB) and setup (how did you benchmark? how many queries?) would allow us to give better answers.


What does "->" do in PHP?




I am studying how to connect database while learning PHP. Just a quick question. Does anyone can tell me what does "->" sign do in PHP? I cannot understand the functionality of this sign so that I have no idea how to edit the code. Thank whoever answer this.



Answer



For real quick and dirty one-liner anonymous objects, just cast an associative array:




$obj = (object) array('foo' => 'bar', 'property' => 'value');

echo $obj->foo; // prints 'bar'
echo $obj->property; // prints 'value'


?>


... no need to create a new class or function to accomplish it.


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

?>

python - Why is it string.join(list) instead of list.join(string)?



This has always confused me. It seems like this would be nicer:



my_list = ["Hello", "world"]
print(my_list.join("-"))
# Produce: "Hello-world"



Than this:



my_list = ["Hello", "world"]
print("-".join(my_list))
# Produce: "Hello-world"


Is there a specific reason it is like this?


Answer




It's because any iterable can be joined, not just lists, but the result and the "joiner" are always strings.



For example:



import urllib2
print('\n############\n'.join(
urllib2.urlopen('http://data.stackexchange.com/users/7095')))

javascript - jQuery Deferred not calling the resolve/done callbacks in order

Answer


Answer




Code example: http://jsfiddle.net/MhEPw/1/



I have two jQuery Deferred objects.




I want to have more than one 'async' request happening - and after they all run I want the callbacks (the .done functions) to be run in order they were specified in. Unfortunately they don't run in order.



Maybe I am looking for some functionality here that Deferred doesn't provide?


Answer



What you need to do is link all of your request with one master deferred object and register all of your callbacks on its promise. The master deferred object would need to listen to the individual requests and resolve accordingly. The simplest way to achieve this would be to define all of the deferred objects up front to avoid the chicken and egg problem:



var d1 = $.Deferred();
var d2 = $.Deferred();
var def = $.when(d1, d2);


def.done(function() {
alert(1);
});
setTimeout(function() {
d1.resolve();
}, 3000);

def.done(function() {
alert(2);
});

setTimeout(function() {
d2.resolve();
}, 1000);


Fiddle: http://jsfiddle.net/pVVad/



Changing the order of deferred objects definitions is possible but it would make the example much more complicated.


mysqli - PHP : Fatal error: Call to a member function fetch_assoc() on boolean

I have this code :



$sql = "SELECT * FROM trading 
WHERE order_status <> 'DELETE'
ORDER BY date DESC
LIMIT 2";
$result = $conn->query($sql);


while($row = $result->fetch_assoc()) { << LINE 96

if ($row["type"] == 'BUY') {
---- CODE CUT HERE ----


and it gives me this error message :



Fatal error: Call to a member function fetch_assoc() on boolean in /**/**.php on line 96



why this line 96 :



while($row = $result->fetch_assoc()) {


produce that error message?

php - Remove escape character from Jquery Post




To my issue there are several similar questions but I haven't found a good one that would help me solve my problem. My problem is:



I want to convert a JQuery object into a Json String, and then post this string to a PHP webPage, This is running very good. But when I received it on the server(php page) it is full of escape characters.



Here is my code on the client:



var jsonRemision =  JSON.stringify(remision,false); 

$.post("updateremision.php",

{
rem:jsonRemision,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: false,
},

function(data,status){
if(status=="success"){
alert("Good Message");

}else{
alert("Bad Message");
}
});


and here is the code on the server:



$remision = json_decode($_POST['rem']);



Now, when I see whats inside of $_POST['rem'] is full of escape characters \" . These escape character are not allowing me to jsondecode... The json full of escape characters looks like this:



{\"id\":\"12\",\"fecha\":\"2014-06-25\",\"ciudad\":\"Manizales\",\"camion\":\"NAQ376\",\"driver\":\"16075519\",\"cant\":\"0\",\"anticipos\":[{\"type\":\"1\",\"com\":\"Comment\",\"costo\":\"1234\"}]}


How can I remove the escape characters ?? thanks in advance for any comment or help :)


Answer



I actually just recently had the same issue.




I fixed it by using stripslashes();



This should work ok unless you actually do have slashes in the data.



var_export(json_decode(stripslashes('{\"id\":\"12\",\"fecha\":\"2014-06-25\",\"ciudad\":\"Manizales\",\"camion\":\"NAQ376\",\"driver\":\"16075519\",\"cant\":\"0\",\"anticipos\":[{\"type\":\"1\",\"com\":\"Comment\",\"costo\":\"1234\"}]}'), true));


outputs:



array (

'id' => '12',
'fecha' => '2014-06-25',
'ciudad' => 'Manizales',
'camion' => 'NAQ376',
'driver' => '16075519',
'cant' => '0',
'anticipos' =>
array (
0 =>
array (

'type' => '1',
'com' => 'Comment',
'costo' => '1234',
),
),
)

pointers - c++ solution fails on leetcode with misaligned address error but runs in visual studio



i'm new to C++ so i'm trying some leetcode problems. i'm currently attempting the min stack problem. i think i've solved it correctly, except i get the following runtime error from leetcode:




Line 24: Char 37: runtime error: member access within misaligned address 0xbebebebebebebebe for type 'struct ListNode', which requires 8 byte alignment (solution.cpp)


here is my visual studio code, with tests - the error originates from the following line in push():



                topStackNode->stackPrev = newNode;


anyone know what would cause this to happen? i read a bit and some people with similar errors say its because ListNode is not initialized to NULL, but i clearly initialize all ListNodes to NULL in my struct. thanks!




#include 
#include
using namespace std;
// design a stack that supports push, pop, top, and retrieving the minimum element in constant time


class MinStack {

struct ListNode {

ListNode* stackNext;
ListNode* stackPrev;
ListNode* minNext;
ListNode* minPrev;
int val;
ListNode(int v) : val(v), stackNext(NULL), stackPrev(NULL), minNext(NULL), minPrev(NULL)
{
}
};


public:
/** initialize your data structure here. */
MinStack() {}

void push(int x) {

ListNode* newNode = new ListNode(x);

if (topStackNode == NULL)
topStackNode = newNode;

else {
topStackNode->stackPrev = newNode;
newNode->stackNext = topStackNode;
topStackNode = newNode;
}

insertNodeMinStack(newNode);
}

void pop() {

removeFromMinStack(topStackNode);
popFromStack();
}

void popFromStack() {
topStackNode = topStackNode->stackNext;
}

void removeFromMinStack(ListNode* node) { // delete the currently popped node from the min stack
if (node != NULL) {

if (node == topMinNode) {
topMinNode = node->minNext;
min = topMinNode->val;
return;
}
if (node->minPrev != NULL)
node->minPrev->minNext = node->minNext;
if (node->minNext != NULL)
node->minNext->minPrev = node->minPrev;
}


}

int top() {
if (topStackNode != NULL)
return topStackNode->val;
else
return NULL;
}


int getMin() {
return min;
}

void insertNodeMinStack(ListNode* node) {
if (topMinNode == NULL) { // inserting node on an empty list
topMinNode = node;
}
else if (node->val < topMinNode->val) { // node has smallest value
topMinNode->minPrev = node;

node->minNext = topMinNode;
topMinNode = node; // set new top min node and update min
min = node->val;
}
else {
ListNode* currentNode = topMinNode;
while (currentNode->minNext != NULL && currentNode->val < node->val) {
currentNode = currentNode->minNext;
}
if (currentNode->minNext == NULL) { // reached end of list, 'node' has largest value in list

currentNode->minNext = node;
node->minPrev = currentNode;
//min remains unchanged
}
else { // we're somewhere in the middle of the list, ie there are nodes surronding 'node'
node->minNext = currentNode->minNext;
node->minPrev = currentNode;
currentNode->minNext = node;
node->minNext->minPrev = node;
}

}
}

private:
int min;
ListNode* topStackNode;
ListNode* topMinNode;
};

int main() {//1,2,6,3,4,5,6

MinStack* ms = new MinStack();

ms->push(5);
ms->push(3);
ms->pop();
ms->push(10);
ms->push(-3);
ms->pop();
ms->pop();
ms->push(-11);


cout << "minstack min = " << ms->getMin() << endl;

}


EDIT - new solution below using shared pointers:



class MinStack {
struct ListNode {

shared_ptr prev;
shared_ptr next;
shared_ptr minNext;
shared_ptr minPrev;
int value;
ListNode(int val) : prev(nullptr), next(nullptr), minNext(nullptr), minPrev(nullptr), value(val) {}
};

public:


shared_ptr topn;
shared_ptr minTop;
shared_ptr node;

MinStack() : topn(nullptr), minTop(nullptr), node(nullptr){}

void push(int value) {

// cout << "pushing value " << value << endl;


if (topn == nullptr) {
topn = make_shared(value);
insertToMinList();
}
else {
node.reset();
node = make_shared(value);
node->next = topn;
topn = node;
insertToMinList();

}
}

void removeFromMinList() {
//removing the node topn from min list
if (topn->minNext != nullptr && topn->minPrev != nullptr) {
// cout << "removing, neither null, " << topn->value << endl;
topn->minNext->minPrev = topn->minPrev;
topn->minPrev->minNext = topn->minNext;
}

else if (topn->minNext != nullptr) {
// cout << "removing, next not null, " << topn->value << endl;
topn->minNext->minPrev = topn->minPrev;
}
else if (topn->minPrev != nullptr) {
// cout << " removing, prev not null, " << topn->value << endl;
topn->minPrev->minNext = topn->minNext;
}
else {
// cout << "no condition met in removign " << endl;

}
if (topn == minTop) {
minTop = topn->minNext;
}

}

void insertToMinList() {
if (minTop == nullptr) {
minTop = topn;

//cout << "min list null, initializing with " << topn->value << endl;
}
else if (topn->value <= minTop->value) {
//cout << "new value is smallest " << topn->value << endl;
minTop->minPrev = topn;
topn->minNext = minTop;
minTop = topn;
}
else {
//cout << "searching list to place value " << topn->value << endl;

shared_ptr temp = make_shared(minTop->value);
temp->minNext = minTop->minNext;

while (temp != nullptr && temp->value < topn->value) { //go down the list
topn->minNext = temp->minNext;
topn->minPrev = temp;
temp = temp->minNext;
}
//while loop completes. now, temp is either nullptr or between two nodes
if (temp == nullptr) {// new value is largest

//cout << "reached end of list, assigning value " << topn->value << endl;
topn->minPrev->minNext = topn;
topn->minNext = nullptr;
}
else { // between two nodes, reassign prev and next
//cout << "in middle of list, assigning vale " << topn->value << endl;
topn->minNext->minPrev = topn;
topn->minPrev->minNext = topn;
}
}

}

void pop() {

//cout << "popping value " << topn->value << endl;
removeFromMinList();
topn = topn->next;


}


int top(){
return topn->value;
}

int getMin() {
return minTop->value;
}
};


Answer



You are not initializing all your class members.



MinStack has members:



int min;
ListNode* topStackNode;
ListNode* topMinNode;



Your constructor for MinStack does not have any member initializer list and doesn't set any of the members:



MinStack() {}


You are using this constructor to construct an object here:



MinStack* ms = new MinStack();



Since the members of MinStack are not declared with any any default initializers specified and the constructor does not provide any initializers for them, they will be default-initialized. Since they are non-class types default-initialization means that no initialization will be performed. The members will keep their indeterminate values.



Then in the next line:



ms->push(5); 


you call push which executes:



if (topStackNode == NULL)



This has undefined behavior, because topStackNode has indeterminate value.






Initialize all your members in the constructor's initializer list or with default member initializers in the class definition:



int min = 0;
ListNode* topStackNode = nullptr;

ListNode* topMinNode = nullptr;


or equivalently:



int min{};
ListNode* topStackNode{};
ListNode* topMinNode{};






Also enable warnings on your compiler.



It will warn you that the initalizer list of ListNode's constructor is not in the same order as the member declarations. It is important that they are in the same order, because the order of initialization is the order of the declarations, not the order of the member initializers. In order to avoid accidentally using an uninitialized member, you should always keep the initializer list order consistent with the member declaration order.



It will also tell you that you are misusing NULL. You are using it as return value for top() which returns int. It is not guaranteed that NULL can be cast to an integer. NULL should only be used to represent a pointer. And since C++11 NULL should not be used at all. Instead use nullptr, which would have given you a proper error that returning it from int top() doesn't make sense.







Also avoid using new. It is not exception-safe, will cause you memory leaks, requires special care to be taken that copy operations of classes are implemented correctly (look up "rule of 0/3/5") and will cause you many headaches.



The new use in main is completely pointless. You can just declare the object directly as variable:



int main() {//1,2,6,3,4,5,6
MinStack ms;

ms.push(5);
ms.push(3);
ms.pop();

ms.push(10);
ms.push(-3);
ms.pop();
ms.pop();
ms.push(-11);

cout << "minstack min = " << ms.getMin() << endl;

}



The new use and use of raw owning pointers in the class can probably also be replaced with std::unique_ptr and std::make_unique. Your class is currently leaking its memory allocations and will likely cause undefined behavior if an instance of it is ever copied (explicitly or implicitly). That would not be a concern when using std::unique_ptr.


Saturday 29 July 2017

string - How to trim whitespace from a Bash variable?

I have a shell script with this code:



var=`hg st -R "$path"`
if [ -n "$var" ]; then

echo $var
fi


But the conditional code always executes, because hg st always prints at least one newline character.




  • Is there a simple way to strip whitespace from $var (like trim() in PHP)?




or




  • Is there a standard way of dealing with this issue?



I could use sed or AWK, but I'd like to think there is a more elegant solution to this problem.

c++ - Why should I use a pointer rather than the object itself?



I'm coming from a Java background and have started working with objects in C++. But one thing that occurred to me is that people often use pointers to objects rather than the objects themselves, for example this declaration:



Object *myObject = new Object;


rather than:



Object myObject;



Or instead of using a function, let's say testFunc(), like this:



myObject.testFunc();


we have to write:



myObject->testFunc();



But I can't figure out why should we do it this way. I would assume it has to do with efficiency and speed since we get direct access to the memory address. Am I right?


Answer



It's very unfortunate that you see dynamic allocation so often. That just shows how many bad C++ programmers there are.



In a sense, you have two questions bundled up into one. The first is when should we use dynamic allocation (using new)? The second is when should we use pointers?



The important take-home message is that you should always use the appropriate tool for the job. In almost all situations, there is something more appropriate and safer than performing manual dynamic allocation and/or using raw pointers.




Dynamic allocation



In your question, you've demonstrated two ways of creating an object. The main difference is the storage duration of the object. When doing Object myObject; within a block, the object is created with automatic storage duration, which means it will be destroyed automatically when it goes out of scope. When you do new Object(), the object has dynamic storage duration, which means it stays alive until you explicitly delete it. You should only use dynamic storage duration when you need it.
That is, you should always prefer creating objects with automatic storage duration when you can.



The main two situations in which you might require dynamic allocation:




  1. You need the object to outlive the current scope - that specific object at that specific memory location, not a copy of it. If you're okay with copying/moving the object (most of the time you should be), you should prefer an automatic object.

  2. You need to allocate a lot of memory, which may easily fill up the stack. It would be nice if we didn't have to concern ourselves with this (most of the time you shouldn't have to), as it's really outside the purview of C++, but unfortunately, we have to deal with the reality of the systems we're developing for.




When you do absolutely require dynamic allocation, you should encapsulate it in a smart pointer or some other type that performs RAII (like the standard containers). Smart pointers provide ownership semantics of dynamically allocated objects. Take a look at std::unique_ptr and std::shared_ptr, for example. If you use them appropriately, you can almost entirely avoid performing your own memory management (see the Rule of Zero).



Pointers



However, there are other more general uses for raw pointers beyond dynamic allocation, but most have alternatives that you should prefer. As before, always prefer the alternatives unless you really need pointers.




  1. You need reference semantics. Sometimes you want to pass an object using a pointer (regardless of how it was allocated) because you want the function to which you're passing it to have access that that specific object (not a copy of it). However, in most situations, you should prefer reference types to pointers, because this is specifically what they're designed for. Note this is not necessarily about extending the lifetime of the object beyond the current scope, as in situation 1 above. As before, if you're okay with passing a copy of the object, you don't need reference semantics.



  2. You need polymorphism. You can only call functions polymorphically (that is, according to the dynamic type of an object) through a pointer or reference to the object. If that's the behavior you need, then you need to use pointers or references. Again, references should be preferred.


  3. You want to represent that an object is optional by allowing a nullptr to be passed when the object is being omitted. If it's an argument, you should prefer to use default arguments or function overloads. Otherwise, you should preferably use a type that encapsulates this behavior, such as std::optional (introduced in C++17 - with earlier C++ standards, use boost::optional).


  4. You want to decouple compilation units to improve compilation time. The useful property of a pointer is that you only require a forward declaration of the pointed-to type (to actually use the object, you'll need a definition). This allows you to decouple parts of your compilation process, which may significantly improve compilation time. See the Pimpl idiom.


  5. You need to interface with a C library or a C-style library. At this point, you're forced to use raw pointers. The best thing you can do is make sure you only let your raw pointers loose at the last possible moment. You can get a raw pointer from a smart pointer, for example, by using its get member function. If a library performs some allocation for you which it expects you to deallocate via a handle, you can often wrap the handle up in a smart pointer with a custom deleter that will deallocate the object appropriately.



How to output MySQL query results in csv format in Windows environment?



Is there an easy way to run a MySQL query from the PowerShell command line and output the results into a csv formatted file?




This question is the same as How to output MySQL query results in CSV format? except in Windows. I had to figure it out in PowerShell but my answer didn't belong on the linux question. So here's the Windows+PowerShell sibling.


Answer



Stan's answer from How to output MySQL query results in CSV format?, adapted for Windows PowerShell



mysql my_database_name -u root | Out-File .\my_output_file.csv


This gives me a mysql prompt, but without the usual mysql > at the start. I type:




source C:\Aboslute\Path\With Spac es\Without\Quotes\To\my_select_statement.sql


It gives an error message and exits if there is a problem with the command, or gives me the empty prompt if the command executed successfully. I type exit to finish up.


oop - Is there a use-case for singletons with database access in PHP?



I access my MySQL database via PDO. I'm setting up access to the database, and my first attempt was to use the following:



The first thing I thought of is global:



$db = new PDO('mysql:host=127.0.0.1;dbname=toto', 'root', 'pwd');


function some_function() {
global $db;
$db->query('...');
}


This is considered a bad practice. After a little search, I ended up with the Singleton pattern, which





"applies to situations in which there needs to be a single instance of a class."




According to the example in the manual, we should do this:



class Database {
private static $instance, $db;

private function __construct(){}


static function singleton() {
if(!isset(self::$instance))
self::$instance = new __CLASS__;

return self:$instance;
}

function get() {
if(!isset(self::$db))
self::$db = new PDO('mysql:host=127.0.0.1;dbname=toto', 'user', 'pwd')


return self::$db;
}
}

function some_function() {
$db = Database::singleton();
$db->get()->query('...');
}


some_function();


Why do I need that relatively large class when I can do this?



class Database {
private static $db;

private function __construct(){}


static function get() {
if(!isset(self::$db))
self::$db = new PDO('mysql:host=127.0.0.1;dbname=toto', 'user', 'pwd');

return self::$db;
}
}

function some_function() {
Database::get()->query('...');

}

some_function();


This last one works perfectly and I don't need to worry about $db anymore.



How can I create a smaller singleton class, or is there a use-case for singletons that I'm missing in PHP?


Answer



Okay, I wondered over that one for a while when I first started my career. Implemented it different ways and came up with two reasons to choose not to use static classes, but they are pretty big ones.




One is that you will find that very often something that you are absolutely sure that you'll never have more than one instance of, you eventually have a second. You may end up with a second monitor, a second database, a second server--whatever.



When this happens, if you have used a static class you're in for a much worse refactor than if you had used a singleton. A singleton is an iffy pattern in itself, but it converts fairly easily to an intelligent factory pattern--can even be converted to use dependency injection without too much trouble. For instance, if your singleton is gotten through getInstance(), you can pretty easily change that to getInstance(databaseName) and allow for multiple databases--no other code changes.



The second issue is testing (And honestly, this is the same as the first issue). Sometimes you want to replace your database with a mock database. In effect this is a second instance of the database object. This is much harder to do with static classes than it is with a singleton, you only have to mock out the getInstance() method, not every single method in a static class (which in some languages can be very difficult).



It really comes down to habits--and when people say "Globals" are bad, they have very good reasons to say so, but it may not always be obvious until you've hit the problem yourself.



The best thing you can do is ask (like you did) then make a choice and observe the ramifications of your decision. Having the knowledge to interpret your code's evolution over time is much more important than doing it right in the first place.



c++ - how to solve the middle block problem(consider edge blocks and leave any block in the middle of row)



I need to solve this algorithm problem. In the diagram, there are many rows with different no. of blocks. Each block is either good or bad. The block with no. 1 on it is good block and rest are all bad. I need to do the grouping of these blocks in 2 in order to find whether the resultant of these groupings is good or bad. If I make a group of 2 , I will check if all the blocks are having '1' on it. If yes, then the resultant block is good, otherwise bad.



Problem: while doing groupings of blocks, I always have to consider the blocks that are on the edges. If the row has odd number of blocks(lets say 9) and I'm making group of 2, then the middle block(5th block) has to be ignored, the blocks on the edges should get preference with respect to middle block. I don't know how to solve the problem as I'm confused with the part of ignoring the middle block in case of odd no. of blocks.It can ignore any block(near to middle block) but have to consider the blocks on the edges.



So basically, First I need to find if the row has odd/even no.of blocks according to the groupsize which is 2. Then if odd no. of blocks are here, leave the middle one and make a group with blocks on edges and find the result if the resultant is good or bad.



In the inputs, I have the X and Y co-ordinate of each and every block and its information as the block is good or bad.




enter image description here


Answer



It seems like throwing away the exact middle block isn't a good solution. With a row of size 7, you should be able to make 3 pairs, but if you discard the center one, you'll only get two pairs usable.



Try taking blocks from both ends alternately: A pair from the left, then a pair from the right, then the next pair inward from the left. When your two pointers (or indexes) cross in the middle, you're done with the row. When necessary you'll discard a block as near to the middle as possible, and you won't need any special case for even vs odd.


mysql - Question mark characters on HTML if I use UTF-8 and weird characters on SQL data if I use ISO-8859-1





I'm making a page with latin accents like á, ã, ç, and others. This site pulls data from a SQL database. I'm using this on the :

With this header the HTML accented characters are fine, but the SQL data is being displayed as çãinstead of ão, and if I change the charset from ISO-8859-1 to UTF-8, all the HTML accented characters are displayed by a � (question mark) and the SQL data shows accents just fine.
Is there any way to fix it besides escaping either all the HTML characters or the SQL ones?



PS: I've already tried mysql_set_charset('utf8'); and SET NAMES utf8, neither worked to me.


Answer



When you see question marks, your document has not been stored in the correct encoding (should be UTF-8 in your case) or it isn't being served with the correct headers and/or meta tags.



If you want to work with special characters like è, your html document should be saved as UTF-8 and served as UTF-8:







Additionally, you have to use UTF-8 for your database connections:




…("SET NAMES utf8");
…("SET CHARACTER SET utf8");




And last but not least, you have to use UTF-8 for the database itself.



As you'll notice, you're already on the correct path… you just have to "use it all" (as I described above) instead of trying one thing at a time and ignoring the rest. It's the combination that makes it work. Simpler said: if you go "UTF-8", you will have to think "UTF-8" everywhere and stick to it in your html files, your headers, your meta tags, your database connections, and the database(s). Use the same encoding everywhere and stick to it, instead of using "a bit UTF-8 here and a bit ISO-whatever there".



c++ - ofstream is open, but does not write




I'm attempting to write data to a file using ofstream, but even though the stream is open, the files are being created (the folder has already been created), there are "endl"s or "\n"s are the end of every line, and I'm flushing the file, the text does not display in any text editor.



Here is the basis of the code:



#include 
#include
#include

int main(int argc, char ** argv) {


ofstream outputData;
stringstream stringFix;
char fileBase[150] = "./Output/outputData";
stringFix << time(NULL) << ".txt";
outputData.open(strcat(fileBase, stringFix.str().c_str()));

outputData.open(fileBase);

assert(outputData.is_open());


while (...) {
//Some data is written to the stream, similar in format to:
outputData << "Trump: " << trumpSuit << endl;
}

outputData.flush();
outputData.close();

cout << "Should have written successfully..." << endl;


}


I've seemingly tried every variation--both with the flushing and without, with "endl"s and "\n"s... For reference, trumpSuit is an enum, and so it should print out an integer, as it previously did when I used cout.



Does anyone have any insight on to what I'm forgetting?


Answer



You are opening your stream twice



char fileBase[150] = "./Output/outputData";

stringFix << time(NULL) << ".txt";
outputData.open(strcat(fileBase, stringFix.str().c_str()));

outputData.open(fileBase); // <<<<< second open here


All you write operations will output to the file named ./Output/outputData and not to ./Output/outputData.txt as I assume you have expected.



The 1st open() will create the file, but it's left empty.


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...