How do parameters work in C callback functions - c

I'm reading some freeRTOS code, and I'm not understanding how a function callbacks work. Take this example. The following function is defined -
static void prov_event_handler(void *user_data,
wifi_prov_cb_event_t event, void *event_data)
{
switch (event) {
case WIFI_PROV_CRED_RECV: {
wifi_sta_config_t *wifi_sta_cfg = (wifi_sta_config_t *)event_data;
...
}
This is the callback function that we want to call from this code:
/* Configuration for the provisioning manager */
wifi_prov_mgr_config_t config = {
.scheme = wifi_prov_scheme_ble,
.scheme_event_handler = WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BTDM,
.app_event_handler = {
.event_cb = prov_event_handler,
.user_data = NULL
}
};
ESP_ERROR_CHECK(wifi_prov_mgr_init(config));
So far, so good. Where I am confused is where the heck do the parameters come from? When prov_event_handler is run, it has values for event_data. How does this generally work?
Thanks.

Related

Problem with windows api called ObRegisterCallbacks

I tried to debug my driver,but the debuged computer always stop at here.enter image description here
And after continue,debuged computer throw a blue screen directly with the error which says SYSTEM THREAD EXCEPTION NOT HANDLED.
I have searched to check the usage of this function,but all of them let the ObjectType equal PsProcessType directly with no error when running.Here is my code:
NTSTATUS DriverEntry(_In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath)
{
POB_CALLBACK_REGISTRATION callBackRegistration = { 0 };
POB_OPERATION_REGISTRATION operationRegistration = { 0 };
UNICODE_STRING altitude;
RtlInitUnicodeString(&altitude, L"60000");
operationRegistration->ObjectType = PsProcessType;//<-- Here is place where I get confused
operationRegistration->Operations = OB_OPERATION_HANDLE_CREATE | OB_OPERATION_HANDLE_DUPLICATE;
operationRegistration->PreOperation = (POB_PRE_OPERATION_CALLBACK) & PobPreOperationCallback;
callBackRegistration->Version = OB_FLT_REGISTRATION_VERSION;
callBackRegistration->OperationRegistrationCount = 1;
callBackRegistration->Altitude = altitude;
callBackRegistration->RegistrationContext = NULL;
callBackRegistration->OperationRegistration = operationRegistration;
KdBreakPoint();
BypassSignCheck(DriverObject);
ObRegisterCallbacks(callBackRegistration,&hRegistration);
DriverObject->DriverUnload = UnloadDriver;
return STATUS_SUCCESS;
}
Change:
POB_CALLBACK_REGISTRATION callBackRegistration = { 0 };
POB_OPERATION_REGISTRATION operationRegistration = {
0 };
to
OB_CALLBACK_REGISTRATION callBackRegistration { };
OB_OPERATION_REGISTRATION operationRegistration { };
and then every time you have a '->' with one of these objects change it to a '.', and tka ethe address using '&' when calling functions.
Right now you have pointers but you never point them at valid objects, but since the rgistration is only needed locally there is no reason to not use stack-based objects.

Angular Translate - how to retrieve dynamic variable list

I have this in the translation json file:
{
"test_key" : "Var1: {{var1}} Var2: {{var2}} Var3: {{var3}}"
}
For this to work, I need to provide var1, var2, and var 3. For example:
$translate('test_key', { var1: 1, var2: 2, var3: 3 });
The issue now is that var1, var2, var3 could be any dynamic variables. What I need now is to get all the list of dynamic variables so I can provide whatever values it may need.
Ideally, this is the goal I am trying to achieve (pseudo code)
var dynamicVars = getDynamicVarList(); // I need this, but how?
dynamicVars.forEach(function (key) {
switch (key) {
case "var1":
return 1;
case "var2":
return 2;
case "var3":
return 3;
default:
return null;
}
});
If it is Pascal Precht translate, then you set JSON file in module options, before application init. It's rather not possible with standard mechanisms. It offer JSON, but when it is loaded, then it's hard to change something, without changing source code of angular translate module.
If the reason you want this is to have many languages, then you can set many languages codes in $translate.
Another solution is to load JSON from server, which performs operations on var1, var2, var3 and hence returns static json, but you can do $http calls with commands to change variables in switch statement.
It looks somehow linguistic approach, Java is good for this. Grails may be fine framework for returning REST services.
Again, to restate the problem, the issue is that you do not know ahead of time which dynamic variables are to be used.
I solved the issue by using a customer interpolator.
So when you do
{{'testkey'|translate}}
and your lang.json has:
"testkey" :"this is number {{variable1}}"
It will get resolved to
this is number 1
Code:
app.factory('customTranslateInterpolator',
["$interpolate",
function ($interpolate) {
var $locale;
var customTranslateInterpolator = {};
/**
* This will be your custom dynamic vars resolution method
*/
var resolveExpressions = function (expressions) {
var values = {};
expressions.forEach(function (key) {
values[key] = resolveVariable(key);
});
return values;
}
/**
* The actual method for key:value mapping
*/
var resolveVariable = function(key) {
var retVal;
switch (key) {
case "variable1":
retVal = 1;
break;
default:
retVal = "";
}
return retVal;
}
customTranslateInterpolator.setLocale = function (locale) {
$locale = locale;
}
customTranslateInterpolator.getInterpolationIdentifier = function () {
return 'custom';
},
/**
* Custom interpolate
* interpolateParams will overwrite resolve expressions. This will allow developers
* to pass values to the translate directives or by using $translate service.
*
* #param {string} string the string retrieved from the language json file
* #param {object} interpolateParams the {key:value} object passed to the angular-translate features.
*/
customTranslateInterpolator.interpolate = function (string, interpolateParams) {
var result;
interpolateParams = interpolateParams || {
};
// Retrieve expressions and resolve them
var interpolatedString = $interpolate(string);
var resolvedExpressions = resolveExpressions(interpolatedString.expressions);
// Merge interpolateParams onto resolvedExpressions so that interpolateParams overwrites resolvedExpressions
angular.extend(resolvedExpressions, interpolateParams);
result = interpolatedString(resolvedExpressions);
return result;
}
return customTranslateInterpolator;
}]);
make sure you let angular-translate know you are using a custom interpolator
$translateProvider.useInterpolation('customTranslateInterpolator');
Note that you can still provide your own translate-values, and this will override whatever you have in resolveVariable()
So if you do
{{'testkey' | translate:"{variable1:'2'}"}}
It will resolve to
this is number 2
Hope this helps others.
-Lucky M.

phpunit: how to check anything changed at all

I'm pretty new in Unit testing.
We made a test
It starts with a certain content of a database
then there can 2 things happen.
Amsterdam is overwritten with Amsterdam
or
Amsterdam stays Amsterdam.... (nothing happens)
What is the best way to verify what of both happened?
Normally, you would test each case, and you can use a Mock Object to remove the dependency on the database.
In this case, you would structure a test that recognizes that nothing changed in the DB record. The Mock object returns a state from the database indicating that nothing has changed. Your test would then check that the code that executes next, reported this condition, and therefore passes the test.
A second test would then be done where the Mock Object returns the state from the database where the item was changed, so then the code that should be executed does what it should, and passes your test.
Repeat the above tests for failing conditions, and you have your code covered.
class YourDBClass {
private $DBRef;
// Constructor Injection, pass the Database object here
public function __construct($DatabaseObject = NULL)
{
if(! is_null($DatabaseObject) )
{
if($DatabaseObject instanceof YourDBAccessClass)
{
$this->SetDBClass($DatabaseObject);
}
}
}
function SetDBClass(YourDBAccessClass $DatabaseObject)
{
$this->DBRef = $DatabaseObject
}
function GetResult($request) {
$DBR = $this->DBRef;
$result = $DBRef->DoSomething($request);
if ($result->success == false)
$result->error = $this->GetErrorCode($result->errorCode);
}
function GetErrorCode($errorCode) {
// do stuff
}
}
Test:
class YourDBClassTest extends PHPUnit_Framework_TestCase
{
// Simple test for GetErrorCode to work Properly
public function testGetErrorCode()
{
$TestClass = new YourDBClass();
$this->assertEquals('One', $TestClass->GetErrorCode(1)); // Assumes GetErrorCode returns a string
$this->assertEquals('Two', $TestClass->GetErrorCode(2));
}
// Could also use dataProvider to send different returnValues, and then check with Asserts.
public function testGetResultsNoChange()
{
// Create a mock for the YourDBAccessClass,
// only mock the GetResult() method.
$MockService = $this->getMock('YourDBAccessClass', array('GetResult'));
// Set up the expectation for the GetResult() method
$MockService->expects($this->any())
->method('GetResult')
->will($this->returnValue("NoChange"));
// Create Test Object - Pass our Mock as the service
$TestClass = new YourDBClass($MockService);
// Or
// $TestClass = new YourDBClass();
// $TestClass->SetDBClass($MockService);
// Test GetResults
$QueryString = 'Some String since we did not specify it to the Mock'; // Could be checked with the Mock functions
$this->assertEquals('NoChange', $TestClass->GetResults($QueryString));
}
// Could also use dataProvider to send different returnValues, and then check with Asserts.
public function testGetResultsChanged()
{
// Create a mock for the YourDBAccessClass,
// only mock the GetResult() method.
$MockService = $this->getMock('YourDBAccessClass', array('GetResult'));
// Set up the expectation for the GetResult() method
$MockService->expects($this->any())
->method('GetResult')
->will($this->returnValue("Amsterdam Changed"));
// Create Test Object - Pass our Mock as the service
$TestClass = new YourDBClass($MockService);
// Or
// $TestClass = new YourDBClass();
// $TestClass->SetDBClass($MockService);
// Test GetResults
$QueryString = 'Some String since we did not specify it to the Mock'; // Could be checked with the Mock functions
$this->assertEquals('Amsterdam Changed', $TestClass->GetResults($QueryString));
}
}
Steven, I discussed with my colleauges, They understand what you do.
but this is what we actually needed:
mysql UPDATE statement - overhead for same values?
I hope you follow. Nevertheless, thank you so much!

Dart VM itself implement `eval` in `dart:mirrors` and developers use it. Are planned to make this method public?

Here is code that use this eval method in Dart platform.
This is done via reflection.
runtime/lib/mirrors_impl.dart
_getFieldSlow(unwrapped) {
// ..... Skipped
var atPosition = unwrapped.indexOf('#');
if (atPosition == -1) {
// Public symbol.
f = _eval('(x) => x.$unwrapped', null);
} else {
// Private symbol.
var withoutKey = unwrapped.substring(0, atPosition);
var privateKey = unwrapped.substring(atPosition);
f = _eval('(x) => x.$withoutKey', privateKey);
}
// ..... Skipped
}
static _eval(expression, privateKey)
native "Mirrors_evalInLibraryWithPrivateKey";
runtime/lib/mirrors.cc
DEFINE_NATIVE_ENTRY(Mirrors_evalInLibraryWithPrivateKey, 2) {
GET_NON_NULL_NATIVE_ARGUMENT(String, expression, arguments->NativeArgAt(0));
GET_NATIVE_ARGUMENT(String, private_key, arguments->NativeArgAt(1));
const GrowableObjectArray& libraries =
GrowableObjectArray::Handle(isolate->object_store()->libraries());
const int num_libraries = libraries.Length();
Library& each_library = Library::Handle();
Library& ctxt_library = Library::Handle();
String& library_key = String::Handle();
if (library_key.IsNull()) {
ctxt_library = Library::CoreLibrary();
} else {
for (int i = 0; i < num_libraries; i++) {
each_library ^= libraries.At(i);
library_key = each_library.private_key();
if (library_key.Equals(private_key)) {
ctxt_library = each_library.raw();
break;
}
}
}
ASSERT(!ctxt_library.IsNull());
return ctxt_library.Evaluate(expression);
runtime/vm/bootstrap_natives.h
V(Mirrors_evalInLibraryWithPrivateKey, 2) \
P.S.
I ask question here becuase I cannot ask it at Dart mail lists.
P.S.
As we can see it static private method in mirrors_impl.dart:
static _eval(expression, privateKey) native "Mirrors_evalInLibraryWithPrivateKey";
Does anyone want that this method should be public? (this is not a question but just a thought aloud).
According to the Dart FAQ a pure string eval like that is not likely to make it into the language, even though other dynamic features will likely be added:
So, for example, Dart isn’t likely to support evaluating a string as
code in the current context, but it may support loading that code
dynamically into a new isolate. Dart isn’t likely to support adding
fields to a value, but it may (through a mirror system) support adding
fields to a class, and you can effectively add methods using
noSuchMethod(). Using these features will have a runtime cost; it’s
important to us to minimize the cost for programs that don’t use them.
This area is still under development, so we welcome your thoughts on
what you need from runtime dynamism.

Variable array/object in one file changes when you change it in a callback in another file

I have two files in Node.js where one requires the other one.
variable_test.js:
TEST = require('./variable_test_external.js');
TEST.get(function(myVariable) {
var changeMeVariable;
console.log(myVariable);
changeMeVariable = myVariable.epicVariable;
changeMeVariable.evenEpicerVariable = "test3";
TEST.get(function(myVariable2) {
console.log(myVariable2);
});
});
variable_test_external.js:
var testVariable = new Array({epicVariable: {evenEpicerVariable: "test1"}}, {epicVariable: {evenEpicerVariable: "test2"}});
exports.get = function(callback) {
callback(testVariable[1]); // I know that the return is unnecessary in this example but in my real application I have return there for compactness.
}
This is the output when run in Node.js with node variable_test.js:
{ epicVariable: { evenEpicerVariable: 'test2' } }
{ epicVariable: { evenEpicerVariable: 'test3' } }
The console.log(myVariable) changes in the two TEST.get's. Why does this happen?
This is a reference copy, not a value copy. You got the object from the array, NOT a copy of them.
changeMeVariable = myVariable.epicVariable;
This would have to fix yout problem
// PSEUDO CODE, i don't know the correct syntax
changeMeVariable = {
epicVariable = myVariable.epicVariable
};
The answer in my case is the following based on the links at the bottom:
changeMeVariable = JSON.parse(JSON.stringify(myVariable.epicVariable));
But, it's much better to manually copy it like the bottom most link like this:
changeMeVariable = {
evenEpicerVariable: myVariable.epicVariable.evenEpicerVariable
}
n0m's answer is similar but if the epicVariable.evenEpicerVariable contained an object that object's reference would still be linked! (I tested it)
References:
What is the most efficient way to deep clone an object in JavaScript?
http://jsperf.com/cloning-an-object/3

Resources