Documentation for the topic is sparse and it's hard to discover an "entry-point" there.
lundi 27 juin 2016
He.net JavaScript browser challenge [on hold]
Anyone have this JavaScript challenge?
http://bgp.he.net/ip/66.249.0.0
It's a javascript challenge that checks if js is enabled then show the content,like also cloudflare browser challenge..
Inconsistency in assigning pointer start array address [on hold]
Hi all, I posted an image above
Please explain this to me, this is from website tutorialspoint.
Thanks
http://www.tutorialspoint.com/cprogramming/c_pointer_arithmetic.htm
Code is here, can somebody post it for me
What is the JavaScript equivalent of ImportXML?
What is the JavaScript equivalent of ImportXML?
Have a Google spreadsheet of 10,000 rows that each contain a city and state. To find their zip code, neither the ImportXML formula nor LibreOffice's FilterXML have worked.
Function that returns array in C. What's wrong?
#include <stdio.h>
#include <stdlib.h>
int* create_array( int n)
{
int *reverse_sorted_array = malloc (n * sizeof(int));
int i;
for (i = 0; i < n; i++)
{
reverse_sorted_array[i] = (n-i);
}
return reverse_sorted_array;
}
}
int main() {
printf("%d", create_array(v, 20)[0]);
return 0;
}
The function "create array" should return a reverse sorted array and the main function should print "19" (the first term of the reverse sorted array). However, it prints "0".
Heroku php and nodejs in the same app
I'm using a node package called exec-php to execute php functions within nodejs app.
I would like to push that app to Heroku, but I'm wondering how to make that and how would be the PHP bin locally i'm using /Applications/MAMP/bin/php/php7.0.0/bin/php what would be the path to php bin in Heroku
I tested vendor/bin/heroku-php-apache2 but it doesn't work, so what would be the path to php binary in heroku
Check if a string contain multiple specific words
How to check, if a string contain multiple specific words?
I can check single words using following code:
$data = "text text text text text text text bad text text naughty";
if (strpos($data, 'bad') !== false) {
echo 'true';
}
But, I want to add more words to check. Something like this:
$data = "text text text text text text text bad text text naughty";
if (strpos($data, 'bad || naughty') !== false) {
echo 'true';
}
?>
(if any of these words is found then it should return true)
But, above code does not work correctly. Any idea, what I'm doing wrong?
Why time complexity of following code is O(n^2)?
void level_order_recursive(struct node *t , int h) //'h' is height of my binary tree
{ //'t' is address of root node
for(int i = 0 ; i <= h ; i++)
{
print_level(t , i);
}
}
After print_level() is called everytime , I think recursive function is called (2^i) times . So 2^0 + 2^1 + 2^2 ....2^h should give time complexity of O(2^n).Where am I going wrong ?
void print_level(struct node * t , int i)
{
if( i == 0)
cout << t -> data <<" ";
else
{
if(t -> left != NULL)
print_level(t -> left , i - 1); //recursive call
if(t -> right != NULL)
print_level(t -> right , i - 1); //recursive call
}
}
MapboxGL set visibility based on property from data loaded from file
I am trying to follow an example posted at https://www.mapbox.com/mapbox-gl-js/example/filter-markers/, however in my case, the GeoJSON data is loaded from an external file:
map.on('load', function() {
map.addSource("cacheData", {
type: "geojson",
data: "./data.geojson",
If I'm following the example, I don't seem to have access to the 'markers' variable to iterate through and add each marker to a layer.
In the original version of Mapbox.js, I am able to enable / disable an individual feature .. I don't seem to be able to do that the same way in mapboxGL.
Is there an event or something I can use to possibly modify the data as it's being loaded to add each marker from the file to a layer?
Rename the files while uploading
I am trying to rename the files while uploading, but it's not renaming as I expected. Just want to add the date and the time front of the name.
Attaching the code below.
if(isset($_FILES['img_ct_1'])){
$today = date("Ymd");
//prepare url
$temp_path = CDN_URL.'photos/';
$name_array = $_FILES['img_ct_1']['name'];
$tmp_name_array = $_FILES['img_ct_1']['tmp_name'];
$type_array = $_FILES['img_ct_1']['type'];
$size_array = $_FILES['img_ct_1']['size'];
$error_array = $_FILES['img_ct_1']['error'];
$upload_dir = $_SERVER['DOCUMENT_ROOT'].'/photos/';
for($i = 0; $i < count($tmp_name_array); $i++){
if(move_uploaded_file($tmp_name_array[$i],$upload_dir.time().$name_array[$i])){
print_r ($name_array[$i]);
$array['path'] = $temp_path.$newfilename;
$array['success'] = true ;
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}
}
Change the title of website (controlled through angular router and ui router) being displayed in google search
I am currently building out an angular 1.5 website through ui router where the title on the webpage changes with a controller depending on what page a user is on. The HTML looks like this
<title ng-controller="pageTitle">Red Vase | {{ page }}</title>
and the controller code is this
angular.module('redvase')
.controller('pageTitle', function($scope, $state, $rootScope) {
$rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
$scope.current = toState.name;
if ($scope.current === "home") {
$scope.page = "Home"
} else if ($scope.current === "inspire") {
$scope.page = "Inspire Others"
} else if ($scope.current === "inspireShop") {
$scope.page = "Inspired Living Store"
} else if ($scope.current === "blog") {
$scope.page = "Blog"
} else if ($scope.current === "contactus") {
$scope.page = "Contact Us"
} else {
$scope.page = "Home"
}
})
})
When searching for the website in Chrome, the autofill history comes up as "myredvase.com - Red Vase | {{ page }}" instead of "myredvase.com - Red Vase | Home".
Can anyone suggest away to make Chrome display "myredvase.com - Red Vase | Home" despite the title tag containing the {{ page }} expression? I have been scratching my head on this one.
Thank you!
Inline assembly that clobbers the red zone
I'm writing a cryptography program, and the core (a wide multiply routine) is written in x86-64 assembly, both for speed and because it extensively uses instructions like adc that are not easily accessible from C. I don't want to inline this function, because it's big and it's called several times in the inner loop.
Ideally I would also like to define a custom calling convention for this function, because internally it uses all the registers (except rsp), doesn't clobber its arguments, and returns in registers. Right now, it's adapted to the C calling convention, but of course this makes it slower (by about 10%).
To avoid this, I can call it with asm("call %Pn" : ... : my_function... : "cc", all the registers); but is there a way to tell GCC that the call instruction messes with the stack? Otherwise GCC will just put all those registers in the red zone, and the top one will get clobbered. I can compile the whole module with -mno-red-zone, but I'd prefer a way to tell GCC that, say, the top 8 bytes of the red zone will be clobbered so that it won't put anything there.
Call to undefined function session_start()
I'm trying to start a session with php, but I always get this error:
Fatal error: Call to undefined function session_start() in /www/test/test.php on line 2
My Code (Copied form http://php.net/manual/en/session.examples.basic.php):
<?php
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
?>
In my php.ini I got extension=session.so . Further, my settings in session section are:
[Session]
session.save_handler = files
session.save_path = "/tmp"
session.use_cookies = 1
;session.cookie_secure =
session.use_only_cookies = 1
session.name = PHPSESSID
session.auto_start = 0
session.cookie_lifetime = 0
session.cookie_path = /
session.cookie_domain =
session.cookie_httponly =
session.serialize_handler = php
session.gc_probability = 1
session.gc_divisor = 100
session.gc_maxlifetime = 1440
session.bug_compat_42 = On
session.bug_compat_warn = On
session.referer_check =
session.entropy_length = 0
;session.entropy_file = /dev/urandom
session.entropy_file =
;session.entropy_length = 16
session.cache_limiter = nocache
session.cache_expire = 180
session.use_trans_sid = 0
session.hash_function = 0
session.hash_bits_per_character = 4
url_rewriter.tags = "a=href,area=href,frame=src,input=src,form=,fieldset="
I'm using PHP Version 5.4.17. The server is running on an Arduino Yun (Linux).
Anyone can help me, or give ma a hint? :)
Thanks!
php check to see if variable is integer
Is there a nicer way to do this?
if( $_POST['id'] != (integer)$_POST['id'] )
echo 'not a integer';
I've tried
if( !is_int($_POST['id']) )
But is_int() doesn't work for some reason.
My form looks like this
<form method="post">
<input type="text" name="id">
</form>
I've researched is_int(), and it seems that if
is_int('23'); // would return false (not what I want)
is_int(23); // would return true
I've also tried is_numeric()
is_numeric('23'); // return true
is_numeric(23); // return true
is_numeric('23.3'); // also returns true (not what I want)
it seems that the only way to do this is: [this is a bad way, do not do it, see note below]
if( '23' == (integer)'23' ) // return true
if( 23 == (integer)23 ) // return true
if( 23.3 == (integer)23.3 ) // return false
if( '23.3' == (integer)'23.3') // return false
But is there a function to do the above ?
Just to clarify, I want the following results
23 // return true
'23' // return true
22.3 // return false
'23.3' // return false
Note: I just figured out my previous solution that I presented will return true for all strings. (thanks redreggae)
$var = 'hello';
if( $var != (integer)$var )
echo 'not a integer';
// will return true! So this doesn't work either.
This is not a duplicate of Checking if a variable is an integer in PHP, because my requirements/definitions of integer is different than theres.
JQuery confirmation dialog after AJAX request
I need to validate, on server side, if a person with a given registration number is already on the database. If this person is already registered, then I proceed with the program flow normally. But, if the number is not already registered, then I'd like to show a confirmation dialog asking if the operator wants to register a new person with the number entered and, if the operator answers yes, then the person will be registered with the number informed on the form on it's submission.
I've tried
Server side(PHP):
if (!$exists_person) {
$resp['success'] = false;
$resp['msg'] = 'Do you want to register a new person?';
echo json_encode($resp);
}
Client side:
function submit(){
var data = $('#myForm').serialize();
$.ajax({
type: 'POST'
,dataType: 'json'
,url: 'myPHP.php'
,async: 'true'
,data: data
,error: function(response){
alert('response');
}
});
return false;
}
I can't even see the alert, that's where I wanted to put my confirmation dialog, with the message written on server side. Other problem, how do I resubmit the entire form appended with the operator's answer, so the server can check if the answer was yes to register this new person?
EDIT
I was able to solve the problem this way:
Server side(PHP):
$person = find($_POST['regNo']);
if ($_POST['register_new'] === 'false' && !$person) {
$resp['exists'] = false;
$resp['msg'] = 'Do you want to register a new person?';
die(json_encode($resp)); //send response to AJAX request on the client side
} else if ($_POST['register_new'] === 'true' && !$person) {
//register new person
$person = find($_POST['regNo']);
}
if($person){
//proceed normal program flow
}
Client side:
function submit(e) {
e.preventDefault();
var data = $('#myForm').serialize();
var ajax1 = $.ajax({
type: 'POST'
, dataType: 'json'
, async: 'true'
, url: 'myPHP.php'
, data: data
, success: function (response) {
if (!response.exists && confirm(response.msg)) {
document.getElementById('register_new').value = 'true'; //hidden input
dados = $('#myForm').serialize(); //reserialize with new data
var ajax2 = $.ajax({
type: 'POST'
, dataType: 'json'
, async: 'true'
, url: 'myPHP.php'
, data: data
, success: function () {
document.getElementById('register_new').value = 'false';
$('#myForm').unbind('submit').submit();
}
});
} else if (response.success) {
alert(response.msg);
$('#myForm').unbind('submit').submit();
}
}
});
}
Imagick extension shows on phpinfo but shows error unable to load dynamic library when running simple php command in command prompt
Successfully install imagick into my system and able to loaded imagick extentsion (appears in phpinfo) but when running simple php command, such as php -v in my command prompt, it shows error
PHP Warning: PHP Startup: Unable to load dynamic library '[MY_SERVER_PATH]PHPextphp_imagick.dll' - The specified module could not be found.
My system info as follows:
- OS: Windows 10 Pro 64Bit
- PHP: 5.6.19
- ImageMagick: ImageMagick-6.9.4-10-Q16-x64-dll
- PHP Imagick: php_imagick-3.3.0-5.6-ts-vc11-x64
My Error screenshot... I run print_r( get_loaded_extensions() ); and the result is:
Array ( [0] => Core 1 => bcmath [2] => calendar [3] => ctype [4] => date [5] => ereg [6] => filter [7] => ftp [8] => hash [9] => iconv [10] => json [11] => mcrypt [12] => SPL [13] => odbc [14] => pcre [15] => Reflection [16] => session [17] => standard [18] => mysqlnd [19] => tokenizer [20] => zip [21] => zlib [22] => libxml [23] => dom [24] => PDO [25] => openssl [26] => SimpleXML [27] => wddx [28] => xml [29] => xmlreader [30] => xmlwriter [31] => apache2handler [32] => curl [33] => fileinfo [34] => gd [35] => intl [36] => imap [37] => mbstring [38] => mysql [39] => mysqli [40] => Phar [41] => pdo_mysql [42] => soap [43] => xmlrpc [44] => imagick [45] => mhash )
I just dont understand why php command prompt always shows error.
P.S: I am not using any XAMPP or WAMPP packages...
update:
I wonder what extension that CLI loaded so i run a simple php script and this is the result:
D:>php -r "print_r( get_loaded_extensions() );"
Warning: PHP Startup: Unable to load dynamic library 'D:EricwebPHPextphp_imagick.dll' - The specified module coul
d not be found.
in Unknown on line 0
Array
(
[0] => Core
[1] => bcmath
[2] => calendar
[3] => ctype
[4] => date
[5] => ereg
[6] => filter
[7] => ftp
[8] => hash
[9] => iconv
[10] => json
[11] => mcrypt
[12] => SPL
[13] => odbc
[14] => pcre
[15] => Reflection
[16] => session
[17] => standard
[18] => mysqlnd
[19] => tokenizer
[20] => zip
[21] => zlib
[22] => libxml
[23] => dom
[24] => PDO
[25] => openssl
[26] => SimpleXML
[27] => wddx
[28] => xml
[29] => xmlreader
[30] => xmlwriter
[31] => curl
[32] => fileinfo
[33] => gd
[34] => intl
[35] => imap
[36] => mbstring
[37] => mysql
[38] => mysqli
[39] => Phar
[40] => pdo_mysql
[41] => soap
[42] => xmlrpc
[43] => mhash
)
How do I achieve a fully working image scrolling effect like in this example?
I just stumbled upon http://www.newego.de/ and would like to know how the "image slide effekt" they are using on the initial page is done.
When you scroll up the background image changes and after you went through all their "intro/welcome"-page slides you are guided to the main website content.
I tried replicating the effect out of curiosity and for learning purposes, hence I recently started digging into responsive webdesign, but I'm kind of stuck and not sure if my approach is a good solution.
This JSFiddle is how far I've come attempting to replicate the image slider.
$(window).bind('mousewheel DOMMouseScroll', function(event){
if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
console.log('scrolling down');
}
else {
console.log('scrolling up');
$('.s1').slideUp('slow');
}
});
* { margin: 0; padding: 0 }
#menubar {
width: 100%;
background-color: orange;
height: 60px;
}
.slide {
position: absolute;
width: 100%;
top: 60px;
bottom: 0;
}
.slide.s1 { background-color: green; }
.slide.s2 { background-color: red; }
.slide.s3 { background-color: cornflowerblue; }
.l1 { z-index: 3; }
.l2 { z-index: 2; }
.l3 { z-index: 1; }
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<html>
<body>
<header id="menubar"><p>hi im a header</p></header>
<section class="slide s1 l1"><p>im the first</p></section>
<section class="slide s2 l2"><p>im the second</p></section>
<section class="slide s3 l3"><p>im the third</p></section>
</body>
</html>
My thinking was to just put three .slide container which fill in the "empty viewport space" on top of each other, using a hierarchy of z-index and then just slide up the topmost .slide container using jQuery's .slideUp() function.
However, I'm not sure if that is a good aproach as I do not know how to select the topmost container to be able to fade it out.
Is there a more simple (and if possible more modular) approach that I should pursue? Is there an effective way (jQuery/CSS selector) to find the topmost .slide-layer that is currently visible?
Modifing RSS nodes in WordPress
I have been asked by my work to add a rel='nofollow' to the WordPress RSS feed on our site. Now the RSS feed already has the rel='nofollow' added to all the <a href> tags which is working fine. What they are really asking is to add the nofollow to the actual RSS node itself.
They basically want <link rel='nofollow'> instead of <link>
Would adding a nofollow at the node level actually do anything? I understand it working at the href level but it seems odd to do this here. If this does work as expected then using PHP how can I modify this node to add this namespace?
Here is an example of my RSS feed.
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
>
<channel>
<title>Article Title here</title>
<link>http://fakewebsiteurl.com</link>
<description>article description here</description>
<language>en-US</language>
<generator>https://wordpress.org/?v=4.5.2</generator>
<item>
<title>Test Article</title>
<link>http://fakewebsiteurl.com/news/test-article/</link>
<comments>http://fakewebsiteurl.com/news/test-article/#respond</comments>
<pubDate>Thu, 05 May 2016 18:16:50 +0000</pubDate>
<description><![CDATA[<p>Description text here</p>
<p>The post <a rel="nofollow" href="fakewebsiteurl.com/news/test-article/">Test Article</a> appeared here</p>
]]></description>
</item>
<item>
...
</item>
</channel>
I have a custom PHP page that modifies this RSS already but I am not sure if I need to replace the node completely or if there is a away to modify it directly. I was thinking of using str_replace but that did not work.
<?php
namespace X;
class RssFeed {
public function __construct() {
add_filter( 'the_content_feed', array( $this, 'add_nofollow_href' ) );
}
function add_nofollow_namespace($content) {
if (is_feed()) {
$link = '<link>';
$linkno = '<link rel="nofollow">';
$updated = str_replace($link, $linkno, $content);
return $updated;
}
}
}
?>
Thanks in advance. Code examples appreciated.
Laravel Input::all() fetching one row only
I have a form with a table example
Name | Review | Rating | Status
This table may have multiple rows and only Status is editable which is a dropdown field
I am able to show all the data, But when I save using code below, I notice that dd is only showing one row. When I save , one row is saved and then an error is displayed. Error:
ErrorException in DashBoardController.php line 432: Creating default object from empty value
where line number 432 is : $approved_reviews->approved= $status1
Below is my code snippet. Please help.
$approve_reviews = Input::except('_token');
foreach ($approve_reviews as $review_id) {
$approved_reviews = dealer_reviews::where('id',$review_id )->first();
$status1 = Input::get('status');
$approved_reviews->approved= $status1;
$approved_reviews->save();
}
I have also tried Input::all(), but dd shows just one row.
My Form Code
@if(isset($pending_reviews))
{!! Form::open(array('action' => array('DashBoardController@ApproveReviews' ), 'class'=>'form','files' => true,'data-toggle' => 'validator' ,'id'=>'edit_form')) !!}
<div class="table-responsive">
<table class="table table-hover table-condensed table-bordered">
<thead>
<tr class="danger">
<td>
<p style="font-weight:500;font-size:1.0em;"> Dealership Name </p>
</td>
<td>
<p style="font-weight:500;"> Review </p>
</td>
<td>
<p style="font-weight:500;"> Rating</p>
</td>
<td>
<p style="font-weight:500;"> Suggestion</p>
</td>
<td>
<p style="font-weight:500;"> Status </p>
</td>
<tr>
</thead>
@foreach($pending_reviews as $p_review)
<tr class="active">
<td>
<p style="font-weight:500;font-size:1.0em;"> {{$p_review-> dealership_name}} </p>
<input type="hidden" value={{$p_review-> id}} name="review_id">
</td>
<td>
<p style="font-weight:500;font-size:1.0em;"> {{$p_review-> review}} </p>
</td>
<td>
<p style="font-weight:500;font-size:1.0em;"> {{$p_review-> rating}} </p>
</td>
<td>
<p style="font-weight:500;font-size:1.0em;"> {{$p_review-> suggestions}} </p>
</td>
<td>
<p style="font-weight:500;font-size:1.0em;">
<select name="status">
<option value="0">Pending</option>
<option value="1">Approve</option>
</select>
</p>
</td>
<tr>
@endforeach
</table>
</div>
<input type='submit' class="btn btn-success" name='Save' value='Submit' />
{!! Form::close() !!}
@else
<h3> No Pending Reviews </h3>
@endif
dimanche 26 juin 2016
mysqli_stmt_fetch() Not Working
I am trying to save a value from a mysqli_stmt_fetch() statement. When my application is run, it returns No Value for this variable. I am new to PHP and cannot fully debug this file. Where is the bug at?
My php file:
<?php
require("password.php");
$connect = mysqli_connect("website", "account", "my_pass", "db");
$name = $_POST["name"];
$theme = $_POST["theme"];
$username = $_POST["username"];
$email = $_POST["email"];
$defaultRadius = $_POST["radius"];
$password = $_POST["password"];
function registerUser() {
global $connect, $name, $username, $theme, $email, $defaultRadius, $password;
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
$statement = mysqli_prepare($connect, "INSERT INTO user (name, username, theme, email, default_radius, password) VALUES (?, ?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "ssssss", $name, $username, $theme, $email, $defaultRadius, $passwordHash);
mysqli_stmt_execute($statement);
mysqli_stmt_bind_result($statement, $colUserID, $colName, $colUsername, $colTheme, $colEmail, $colDefaultRadius, $colPassword);
while(mysqli_stmt_fetch($statement)){
$response["userId"] = $colUserID;
}
mysqli_stmt_close($statement);
}
function usernameAvailable() {
global $connect, $username;
$statement = mysqli_prepare($connect, "SELECT * FROM user WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
$count = mysqli_stmt_num_rows($statement);
mysqli_stmt_close($statement);
if ($count < 1){
return true;
} else {
return false;
}
}
$response = array();
$response["success"] = false;
$response["reason"] = 0;
if (usernameAvailable()){
registerUser();
$response["success"] = true;
} else {
$response["reason"] = 1;
}
echo json_encode($response);
?>
The variable that I am trying to set is located inside the registerUser function. It states:
while(mysqli_stmt_fetch($statement)){
$response["userId"] = $colUserID;
}
Thanks for any help!
Edit: My new/current code is as follows:
<?php
require("password.php");
$connect = mysqli_connect("xenicdev.x10host.com", "xenicdev_root", "shadow1", "xenicdev_data");
$name = $_POST["name"];
$theme = $_POST["theme"];
$username = $_POST["username"];
$email = $_POST["email"];
$defaultRadius = $_POST["radius"];
$password = $_POST["password"];
function registerUser() {
global $connect, $name, $username, $theme, $email, $defaultRadius, $password, $response;
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
$statement = mysqli_prepare($connect, "INSERT INTO user (name, username, theme, email, default_radius, password) VALUES (?, ?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "ssssss", $name, $username, $theme, $email, $defaultRadius, $passwordHash);
mysqli_stmt_execute($statement);
mysqli_stmt_bind_result($statement, $colUserID, $colName, $colUsername, $colTheme, $colEmail, $colDefaultRadius, $colPassword);
while(mysqli_stmt_fetch($statement)){
return $colUserID;
}
}
function usernameAvailable() {
global $connect, $username;
$statement = mysqli_prepare($connect, "SELECT * FROM user WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
$count = mysqli_stmt_num_rows($statement);
mysqli_stmt_close($statement);
if ($count < 1){
return true;
} else {
return false;
}
}
$response = array();
$response["success"] = false;
$response["reason"] = 0;
if (usernameAvailable()){
$userId = registerUser();
$response["userId"] = $userId;
$response["success"] = true;
} else {
$response["reason"] = 1;
}
echo json_encode($response);
?>
It returns null as "userId" instead of the ID though... Please note the ID is not null in the SQL Database. In my testing case, the ID is 8.
StringRequest code used to call this PHP file from Android:
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://xenicdev.x10host.com/Register.php";
private Map<String, String> params;
public RegisterRequest(String name, String username, int themeId, String password, String email, int defaultRadius, Response.Listener<String> listener) {
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("name", name);
params.put("username", username);
params.put("theme", themeId + "");
params.put("email", email);
params.put("radius", defaultRadius + "");
params.put("password", password);
}
@Override
public Map<String, String> getParams() {
return params;
}
}
How to print properly HTML table do PDF using jspdf.js?
here is what i am trying to achieve, i trying to print a html table that included HTML table inside too loop my detail (i have header and detail) data. But when i use jspdf.js to print my HTML table, the table in the pdf is broken, is not look like the HTML, the looping table inside the main table is messy, look like it won't create the insider table. How to print the table inside table properly?
here is my HTML look like
index.html
<div id="customers">
<div class="table-responsive">
<table id="tbl" class="table table-hover">
<thead>
<tr>
<th style="background-color: #928989; color; white;">No BPS</th>
<th style="background-color: #928989; color; white;">Tanggal BPS</th>
<th style="background-color: #928989; color; white;">Tanggal Input</th>
<th style="background-color: #928989; color; white;">Status</th>
</tr>
</thead>
<tbody>
<tr ng-repeat-start="listLaporanRetur in listLaporanReturs | limitTo:quantity">
<td class="btn btn-mini btn-primary pull-center">BPXXXXXXX</td>
<td>2016-06-22</td>
<td>2016-06-22</td>
<td>SENT</td>
</tr>
<tr ng-repeat-end="">
<td colspan="10" style="padding: 0">
<div>
<table class="table table-bordered table-hover">
<tr>
<td style="background-color: #80A3C1;">Kode Barang</td>
<td style="background-color: #80A3C1;">Qty</td>
<td style="background-color: #80A3C1;">Merk</td>
<td style="background-color: #80A3C1;">Hasil</td>
</tr>
<tr ng-repeat-start="details in listLaporanRetur.returDetailList">
<td>STUFFID1</td>
<td>10</td>
<td>APPLE</td>
<td>BOOM</td>
</tr>
<tr>
<td>STUFFID2</td>
<td>40</td>
<td>SONY</td>
<td>BREAK</td>
</tr>
<tr ng-repeat-end=""></tr>
</table>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<button onclick="javascript:demoFromHTML();">PDF</button>
then here is my javascript
function demoFromHTML() {
var pdf = new jsPDF('p', 'pt', 'letter');
// source can be HTML-formatted string, or a reference
// to an actual DOM element from which the text will be scraped.
source = $('#customers')[0];
// we support special element handlers. Register them with jQuery-style
// ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
// There is no support for any other type of selectors
// (class, of compound) at this time.
specialElementHandlers = {
// element with id of "bypass" - jQuery style selector
'#bypassme': function (element, renderer) {
// true = "handled elsewhere, bypass text extraction"
return true
}
};
margins = {
top: 80,
bottom: 60,
left: 10,
width: 700
};
// all coords and widths are in jsPDF instance's declared units
// 'inches' in this case
pdf.fromHTML(
source, // HTML string or DOM elem ref.
margins.left, // x coord
margins.top, { // y coord
'width': margins.width, // max width of content on PDF
'elementHandlers': specialElementHandlers
},
function (dispose) {
// dispose: object with X, Y of the last line add to the PDF
// this allow the insertion of new lines after html
pdf.save('Test.pdf');
}, margins);
}
here is my jsfiddle http://jsfiddle.net/ugD5L/126/
how to print the table properly so i don't have to get messy table in the pdf?
External Library with _penter definition (/Gh) not recognized by project configuration type Dynamic Library dll
I have added the link of two projects, exactly same dummy code but different project types, first one is "Application (.exe)" {link to download} and the second one is "Dynamic Library (dll)" {link to download}. I am using Visual Studio Enterprise 2015, with the /Gh compiler option for both projects. There is another project included in both solutions that is NOT compiled with /Gh option and has implementation of _penter hook function. Strangely, the first project compiles fine and _penter is reached and functions properly (prints on console). The second one (dll) is throwing compilation error of "LNK2019 unresolved external symbol __penter referenced in function _DllMain@12" when compiled with /Gh switch. Also, I have tried with c and c++ code in both solutions, first one works with both and second works with none.
Configuration of Library Project
Just for reference, code content is pasted below.
Dll Project -- dllmain.c
// dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
#include "ProfileProfile.h"
int a = 7;
char ch = 'a';
char y(char c) {
return c + 1;
}
int xx2(int c, int d) {
y(ch++); return c + 3;
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
a = xx2(5, 100);
a = xx2(70, 200);
a = xx2(150, 300);
ch = y(ch);
ch = y(ch);
ch = y(ch);
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
Exe Project -- sample.c
// Sample.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "ProfileProfile.h"
int a = 7;
char ch = 'a';
char y(char c) {
printf("%c", c); return c + 1;
}
int xx2(int c, int d) {
printf("%d", c); y(ch++); return c + 3;
}
int main() {
//PassSomething(xx2, "int xx2(int c, int d)");
a = xx2(5, 100);
a = xx2(70, 200);
a = xx2(150, 300);
ch = y(ch);
ch = y(ch);
ch = y(ch);
}
Included Profiler Project - header profile.h
#include <windows.h>
#include <assert.h>
#include <tchar.h>
typedef struct
{
const void * function; // function address
const TCHAR * parameter; // formatting string for parameter decoding, '?' for class method
const TCHAR * returnval; // formatting string for return value decoding,
} Signature;
typedef struct
{
void * Pointer;
char Name[100];
char Parameters[20][100];
char ReturnType[20];
} Function;
Included Profiler Project - code profile.cpp
#define STRICT
#include "profile.h"
#define MAX_DEPTH 512 // good enough for 512 levels of nesting
void * Stack[MAX_DEPTH * 2]; // NOT multi-thread safe
int SP = 0;
int depth = 0;
void _stdcall ExitFunc(unsigned * pStack)
{
TCHAR temp[MAX_PATH];
Signature * pSig;
OutputDebugString("Exit n");
SP--;
pSig = (Signature *)Stack[SP];
SP--;
pStack[0] = (unsigned)Stack[SP]; // change return address to point to original caller
}
extern "C" __declspec(naked) void __cdecl _pexit()
{
_asm
{
push eax // function return value and placehold for return to original caller
pushad // save all general purpose registers
mov eax, esp // current stack pointer
add eax, 32 // stack pointer before pushad
push eax // push pointer to where EAX is saved as parameter to ExitFunc
call ExitFunc
popad // restore general registers
ret // return to original caller
}
}
void _stdcall EnterFunc(unsigned * pStack)
{
char temp[MAX_PATH];
Signature * pSig;
void * pCaller;
pCaller = (void *)(pStack[0] - 5); // the instruction for calling _penter is 5 bytes long
pSig = NULL;//FuncTable;
OutputDebugString("Entered n");
Stack[SP++] = (void *)pStack[1]; // save return address to original caller
Stack[SP++] = pSig; // save functions signature
pStack[1] = (unsigned)_pexit; // HACK stack to link to _pexit
depth++;
}
void _stdcall EnterFunc0(unsigned * pStack)
{
EnterFunc(pStack); // process the call
}
extern "C" __declspec(naked) void __cdecl _penter()
{
_asm
{
pushad // save all general purpose registers
mov eax, esp // current stack pointer
add eax, 32 // stack pointer before pushad
push eax // push pointer to return address as parameter to EnterFunc0
call EnterFunc0
popad // restore general purpose registers
ret // start executing original function
}
}
NOTE: Complete solution links are provided inline.
PHP form with jquery and ajax in different documents
How can I submit a form in a PHP document, take that values with a Jquery that is in another document and send it by Ajax to another PHP document.
Note: If there is a way to put the Ajax into the HEAD tag, I'll apreciate if you tell me how so I would discart the option with Jquery. But we really want to put the less as possible code in the Item.php file
Thank you very much !
Here is what we got:
// Item.PHP
<head>
<meta http-equiv="content-type" content="text/html; UTF-8" />
<link href="../css/home.css" rel="stylesheet" type="text/css">
<title>Items</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script src="../includes/ec.js"></script>
<script src="../includes/js/controller/ItemController.js"></script>
<script type='text/javascript' src='../includes/js/Jquery/InviteP.js'></script>
</head>
<body>
<form id='inviteFriend'>
<input value="{$company['product_id']}" class='mainResultsInfo' name='iProduct'></input>
<input value='{$userName}' class='mainResultsInfo' name='uProduct'></input>
<input value='1' class='mainResultsInfo' name='sProduct'></input>
<input type='image' src='../img/EC%20-%20Add%20plus.png' class='mainResultsConnect' name='sendInivitation'>
</input>
</form>
</body>
The intention was to take the form data with this Jquery, already pluged-in in ITEM.PHP
// InviteP.js
$(document).ready(function(){
$('input[name="sendInivitation"]').click(function() {
var url = "../includes/server/inviteProduct.php";
$.ajax({
type: "POST",
url: url,
data: $("#inviteFriend").serialize(),
success: function(data)
{
alert("Listo !");
}
});
e.preventDefault();
});
});
Then this one will send information to database through InviteProduct.php
// InviteProduct.php
<?php
SESSION_START();
if(isset($_SESSION["user"]))
{
$data['session'] = true;
}
$data;
$data['info'] = "";
$data['session'] = "";
$tmOp = $_SESSION["user"];
$dsn = 'mysql:dbname=asd;host=localhost;port=3306';
$user = 'root';
$password = '';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
$connection = new PDO($dsn, $user, $password, $options);
} catch (PDOException $e) {
echo 'Fallo conexión: '. $e->getMessage();
}
$iProduct=$_POST['iProduct'];
$uProduct=$_POST['uProduct'];
$sProduct=$_POST['sProduct'];
$sql = "INSERT INTO products_request (product_id, product_requested_id, send_request) VALUES ('$iProduct','$uProduct','$sProduct');
";
$addCompany = $connection->prepare($sql);
$addCompany->execute();
?>
Why does my program crash after some time?
I'm writing a program to simulate a cruise control application with the Altera 2 FPGA. My problem is that after a while, the simulation stops. I use semaphores and priorities that seem to work at the beginning of the program, but then the program just stops. I pasted the output at this link. The code is
#include <stdio.h>
#include "system.h"
#include "includes.h"
#include "altera_avalon_pio_regs.h"
#include "sys/alt_irq.h"
#include "sys/alt_alarm.h"
#define DEBUG 1
#define HW_TIMER_PERIOD 100 /* 100ms */
/* Button Patterns */
#define GAS_PEDAL_FLAG 0x08
#define BRAKE_PEDAL_FLAG 0x04
#define CRUISE_CONTROL_FLAG 0x02
/* Switch Patterns */
#define TOP_GEAR_FLAG 0x00000002
#define ENGINE_FLAG 0x00000001
/* LED Patterns */
#define LED_RED_0 0x00000001 // Engine
#define LED_RED_1 0x00000002 // Top Gear
#define LED_GREEN_0 0x0001 // Cruise Control activated
#define LED_GREEN_2 0x0002 // Cruise Control Button
#define LED_GREEN_4 0x0010 // Brake Pedal
#define LED_GREEN_6 0x0040 // Gas Pedal
/*
* Definition of Tasks
*/
#define TASK_STACKSIZE 2048
OS_STK StartTask_Stack[TASK_STACKSIZE];
OS_STK ControlTask_Stack[TASK_STACKSIZE];
OS_STK VehicleTask_Stack[TASK_STACKSIZE];
OS_STK ButtonIO_Stack[TASK_STACKSIZE];
OS_STK SwitchIO_Stack[TASK_STACKSIZE];
OS_EVENT *aSemaphore;
OS_EVENT *aSemaphore2;
OS_EVENT *aSemaphore3;
OS_EVENT *aSemaphore4;
// SW-Timer
OS_TMR *SWTimer;
alt_u32 ticks;
alt_u32 time_1;
alt_u32 time_2;
alt_u32 timer_overhead;
// Task Priorities
#define STARTTASK_PRIO 5
#define VEHICLETASK_PRIO 10
#define BUTTONIO_PRIO 12
#define CONTROLTASK_PRIO 12
#define SWITCHIO_PRIO 12
// Task Periods
#define CONTROL_PERIOD 300
#define VEHICLE_PERIOD 300
/*
* Definition of Kernel Objects
*/
// Mailboxes
OS_EVENT *Mbox_Throttle;
OS_EVENT *Mbox_Velocity;
// Semaphores
// SW-Timer
/*
* Types
*/
enum active {on, off};
enum active gas_pedal = off;
enum active brake_pedal = off;
enum active top_gear = off;
enum active engine = off;
enum active cruise_control = off;
/*
* Global variables
*/
int delay; // Delay of HW-timer
INT16U led_green = 0; // Green LEDs
INT32U led_red = 0; // Red LEDs
int buttons_pressed(void)
{
return ~IORD_ALTERA_AVALON_PIO_DATA(DE2_PIO_KEYS4_BASE);
}
int switches_pressed(void)
{
return IORD_ALTERA_AVALON_PIO_DATA(DE2_PIO_TOGGLES18_BASE);
}
/*
* ISR for HW Timer
*/
alt_u32 alarm_handler(void* context)
{
OSTmrSignal(); /* Signals a 'tick' to the SW timers */
return delay;
}
static int b2sLUT[] = {0x40, //0
0x79, //1
0x24, //2
0x30, //3
0x19, //4
0x12, //5
0x02, //6
0x78, //7
0x00, //8
0x18, //9
0x3F, //-
};
/*
* convert int to seven segment display format
*/
int int2seven(int inval){
return b2sLUT[inval];
}
/*
* output current velocity on the seven segement display
*/
void show_velocity_on_sevenseg(INT8S velocity){
int tmp = velocity;
int out;
INT8U out_high = 0;
INT8U out_low = 0;
INT8U out_sign = 0;
if(velocity < 0){
out_sign = int2seven(10);
tmp *= -1;
}else{
out_sign = int2seven(0);
}
out_high = int2seven(tmp / 10);
out_low = int2seven(tmp - (tmp/10) * 10);
out = int2seven(0) << 21 |
out_sign << 14 |
out_high << 7 |
out_low;
IOWR_ALTERA_AVALON_PIO_DATA(DE2_PIO_HEX_LOW28_BASE,out);
}
/*
* shows the target velocity on the seven segment display (HEX5, HEX4)
* when the cruise control is activated (0 otherwise)
*/
void show_target_velocity(INT8U target_vel)
{
}
/*
* indicates the position of the vehicle on the track with the four leftmost red LEDs
* LEDR17: [0m, 400m)
* LEDR16: [400m, 800m)
* LEDR15: [800m, 1200m)
* LEDR14: [1200m, 1600m)
* LEDR13: [1600m, 2000m)
* LEDR12: [2000m, 2400m]
*/
void show_position(INT16U position)
{
}
/*
* The function 'adjust_position()' adjusts the position depending on the
* acceleration and velocity.
*/
INT16U adjust_position(INT16U position, INT16S velocity,
INT8S acceleration, INT16U time_interval)
{
INT16S new_position = position + velocity * time_interval / 1000
+ acceleration / 2 * (time_interval / 1000) * (time_interval / 1000);
if (new_position > 24000) {
new_position -= 24000;
} else if (new_position < 0){
new_position += 24000;
}
show_position(new_position);
return new_position;
}
/*
* The function 'adjust_velocity()' adjusts the velocity depending on the
* acceleration.
*/
INT16S adjust_velocity(INT16S velocity, INT8S acceleration,
enum active brake_pedal, INT16U time_interval)
{
INT16S new_velocity;
INT8U brake_retardation = 200;
if (brake_pedal == off)
new_velocity = velocity + (float) (acceleration * time_interval) / 1000.0;
else {
if (brake_retardation * time_interval / 1000 > velocity)
new_velocity = 0;
else
new_velocity = velocity - brake_retardation * time_interval / 1000;
}
return new_velocity;
}
int cruise_velocity =0;
void SwitchIO(void* pdata)
{
printf("SwitchIO task created!n");
INT8U err;
while(1)
{
OSSemPend(aSemaphore4, 0, &err);
/* int w[700];
int tmp = 600;
int x[13];
int a;
int i, j;
timer_overhead = 0;
if (switches_pressed()==1) {
engine = on;
top_gear=off;
show_position(position);
printf("The engine is turned onn");
} else if (switches_pressed()==3) {
engine = on;
top_gear=on;
show_position(position);
}
else if (switches_pressed()==0) {
printf("switches_pressed()==0n");
top_gear = off;
engine = off;
show_position(position);
}
else if (switches_pressed()==2) {
}
else if ((switches_pressed()-19)/16 >= 0) {
int number = (switches_pressed()-19)/16+1;
if (number > 50) {
number = 50;
}
printf("extra load %dn", number);
for (i = 0; i < 10; i++) {
start_measurement();
stop_measurement();
timer_overhead = timer_overhead + time_2 - time_1;
}
initArray(w, 600);
initArray(x, 13);
start_measurement();
j=tmp+number*4;
for (i = 0; i < j; i++)
w[i]++;
stop_measurement();
printf("%5.2f us", (float) microseconds(ticks - timer_overhead));
printf("(%d ticks)n", (int) (ticks - timer_overhead));
}*/
printf("switches_pressed: %dn", switches_pressed());
printf("switches_pressed: %dn", (switches_pressed()-19)/16);
}
}
void ButtonIO(void* pdata)
{
printf("ButtonIO task created!n");
INT8U err;
while(1)
{
OSSemPend(aSemaphore3, 0, &err); // Trying to access the key
/* int btn_reg = IORD_ALTERA_AVALON_PIO_DATA(DE2_PIO_KEYS4_BASE);
if (btn_reg == 7) {
gas_pedal = on;
cruise_control = off;
IOWR_ALTERA_AVALON_PIO_DATA(DE2_PIO_GREENLED9_BASE,LED_GREEN_6);
} else if (buttons_pressed() == -16) {
gas_pedal = off;
if (! cruise_velocity > 0 ) {
IOWR_ALTERA_AVALON_PIO_DATA(DE2_PIO_GREENLED9_BASE,0x00000);
} else {
IOWR_ALTERA_AVALON_PIO_DATA(DE2_PIO_GREENLED9_BASE, LED_GREEN_0);
}
}*/
printf("ButtonIO buttons_pressed: %dn", buttons_pressed());
}
}
/*
* The task 'VehicleTask' updates the current velocity of the vehicle
*/
void VehicleTask(void* pdata)
{
INT8U err;
void* msg;
INT8U* throttle;
INT8S acceleration; /* Value between 40 and -20 (4.0 m/s^2 and -2.0 m/s^2) */
INT8S retardation; /* Value between 20 and -10 (2.0 m/s^2 and -1.0 m/s^2) */
INT16U position = 0; /* Value between 0 and 20000 (0.0 m and 2000.0 m) */
INT16S velocity = 0; /* Value between -200 and 700 (-20.0 m/s amd 70.0 m/s) */
INT16S wind_factor; /* Value between -10 and 20 (2.0 m/s^2 and -1.0 m/s^2) */
printf("Vehicle task created!n");
while(1)
{ OSSemPend(aSemaphore2, 0, &err);
err = OSMboxPost(Mbox_Velocity, (void *) &velocity);
// OSTimeDlyHMSM(0,0,0,VEHICLE_PERIOD);
/* Non-blocking read of mailbox:
- message in mailbox: update throttle
- no message: use old throttle
*/
msg = OSMboxPend(Mbox_Throttle, 1, &err);
if (err == OS_NO_ERR)
throttle = (INT8U*) msg;
/* Retardation : Factor of Terrain and Wind Resistance */
if (velocity > 0)
wind_factor = velocity * velocity / 10000 + 1;
else
wind_factor = (-1) * velocity * velocity / 10000 + 1;
if (position < 4000)
retardation = wind_factor; // even ground
else if (position < 8000)
retardation = wind_factor + 15; // traveling uphill
else if (position < 12000)
retardation = wind_factor + 25; // traveling steep uphill
else if (position < 16000)
retardation = wind_factor; // even ground
else if (position < 20000)
retardation = wind_factor - 10; //traveling downhill
else
retardation = wind_factor - 5 ; // traveling steep downhill
acceleration = *throttle / 2 - retardation;
position = adjust_position(position, velocity, acceleration, 300);
velocity = adjust_velocity(velocity, acceleration, brake_pedal, 300);
printf("Position: %dmn", position / 10);
printf("Velocity: %4.1fm/sn", velocity /10.0);
printf("Throttle: %dVn", *throttle / 10);
show_velocity_on_sevenseg((INT8S) (velocity / 10));
}
}
/*
* The task 'ControlTask' is the main task of the application. It reacts
* on sensors and generates responses.
*/
void ControlTask(void* pdata)
{
INT8U err;
INT8U throttle = 40; /* Value between 0 and 80, which is interpreted as between 0.0V and 8.0V */
void* msg;
INT16S* current_velocity;
printf("Control Task created!n");
while(1)
{
OSSemPend(aSemaphore, 0, &err); // Trying to access the key
msg = OSMboxPend(Mbox_Velocity, 0, &err);
current_velocity = (INT16S*) msg;
err = OSMboxPost(Mbox_Throttle, (void *) &throttle);
// OSTimeDlyHMSM(0,0,0, CONTROL_PERIOD);
}
}
void release()
{
OSSemPost(aSemaphore);
OSSemPost(aSemaphore2);
OSSemPost(aSemaphore3);
OSSemPost(aSemaphore4);
}
/*
* The task 'StartTask' creates all other tasks kernel objects and
* deletes itself afterwards.
*/
void StartTask(void* pdata)
{
INT8U err;
void* context;
static alt_alarm alarm; /* Is needed for timer ISR function */
/* Base resolution for SW timer : HW_TIMER_PERIOD ms */
delay = alt_ticks_per_second() * HW_TIMER_PERIOD / 1000;
printf("delay in ticks %dn", delay);
/*
* Create Hardware Timer with a period of 'delay'
*/
if (alt_alarm_start (&alarm,
delay,
alarm_handler,
context) < 0)
{
printf("No system clock available!n");
}
/*
* Create and start Software Timer
*/
SWTimer = OSTmrCreate(0,
CONTROL_PERIOD/(4*OS_TMR_CFG_TICKS_PER_SEC),
OS_TMR_OPT_PERIODIC,
release,
NULL,
NULL,
&err);
if (err == OS_ERR_NONE) {
/* Timer was created but NOT started */
printf("SWTimer was created but NOT started n");
}
BOOLEAN status = OSTmrStart(SWTimer,
&err);
if (status > 0 && err == OS_ERR_NONE) {
/* Timer was started */
printf("SWTimer was started!n");
}
/*
* Creation of Kernel Objects
*/
// Mailboxes
Mbox_Throttle = OSMboxCreate((void*) 0); /* Empty Mailbox - Throttle */
Mbox_Velocity = OSMboxCreate((void*) 0); /* Empty Mailbox - Velocity */
/*
* Create statistics task
*/
OSStatInit();
/*
* Creating Tasks in the system
*/
err = OSTaskCreateExt(
ControlTask, // Pointer to task code
NULL, // Pointer to argument that is
// passed to task
&ControlTask_Stack[TASK_STACKSIZE-1], // Pointer to top
// of task stack
CONTROLTASK_PRIO,
CONTROLTASK_PRIO,
(void *)&ControlTask_Stack[0],
TASK_STACKSIZE,
(void *) 0,
OS_TASK_OPT_STK_CHK);
err = OSTaskCreateExt(
VehicleTask, // Pointer to task code
NULL, // Pointer to argument that is
// passed to task
&VehicleTask_Stack[TASK_STACKSIZE-1], // Pointer to top
// of task stack
VEHICLETASK_PRIO,
VEHICLETASK_PRIO,
(void *)&VehicleTask_Stack[0],
TASK_STACKSIZE,
(void *) 0,
OS_TASK_OPT_STK_CHK);
err = OSTaskCreateExt(
SwitchIO, // Pointer to task code
NULL, // Pointer to argument that is
// passed to task
&SwitchIO_Stack[TASK_STACKSIZE-1], // Pointer to top
// of task stack
SWITCHIO_PRIO,
SWITCHIO_PRIO,
(void *)&ButtonIO_Stack[0],
TASK_STACKSIZE,
(void *) 0,
OS_TASK_OPT_STK_CHK);
err = OSTaskCreateExt(
SwitchIO, // Pointer to task code
NULL, // Pointer to argument that is
// passed to task
&SwitchIO_Stack[TASK_STACKSIZE-1], // Pointer to top
// of task stack
SWITCHIO_PRIO,
SWITCHIO_PRIO,
(void *)&SwitchIO_Stack[0],
TASK_STACKSIZE,
(void *) 0,
OS_TASK_OPT_STK_CHK);
printf("All Tasks and Kernel Objects generated!n");
/* Task deletes itself */
OSTaskDel(OS_PRIO_SELF);
}
/*
*
* The function 'main' creates only a single task 'StartTask' and starts
* the OS. All other tasks are started from the task 'StartTask'.
*
*/
int main(void) {
printf("Lab: Cruise Controln");
OSTaskCreateExt(
StartTask, // Pointer to task code
NULL, // Pointer to argument that is
// passed to task
(void *)&StartTask_Stack[TASK_STACKSIZE-1], // Pointer to top
// of task stack
STARTTASK_PRIO,
STARTTASK_PRIO,
(void *)&StartTask_Stack[0],
TASK_STACKSIZE,
(void *) 0,
OS_TASK_OPT_STK_CHK | OS_TASK_OPT_STK_CLR);
OSStart();
return 0;
}
jeudi 23 juin 2016
how to develop a mobile application using nodejs/js frameworks?
I am new to node js,Is there any common js framework or tool to develop mobile application which support android,ios,windows mobile.
Fetching random articles from wikipedia
Hi i am working on a site which fetches random articles from Wikipedia and displays them on my site. The problem is i have no idea how to retrieve those articles. Documentation is also of no help. Can someone advice me how to approach it? Can we use api's? I am using PHP+HTML.
AngularJS element.bind('resize') not updating $scope variable
I am trying to set a scope variable for the innerWidth of the browser window using the code below. It works when viewed in the console, but the function is not updating the $scope variable. Why?
angular.element($window).bind('resize', function () {
console.log('resize', $window.innerWidth); // I can see change here
$scope.window_width = $window.innnerWidth; // no change here
});
react.js change input value with javascript
I would like to change the values with javascript/jquery but when I hit submit, the old initial values are used and not my new ones.
I cannot change the react code, I can only change the values with javascript/jquery as shown below.
var value = "randomIntValue";
$("input[data-reactid='.0.2.0.0.0.0.0.2.0.0.3.0.3.0.0']").val(value).change();
The above code doesn't work!
update() with find() in laravel is not working
I am new to laravel, I am facing problem while creating generic update function,
code 1: this is not working
if ($obj->find($primaryKey)->update($data)){
return TRUE;
}
else
return FALSE;
code 2: but if i tried this, it is working:
if ($obj->where("candidate_id", $primaryKey)->update($data)){
return TRUE;
}
else
return FALSE;
i want code 1 should work
jQuery trigger click after insertBefore
I'm trying to figure out how to trigger click event right after insertBefore
$this = $(this);
var changeImageHTML = '<div class="sample1 sample2"> </div>';
//attempt 1
$(changeImageHTML).insertBefore($this).trigger('click');
//attempt 2
$(changeImageHTML).insertBefore($this).find('.sample2').trigger('click');
//attempt 3
$(changeImageHTML).insertBefore($this).find('.sample1.sample2').trigger('click');
//attempt 4
$(changeImageHTML).insertBefore($this).bind('click').trigger('click');
Version: jQuery 2.1
Thanks for your help. :)
mercredi 22 juin 2016
Nested if in coffeescript
I need to have these conditions in a coffeescript file of my rails app:
if window.location.href == "website.com/rooms"
if $(".panel-heading")[0].id == data["room"] &&
$('.messages').append data['message']
$("div#" + data["room"]).find("#status").text(data["status"])
else
$('.messages').append data['message']
$("#wrapper").scrollTop($("#wrapper")[0].scrollHeight)
However, I get an error for the nested if: unexpected if
How can I use nested if statements in coffeescript ?
In JS, I could do this:
if(condition){
if(condition){
}
}
else{
}
How to call .change() event inside revealing module pattern? - Javascript
I want to get the id of the select element on change event. My .change() event is defined inside a private function. As I am learning design patterns in javascript, I have used Revealing Module Pattern to define my functions.
I tried out two examples which are almost same(change is only in HTML) but one works and other doesn't.
This code snippet DOES NOT work
I can't figure out the reason why this is happening
Also please comment on the proper way/standard way to define events inside revealing pattern
How we can clone html any element with drag then drop it in another column (only in that column not outside from it)
I am doing work on DnD htlm5 . someone suggest me use jquery-ui because there have lot of stuff already implemented . I am able to drag and drop any html element only in one column right now , but I want clone any html element from one column to another column , In previous column cloning element will stay, that I want. That is shown in following example please see :
http://jsbin.com/aseqid/10/edit
I this example "test" div cloning and dropping anywhere , but I want drop it only in "drop" column , in this column we can drop anywhere . After dropping I want also rezise it , change there positions , save there properties like size, width, height in file or DB . So please anyone help me for that .
How to draw scatter chart with labels on google chart?
Look at this Google chart in spreadsheet.
How to draw this names on chart rather than tooltips? Is there need to change in data or options given to Google chart?
You can check this plunker.
var chart2 = {};
chart2.type = "ScatterChart";
chart2.cssStyle = "height:400px; width:500px;";
chart2.data = [
['Age', 'Weight'],
[ {'v':8,'f':'Name 1'}, -12],
[ {'v':-4,'f':'Name 2'}, 5.5],
[ {'v':11,'f':'Name 3'}, 14],
[ {'v':-4,'f':'Name 4'}, -5],
[ {'v':3,'f':'Name 5'}, 3.5],
[ {'v':6.5,'f':'Name 6'}, -7]
];
chart2.options = {
"title": "Age Vs Maturity",
"isStacked": "true",
"fill": 20,
"hAxis": {"title": "Age", minValue: -15, maxValue: 15},
"vAxis": {"title": "Maturity", minValue: -15, maxValue: 15},
"legend": 'none'
};
$scope.chart2 = chart2;
how to change view's vairable in js of rails
how to change view's variable value in javascript. I mean when i select April from dropdown table will show only April's data and current table data will disappear and refreshed. How can i do it? Help me
My JS
:javascript
var updateMonth = function(){
var month_id = $("#select_other_month").val();
console.log(month_id)
}
here is my select tag (dropdown)
%select{:name => "options", :id=>"select_other_month",:onchange=>"updateMonth()"}
%option.placeholder{:disabled => "", :selected => "", :value => ""} see other months
%option{:value => "0"} this month
-a=@this_month - 1.month
%option{:value => "5"}=a.strftime('%Y-%m')
-b=@this_month - 2.month
%option{:value => "4"}=b.strftime('%Y-%m')
-c=@this_month - 3.month
%option{:value => "3"}=c.strftime('%Y-%m')
-d=@this_month - 4.month
%option{:value => "2"}=d.strftime('%Y-%m')
-e=@this_month - 5.month
%option{:value => "1"}=e.strftime('%Y-%m')
and my table looks like this
.table{:id=>"time_table"}
%table{:border=>"1"}
%thead
%tr
%th No
%th Name
-(@xmonth.at_beginning_of_month..@xmonth.at_end_of_month).each do |day|
-if (day.saturday? || day.sunday?)==false
%th=day.strftime("%d")
%th Total days
%th Total time
I want change my @xmonth vairable from JS
Note: @this_month = Date.today
OpenGL: Wrapping texture around cylinder
I am trying to add textures to a cylinder to draw a stone well. I'm starting with a cylinder and then mapping a stone texture I found here but am getting some weird results. Here is the function I am using:
void draw_well(double x, double y, double z,
double dx, double dy, double dz,
double th)
{
// Set specular color to white
float white[] = {1,1,1,1};
float black[] = {0,0,0,1};
glMaterialfv(GL_FRONT_AND_BACK,GL_SHININESS,shinyvec);
glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,white);
glMaterialfv(GL_FRONT_AND_BACK,GL_EMISSION,black);
glPushMatrix();
// Offset
glTranslated(x,y,z);
glRotated(th,0,1,0);
glScaled(dx,dy,dz);
// Enable textures
glEnable(GL_TEXTURE_2D);
glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);
glBindTexture(GL_TEXTURE_2D,texture[0]); // Stone texture
glBegin(GL_QUAD_STRIP);
for (int i = 0; i <= 359; i++)
{
glNormal3d(Cos(i), 1, Sin(i));
glTexCoord2f(0,0); glVertex3f(Cos(i), -1, Sin(i));
glTexCoord2f(0,1); glVertex3f(Cos(i), 1, Sin(i));
glTexCoord2f(1,1); glVertex3f(Cos(i + 1), 1, Sin(i + 1));
glTexCoord2f(1,0); glVertex3f(Cos(i + 1), -1, Sin(i + 1));
}
glEnd();
glPopMatrix();
glDisable(GL_TEXTURE_2D);
}
// Later down in the display function
draw_well(0, 0, 0, 1, 1, 1, 0);
and the output I receive is
I'm still pretty new to OpenGL and more specifically textures so my understanding is pretty limited. My thought process here is that I would map the texture to each QUAD used to make the cylinder, but clearly I am doing something wrong. Any explanation on what is causing this weird output and how to fix it would be greatly appreciated.
ASP.NET Core MVC - Jquery button - placing an icon on the right side and not have it default to a second line
I have looked for an answer to this in a few questions. I have a set of three jquery buttons in line being created via a jquery widget, the function for which I have added below:
//Render the back/forward buttons
_renderCalendarButtons: function ($calendarContainer) {
var self = this, options = this.options;
if (!options.showHeader) return;
if (options.buttons) {
calendarNavHtml = "<div class="sc-nav">
<button class="sc-prev"></button>
<button class="sc-today"></button>
<button class="sc-next"></button>
</div>";
$(calendarNavHtml).appendTo($calendarContainer);
$calendarContainer.find(".sc-nav .sc-prev")
.button({
icons: { primary: 'ui-icon-seek-prev' },
label: options.buttonText.lastWeek,
})
.click(function () {
self.element.scheduler("prevWeek");
return false;
});
$calendarContainer.find(".sc-nav .sc-today")
.button({
icons: { primary: 'ui-icon-home' },
label: options.buttonText.today
})
.click(function () {
self.element.scheduler("today");
return false;
});
$calendarContainer.find(".sc-nav .sc-next")
.button({
icons: { secondary: 'ui-icon-seek-next' },
label: options.buttonText.nextWeek
})
.click(function () {
self.element.scheduler("nextWeek");
return false;
});
}
},
The left says "Prev" the middle says "Today" and the one on the right says "Next".
The right button has an icon in it situated to the left. same with the middle button but for the right I wanted the icon to be situated on the right of the text. So based on the information in a Stackoverflow question I used:
.button({
icons: { secondary: 'ui-icon-seek-next' },
label: options.buttonText.nextWeek
..and this worked prviding an icon the right. However, the icon is being displayed below the text as if the button is not big enough. I have tried modifying the style as per another Stackoverflow question including "display: inline":
.sc-nav button {
margin: 0 0.5em;
width: 10em;
padding-top: 10px;
padding-bottom: 10px;
display:inline;
}
But I still get the icon on the second row... can someone point out how this can all just appear on one line with no two line buttons...
Get the checkbo value php
Good day sir. Please check my script first.
Good day sir. Please check my script first.
<div class="form-group">
<label class="btn control-label col-sm-2" for="email">Developer</label>
<label class="btn btn-info">
<input name='pilihan[]' value='1' type="checkbox" autocomplete="off"> Konfigurasi Menu <span class="glyphicon glyphicon-ok"></span></label>
<label class="btn btn-info">
<input name='pilihan[]' value='2' type="checkbox" autocomplete="off"> Konfigurasi User <span class="glyphicon glyphicon-ok"></span>
</label>
<label class="btn btn-info">
<input name='pilihan[]' value='16' type="checkbox" autocomplete="off"> User Akses <span class="glyphicon glyphicon-ok"></span>
</label>
</div>
<div class="form-group">
<label class="btn control-label col-sm-2" for="email">Admin</label>
<label class="btn btn-info">
<input name='pilihan[]' value='1' type="checkbox" autocomplete="off"> Konfigurasi Menu <span class="glyphicon glyphicon-ok"></span>
</label>
<label class="btn btn-info">
<input name='pilihan[]' value='2' type="checkbox" autocomplete="off"> Konfigurasi User <span class="glyphicon glyphicon-ok"></span>
</label>
<label class="btn btn-info">
<input name='pilihan[]' value='16' type="checkbox" autocomplete="off"> User Akses <span class="glyphicon glyphicon-ok"></span>
</label>
</div>
<div class="form-group">
<label class="btn control-label col-sm-2" for="email">Outlet</label>
<label class="btn btn-info">
<input name='pilihan[]' value='1' type="checkbox" autocomplete="off"> Konfigurasi Menu <span class="glyphicon glyphicon-ok"></span>
</label>
<label class="btn btn-info">
<input name='pilihan[]' value='2' type="checkbox" autocomplete="off"> Konfigurasi User <span class="glyphicon glyphicon-ok"></span>
</label>
<label class="btn btn-info">
<input name='pilihan[]' value='16' type="checkbox" autocomplete="off"> User Akses <span class="glyphicon glyphicon-ok"></span>
</label>
</div>
So what i want to is save the checkbox value. For now what i can do is
[pilihan] => Array
(
[0] => 1
[1] => 2
[2] => 16
)
i can get the value but the value are free . As you can see from my form above there are developer,admin & Outlet. My question is, how to set the value for developer,admin & Outlet.
How to encode the value in base64
Here I am using file upload,here I did base64 encode image upto
**$encodeimage = base64_encode(file_get_contents($filename));
//here we got encoded image value** now I got answer,after that I want to encrypt the base64 encoded value,I am writing below code but I can't get encrypt value?
<?php
require_once 'Security.php';
define ("MAX_SIZE","1000");
$errors=0;
$image =$_FILES["file"]["name"];//i got filename here
$uploadedfile = $_FILES['file']['tmp_name'];
$filetype = $_FILES['file']['type'];
if ($image)
{
$filename = stripslashes($_FILES['file']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
$error_msg = ' Unknown Image extension ';
$errors=1;
}
else{
$size=filesize($_FILES['file']['tmp_name']);
if ($size > MAX_SIZE*1024)
{
$error_msg = "You have exceeded the size limit";
$errors=1;
}
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
$newwidth=600;
/*$newheight=($height/$width)*$newwidth;*/
$newheight=600;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = $_FILES['file']['name'];
imagejpeg($tmp,$filename,100);
$encodeimage = base64_encode(file_get_contents($filename));//here we got encodede image value
$encrypt_image = "data:".$filetype."base64,".$encodeimage;
$security = new Security();
/*$string = $_POST['user_string'];*/
$publicKey = $security->genRandString(32);
$encryptedData = $security->encrypt($encrypt_image, $publicKey);
imagedestroy($src);
imagedestroy($tmp);
}
}
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$id_proof = array("filename" =>$filename,
"base64_encodeimage" =>$encrypt_image,
"encryptedData" => $encryptedData,//getting null value here
"error_msg" =>$error_msg
);
echo json_encode($id_proof);
?>
----------
**Security.php**
<?php
class Security {
// Private key
public static $salt = 'Lu70K$i3pu5xf7*I8tNmd@x2oODwwDRr4&xjuyTh';
// Encrypt a value using AES-256.
public static function encrypt($plain, $key, $hmacSalt = null) {
self::_checkKey($key, 'encrypt()');
if ($hmacSalt === null) {
$hmacSalt = self::$salt;
}
$key = substr(hash('sha256', $key . $hmacSalt), 0, 32); # Generate the encryption and hmac key
$algorithm = MCRYPT_RIJNDAEL_128; # encryption algorithm
$mode = MCRYPT_MODE_CBC; # encryption mode
$ivSize = mcrypt_get_iv_size($algorithm, $mode); # Returns the size of the IV belonging to a specific cipher/mode combination
$iv = mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM); # Creates an initialization vector (IV) from a random source
$ciphertext = $iv . mcrypt_encrypt($algorithm, $key, $plain, $mode, $iv); # Encrypts plaintext with given parameters
$hmac = hash_hmac('sha256', $ciphertext, $key); # Generate a keyed hash value using the HMAC method
return $hmac . $ciphertext;
}
// Check key
protected static function _checkKey($key, $method) {
if (strlen($key) < 32) {
echo "Invalid public key $key, key must be at least 256 bits (32 bytes) long."; die();
}
}
// Decrypt a value using AES-256.
public static function decrypt($cipher, $key, $hmacSalt = null) {
self::_checkKey($key, 'decrypt()');
if (empty($cipher)) {
echo 'The data to decrypt cannot be empty.'; die();
}
if ($hmacSalt === null) {
$hmacSalt = self::$salt;
}
$key = substr(hash('sha256', $key . $hmacSalt), 0, 32); # Generate the encryption and hmac key.
// Split out hmac for comparison
$macSize = 64;
$hmac = substr($cipher, 0, $macSize);
$cipher = substr($cipher, $macSize);
$compareHmac = hash_hmac('sha256', $cipher, $key);
if ($hmac !== $compareHmac) {
return false;
}
$algorithm = MCRYPT_RIJNDAEL_128; # encryption algorithm
$mode = MCRYPT_MODE_CBC; # encryption mode
$ivSize = mcrypt_get_iv_size($algorithm, $mode); # Returns the size of the IV belonging to a specific cipher/mode combination
$iv = substr($cipher, 0, $ivSize);
$cipher = substr($cipher, $ivSize);
$plain = mcrypt_decrypt($algorithm, $key, $cipher, $mode, $iv);
return rtrim($plain, "");
}
//Get Random String - Usefull for public key
public function genRandString($length = 0) {
$charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$str = '';
$count = strlen($charset);
while ($length-- > 0) {
$str .= $charset[mt_rand(0, $count-1)];
}
return $str;
}
}
PHPMailer SMTP Error: data not accepted
I'm trying out PHPMailer using outlook.com's SMTP server but I keep getting SMTP Error I followed the example code from PHPMailer's github page, and I've also looked at other questions on SO, but the answers there don't solve my problem
This is the code
<?php
date_default_timezone_set('Etc/UTC');
require_once 'vendor/autoload.php';
$mail = new PHPMailer;
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
//Tell PHPMailer to use SMTP
$mail->isSMTP();
$mail->SMTPDebug = 2;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = 'smtp-mail.outlook.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication
$mail->Username = "user@outlook.com";
//Password to use for SMTP authentication
$mail->Password = "pass";
//Set who the message is to be sent from
$mail->setFrom('user@outlook.com', 'User');
//Set who the message is to be sent to
$mail->addAddress('recipient@gmail.com', 'Recipient');
//Set the subject line
$mail->Subject = 'PHPMailer SMTP test';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//send the message, check for errors
if (!$mail->send()) {
echo "<br><br>Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
And here is the debug output
SERVER -> CLIENT: 220 BLU436-SMTP81.smtp.hotmail.com Microsoft ESMTP MAIL Service, Version: 8.0.9200.16384 ready at Mon, 20 Jun 2016 23:35:39 -0700
CLIENT -> SERVER: EHLO localhost
SERVER -> CLIENT: 250-BLU436-SMTP81.smtp.hotmail.com Hello [139.193.110.46]250-TURN250-SIZE 41943040250-ETRN250-PIPELINING250-DSN250-ENHANCEDSTATUSCODES250-8bitmime250-VRFY250-TLS250-STARTTLS250 OK
CLIENT -> SERVER: STARTTLS
SERVER -> CLIENT: 220 2.0.0 SMTP server ready
CLIENT -> SERVER: EHLO localhost
SERVER -> CLIENT: 250-BLU436-SMTP81.smtp.hotmail.com Hello [139.193.110.46]250-TURN250-SIZE 41943040250-ETRN250-PIPELINING250-DSN250-ENHANCEDSTATUSCODES250-8bitmime250-VRFY250-AUTH LOGIN PLAIN XOAUTH2250 OK
CLIENT -> SERVER: AUTH LOGIN
SERVER -> CLIENT: 334 VXNlcm5hbWU6
CLIENT -> SERVER: amF5YWNvbWFscGhhZWxlY3Ryb25pY0BvdXRsb29rLmNvbQ==
SERVER -> CLIENT: 334 UGFzc3dvcmQ6
CLIENT -> SERVER: SmF5YTIwMTU=
SERVER -> CLIENT: 235 2.7.0 Authentication succeeded
CLIENT -> SERVER: MAIL FROM:<user@outlook.com>
SERVER -> CLIENT: 250 2.1.0 user@outlook.com....Sender OK
CLIENT -> SERVER: RCPT TO:<Recipient@gmail.com>
SERVER -> CLIENT: 250 2.1.5 Recipient@gmail.com
CLIENT -> SERVER: DATA
SERVER -> CLIENT: 354 Start mail input; end with <CRLF>.<CRLF>
CLIENT -> SERVER: Date: Tue, 21 Jun 2016 06:35:39 +0000
CLIENT -> SERVER: To: Recipient <Recipient@gmail.com>
CLIENT -> SERVER: From: User <user@outlook.com>
CLIENT -> SERVER: Subject: PHPMailer SMTP test
CLIENT -> SERVER: Message-ID: <405c2ef139a1fa30da7bd01a6f945eb0@localhost>
CLIENT -> SERVER: X-Mailer: PHPMailer 5.2.16 (https://github.com/PHPMailer/PHPMailer)
CLIENT -> SERVER: MIME-Version: 1.0
CLIENT -> SERVER: Content-Type: multipart/alternative;
CLIENT -> SERVER: boundary="b1_405c2ef139a1fa30da7bd01a6f945eb0"
CLIENT -> SERVER: Content-Transfer-Encoding: 8bit
CLIENT -> SERVER:
CLIENT -> SERVER: This is a multi-part message in MIME format.
CLIENT -> SERVER:
CLIENT -> SERVER: --b1_405c2ef139a1fa30da7bd01a6f945eb0
CLIENT -> SERVER: Content-Type: text/plain; charset=us-ascii
CLIENT -> SERVER:
CLIENT -> SERVER: This is a plain-text message body
CLIENT -> SERVER:
CLIENT -> SERVER:
CLIENT -> SERVER: --b1_405c2ef139a1fa30da7bd01a6f945eb0
CLIENT -> SERVER: Content-Type: text/html; charset=us-ascii
CLIENT -> SERVER:
CLIENT -> SERVER: This is the HTML message body <b>in bold!</b>
CLIENT -> SERVER:
CLIENT -> SERVER:
CLIENT -> SERVER:
CLIENT -> SERVER: --b1_405c2ef139a1fa30da7bd01a6f945eb0--
CLIENT -> SERVER:
CLIENT -> SERVER: .
SERVER -> CLIENT: 550 5.3.4 554-554 5.2.0 STOREDRV.Deliver; delivery result banner
SMTP ERROR: DATA END command failed: 550 5.3.4 554-554 5.2.0 STOREDRV.Deliver; delivery result banner
SMTP Error: data not accepted.
Failed to compile or link yasm program that call c function
When try to call c function from assembly code (yasm) on linux (x86-64), it failed to execute.
Code
function_call_c.asm:
; yasm assembly program, instruction - call c function
; compile: yasm -f elf64 function_call_c.asm -g dwarf2 && ld function_call_c.o -lc
; execute: ./a.out
section .data
msg_format db "hello"
section .text
extern printf
global _start
_start:
lea rdi, [msg_format]
call printf
_exit:
; exit
mov eax,1
mov ebx,5
int 0x80
Compile:
yasm -f elf64 function_call_c.asm -g dwarf2 && ld function_call_c.o -lc
When execute:
It tips:
bash: ./a.out: No such file or directory
but a.out do exists, and has execution permission.
Using readelf, get the compiled code:
ELF Header:
Magic: 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00
Class: ELF64
Data: 2's complement, little endian
Version: 1 (current)
OS/ABI: UNIX - System V
ABI Version: 0
Type: EXEC (Executable file)
Machine: Advanced Micro Devices X86-64
Version: 0x1
Entry point address: 0x400230
Start of program headers: 64 (bytes into file)
Start of section headers: 1432 (bytes into file)
Flags: 0x0
Size of this header: 64 (bytes)
Size of program headers: 56 (bytes)
Number of program headers: 5
Size of section headers: 64 (bytes)
Number of section headers: 21
Section header string table index: 18
Section Headers:
[Nr] Name Type Address Offset
Size EntSize Flags Link Info Align
[ 0] NULL 0000000000000000 00000000
0000000000000000 0000000000000000 0 0 0
[ 1] .interp PROGBITS 0000000000400158 00000158
000000000000000f 0000000000000000 A 0 0 1
[ 2] .hash HASH 0000000000400168 00000168
0000000000000014 0000000000000004 A 3 0 8
[ 3] .dynsym DYNSYM 0000000000400180 00000180
0000000000000030 0000000000000018 A 4 1 8
[ 4] .dynstr STRTAB 00000000004001b0 000001b0
000000000000001e 0000000000000000 A 0 0 1
[ 5] .gnu.version VERSYM 00000000004001ce 000001ce
0000000000000004 0000000000000002 A 3 0 2
[ 6] .gnu.version_r VERNEED 00000000004001d8 000001d8
0000000000000020 0000000000000000 A 4 1 8
[ 7] .rela.plt RELA 00000000004001f8 000001f8
0000000000000018 0000000000000018 A 3 8 8
[ 8] .plt PROGBITS 0000000000400210 00000210
0000000000000020 0000000000000010 AX 0 0 16
[ 9] .text PROGBITS 0000000000400230 00000230
0000000000000019 0000000000000000 AX 0 0 16
[10] .eh_frame PROGBITS 0000000000400250 00000250
0000000000000000 0000000000000000 A 0 0 8
[11] .dynamic DYNAMIC 0000000000600250 00000250
0000000000000140 0000000000000010 WA 4 0 8
[12] .got.plt PROGBITS 0000000000600390 00000390
0000000000000020 0000000000000008 WA 0 0 8
[13] .data PROGBITS 00000000006003b0 000003b0
0000000000000005 0000000000000000 WA 0 0 4
[14] .debug_aranges PROGBITS 0000000000000000 000003c0
0000000000000030 0000000000000000 0 0 16
[15] .debug_info PROGBITS 0000000000000000 000003f0
0000000000000089 0000000000000000 0 0 1
[16] .debug_abbrev PROGBITS 0000000000000000 00000479
0000000000000014 0000000000000000 0 0 1
[17] .debug_line PROGBITS 0000000000000000 0000048d
000000000000004b 0000000000000000 0 0 1
[18] .shstrtab STRTAB 0000000000000000 000004d8
00000000000000bc 0000000000000000 0 0 1
[19] .symtab SYMTAB 0000000000000000 00000ad8
00000000000002b8 0000000000000018 20 24 8
[20] .strtab STRTAB 0000000000000000 00000d90
0000000000000078 0000000000000000 0 0 1
Key to Flags:
W (write), A (alloc), X (execute), M (merge), S (strings), l (large)
I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown)
O (extra OS processing required) o (OS specific), p (processor specific)
There are no section groups in this file.
Program Headers:
Type Offset VirtAddr PhysAddr
FileSiz MemSiz Flags Align
PHDR 0x0000000000000040 0x0000000000400040 0x0000000000400040
0x0000000000000118 0x0000000000000118 R E 8
INTERP 0x0000000000000158 0x0000000000400158 0x0000000000400158
0x000000000000000f 0x000000000000000f R 1
[Requesting program interpreter: /lib/ld64.so.1]
LOAD 0x0000000000000000 0x0000000000400000 0x0000000000400000
0x0000000000000250 0x0000000000000250 R E 200000
LOAD 0x0000000000000250 0x0000000000600250 0x0000000000600250
0x0000000000000165 0x0000000000000165 RW 200000
DYNAMIC 0x0000000000000250 0x0000000000600250 0x0000000000600250
0x0000000000000140 0x0000000000000140 RW 8
Section to Segment mapping:
Segment Sections...
00
01 .interp
02 .interp .hash .dynsym .dynstr .gnu.version .gnu.version_r .rela.plt .plt .text
03 .dynamic .got.plt .data
04 .dynamic
Dynamic section at offset 0x250 contains 15 entries:
Tag Type Name/Value
0x0000000000000001 (NEEDED) Shared library: [libc.so.6]
0x0000000000000004 (HASH) 0x400168
0x0000000000000005 (STRTAB) 0x4001b0
0x0000000000000006 (SYMTAB) 0x400180
0x000000000000000a (STRSZ) 30 (bytes)
0x000000000000000b (SYMENT) 24 (bytes)
0x0000000000000015 (DEBUG) 0x0
0x0000000000000003 (PLTGOT) 0x600390
0x0000000000000002 (PLTRELSZ) 24 (bytes)
0x0000000000000014 (PLTREL) RELA
0x0000000000000017 (JMPREL) 0x4001f8
0x000000006ffffffe (VERNEED) 0x4001d8
0x000000006fffffff (VERNEEDNUM) 1
0x000000006ffffff0 (VERSYM) 0x4001ce
0x0000000000000000 (NULL) 0x0
Relocation section '.rela.plt' at offset 0x1f8 contains 1 entries:
Offset Info Type Sym. Value Sym. Name + Addend
0000006003a8 000100000007 R_X86_64_JUMP_SLO 0000000000000000 printf + 0
The decoding of unwind sections for machine type Advanced Micro Devices X86-64 is not currently supported.
Symbol table '.dynsym' contains 2 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 0000000000000000 0 NOTYPE LOCAL DEFAULT UND
1: 0000000000000000 0 FUNC GLOBAL DEFAULT UND printf@GLIBC_2.2.5 (2)
Symbol table '.symtab' contains 29 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 0000000000000000 0 NOTYPE LOCAL DEFAULT UND
1: 0000000000400158 0 SECTION LOCAL DEFAULT 1
2: 0000000000400168 0 SECTION LOCAL DEFAULT 2
3: 0000000000400180 0 SECTION LOCAL DEFAULT 3
4: 00000000004001b0 0 SECTION LOCAL DEFAULT 4
5: 00000000004001ce 0 SECTION LOCAL DEFAULT 5
6: 00000000004001d8 0 SECTION LOCAL DEFAULT 6
7: 00000000004001f8 0 SECTION LOCAL DEFAULT 7
8: 0000000000400210 0 SECTION LOCAL DEFAULT 8
9: 0000000000400230 0 SECTION LOCAL DEFAULT 9
10: 0000000000400250 0 SECTION LOCAL DEFAULT 10
11: 0000000000600250 0 SECTION LOCAL DEFAULT 11
12: 0000000000600390 0 SECTION LOCAL DEFAULT 12
13: 00000000006003b0 0 SECTION LOCAL DEFAULT 13
14: 0000000000000000 0 SECTION LOCAL DEFAULT 14
15: 0000000000000000 0 SECTION LOCAL DEFAULT 15
16: 0000000000000000 0 SECTION LOCAL DEFAULT 16
17: 0000000000000000 0 SECTION LOCAL DEFAULT 17
18: 0000000000000000 0 FILE LOCAL DEFAULT ABS function_call_c.asm
19: 000000000040023d 0 NOTYPE LOCAL DEFAULT 9 _exit
20: 00000000006003b0 0 NOTYPE LOCAL DEFAULT 13 msg_format
21: 0000000000000000 0 FILE LOCAL DEFAULT ABS
22: 0000000000600250 0 OBJECT LOCAL DEFAULT 11 _DYNAMIC
23: 0000000000600390 0 OBJECT LOCAL DEFAULT 12 _GLOBAL_OFFSET_TABLE_
24: 00000000006003b5 0 NOTYPE GLOBAL DEFAULT 13 _edata
25: 0000000000000000 0 FUNC GLOBAL DEFAULT UND printf@@GLIBC_2.2.5
26: 00000000006003b8 0 NOTYPE GLOBAL DEFAULT 13 _end
27: 0000000000400230 0 NOTYPE GLOBAL DEFAULT 9 _start
28: 00000000006003b5 0 NOTYPE GLOBAL DEFAULT 13 __bss_start
Histogram for bucket list length (total of 1 buckets):
Length Number % of total Coverage
0 0 ( 0.0%)
1 1 (100.0%) 100.0%
Version symbols section '.gnu.version' contains 2 entries:
Addr: 00000000004001ce Offset: 0x0001ce Link: 3 (.dynsym)
000: 0 (*local*) 2 (GLIBC_2.2.5)
Version needs section '.gnu.version_r' contains 1 entries:
Addr: 0x00000000004001d8 Offset: 0x0001d8 Link: 4 (.dynstr)
000000: Version: 1 File: libc.so.6 Cnt: 1
0x0010: Name: GLIBC_2.2.5 Flags: none Version: 2
The question is:
- Why it failed to execute, is the code wrong? or I compiled it in a wrong way?