Sunday, 1 September 2019

c# - how variables are stored on stack?



I've read that there are two regions of memory one stack and other heap. Basic data types like int, double, float etc. are stored on stack while reference types are stored on heap. As we know that stack is LIFO that means last element pushed will be removed first. now assuming following code



int first = 10;
double second = 20.0;
float third = 3.0F;



so, first will be pushed first, then second and then third. so variable third which is of type float will be on top of the stack but if I use following code (assuming in C#)



Console.WriteLine(second);


how value of variable second will be accessed while variable third is on top of the stack?


Answer



Stack behaves as LIFO with PUSH and POP insturctions.But that doesnt mean without pop you can read the stack memory .
In your case

you



        push int first            (* its not a opcode of machine, just trying to explain)
push double second
push float third

Now you have 2 options to access the variables that you have pushed.

1) pop -> This is the one that reads and makes stack look like lifo.
if you pop it

stack will be
int first
double second.
Bsically it removes(not exactly,just a register is chaged to show the stacks last valid memory position)

2) But if you want you can jst read it without pop.Thus not removing the last times.
So you will say Read me double.And it will access the same way it does in heaps..
That will cause machine to execute a mov instruction .

Please note its EBP(Base pointer) and ESP(Stack pointer) that points to the location of a stacks variables.And machines read variables as mov eax,[ebp+2(distance of "second" from where base pointer is now pointing]].


Printing value of pointer in a vector of pointer c++

here is my code:



vector *ptr;
int *tab = new int(20);

ptr->push_back(tab);
cout << *(ptr->at(0)) << endl;


I want to print 20 on the screen, but I got a segmentation fault.
when I use only



vector ptr;



it prints out fine. I get easily the result just by doing :



*ptr.at(0);


But I want to use a pointer not a simple variable.
Can I have some enlightenment?



Thanks

swing - Java JFRAME button then new gui





So, I try to make a Java Program, that when you run it, the first screen will be welcome, under it button "login", under it "register". And now I need to figure how if I press one of these buttons, how can I call new GUI, which I will define somewhere. (e.g) i call register button and it calls new gui where is normal things that asks you when you register(login,email,pass,date of birth)



EDIT: problem solved, but there is a one more thing. How can I close the first window?



This is my code so far:



import javax.swing.*;
import java.awt.*;
import java.awt.GridLayout;
import java.awt.BorderLayout;

import javax.swing.BorderFactory;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.util.*;
import javax.swing.JFrame;
import java.awt.Dimension;
public class Gui extends JFrame
{
private JLabel lab1,lab2;

private JButton butt1,butt2;
private JPanel p1,p2;
public static void main(String[] args)
{
Gui okno = new Gui();
//vytáhne z defaultního monitoru width a height
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int width = (int) screenSize.getWidth();
int height = (int) screenSize.getHeight();
//velikost okna

Dimension appSize = new Dimension(210,250);
okno.setPreferredSize(appSize);
//nastavení na stred
okno.setLocation((width/2)-105,(height/2)-125);
okno.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
okno.setVisible(true);
//okno.setLocationRelativeTo(null); todle dá do středu obrazovky jen první body x a y od kterejch se to odvíjí
okno.setResizable(false);
okno.pack();


}

public Gui(){
super("Jméno hry vole");
setLayout(new BorderLayout(20,20));
/////////////////////////////////////////////////////////////////
// p1
p1 = new JPanel();
add(p1,BorderLayout.NORTH);
lab1 = new JLabel("Welcome",SwingConstants.CENTER); //centr labelu

lab2 = new JLabel("Created by DECHKR",SwingConstants.CENTER); //centr labelu
lab1.setFont(new Font("Serif", Font.PLAIN, 36)); //velikost fontu
p1.add(lab1);
//p2
p2 = new JPanel(new GridLayout(2,1,0,5));
add(p2,BorderLayout.SOUTH);

Dimension d = new Dimension(210,75);
butt1 = new JButton("Login");
butt1.setPreferredSize(d);

butt2 = new JButton("Register");
butt2.setPreferredSize(d);
p2.add(butt1);
p2.add(butt2);


butt1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
//Gui okno = new Gui();
//System.exit(0); endne celej jvm proces




}

});

butt2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){



}

});
}

Answer



I am still learning, but want to try and help.I would try making a new JFrame in the actionPerformed method of the listener. I also would probably make separate classes for your button action listeners otherwise you won't be able to perform separate task. I.E.



 class button1Listener implements ActionListener {

public void actionPerformed(ActionEvent ev){
JFrame frame = new JFrame();
(ETC CODE...)
}
}

php - Unexpected character in input: '' (ASCII=92) state=1

My client says he is getting this error using my script:



Warning: Unexpected character in input: '\' (ASCII=92) state=1 in /path/to//header.php  on line 34
Parse error: syntax error, unexpected T_STRING, expecting T_CONSTANT_ENCAPSED_STRING or '(' in/path/to/header.php on line 34


The line 34 in header.php is just use \Main\Class;




Now, I told him he has to have PHP >= 5.3.0 and he says his PHP version is 5.3.24



What could be the problem?



EDIT: The lines before and after



30. // Define absolute path
31. define("ABSPATH", $abs_path);
32. $_SESSION["abs_path"] = ABSPATH;

33.
34. use \CNS\main\CNS;
35. $cns = new CNS();


EDIT 2:



He sent me this:



Program     Version

Apache: 2.2.24
CentOS: CentOS release 6.4 (Final)
cPanel: 11.36.1 (build 8)
Curl: 7.12.1
MySQL 5.5.30
phpMyAdmin 3.5.5
Python: 2.6.6
Program Version
Perl: 5.8.8
**PHP: 5.3.24**

ionCube Loader: 4.2.2
Zend Optimizer: 3.3.9
Ruby: 1.8.7
Rails: 3.2.8
OpenSSL: 1.0.0-fips

angularjs - Can ngRoute support non-configured links?



I am trying to fix up an existing implementation, however I can't do it all at once. Is there anyway I can get ngRoute, even if it's a hack, to support old links that expect to make a direct request?



Here's what I mean, we have three links in this weird example TODO App:



Home
New Task
Complete Task



"Home" and "New Task" should use the angular ngRoute, making it nice and snappy. My other links, such as "Complete" would need to work like they always have, the full round trip.



Initially I configured ngRoute with this:



angular.module('TodoApp', [
// Angular modules
'ngRoute'
// Custom modules


// 3rd Party Modules
]).config(['$locationProvider', '$routeProvider',
function config($locationProvider, $routeProvider) {
$routeProvider.when('/', {
templateUrl: 'Templates/index.html',
controller: 'TodoController'
})
.when('/Home/AddItem', {
templateUrl: 'Templates/AddItem.html',

controller: 'AddItemController'
});
// Otherwise, continue to the link like normal.
$locationProvider.html5Mode(true);
}
]);


However that won't work, so far, here's the full list of options that I've tried:




Don't configure otherwise



This only gave me a blank page as ngRoute is blocking the browser from making an http request.



Hide/Show view div



I've tried configuring the router to hide or show the divs based on what url is being rendered, this almost works. I can go to a bookmarked page and it will render, but I can't navigate through the website via clicking an link. I get the same blank page because ngRoute blocked it again.



Configure otherwise




I tried a "NoView" controller, doesn't work. Also found that if I put this code in



redirectTo: function() {
return undefined;
}


I can get it to at least render without errors, but again ngRoute blocks the browser from making an http request.



Disable ngRoute




I tried detecting when the configured path is being used, only then would I enable angular. While there are errors in the console at least it works for bookmarked links. Again though, once it becomes enabled ngRoute will start blocking links while clicking around the site. You'll start to see blank pages instead.



I would try the alternative angular-ui-route, but I don't know if it supports this case. Routing seems to be all or nothing. Are there any hacks to get around this or another framework that supports this case?



There's a lot of links so I would like to leave them alone and only enable new features until we can go back and fix up the old ones.



Final Approach



Adding for those who are curious, I ended up merging one of my attempts with Horst Jahns answer. Basically it looks like this:




var angularConfigs = [
// Set all configs here, routing will be conditionally added later.
// Angular modules

// Custom modules

// 3rd Party Modules
];


var routeSettings = [{
entry: '/',
template: 'Templates/index.html',
controller: 'TodoController'
}, {
entry: '/Home/AddItem',
template: 'Templates/AddItem.html',
controller: 'AddItemController'
}
];


// Check current url matches routes being registered. If so enable routing.
var enableRotues = false;
for (var i = 0; i < routeSettings.length; i++) {
if (routeSettings[i].entry === window.location.pathname) {
enableRotues = true;
break;
}
}


if (enableRotues) {
// Attach the module to existing configurations.
angularConfigs.push('ngRoute');
var todoApp = angular.module('TodoApp', angularConfigs);

todoApp.config([
'$locationProvider', '$routeProvider',
function config($locationProvider, $routeProvider) {
var provider = $routeProvider;


// Go through each setting and configure the route provider.
for (var i = 0; i < routeSettings.length; i++) {
var route = routeSettings[i];

provider = provider.when(route.entry,
{
templateUrl: route.template,
controller: route.controller
});
}


// This enables links without hashes, gracefully degrades.
$locationProvider.html5Mode(true);
}
]);

// This directive will disable routing on all links NOT
// marked with 'data-routing-enabled="true"'.
todoApp.directive('a', function() {
return {

restrict: 'E',
link: function(scope, element, attrs) {
if (attrs.routingEnabled) {
// Utilize the ngRoute framework.
} else {
// Disable ngRoute so pages continue to load like normal.
element.bind('click', function(event) {
if (!scope.enabled) {
event.preventDefault();
window.location.href = attrs.href;

}
});
}
}
};
});
} else {
// In this case we still want angular to properly be stood
// up and register controllers in my case for backward
// compatibility.

angular.module('TodoApp', angularConfigs);
}

Answer



You could write a directive and set it on all the links, which are not configured.



Angular



app.directive('nonConfig', function() {
return {

restrict: 'A',
link: function(scope, element, attrs) {
element.bind('click', function(event) {
if(!scope.enabled) {
event.preventDefault();
window.location.href = attrs.href;
}
});
}
};

});


HTML



test

php - The second argument to copy() function cannot be a directory



Anyone know why this:



$title = trim($_POST['title']);
$description = trim($_POST['description']);


// Array of allowed image file formats
$allowedExtensions = array('jpeg', 'jpg', 'jfif', 'png', 'gif', 'bmp');

foreach ($_FILES as $file) {
if ($file['tmp_name'] > '') {
if (!in_array(end(explode(".",
strtolower($file['name']))),
$allowedExtensions)) {
echo '
Invalid file type.
';
}

}
}

if (strlen($title) < 3)
echo '
Too short title
';
else if (strlen($description) > 70)
echo '
Too long desccription.
';

else {
move_uploaded_file($_FILES['userfile']['tmp_name'], 'c:\wamp\www\uploads\images/');

}


Gives:



Warning: move_uploaded_file() [function.move-uploaded-file]: The second argument to copy() function cannot be a directory in C:\wamp\www\upload.php on line 41


Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\wamp\tmp\php1AB.tmp' to 'c:\wamp\www\uploads\images/' in C:\wamp\www\upload.php on line 41

Answer



It's because you're moving a file and it thinks you're trying to rename that file to the second parameter (in this case a director).




it should be:



move_uploaded_file($_FILES['userfile']['tmp_name'], 'c:/wamp/www/uploads/images/'.$file['name']);

mysql - mysql_connect in php 5.6 +

I was using PHP 5.4 in Godaddy Hosting. I have one PHP script which was working fine in it. Now I have changed Hosting and New Hosting company Provide PHP 5.6. I do not PHP coding. I am getting error in my script as below



Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /home4/z4g9f1v6/public_html/mydomain.com/folder/config.php on line 7



My Configure file is like below


$mysql_hostname = "localhost";
$mysql_user = "dbuser";
$mysql_password = "dbpass";
$mysql_database = "dbname";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");

and I am using it in my Search.php like below


include("config.php");
if($_SERVER["REQUEST_METHOD"] == "POST")
{
mysql_query('SET character_set_results=utf8');
mysql_query('SET names=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_results=utf8');
mysql_query('SET collation_connection=utf8_general_ci');
$q=$_POST['q'];
$q=mysql_escape_string($q);
$q_fix=str_replace(" ","%",$q); // Space replacing with %
$sql=mysql_query("SELECT qu_text FROM quotes WHERE qu_text LIKE '%$q%'");
}while($row=mysql_fetch_array($sql)){$title=$row['qu_text'];

Please help me. How can I solve the issue ?


Thanks

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...