Wednesday 31 July 2019

php - Warning: mysql_connect(): Access denied




i have this php function to read my dbinfo out of a textfile on my pc:



function loaddb(){
$fh = fopen('dta.txt','r');
$line = fgets($fh);
$_SESSION['dbname']=$line;

$line = fgets($fh);
$_SESSION['dbuser']=$line;


$line = fgets($fh);
$_SESSION['dbpass']=$line;

$line = fgets($fh);
$_SESSION['server']=$line;
fclose($fh);
};


and this code works. but when it returns my code into my session var i see it has added extra line breaks in the actual variable, so the result when i connect is





Warning: mysql_connect(): Access denied for user 'root



'@'localhost' (using password: YES) in
C:\Users\Jacques\Dropbox\Jacques\Web\Code.php on line 37 Could not
connect: Access denied for user 'root



'@'localhost' (using password: YES)





how can i fix this. i have tried replacing all character return and spaces but it doesnt help



this is the text in my textfile




dbname



root




password



localhost:3306



Answer



If you're sure that the whitespaces are on each end of the string, you can use trim()



$_SESSION['dbname']= trim($line);



When you're dealign with a string that can have several spaces, you can solve that with a simple regular expression:



$regex = '/(\s)\s+/'; // Select a whitespace and following whitespaces
$str = preg_replace($regex, '$1', $str); // Replace with the first whitespace








Saving your database credentials in a text file in your www folder is a very bad practise. If someone happens to find the filename he can read your credentials.



PHP code however is parsed before sent to the client, thus client's can't access the credentials (unless you echo them).



config.php



define('DB_HOST', 'localhost:3306');
define('DB_NAME', 'dbname');
define('DB_USER', 'root');

define('DB_PASS', 'password');


Then, whenever you need your database credentials:



require 'config.php';
// connect here






Another sidenote



The mysql_ functions are deprecated as of PHP 5.5.0. You should use mysqli_ or PDO instead. I prefer PDO myself.


what does something::something means in yii?

I'm a newbie in programming and now I'm learning yii framework and it's really hard.



What does this declaration mean :
something::something



for instance : CHtml::encode, yii::appname, CHtml::dropDownList, etc...



    Yii::app()->request->baseUrl;


CHtml::encode($data->getAttributeLabel


What does it actually means?



And do you guys have a recommendation for learning yii framework other than Larry Ullman's?
I really need a tutorial.



Thanks.

go - Assign additional field when unmarshalling JSON object to struct

What is the best way to assign additional field to struct and all it references sub-structure when encoding it from []byte and this field is not a part of unmarshalling []byte?



Let me clarify by example...




  1. We have a few struct:





type Update struct {
UpdateID int32 `json:"update_id"`
Message *Message `json:"message,omitempty"`
...
}

type Message struct {
MessageID int32 `json:"message_id"`
From *User `json:"from,omitempty"`
Date int32 `json:"date"`
Chat Chat `json:"chat"`
...
}




  1. Our core struct is APIClient and it has many methods for send something or get something (API wrapper)





type API struct {
Token string
PollInt int32
URL string

client *http.Client
}

func(a *API) ... () {

}

func(a *API) ... () {

}

...




  1. Main loop poller make http request and return json response as "res" – []byte, so we can use json.Unmarshal to map it to special Update struct





func (a *API) GetUpdates(ctx context.Context, gu *GetUpdates) ([]Update, error) {
buf := bytes.Buffer{}
err := json.NewEncoder(&buf).Encode(gu)
if err != nil {
return nil, fmt.Errorf("getupdates: %s", err)
}

res, err := a.DoRequest(&ctx, "getUpdates", &buf)
if err != nil {
return nil, fmt.Errorf("getupdates: %s", err)
}

var result []Update
err = json.Unmarshal(res.Result, &result)
if err != nil {
return nil, fmt.Errorf("getupdates: %s", err)
}

return result, nil
}




  1. Is it any way to extend ALL structs in unmarhsaling chain for a additional field when use json.Unmarshal





type Update struct {
UpdateID int32 `json:"update_id"`
Message *Message `json:"message,omitempty"`
...

API `json:"-"`
}

type Message struct {
MessageID int32 `json:"message_id"`
From *User `json:"from,omitempty"`
Date int32 `json:"date"`
Chat Chat `json:"chat"`
...

API `json:"-"`
}



So we can do something like:





var result []Update
err = json.Unmarshal(res.Result, &result, api)
if err != nil {
return nil, fmt.Errorf("getupdates: %s", err)
}



And then use it:





result[0].RejectUpdate()
result[0].Message.SendReply()
...
func (u *Update) RejectUpdate(cause string) {
m.API.SendMessage(u.Chat.ID, text)
m.API.Reject(u.ID, cause)
}
func (m *Message) SendReply(text string) {
m.API.SendMessage(m.Chat.ID, text)
}



All struct will be extended by api (embedded struct) on unmarshaling...



My thoughts about solution:




  1. Patch standard encoding/json library – not a good choice

  2. Get custom encoding library and rewrite a little bit – questionable choice

  3. Manually unmarshal all object – awful code





type Bot struct {
superCLient string
}

type Image struct {
Name string
Path string

*Bot `json:"-"`
}

type FormFile struct {
Img *Image
Name string

*Bot `json:"-"`
}

func main() {
data := []byte(`{"Img": {"Name": "Vi", "Path": "/etc/log"}, "Name": "Josh"}`)
bot := &Bot{
superCLient: "ClientExample",
}
var omg FormFile
omg.CustomUnmarshal(data, bot)
fmt.Println(omg)
}

func (ff *FormFile) CustomUnmarshal(data []byte, bot *Bot) error {
var f map[string]*json.RawMessage
json.Unmarshal(data, &f)

var i Image
i.CustomUnmarshal(*f["Img"], bot)
ff.Img = &i

json.Unmarshal(*f["Name"], ff.Name)

ff.Bot = bot

return nil
}

func (img *Image) CustomUnmarshal(data []byte, bot *Bot) error {
err := json.Unmarshal(data, img)
img.Bot = bot
return err
}

javascript - Google Visualization API php ajax



I am using this Achieving Google Visualization chart reloads using ajax example to dynamically retrieve data from Mysql database and I get "Uncaught SyntaxError: Unexpected token <" error.
This is my HTML file




















and This is my PHP file test.php







$con = mysql_connect("localhost","userName","password");

if (!$con)

{

die('Could not connect: ' . mysql_error());


}

mysql_select_db("DB_NAME", $con);

$result = mysql_query("call cargosys.rpt_salesByDate('2013/03/05','2013/03/10')");
$output = array();
while($row = mysql_fetch_array($result)) {
// create a temp array to hold the data
$temp = array();


// add the data
$temp[] = $row['inv_no'];
$temp[] = ''' . $row['bl_no'] . ''';
$temp[] = ''' . $row['inv_date'] . ''';
$temp[] = ''' . $row['cust_name'] . ''';
$temp[] = $row['Amount'];

// implode the temp array into a comma-separated list and add to the output array
$output[] = '[' . implode(', ', $temp) . ']';

}

// implode the output into a comma-newline separated list and echo
echo implode(",\n", $output);
//echo json_encode($output);
mysql_close($con);


Answer



Inside the success function do:




console.log(responseData);


Then copy and paste responseData into the JSON validator at jsonlint.com



I am guessing it's a JSON syntax error, which the validator will point out to you.


What is the function of the push / pop instructions used on registers in x86 assembly?



When reading about assembler I often come across people writing that they push a certain register of the processor and pop it again later to restore it's previous state.




  • How can you push a register? Where is it pushed on? Why is this needed?

  • Does this boil down to a single processor instruction or is it more complex?


Answer



pushing a value (not necessarily stored in a register) means writing it to the stack.



popping means restoring whatever is on top of the stack into a register. Those are basic instructions:



push 0xdeadbeef      ; push a value to the stack
pop eax ; eax is now 0xdeadbeef

; swap contents of registers
push eax
mov eax, ebx
pop ebx

c++ - When to use reinterpret_cast?



I am little confused with the applicability of reinterpret_cast vs static_cast. From what I have read the general rules are to use static cast when the types can be interpreted at compile time hence the word static. This is the cast the C++ compiler uses internally for implicit casts also.



reinterpret_casts are applicable in two scenarios:




  • convert integer types to pointer types and vice versa

  • convert one pointer type to another. The general idea I get is this is unportable and should be avoided.




Where I am a little confused is one usage which I need, I am calling C++ from C and the C code needs to hold on to the C++ object so basically it holds a void*. What cast should be used to convert between the void * and the Class type?



I have seen usage of both static_cast and reinterpret_cast? Though from what I have been reading it appears static is better as the cast can happen at compile time? Though it says to use reinterpret_cast to convert from one pointer type to another?


Answer



The C++ standard guarantees the following:



static_casting a pointer to and from void* preserves the address. That is, in the following, a, b and c all point to the same address:



int* a = new int();

void* b = static_cast(a);
int* c = static_cast(b);


reinterpret_cast only guarantees that if you cast a pointer to a different type, and then reinterpret_cast it back to the original type, you get the original value. So in the following:



int* a = new int();
void* b = reinterpret_cast(a);
int* c = reinterpret_cast(b);



a and c contain the same value, but the value of b is unspecified. (in practice it will typically contain the same address as a and c, but that's not specified in the standard, and it may not be true on machines with more complex memory systems.)



For casting to and from void*, static_cast should be preferred.


javascript - from origin 'null' has been blocked by CORS policy: Cross origin requests

This error occurred while calling up JSON.
I don't know why this error is happening.



$.getJSON(url, function(data){
console.log(data);
});


Error:




Access to XMLHttpRequest at (this is JSON URL) from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

Tuesday 30 July 2019

c - fopen returns non-null pointer even though file does not exist

I have a Hex file whose contents are like below:



0x14000800
0x52100000
0xD503201F
0xD503201F
0x0030A308
0x0032D138

0x00000000
0x00000000
0x00000000
0x00000000



I need to open and read this file. Below is my code:



#include 
#include


int main(void)
{
char ch, boot_rom_golden[16];
FILE *myFile = NULL;

myFile = fopen("/prj/vlsi/tests/boot_rom_fail/src/apps_proc0/sm6140_rom.a52100000_ROM_FULL.hex", "r");

if (myFile == NULL) {
printf("Error Reading File\n");
exit(0);

}

while ((ch = fgetc(myFile)) != EOF) {
printf("%x \n", ch);
}


I have two questions:





  1. My understanding is if the file does not exist in the above mentioned path, then fopen should return a NULL. Observation is : even if the file does not exist in the above path (/prj/vlsi/....) , fopen is returning some value and then it goes to while loop trying to print the content. Why is this happening? My main.c and the hex file are residing in the same path. But still I tried giving the complete path which also gave the same results (i.e. even if file does not exist it is returning a non zero pointer value)


  2. When the code executes while loop, it prints "FF" indefinitely. It should be because of reason stated above.




Please help to know the issue and how to debug these kind of issues ?

java - Mockito - verify object not invoked at all



How can you verify a mocked object is not invoked at all? I am trying to test the empty implementation of an interface method using Mockito.


Answer



See Mockito API Article 7. Making sure interaction(s) never happened on mock


Do all the McBain clips in The Simpsons form a film when pieced together? - Movies & TV




I was told before that all the McBain clips on The Simpsons, though they may seem independent, when pieced together actually make a full film where each clip follows on from the previous one.



I've looked on YouTube but I couldn't find anything. Does anyone know if this is the case?


Answer



Funny or Die pieced all the clips together and can be seen here and they do make one long clip.



From FoD




McBain from the Simpsons is actually a full length film when you put them all together.




c# - How to pass generic enum parameter to method?

public static string GetCustomerIssueStatus(this HtmlHelper html, byte number)
{
return Enum.GetName(typeof(Shared.Enumerators.CustomerIssueStatus), number);
}


How could I create this extension method, to accept all enum types as parameter?

dynamic languages - How does JavaScript .prototype work?




I'm not that into dynamic programming languages but I've written my fair share of JavaScript code. I never really got my head around this prototype-based programming, does any one know how this works?



var obj = new Object();
obj.prototype.test = function() { alert('Hello?'); };
var obj2 = new obj();
obj2.test();


I remember a lot discussion I had with people a while back (I'm not exactly sure what I'm doing) but as I understand it, there's no concept of a class. It's just an object, and instances of those objects are clones of the original, right?




But what is the exact purpose of this ".prototype" property in JavaScript? How does it relate to instantiating objects?



Update: correct way



var obj = new Object(); // not a functional object
obj.prototype.test = function() { alert('Hello?'); }; // this is wrong!

function MyObject() {} // a first class functional object
MyObject.prototype.test = function() { alert('OK'); } // OK



Also these slides really helped a lot.


Answer



Every JavaScript object has an internal property called [[Prototype]]. If you look up a property via obj.propName or obj['propName'] and the object does not have such a property - which can be checked via obj.hasOwnProperty('propName') - the runtime looks up the property in the object referenced by [[Prototype]] instead. If the prototype-object also doesn't have such a property, its prototype is checked in turn, thus walking the original object's prototype-chain until a match is found or its end is reached.



Some JavaScript implementations allow direct access to the [[Prototype]] property, eg via a non-standard property named __proto__. In general, it's only possible to set an object's prototype during object creation: If you create a new object via new Func(), the object's [[Prototype]] property will be set to the object referenced by Func.prototype.



This allows to simulate classes in JavaScript, although JavaScript's inheritance system is - as we have seen - prototypical, and not class-based:




Just think of constructor functions as classes and the properties of the prototype (ie of the object referenced by the constructor function's prototype property) as shared members, ie members which are the same for each instance. In class-based systems, methods are implemented the same way for each instance, so methods are normally added to the prototype, whereas an object's fields are instance-specific and therefore added to the object itself during construction.


analysis - Which audience was targeted by "Scarecrow and Mrs. King"? - Movies & TV



"Scarecrow and Mrs. King" told the story of a divorced mom who accidentally meets a hunky secret agent and -- unbeknownst to her family and friends -- joins the secret agent on many spy adventures.




As a pre-teen viewer, I liked the show for its action and adventure, and I also had a boy's crush on Mrs. King (Kate Jackson). But more than 20 years later, I realize the show also seems to have offered an appealing escape fantasy to adult women, not to mention the cute capering of a former Charlie's Angel to adult men.



For a long time, I assumed "Scarecrow & Mrs. King" was aimed at kids, kind of like "A-Team" or "Knight Rider". But is that accurate? Which audience was "Scarecrow and Mrs. King" trying to attract -- kids, adult women, adult men, or some combination of the three?


Answer



I think the audience desired was Nielsen Families. Really the three shows you described all had a target audience of families. In the 80's there were a lot of family shows that were trying to include action into their format. So most shows on during primetime were either an action family show or a family sitcom. This show really did attract a wide range of audience though. Having a former Charlie's Angel on attracted both men and women, a bored house wife appealed to women, the handsome secret agent pulled in women for the handsome and men and kids for the secret agent. Also kids and moms related to Mrs. King since she was a regular mom. Women could daydream they were Mrs. King men could daydream they were the secret agent and kids could daydream that their mom was a spy while they were at school.


film techniques - How do they prevent animal cruelty in movies?

According to a number of sources, cruelty to animals is an offence and it is punishable in most countries. But in historical film it's inevitable, because if a film is looking to be historically accurate, and hunting animals (for example) was something important to the historical period and in battle sequences. For instance, in Gladiator the horse sequence at the initial battle were worst and of course that's a worst animal abuse sequences.


According to wikipedia,



TV & film making


Animal cruelty has long been an issue with the art form of filmmaking,
with even some big-budget Hollywood films receiving criticism for
allegedly harmful—and sometimes lethal—treatment of animals during
production. One of the most infamous examples of animal cruelty in
film was Michael Cimino's legendary flop Heaven's Gate, in which
numerous animals were brutalized and even killed during production.



I'm curious to know about, nowadays, do the directors follow any techniques to prevent animal cruelty i.e filming with trained animals, faking the slaughter of animals?


r - Change hover over values in a plotly plot



I have the following Shiny Application:



library(shiny)
library(plotly)

ui <- fluidPage(

plotlyOutput("plot")
)

server <- function(input, output) {

# renderPlotly() also understands ggplot2 objects!
output$plot <- renderPlotly({
plot_ly(mtcars, x = ~mpg, y = ~wt)
})


}

shinyApp(ui, server)


If I now hoover over a point I get values like: (14.5, 17.3). Is there an easy way to make sure these values appear as:



mpg: 12.3 [enter]
wt: 45.2


Answer




I believe the following does what you want:



library(shiny)
library(plotly)

ui <- fluidPage(
plotlyOutput("plot")
)

server <- function(input, output) {


# renderPlotly() also understands ggplot2 objects!
output$plot <- renderPlotly({
plot_ly(mtcars,
x = ~mpg,
y = ~wt,
hoverinfo="text",
text = ~paste0("mpg: ", mpg, "\nwt: ", wt))
})


}

shinyApp(ui, server)


enter image description here



Hope this helps!


language agnostic - Pass by reference or pass by value?

When learning a new programming language, one of the possible roadblocks you might encounter is the question whether the language is, by default, pass-by-value or pass-by-reference.



So here is my question to all of you, in your favorite language, how is it actually done? And what are the possible pitfalls?



Your favorite language can, of course, be anything you have ever played with: popular, obscure, esoteric, new, old...

Parameterised IN Clause in prepared statement using MySql,PHP and ADODB




I am writing some SQL and using AdoDb to connect to my database and run the queries and so on. I am using parametrized queries and have run into a snag.



Is their a way to pass an array of values to an in_clause in AdoDb/MySql for parametrization.



My problem is that if I pass a prepared string as the parameter i.e. 'test','test2','test3' it does not work as the library or database auto escapes it and adds external quotes at the start and end so all the internal quotes are then auto escaped thus the query returns nothing as it looks for '\'test\',\'test2\',\'test3\'' as opposed to what I fed it.



UPDATED WITH ANOTHER POSSIBLE METHOD TO ACCOMPLISH THIS




$in_clause = implode(",", $first_names);

$query = "
SELECT
mytable_id_pk
FROM
mytable
WHERE
FIND_IN_SET(mytable_fname," . $DB->Param('first_names') . ")"


$stmt = $DB->Prepare($query);

$result = $DB->Execute($stmt,array($in_clause));
?>

Answer



I would do it this way (as I was googling for a while and google came up with nothing useful):



$count = count($first_names);
$in_params = trim(str_repeat('?, ', $count), ', ');


$query = "
SELECT
mytable_id_pk
FROM
mytable
WHERE
mytable_fname IN ({$in_params});";

$stmt = $DB->Prepare($query);

$result = $DB->Execute($stmt, $first_names);


This should do it...


mysql - Cannot add foreign key constraint (GUID)



I developing a synchronization module in vb.net, so for avoid duplicate id on different record I'm using the GUID. Now what I'm trying to do is set the GUID as primary key (PK) on my table. This is the structure of the two table:



USERS




CREATE TABLE IF NOT EXISTS `users` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`GUID` char(36) NOT NULL,
`first_name` varchar(256) DEFAULT NULL,
`last_name` varchar(512) DEFAULT NULL,
`email` varchar(512) DEFAULT NULL,
`mobile_number` varchar(128) DEFAULT NULL,
`phone_number` varchar(128) DEFAULT NULL,
`address` varchar(256) DEFAULT NULL,

`city` varchar(256) DEFAULT NULL,
`state` varchar(128) DEFAULT NULL,
`zip_code` varchar(64) DEFAULT NULL,
`notes` text,
`id_roles` bigint(20) unsigned NOT NULL,
`data` int(11) NOT NULL,
`lastUpdated` varchar(36),
PRIMARY KEY (`id`),
KEY `id_roles` (`id_roles`)
) ENGINE=InnoDB AUTO_INCREMENT=85 DEFAULT CHARSET=utf8;



USER_SETTINGS



CREATE TABLE IF NOT EXISTS `user_settings` (
`id_users` bigint(20) unsigned NOT NULL,
`GUID` char(36) NOT NULL,
`username` varchar(256) DEFAULT NULL,
`password` varchar(512) DEFAULT NULL,
`salt` varchar(512) DEFAULT NULL,

`working_plan` text,
`notifications` tinyint(4) DEFAULT '0',
`google_sync` tinyint(4) DEFAULT '0',
`google_token` text,
`google_calendar` varchar(128) DEFAULT NULL,
`sync_past_days` int(11) DEFAULT '5',
`sync_future_days` int(11) DEFAULT '5',
`lastUpdated` varchar(36),
PRIMARY KEY (`GUID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;



How you can see I've set the FK as GUID field in user_settings table, the GUID is taken from the users table by this:



ALTER TABLE `user_settings`
ADD CONSTRAINT `user_settings_ibfk_1` FOREIGN KEY (`GUID`) REFERENCES `users` (`GUID`) ON DELETE CASCADE ON UPDATE CASCADE;


But I ge this error message:





1215 - Cannot add foreign key constraint




What I did wrong?


Answer



The parent field (field in users) needs to be the primary key. You have the GUID field in the user_settings table defined as primary key. That doesnt make sense. You should have the GUID in the users as primary key, in the user_settings as simple field. Then the relationship works. Or you create an ID field in user_settings and use the 2 id fields to create the foreign key constraint.



CREATE TABLE IF NOT EXISTS `users` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,

`GUID` char(36) NOT NULL,
`first_name` varchar(256) DEFAULT NULL,
`last_name` varchar(512) DEFAULT NULL,
`email` varchar(512) DEFAULT NULL,
`mobile_number` varchar(128) DEFAULT NULL,
`phone_number` varchar(128) DEFAULT NULL,
`address` varchar(256) DEFAULT NULL,
`city` varchar(256) DEFAULT NULL,
`state` varchar(128) DEFAULT NULL,
`zip_code` varchar(64) DEFAULT NULL,

`notes` text,
`id_roles` bigint(20) unsigned NOT NULL,
`data` int(11) NOT NULL,
`lastUpdated` varchar(36),
PRIMARY KEY (`id`),
KEY `id_roles` (`id_roles`)
) ENGINE=InnoDB AUTO_INCREMENT=85 DEFAULT CHARSET=utf8;


CREATE TABLE IF NOT EXISTS `user_settings` (

`id_users` bigint(20) unsigned NOT NULL,
`id` bigint(20) unsigned NOT NULL,
`GUID` char(36) NOT NULL,
`username` varchar(256) DEFAULT NULL,
`password` varchar(512) DEFAULT NULL,
`salt` varchar(512) DEFAULT NULL,
`working_plan` text,
`notifications` tinyint(4) DEFAULT '0',
`google_sync` tinyint(4) DEFAULT '0',
`google_token` text,

`google_calendar` varchar(128) DEFAULT NULL,
`sync_past_days` int(11) DEFAULT '5',
`sync_future_days` int(11) DEFAULT '5',
`lastUpdated` varchar(36),
PRIMARY KEY (`GUID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `user_settings`
ADD CONSTRAINT `user_settings_ibfk_1` FOREIGN KEY (`id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE



With this example all user_settings for a user will be deleted.


Best Video Tutorial/Books or Tutorials Sites to Learn VB.NET/C&C++ and C#.NET


Possible Duplicates:
Beginning C#
The Definitive C++ Book Guide and List
How to start programming from scratch?






I'm currently trying these programming languanges but I dont' know where to find my resources.Please help me guys.

c++ - How to increase file reading speed?

I have large .txt files with more than a million lines and 7 colums of float numbers per line. The columns are seperated via spaces.



Currently, I import the files by reading each line (getline), transforming the line to a stream and then storing the seven values into array variables (please see my minimal example). However, this procedure is quite slow and takes around 10 minutes for 3 million lines (500MB). This corresponds to 0.8 MB/s and is much slower than it takes to write the files. My hard drive is SSD.



Can you give me advice of how to improve the efficiency of the code?



Bests, Fabian



C++



#include 
#include
#include
#include

struct Container { double a, b, c, d, e, f, g; };

void read_my_file(std::ifstream &file, Container *&data) {
std::string line;
std::stringstream line_as_stream;
unsigned int column;
unsigned long int row;

data = new Container[300000]; //dynamically allocated because the
//length is usually a user input.

for (row = 0; row < 300000; row++) {
getline(file, line);
line_as_stream.str(line);

for (column = 0; column < 7; column++) {
line_as_stream >> data[row].a;
line_as_stream >> data[row].b;
line_as_stream >> data[row].c;
line_as_stream >> data[row].d;
line_as_stream >> data[row].e;
line_as_stream >> data[row].f;
line_as_stream >> data[row].g;
}

line_as_stream.clear();
}
}

int main(void) {
Container *data = nullptr;
std::ifstream file;

file.open("./myfile.txt", std::ios::in);
read_my_file(file, data);
std::cout << data[2].b << "\n";

file.close();

return 0;
}

how to unzip zip files in php

My gallery script provides me with the option to upload a bunch of images through a zip file.
When I try to do this I receive the error line:

Fatal error: Call to undefined function: zip_open() in ..



Heres an extract of the phpinfo:



ZLib Support: enabled
Compiled Version: 1.1.4
Linked Version: 1.1.4



zlib.output_compression: Off
zlib.output_compression_level: -1

zlib.output_handler: no value



Zlib is enabled .. so why do I receive that error message?
Thank you for helping me.

Include a JavaScript file






Possible Duplicates:
Include javascript file inside javascript file?
How do you dynamically load a javascript file? (Think C's #include)






Is there a way to include a JavaScript file from a .js file?
You know: like how I link .css files at the top of a .css file.






xxx.js contains:



Some sort of @import yyy.js
followed by other js commands.

Answer



this is my workaround to do this:



if (typeof (jQuery) == "undefined") 
document.write(unescape("%3Cscript src='" + server_url + "/js/jquery-1.4.2.min.js' type='text/javascript'%3E%3C/script%3E"));



of course, for anything other than jquery you'd have to figure out if you needed it or not then do the same with that file.



server_url needs to be set also.



here is a working example of this



http://my.digitalscout.com/Widgets/schedule.html


parsing - How to reformat JSON in Notepad++?



I need Notepad++ to take a json string from this



{"menu": {"id": "file","value": "File","popup": {"menuitem": [{"value": "New", "onclick": "CreateNewDoc()"},{"value": "Open", "onclick": "OpenDoc()"},{"value": "Close", "onclick": "CloseDoc()"}]}}}



to this...



{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},

{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}


I looked around at all the TextFX options but couldn't find anything that worked.


Answer




Update:




As of Notepad++ v7.6, use Plugin Admin to install JSTool per this answer




INSTALL



Download it from http://sourceforge.net/projects/jsminnpp/ and copy JSMinNpp.dll to plugin directory of Notepad++. Or you can just install "JSTool" from Plugin Manager in Notepad++.



New Notepad++ install and where did PluginManager go? See How to view Plugin Manager in Notepad++




{
"menu" : {
"id" : "file",
"value" : "File",
"popup" : {
"menuitem" : [{
"value" : "New",
"onclick" : "CreateNewDoc()"
}, {
"value" : "Open",

"onclick" : "OpenDoc()"
}, {
"value" : "Close",
"onclick" : "CloseDoc()"
}
]
}
}
}



enter image description here
Tip: Select the code you want to reformat, then Plugins | JSTool | JSFormat.


operators - What does ||= (or-equals) mean in Ruby?

a ||= b is the same as saying a = b if a.nil? or a = b unless a


But do all 3 options show the same performance? With Ruby 2.5.1 this


1000000.times do
a ||= 1
a ||= 1
a ||= 1
a ||= 1
a ||= 1
a ||= 1
a ||= 1
a ||= 1
a ||= 1
a ||= 1
end

takes 0.099 Seconds on my PC, while


1000000.times do
a = 1 unless a
a = 1 unless a
a = 1 unless a
a = 1 unless a
a = 1 unless a
a = 1 unless a
a = 1 unless a
a = 1 unless a
a = 1 unless a
a = 1 unless a
end

takes 0.062 Seconds. That's almost 40% faster.


and then we also have:


1000000.times do
a = 1 if a.nil?
a = 1 if a.nil?
a = 1 if a.nil?
a = 1 if a.nil?
a = 1 if a.nil?
a = 1 if a.nil?
a = 1 if a.nil?
a = 1 if a.nil?
a = 1 if a.nil?
a = 1 if a.nil?
end

which takes 0.166 Seconds.


Not that this will make a significant performance impact in general, but if you do need that last bit of optimization, then consider this result.
By the way: a = 1 unless a is easier to read for the novice, it is self-explanatory.


Note 1: reason for repeating the assignment line multiple times is to reduce the overhead of the loop on the time measured.


Note 2: The results are similar if I do a=nil nil before each assignment.

Monday 29 July 2019

scope - What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?



I have been reading a lot of Javascript lately and I have been noticing that the whole file is wrapped like the following in the .js files to be imported.



(function() {
...
code
...
})();



What is the reason for doing this rather than a simple set of constructor functions?


Answer



It's usually to namespace (see later) and control the visibility of member functions and/or variables. Think of it like an object definition. jQuery plugins are usually written like this.



In Javascript, you can nest functions. So, the following is legal:



function outerFunction() {
function innerFunction() {

// code
}
}


Now you can call outerFunction(), but the visiblity of innerFunction() is limited to the scope of outerFunction(), meaning it is private to outerFunction(). It basically follows the same principle as variables in Javascript:



var globalVariable;

function someFunction() {

var localVariable;
}


Correspondingly:



function globalFunction() {

var localFunction1 = function() {
//I'm anonymous! But localFunction1 is a reference to me!

};

function localFunction2() {
//I'm named!
}
}


In the above scenario, you can call globalFunction() from anywhere, but you cannot call localFunction1 or localFunction2.




What you're doing when you write (function() { ... code ... })(), is you're making the code inside a function literal (meaning the whole "object" is actually a function). After that, you're self-invoking the function (the final ()). So the major advantage of this as I mentioned before, is that you can have private methods/functions and properties:



(function() {
var private_var;

function private_function() {
//code
}
})()



In the first example, globalFunction() was the public function that could be called to access the public functionality, but in the above example how do you call it? Here the self-invoking function makes the code automatically run at start up. Just like you can add initMyStuff(); to the top of any .js file and it will automatically run as part of the global scope, this self-invoking function will also automatically run, although since it's an unnamed function it cannot be called multiple times like initMyStuff() could be.



The neat thing is that you can also define things inside and expose it to the outside world so (an example of namespacing so you can basically create your own library/plugin):



var myPlugin = (function() {
var private_var;

function private_function() {
}


return {
public_function1: function() {
},
public_function2: function() {
}
}
})()



Now you can call myPlugin.public_function1(), but you cannot access private_function()! So pretty similar to a class definition. To understand this better, I recommend the following links for some further reading:





EDIT



I forgot to mention. In that final (), you can pass anything you want inside. For example, when you create jQuery plugins, you pass in jQuery or $ like so:



(function(jQ) { ... code ... })(jQuery) 



So what you're doing here is defining a function that takes in one parameter (called jQ, a local variable, and known only to that function). Then you're self-invoking the function and passing in a parameter (also called jQuery, but this one is from the outside world and a reference to the actual jQuery itself). There is no pressing need to do this, but there are some advantages:




  • You can redefine a global parameter and give it a name that makes sense in the local scope.

  • There is a slight performance advantage since it is faster to look things up in the local scope instead of having to walk up the scope chain into the global scope.

  • There are benefits for compression (minification).



Earlier I described how these functions run automatically at startup, but if they run automatically who is passing in the arguments? This technique assumes all the parameters are defined as global variables. So if jQuery wasn't defined as a global variable this example would not work, and could not be called any other way since our example is an anonymous function. As you might guess, one things jquery.js does during it's initialization is define a 'jQuery' global variable, as well as it's more famous '$' global variable, which allows this code to work after jquery.js is included.



javascript - Uncaught TypeError: Cannot set property 'onclick' of null

I'm having problems making my window alert pop up with a simple checkbox and can't for the life of me figure out why. Here's the basic Javascript and HTML:






var blue_box=document.getElementById("color-blue");
function colorFunction() {
window.alert("This color is blue!");
}

blue_box.onclick=colorFunction;



Form!
















Which throws: Uncaught TypeError: Cannot set property 'onclick' of null
under



blue_box.onclick=colorFunction;



Are there any visible reasons for this error in my code?

javascript - jQuery $.getJSON throws Unexpected Token



I'm a JavaScript beginner. I want to retrieve some data from Steam Market using the following URL:



https://steamcommunity.com/market/priceoverview/?country=PL¤cy=3&appid=730&callback=?&market_hash_name=Operation%20Vanguard%20Weapon%20Case#



I get this response in my browser:



{"success":true,"lowest_price":"0,09\u20ac","volume":"1,017","median_price":"0,10\u20ac"}


But I can't get it to work in JS.



var amount = prompt("How many cases do you have?\t");
$.getJSON("http://steamcommunity.com/market/priceoverview/?country=PL¤cy=3&appid=730&callback=?&market_hash_name=Operation%20Vanguard%20Weapon%20Case#",

function(json) {
var raw_price = json.lowest_price;
var price = raw_price.split('&')[0];
var price_total = price*parseInt(amount);
alert(price_total + '€');
});


It just throws me:





Uncaught SyntaxError: Unexpected token :




What's wrong with this code?


Answer



The problem has been eventually solved by me. The issue was that Steam didn't allow to access their market data using a JavaScript code in a browser because of Access-Control-Allow-Origin.



I have rewritten my JS code to PHP and sent the same request, but this time from my own WWW server:




function get_price() {
$url = "https://steamcommunity.com/market/priceoverview/?country=PL¤cy=3&appid=730&callback=?&market_hash_name=Operation%20Vanguard%20Weapon%20Case";
$json = file_get_contents($url);
$price = json_decode($json);
$price_case = $price->{"lowest_price"};
return number_format($price_case, 2);
}


Worked like a charm.



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.


Android error: Failed to install *.apk on device *: timeout




I'm getting this error from time to time and don't know what causing this:
When trying to run/debug an Android app on a real device (Galaxy Samsung S in my case) I'm getting the following error in the Console:





Failed to install *.apk on device *:



timeout Launch canceled!




This is all the Console is telling me. LogCat doesn't provide any information. Eclipse Problems view is not showing any issues.



I tried the following steps with no success:
1. Cleaning the project (Project->Clean)
2. Restarting device, Eclipse, laptop, all of the above...
3. Moving the project to a location without spaces, according to Failed to install apk on device 'emulator-5554': timeout




The app has been debugged in the past on that device many times (app is live on Market), but this problem happens every so often, and is VERY FRUSTRATING...



Any help would be greatly appreciated! Thanks.


Answer



Try changing the ADB connection timeout. I think it defaults that to 5000ms and I changed mine to 10000ms to get rid of that problem.



If you are in Eclipse, you can do this by going through



Window -> Preferences -> Android -> DDMS -> ADB Connection Timeout (ms)


java - When a map variable is passed to constructor of different instances, all instances member variables are updated to latest value of map





Main Class --



package test;
import java.util.Map;

public class Client {
private static ArrayList allInstances = new ArrayList();
private static Map var1 = new HashMap();

public static void main(String[] args)

{
var1.put("key1","value1");
Class1 instance1 = new Class1(var1);
allInstances.add(instance1);

var1.put("key2","value2");
Class1 instance2 = new Class1(var1);
allInstances.add(instance2);

getInstances();

}

public static void getInstances() {
for(Class1 c: allInstances) {
System.out.println(c.getClassDetails());
}
}


Class Class1 --




package test
import java.util.Map;

public class Class1 {
private Map classDetails;

public Class1(Map classDetails) {
this.classDetails = classDetails;
}


public Map getClassDetails(){
return this.classDetails;
}
}


Output--



{key2=value2}

{key2=value2}


As we can see from the output above, both instances variable returns the same updated value. Should'nt instance1 return {key1=value1}



Also, if this is the expected behavior, what can be done to tackle this issue.


Answer



As it is appeared from your code, you referenced same HashMap to instacne1 and instance2 objects and in getClassDetails method the tostring method of same hashmap will invoked so the outputs is the same , use this code snippet :



import java.util.*;


public class Main {
private static ArrayList allInstances = new ArrayList();

public static void main(String[] args)
{
Map var = new HashMap();
var.put("key1","value1");
Class1 instance1 = new Class1(var);
allInstances.add(instance1);


var = new HashMap();
var.put("key2","value2");
Class1 instance2 = new Class1(var);
allInstances.add(instance2);

getInstances();
}

public static void getInstances() {

for(Class1 c: allInstances)
System.out.println(c.getClassDetails());
}
}

javascript - How to update the URL in the address bar but without reload to that URL?

How to update the URL in the address bar but without reload to that URL?



I found 2 solutions :




Solution 1:
Read here https://stackoverflow.com/a/4059844/2642351
Using window.history.replaceState.
However, when I implement it in my angularjs project it reverts back the URL immediately ot the previous one.



Solution 2:
Read here https://stackoverflow.com/a/24102139/2642351
This works for ngRoute however, Im using uiRouter. Is there a similar solution in uiRouter?

How to measure time taken by Java code?

Say you have a particular method that you would like to put under the microscope. You can do that as follows:



long time1 = System.nanoTime();
thatMethod();
long time2 = System.nanoTime();
long timeTaken = time2 - time1;
System.out.println("Time taken " + timeTaken + " ns");



Computers are really fast so it may happen that time difference when using getTimeMillis() maybe zero. Hence, use nanoTime()



You can also use Caliper. They have a video to get started. Plus, thoroughly read the answer pointed to by creichen. It has a lot of great stuff in it.

python - Remove the first character of a string

Your problem seems unclear. You say you want to remove "a character from a certain position" then go on to say you want to remove a particular character.



If you only need to remove the first character you would do:




s = ":dfa:sif:e"
fixed = s[1:]


If you want to remove a character at a particular position, you would do:



s = ":dfa:sif:e"
fixed = s[0:pos]+s[pos+1:]



If you need to remove a particular character, say ':', the first time it is encountered in a string then you would do:



s = ":dfa:sif:e"
fixed = ''.join(s.split(':', 1))

Excel VBA: Update the formatting for all worksheets




I read through a few online tutorials, and use the macro record to learn how to set formats. But I am wondering is there a way to do the following, without using .Select? Or what is the preferred way by programmers?



Requirement for the simple macro:




  1. Loop through all the worksheets (visible only)

  2. Set bold format to the top row, and set the background to grey

  3. Reset the selection to A1 position




()



Sub SetAllTopRowBold()
Dim ws As Worksheet
On Error Resume Next

For Each ws In ThisWorkbook.Worksheets
If ws.Visible Then
ws.Activate

Rows(1).Select
Selection.Font.Bold = True
Selection.Interior.Color = RGB(190, 190, 190)
Range("A1").Select
End If
Next ws
End Sub

Answer



You can do it directly against the range object:




For Each ws In ThisWorkbook.Worksheets
If ws.Visible Then
ws.Rows(1).Font.Bold = True
ws.Rows(1).Interior.Color = RGB(190, 190, 190)
ws.Select
ws.Range("A1").Select
End If
Next ws


Sunday 28 July 2019

android - Device ID Giving null Value

I am trying to get Unique ID[I.E unique id of a device] by using below code



TelephonyManager tManager;

tManager = (TelephonyManager).getSystemService(Context.TELEPHONY_SERVICE);

String deviceId = tManager.getDeviceId();


Where deviceId Gives me Unique ID for Android Device. I am not testing this on emulator because in emulator i am getting value 000000000000000




Any way i am testing it on real devices,and this works fine for mostly all devices , but in some device i am getting value null



I have tested this on



Samsung Galaxy S3

Samsung Galaxy Tab3

Samsung Galaxy Star


Google Nexus4

Google Nexus5

Google Nexus7


In all the devices listed above it gives me correct out put except one Device and that is Google Nexus7, in this i m getting value null




So, ultimately my goal is to get unique value for each particular device, In case if this code gives me null value than i can try some alternate way



i heard that Device MAC Address is a unique for all devices, But unfortunately it just works on wifi connection.



So is there any other way to get unique value of each particular device?



Thanks Any way

javascript - onclick closing other onclicks



I have multiple div elements on my page, which have the display switch function .



 onclick = "document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'" 
onclick="if(document.getElementById('spoiler2') .style.display=='none') {document.getElementById('spoiler2') .style.display=''}else{document.getElementById('spoiler2') .style.display='none'}"



I am looking for a way to close each other opened element when opening a new one, so that only one can stay open.



Thanks


Answer



It's pretty hard to understand without looking at your html, but you can try something like this:



$(document).ready(function() {

$("#light").on("click", function() {

$("#spoiler2").hide();
$(this).show();
});

});

javascript - Template literal trapped in a string variable



I have a template Hello, ${user.name} stored in a variable. I am reading this from an external file using fs.read.



Now, obviously when I attach to the innerHTML of a target div, it shows the string as it is and not "Hello, James" (assuming user.name = James) as intended.
Is there a way to make it happen?



extfile.txt =>
{"A":"`Welcome, ${user.name}`"}



Node.js code =>




fs.readFile(__dirname + '/extfile.txt', 'utf8', function (err,data) {
if (err) {
return console.log(err);
} else {
let x = JSON.parse(data);
socket.emit('var',x.A);
}
});


HTML =>



socket.on('var',function(x)){
getElementById('target').innerHTML = x;
}

Answer



I've slightly rewritten a solution presented here.



Here, eval_template evaluates an ES6 template string provided as a regular string. Any variable in local scope used in the template string needs to be provided as a property of the object passed in the second parameter (because functions created using Function are in the global scope and cannot access local variables).



This is perilously close to using eval. You might want to choose a different approach to handling your template strings. ES6 template strings are designed to be a run-time mechanism to create string literals, not a templating language whose templates can be stored and re-used.





function eval_template(s, params) {
return Function(...Object.keys(params), "return " + s)
(...Object.values(params));
}

const template = "`Welcome, ${user.name}`";
console.log(eval_template(template, {user: {name: "James"}}));





There is no reason this could not be used with a tagged template string, as long as the tag is passed in as a parameter:



eval_template("tag`${boo}`", {tag, boo});

facebook - How do I resolve the error "PHP Notice: Use of undefined constant"?

I have a strange error message after using the post to wall function. It did successfully post to the wall however i got a very weird strange error.





[30-Jan-2012 23:36:49] PHP Notice: Use of undefined constant message
- assumed 'message' in C:\www\jetstar\starpick\rewards.php on line 33



[30-Jan-2012 23:36:49] PHP Notice: Use of undefined constant picture
- assumed 'picture' in C:\www\jetstar\starpick\rewards.php on line 34



[30-Jan-2012 23:36:49] PHP Notice: Use of undefined constant link -
assumed 'link' in C:\www\jetstar\starpick\rewards.php on line 35



[30-Jan-2012 23:36:49] PHP Notice: Use of undefined constant name -

assumed 'name' in C:\www\jetstar\starpick\rewards.php on line 36



[30-Jan-2012 23:36:49] PHP Notice: Use of undefined constant caption
- assumed 'caption' in C:\www\jetstar\starpick\rewards.php on line 37




This is the codes i use



$facebook->api("/me/feed", "post", array(
message => "I have won a ".$prizename,

picture => "http://i1172.photobucket.com/albums/r574/092810c/starpicklogo-1.png",
link => "https://apps.facebook.com/starpick/",
name => "StarPick",
caption => "Stand to Win Attractive Prizes!!!"));

php - Double quotes are not copied normally. How can I edit them?

When I copy the words with double quotes, .php pages show an error. Double quotes don't get copied normally. How can I solve it? Which codes can I edit? (My script is Wordpress.)



Example: $goster = getenv(“HTTP_USER_AGENT”);



Before HTTP and after AGENT double quotes in example above. It is a problem with my users. I think I must edit in blockquotes function in Wordpress. Any idea?

java - How to verify that a specific method was not called using Mockito?



How to verify that a method is not called on an object's dependency?



For example:



public interface Dependency {
void someMethod();
}


public class Foo {
public bar(final Dependency d) {
...
}
}


With the Foo test:



public class FooTest {

@Test
public void dependencyIsNotCalled() {
final Foo foo = new Foo(...);
final Dependency dependency = mock(Dependency.class);
foo.bar(dependency);
**// verify here that someMethod was not called??**
}
}

Answer




Even more meaningful :



import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;

// ...

verify(dependency, never()).someMethod();



The documentation of this feature is there §4 "Verifying exact number of invocations / at least x / never", and the never javadoc is here.


Escape spaces in bash script





I am trying to do something in a bash script whenever a file in a directory I am iterating over contains a string using grep. The problem comes in where a subset of the files in the directory contain spaces in the name. Therefore, I have tried to replace the spaces with escaped spaces in place using sed:



if grep -c "main" ${source} | sed 's/ /\\ /g'; then
# do something
fi



However, I still get the error:




grep: /Users/me/Desktop/theDir/nameWith: No such file or directory



grep: spaces.txt: No such file or directory




What am I doing wrong?



Answer



You should quote the name of the file being grep'ed:



if grep -c main "$source" ; then
# do something
fi


...assuming $source is the name of a file. If $source is the name of a directory, I'll need more information about what you're trying to do.


javascript - "getElementsByTagName(...)[0]" is undefined?



I have the following code, which basically toggles through a bunch of images.











Press Here!







For some reason, when I run it, nothing happens, because of the following error as displayed by my Firebug console.



    hbutton is undefined    

---
hbutton.onclick = function() {


When I run just the JS after the page has loaded however, it works perfectly fine!!! Why is this?


Answer



Your code is executing before the h1 tag is defined. You must run it in an onload handler or put it just before /body


security - Exploitable PHP functions





I'm trying to build a list of functions that can be used for arbitrary code execution. The purpose isn't to list functions that should be blacklisted or otherwise disallowed. Rather, I'd like to have a grep-able list of red-flag keywords handy when searching a compromised server for back-doors.



The idea is that if you want to build a multi-purpose malicious PHP script -- such as a "web shell" script like c99 or r57 -- you're going to have to use one or more of a relatively small set of functions somewhere in the file in order to allow the user to execute arbitrary code. Searching for those those functions helps you more quickly narrow down a haystack of tens-of-thousands of PHP files to a relatively small set of scripts that require closer examination.



Clearly, for example, any of the following would be considered malicious (or terrible coding):











and so forth.



Searching through a compromised website the other day, I didn't notice a piece of malicious code because I didn't realize preg_replace could be made dangerous by the use of the /e flag (which, seriously? Why is that even there?). Are there any others that I missed?



Here's my list so far:



Shell Execute





  • system

  • exec

  • popen

  • backtick operator

  • pcntl_exec



PHP Execute





  • eval

  • preg_replace (with /e modifier)

  • create_function

  • include[_once] / require[_once] (see mario's answer for exploit details)



It might also be useful to have a list of functions that are capable of modifying files, but I imagine 99% of the time exploit code will contain at least one of the functions above. But if you have a list of all the functions capable of editing or outputting files, post it and I'll include it here. (And I'm not counting mysql_execute, since that's part of another class of exploit.)


Answer




To build this list I used 2 sources. A Study In Scarlet and RATS. I have also added some of my own to the mix and people on this thread have helped out.



Edit: After posting this list I contacted the founder of RIPS and as of now this tools searches PHP code for the use of every function in this list.



Most of these function calls are classified as Sinks. When a tainted variable (like $_REQUEST) is passed to a sink function, then you have a vulnerability. Programs like RATS and RIPS use grep like functionality to identify all sinks in an application. This means that programmers should take extra care when using these functions, but if they where all banned then you wouldn't be able to get much done.



"With great power comes great responsibility."



--Stan Lee




Command Execution



exec           - Returns last line of commands output
passthru - Passes commands output directly to the browser
system - Passes commands output directly to the browser and returns last line
shell_exec - Returns commands output
`` (backticks) - Same as shell_exec()
popen - Opens read or write pipe to process of a command
proc_open - Similar to popen() but greater degree of control
pcntl_exec - Executes a program



PHP Code Execution



Apart from eval there are other ways to execute PHP code: include/require can be used for remote code execution in the form of Local File Include and Remote File Include vulnerabilities.



eval()
assert() - identical to eval()
preg_replace('/.*/e',...) - /e does an eval() on the match
create_function()

include()
include_once()
require()
require_once()
$_GET['func_name']($_GET['argument']);
$func = new ReflectionFunction($_GET['func_name']); $func->invoke(); or $func->invokeArgs(array());


List of functions which accept callbacks




These functions accept a string parameter which could be used to call a function of the attacker's choice. Depending on the function the attacker may or may not have the ability to pass a parameter. In that case an Information Disclosure function like phpinfo() could be used.



Function                     => Position of callback arguments
'ob_start' => 0,
'array_diff_uassoc' => -1,
'array_diff_ukey' => -1,
'array_filter' => 1,
'array_intersect_uassoc' => -1,
'array_intersect_ukey' => -1,
'array_map' => 0,

'array_reduce' => 1,
'array_udiff_assoc' => -1,
'array_udiff_uassoc' => array(-1, -2),
'array_udiff' => -1,
'array_uintersect_assoc' => -1,
'array_uintersect_uassoc' => array(-1, -2),
'array_uintersect' => -1,
'array_walk_recursive' => 1,
'array_walk' => 1,
'assert_options' => 1,

'uasort' => 1,
'uksort' => 1,
'usort' => 1,
'preg_replace_callback' => 1,
'spl_autoload_register' => 0,
'iterator_apply' => 1,
'call_user_func' => 0,
'call_user_func_array' => 0,
'register_shutdown_function' => 0,
'register_tick_function' => 0,

'set_error_handler' => 0,
'set_exception_handler' => 0,
'session_set_save_handler' => array(0, 1, 2, 3, 4, 5),
'sqlite_create_aggregate' => array(2, 3),
'sqlite_create_function' => 2,


Information Disclosure



Most of these function calls are not sinks. But rather it maybe a vulnerability if any of the data returned is viewable to an attacker. If an attacker can see phpinfo() it is definitely a vulnerability.




phpinfo
posix_mkfifo
posix_getlogin
posix_ttyname
getenv
get_current_user
proc_get_status
get_cfg_var
disk_free_space

disk_total_space
diskfreespace
getcwd
getlastmo
getmygid
getmyinode
getmypid
getmyuid



Other



extract - Opens the door for register_globals attacks (see study in scarlet).
parse_str - works like extract if only one argument is given.
putenv
ini_set
mail - has CRLF injection in the 3rd parameter, opens the door for spam.
header - on old systems CRLF injection could be used for xss or other purposes, now it is still a problem if they do a header("location: ..."); and they do not die();. The script keeps executing after a call to header(), and will still print output normally. This is nasty if you are trying to protect an administrative area.
proc_nice
proc_terminate

proc_close
pfsockopen
fsockopen
apache_child_terminate
posix_kill
posix_mkfifo
posix_setpgid
posix_setsid
posix_setuid



Filesystem Functions



According to RATS all filesystem functions in php are nasty. Some of these don't seem very useful to the attacker. Others are more useful than you might think. For instance if allow_url_fopen=On then a url can be used as a file path, so a call to copy($_GET['s'], $_GET['d']); can be used to upload a PHP script anywhere on the system.
Also if a site is vulnerable to a request send via GET everyone of those file system functions can be abused to channel and attack to another host through your server.



// open filesystem handler
fopen
tmpfile
bzopen

gzopen
SplFileObject->__construct
// write to filesystem (partially in combination with reading)
chgrp
chmod
chown
copy
file_put_contents
lchgrp
lchown

link
mkdir
move_uploaded_file
rename
rmdir
symlink
tempnam
touch
unlink
imagepng - 2nd parameter is a path.

imagewbmp - 2nd parameter is a path.
image2wbmp - 2nd parameter is a path.
imagejpeg - 2nd parameter is a path.
imagexbm - 2nd parameter is a path.
imagegif - 2nd parameter is a path.
imagegd - 2nd parameter is a path.
imagegd2 - 2nd parameter is a path.
iptcembed
ftp_get
ftp_nb_get

// read from filesystem
file_exists
file_get_contents
file
fileatime
filectime
filegroup
fileinode
filemtime
fileowner

fileperms
filesize
filetype
glob
is_dir
is_executable
is_file
is_link
is_readable
is_uploaded_file

is_writable
is_writeable
linkinfo
lstat
parse_ini_file
pathinfo
readfile
readlink
realpath
stat

gzfile
readgzfile
getimagesize
imagecreatefromgif
imagecreatefromjpeg
imagecreatefrompng
imagecreatefromwbmp
imagecreatefromxbm
imagecreatefromxpm
ftp_put

ftp_nb_put
exif_read_data
read_exif_data
exif_thumbnail
exif_imagetype
hash_file
hash_hmac_file
hash_update_file
md5_file
sha1_file

highlight_file
show_source
php_strip_whitespace
get_meta_tags

c# - Am I misunderstanding LINQ to SQL .AsEnumerable()?



Consider this code:



var query = db.Table
.Where(t => SomeCondition(t))

.AsEnumerable();

int recordCount = query.Count();
int totalSomeNumber = query.Sum();
decimal average = query.Average();


Assume query takes a very long time to run. I need to get the record count, total SomeNumber's returned, and take an average at the end. I thought based on my reading that .AsEnumerable() would execute the query using LINQ-to-SQL, then use LINQ-to-Objects for the Count, Sum, and Average. Instead, when I do this in LINQPad, I see the same query is run three times. If I replace .AsEnumerable() with .ToList(), it only gets queried once.



Am I missing something about what AsEnumerable is/does?



Answer



Calling AsEnumerable() does not execute the query, enumerating it does.



IQueryable is the interface that allows LINQ to SQL to perform its magic. IQueryable implements IEnumerable so when you call AsEnumerable(), you are changing the extension-methods being called from there on, ie from the IQueryable-methods to the IEnumerable-methods (ie changing from LINQ to SQL to LINQ to Objects in this particular case). But you are not executing the actual query, just changing how it is going to be executed in its entirety.



To force query execution, you must call ToList().


Is there a way to crack the password on an Excel VBA Project?



I've been asked to update some Excel 2003 macros, but the VBA projects are password protected, and it seems there's a lack of documentation... no-one knows the passwords.



Is there a way of removing or cracking the password on a VBA project?



Answer



You can try this direct VBA approach which doesn't require HEX editing. It will work for any files (*.xls, *.xlsm, *.xlam ...).



Tested and works on:




Excel 2007
Excel 2010
Excel 2013 - 32 bit version
Excel 2016 - 32 bit version




Looking for 64 bit version? See this answer




How it works



I will try my best to explain how it works - please excuse my English.




  1. The VBE will call a system function to create the password dialog box.

  2. If user enters the right password and click OK, this function returns 1. If user enters the wrong password or click Cancel, this function returns 0.

  3. After the dialog box is closed, the VBE checks the returned value of the system function

  4. if this value is 1, the VBE will "think" that the password is right, hence the locked VBA project will be opened.


  5. The code below swaps the memory of the original function used to display the password dialog with a user defined function that will always return 1 when being called.



Using the code



Please backup your files first!




  1. Open the file(s) that contain your locked VBA Projects

  2. Create a new xlsm file and store this code in Module1




    code credited to Siwtom (nick name), a Vietnamese developer



    Option Explicit

    Private Const PAGE_EXECUTE_READWRITE = &H40

    Private Declare Sub MoveMemory Lib "kernel32" Alias "RtlMoveMemory" _
    (Destination As Long, Source As Long, ByVal Length As Long)


    Private Declare Function VirtualProtect Lib "kernel32" (lpAddress As Long, _
    ByVal dwSize As Long, ByVal flNewProtect As Long, lpflOldProtect As Long) As Long

    Private Declare Function GetModuleHandleA Lib "kernel32" (ByVal lpModuleName As String) As Long

    Private Declare Function GetProcAddress Lib "kernel32" (ByVal hModule As Long, _
    ByVal lpProcName As String) As Long

    Private Declare Function DialogBoxParam Lib "user32" Alias "DialogBoxParamA" (ByVal hInstance As Long, _
    ByVal pTemplateName As Long, ByVal hWndParent As Long, _

    ByVal lpDialogFunc As Long, ByVal dwInitParam As Long) As Integer

    Dim HookBytes(0 To 5) As Byte
    Dim OriginBytes(0 To 5) As Byte
    Dim pFunc As Long
    Dim Flag As Boolean

    Private Function GetPtr(ByVal Value As Long) As Long
    GetPtr = Value
    End Function


    Public Sub RecoverBytes()
    If Flag Then MoveMemory ByVal pFunc, ByVal VarPtr(OriginBytes(0)), 6
    End Sub

    Public Function Hook() As Boolean
    Dim TmpBytes(0 To 5) As Byte
    Dim p As Long
    Dim OriginProtect As Long


    Hook = False

    pFunc = GetProcAddress(GetModuleHandleA("user32.dll"), "DialogBoxParamA")


    If VirtualProtect(ByVal pFunc, 6, PAGE_EXECUTE_READWRITE, OriginProtect) <> 0 Then

    MoveMemory ByVal VarPtr(TmpBytes(0)), ByVal pFunc, 6
    If TmpBytes(0) <> &H68 Then


    MoveMemory ByVal VarPtr(OriginBytes(0)), ByVal pFunc, 6

    p = GetPtr(AddressOf MyDialogBoxParam)

    HookBytes(0) = &H68
    MoveMemory ByVal VarPtr(HookBytes(1)), ByVal VarPtr(p), 4
    HookBytes(5) = &HC3

    MoveMemory ByVal pFunc, ByVal VarPtr(HookBytes(0)), 6
    Flag = True

    Hook = True
    End If
    End If
    End Function

    Private Function MyDialogBoxParam(ByVal hInstance As Long, _
    ByVal pTemplateName As Long, ByVal hWndParent As Long, _
    ByVal lpDialogFunc As Long, ByVal dwInitParam As Long) As Integer
    If pTemplateName = 4070 Then
    MyDialogBoxParam = 1

    Else
    RecoverBytes
    MyDialogBoxParam = DialogBoxParam(hInstance, pTemplateName, _
    hWndParent, lpDialogFunc, dwInitParam)
    Hook
    End If
    End Function

  3. Paste this code under the above code in Module1 and run it




    Sub unprotected()
    If Hook Then
    MsgBox "VBA Project is unprotected!", vbInformation, "*****"
    End If
    End Sub

  4. Come back to your VBA Projects and enjoy.



Saturday 27 July 2019

Updated text fields to JSON string - Javascript/JQuery

I have a dynamic form that has text fields which change to input boxes when they need to be updated.



When they have been updated and the user clicks submit I want to add the updated values to a json string which i can post to an ASP.NET script.



Here is the html of 2 rows in the table:




Colleague 1:
















Del







Colleague 2:















Del






Here is the jQuery I'm using to detect which input boxes have been updated:



$("#subdetails").click(function () {
$("#mantab input[type=text]").each(function () {
if ($(this).val() !== this.defaultValue) {

//code to create json string


}
});
});


This is an example of a json string i would like to create if the following field were updated:



{
"1":{
"c1nametb": "newname",

"c1exttb": "22227",
}
"2":{
"c2eaddtb": "neweadd@company.co.uk",
"c2pnotb": "0111122210",
}
}


Can any one please help me with the code to create this string, or advise on a better way of doing this?




Thanks
Ryan

What does a . (dot) do in PHP?



What does the following command do in PHP?




. $string   // ($string is something which i declared in the program)

Answer



On its own, that does nothing at all (it's not valid syntax). However, if you have something like this:




$string1 = "Hello ";
$string2 = "world!";
$string = $string1 . $string2;


echo $string;

?>


You will see Hello world!. The . is the string concatenation operator.


pass by reference - Passing values in Python




When you pass a collection like list, array to another function in python, does it make a copy of it, or is it just a pointer?


Answer




Python passes references-to-objects by value.




Python passes references-to-objects by
value (like Java), and everything in
Python is an object. This sounds
simple, but then you will notice that
some data types seem to exhibit
pass-by-value characteristics, while
others seem to act like

pass-by-reference... what's the deal?



It is important to understand mutable
and immutable objects. Some objects,
like strings, tuples, and numbers, are
immutable. Altering them inside a
function/method will create a new
instance and the original instance
outside the function/method is not
changed. Other objects, like lists

and dictionaries are mutable, which
means you can change the object
in-place. Therefore, altering an
object inside a function/method will
also change the original object
outside.



realism - Is the electric track the tour vehicles follow on in Jurassic Park actually possible?

Jurassic Park tour vehicle


Based on the image above and examination while viewing Jurassic Park, it appears there is no physical connection between truck and track (though there may be).


Is the proposed method of moving the tour vehicles - having them follow a track that moves them along with electricity - actually a viable method of moving a vehicle?




To clarify, what @Shufler realizes in his comment:



I just understood the difference between the JP SUVs and electric trains (and OP's original question) -- that the SUVs don't appear to contact the track, where as subways and other electric trains have physical contact with a "third rail" or wire.



This is what I was getting at - I am familiar with monorails and how they work. What I was hoping to learn was whether or not a a track could propel a car without (discernible) contact electrically - which @wbogacz addresses.


Answer


I think the question is whether an autonomous car technology exists. The answer is yes.

The movie displays electronics that depended on communication on a short range of 1-2 ft. The current vision is to include communications to drive cars from 'such techniques as laser, radar, lidar, GPS and computer vision.'

People have been talking about autonomous cars and driverless highways since the 40's (corrected from 70's), and I met people during my job in the 90's who were hired to design such systems.

Also, the technology is independent of the power needed to propel the car. Gasoline/electric power - the technology makes no distinction. I think the movie made the car electric because it could be easily disabled for the plot.

UPDATE: While reviewing the relevant movie section, I hear Samuel Jackson specifically mentions the car batteries, leading me to think the track supplies no energy.

When the kids and the scientists jump out of the car to aid the Triceratops, the central computer says something to the effect 'Stopping park vehicles...'.

When Nedry (Newmann) sets the power to fail so he can escape, the track data flow fails to the vehicles bringing them to a halt right next to the T-Rex cage. T-Rex is no longer contained by 10k volts.


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