How to correct use BOOST_SCOPE_EXIT in lambda function? - boost

Recently I move my project to boost 1.79 and MSVC 2022, and this code is no longer compiled now. Before MSVC 2022 I used boost 1.75 and VSVC 2017 and it was compilable.
I'm pretty sure that problem is not with a "boost" but with the compiler.
struct test
{
test()
{
BOOST_SCOPE_EXIT(this_) { //OK
this_->m_bool = true;
} BOOST_SCOPE_EXIT_END;
auto l = [this]()
{
m_bool = false;
{ // <<-- syntax error: missing ';' before '{'
BOOST_SCOPE_EXIT(&m_bool) {
m_bool = true;
} BOOST_SCOPE_EXIT_END;
}
{ // <<-- syntax error: 'identifier' was unexpected here; expected ')'
BOOST_SCOPE_EXIT(this_) {
this_->m_bool = true;
} BOOST_SCOPE_EXIT_END;
}
{
struct scope_exit { // <<-- OK
std::function<void()> m_exit_f;
scope_exit(std::function<void()> exit_f)
: m_exit_f(exit_f)
{}
~scope_exit() {
m_exit_f();
}
} _inst([this]() { m_bool = false; });
}
};
}
bool m_bool;
};

Related

Issue with Xamarin Firebase Subscribe to a Child with no Key - Newtonsoft.Json error

I have a Firebase Child called "Parameters" that stores some data while my program runs. I populate it with "Put" and "Patch" actions. I cannot get the subscribe to work... I'm stuck on this Newtonsoft.Json.JsonSerializationException and I've tried several things but cannot figure it out. You can see in the error, I am getting the payload back... I just cannot parse it into my ViewParameterModel property variables. I would appreciate any help to get this working. Thanks, Brian
$exception {Firebase.Database.FirebaseException: Exception occured while processing the request.
Request Data: Response: {"aug":true,"fan":true,"ign":false,"mode":"Off","target":200}
---> Newtonsoft.Json.JsonSerializationException: Error converting value True to type 'Chart_sample.ViewParameterModel'. Path 'aug', line 1, position 11.
---> System.ArgumentException: Could not cast or convert from System.Boolean to Chart_sample.ViewParameterModel.
FirebaseHelper.cs
...
private readonly string ChildParams = "ControllerData/Pellet_Pirate_1/Parameters";
public ObservableCollection<Parameter> GetParameters()
{
firebase.Child(ChildParams).AsObservable<ViewParameterModel>().Subscribe(snapp =>
{
ViewParameterModel.aug = snapp.Object.aug;
ViewParameterModel.fan = snapp.Object.fan;
ViewParameterModel.ign = snapp.Object.ign;
ViewParameterModel.mode = snapp.Object.mode;
ViewParameterModel.target = snapp.Object.target;
});
return null;
}
...
ViewParameterModel.cs
public class ViewParameterModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private bool Fan = false;
public bool fan
{
get
{
return Fan;
}
set
{
if (Fan != value)
{
Fan = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("fan"));
}
}
}
private bool Igniter = false;
public bool ign
{
get
{
return Igniter;
}
set
{
if (Igniter != value)
{
Igniter = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("ign"));
}
}
}
private bool Auger = false;
public bool aug
{
get
{
return Auger;
}
set
{
if (Auger != value)
{
Auger = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("aug"));
}
}
}
private string Mode = "Off";
public string mode
{
get
{
return Mode;
}
set
{
if (Mode != value)
{
Mode = value;
Debug.WriteLine("Mode: " + Mode);
if (SegmentBindingContext != null)
{
SegmentBindingContext.index = Mode.Equals("Off") ? 0 : Mode.Equals("Start") ? 1 : Mode.Equals("Smoke") ? 2 :
Mode.Equals("Hold") ? 3 : Mode.Equals("Ignite") ? 4 : 5;
}
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("mode"));
}
}
}
private int Target = 0;
public int target
{
get
{
return Target;
}
set
{
if (Target != value)
{
Target = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("target"));
}
}
}
}
}

Ashley Mills reachability not sending notification when wifi turns back on?

I have a set up, using Ashley Mills Reachability, which is supposed to send a notification, using NotificationCenter, to the application when the connection of the app changes. It is set up as follows:
func reachabilityChanged(note: Notification) {
let reachability = note.object as! Reachability
switch reachability.connection {
case .wifi:
print("Reachable via WiFi")
case .cellular:
print("Reachable via Cellular")
case .none:
print("Network not reachable")
}
}
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(self.reachabilityChanged), name: .reachabilityChanged, object: reachability)
do{
try reachability.startNotifier()
}catch{
print("could not start reachability notifier")
}
}
With my computer (which is what I am running the simulator on) connected to wifi, the console accurately prints "Reachable via Wifi". Turning off the wifi causes the console to, again, accurately print "Network not reachable". I run into an issue, though, when I turn the wifi back on. "Reachable via Wifi" does not get printed to the log... in fact, nothing gets printed to the log. I do not know why this is happening nor how to fix it. Anyone have any ideas?
This is the reachability code:
import SystemConfiguration
import Foundation
public enum ReachabilityError: Error {
case FailedToCreateWithAddress(sockaddr_in)
case FailedToCreateWithHostname(String)
case UnableToSetCallback
case UnableToSetDispatchQueue
}
#available(*, unavailable, renamed: "Notification.Name.reachabilityChanged")
public let ReachabilityChangedNotification = NSNotification.Name("ReachabilityChangedNotification")
extension Notification.Name {
public static let reachabilityChanged = Notification.Name("reachabilityChanged")
}
func callback(reachability:SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) {
guard let info = info else { return }
let reachability = Unmanaged<Reachability>.fromOpaque(info).takeUnretainedValue()
reachability.reachabilityChanged()
}
public class Reachability {
public typealias NetworkReachable = (Reachability) -> ()
public typealias NetworkUnreachable = (Reachability) -> ()
#available(*, unavailable, renamed: "Conection")
public enum NetworkStatus: CustomStringConvertible {
case notReachable, reachableViaWiFi, reachableViaWWAN
public var description: String {
switch self {
case .reachableViaWWAN: return "Cellular"
case .reachableViaWiFi: return "WiFi"
case .notReachable: return "No Connection"
}
}
}
public enum Connection: CustomStringConvertible {
case none, wifi, cellular
public var description: String {
switch self {
case .cellular: return "Cellular"
case .wifi: return "WiFi"
case .none: return "No Connection"
}
}
}
public var whenReachable: NetworkReachable?
public var whenUnreachable: NetworkUnreachable?
#available(*, deprecated: 4.0, renamed: "allowsCellularConnection")
public let reachableOnWWAN: Bool = true
/// Set to `false` to force Reachability.connection to .none when on cellular connection (default value `true`)
public var allowsCellularConnection: Bool
// The notification center on which "reachability changed" events are being posted
public var notificationCenter: NotificationCenter = NotificationCenter.default
#available(*, deprecated: 4.0, renamed: "connection.description")
public var currentReachabilityString: String {
return "\(connection)"
}
#available(*, unavailable, renamed: "connection")
public var currentReachabilityStatus: Connection {
return connection
}
public var connection: Connection {
guard isReachableFlagSet else { return .none }
// If we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi
guard isRunningOnDevice else { return .wifi }
var connection = Connection.none
if !isConnectionRequiredFlagSet {
connection = .wifi
}
if isConnectionOnTrafficOrDemandFlagSet {
if !isInterventionRequiredFlagSet {
connection = .wifi
}
}
if isOnWWANFlagSet {
if !allowsCellularConnection {
connection = .none
} else {
connection = .cellular
}
}
return connection
}
fileprivate var previousFlags: SCNetworkReachabilityFlags?
fileprivate var isRunningOnDevice: Bool = {
#if (arch(i386) || arch(x86_64)) && os(iOS)
return false
#else
return true
#endif
}()
fileprivate var notifierRunning = false
fileprivate let reachabilityRef: SCNetworkReachability
fileprivate let reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability")
required public init(reachabilityRef: SCNetworkReachability) {
allowsCellularConnection = true
self.reachabilityRef = reachabilityRef
}
public convenience init?(hostname: String) {
guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else { return nil }
self.init(reachabilityRef: ref)
}
public convenience init?() {
var zeroAddress = sockaddr()
zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size)
zeroAddress.sa_family = sa_family_t(AF_INET)
guard let ref = SCNetworkReachabilityCreateWithAddress(nil, &zeroAddress) else { return nil }
self.init(reachabilityRef: ref)
}
deinit {
stopNotifier()
}
}
public extension Reachability {
// MARK: - *** Notifier methods ***
func startNotifier() throws {
guard !notifierRunning else { return }
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
context.info = UnsafeMutableRawPointer(Unmanaged<Reachability>.passUnretained(self).toOpaque())
if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) {
stopNotifier()
throw ReachabilityError.UnableToSetCallback
}
if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) {
stopNotifier()
throw ReachabilityError.UnableToSetDispatchQueue
}
// Perform an initial check
reachabilitySerialQueue.async {
self.reachabilityChanged()
}
notifierRunning = true
}
func stopNotifier() {
defer { notifierRunning = false }
SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil)
SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil)
}
// MARK: - *** Connection test methods ***
#available(*, deprecated: 4.0, message: "Please use `connection != .none`")
var isReachable: Bool {
guard isReachableFlagSet else { return false }
if isConnectionRequiredAndTransientFlagSet {
return false
}
if isRunningOnDevice {
if isOnWWANFlagSet && !reachableOnWWAN {
// We don't want to connect when on cellular connection
return false
}
}
return true
}
#available(*, deprecated: 4.0, message: "Please use `connection == .cellular`")
var isReachableViaWWAN: Bool {
// Check we're not on the simulator, we're REACHABLE and check we're on WWAN
return isRunningOnDevice && isReachableFlagSet && isOnWWANFlagSet
}
#available(*, deprecated: 4.0, message: "Please use `connection == .wifi`")
var isReachableViaWiFi: Bool {
// Check we're reachable
guard isReachableFlagSet else { return false }
// If reachable we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi
guard isRunningOnDevice else { return true }
// Check we're NOT on WWAN
return !isOnWWANFlagSet
}
var description: String {
let W = isRunningOnDevice ? (isOnWWANFlagSet ? "W" : "-") : "X"
let R = isReachableFlagSet ? "R" : "-"
let c = isConnectionRequiredFlagSet ? "c" : "-"
let t = isTransientConnectionFlagSet ? "t" : "-"
let i = isInterventionRequiredFlagSet ? "i" : "-"
let C = isConnectionOnTrafficFlagSet ? "C" : "-"
let D = isConnectionOnDemandFlagSet ? "D" : "-"
let l = isLocalAddressFlagSet ? "l" : "-"
let d = isDirectFlagSet ? "d" : "-"
return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)"
}
}
fileprivate extension Reachability {
func reachabilityChanged() {
guard previousFlags != flags else { return }
let block = connection != .none ? whenReachable : whenUnreachable
DispatchQueue.main.async {
block?(self)
self.notificationCenter.post(name: .reachabilityChanged, object:self)
}
previousFlags = flags
}
var isOnWWANFlagSet: Bool {
#if os(iOS)
return flags.contains(.isWWAN)
#else
return false
#endif
}
var isReachableFlagSet: Bool {
return flags.contains(.reachable)
}
var isConnectionRequiredFlagSet: Bool {
return flags.contains(.connectionRequired)
}
var isInterventionRequiredFlagSet: Bool {
return flags.contains(.interventionRequired)
}
var isConnectionOnTrafficFlagSet: Bool {
return flags.contains(.connectionOnTraffic)
}
var isConnectionOnDemandFlagSet: Bool {
return flags.contains(.connectionOnDemand)
}
var isConnectionOnTrafficOrDemandFlagSet: Bool {
return !flags.intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty
}
var isTransientConnectionFlagSet: Bool {
return flags.contains(.transientConnection)
}
var isLocalAddressFlagSet: Bool {
return flags.contains(.isLocalAddress)
}
var isDirectFlagSet: Bool {
return flags.contains(.isDirect)
}
var isConnectionRequiredAndTransientFlagSet: Bool {
return flags.intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection]
}
var flags: SCNetworkReachabilityFlags {
var flags = SCNetworkReachabilityFlags()
if SCNetworkReachabilityGetFlags(reachabilityRef, &flags) {
return flags
} else {
return SCNetworkReachabilityFlags()
}
}
}
it get's triggered only for one time per run in the simulator, but on a real iOS device, it works normally.

Dart: Magic Constant Equivalents

PHP offers useful magic constants like:
__CLASS__
__FILE__
__METHOD__
and so on. Also the
get_class()
function provides a similar functionality.
Is there anything similar in Dart?
Compiler constants similar to PHP not available. But you can do this manually (not constant value).
This slower but it works.
import 'package:stack_trace/stack_trace.dart';
void main() {
print(__LINE__);
print(__METHOD__);
print(__FILE__);
new Foo();
}
class Foo {
Foo() {
print(__CLASS__);
}
}
String get __CLASS__ {
var frames = new Trace.current().frames;
if(frames.length > 1) {
var member = frames[1].member;
var parts = member.split(".");
if(parts.length > 1) {
return parts[1];
}
}
return null;
}
String get __METHOD__ {
var frames = new Trace.current().frames;
if(frames.length > 1) {
return frames[1].member;
}
return null;
}
String get __FILE__ {
var frames = new Trace.current().frames;
if(frames.length > 1) {
return frames[1].uri.path;
}
return null;
}
int get __LINE__ {
var frames = new Trace.current().frames;
if(frames.length > 1) {
return frames[1].line;
}
return null;
}
4
main
/home/andrew/dart/for_web/test/bin/test.dart
Foo

Dart JavaScript output fails with: method not found: 'new ToDos:1:0' Receiver: Instance of 'JsClassMirror'

I've ported a handy JS library to Dart: dartscale. The crucial part of it's functionality can be broken down to:
final Map<Symbol, ClassMirror> _registeredModules = new Map<Symbol, ClassMirror>();
register(module, [String moduleName]) {
final uniqueModuleName = moduleName != null ? moduleName : module.runtimeType.toString();
final Symbol uniqueModuleIdentifier = new Symbol(uniqueModuleName);
if (_registeredModules.containsKey(uniqueModuleName)) {
throw new StateError("Module ${moduleName} already registered!");
}
final ClassMirror mirror = reflect(module).type;
_registeredModules[uniqueModuleIdentifier] = mirror;
}
start(Symbol moduleName, String id, options) {
if (!_registeredModules.containsKey(moduleName)) {
throw new StateError("Module ${moduleName} not registered!");
}
final ClassMirror mirror = _registeredModules[moduleName];
final Symbol moduleId = id != null ? new Symbol(id) : moduleName;
final Sandbox sandbox = new Sandbox(this.mediator);
if (_runningModules.containsKey(moduleId)) {
throw new StateError("Module with id #${moduleId} already running!");
}
final InstanceMirror moduleInstance = mirror.newInstance(new Symbol(''), [sandbox], null);
moduleInstance.invoke(new Symbol("start"), [options]);
_runningModules[moduleId] = moduleInstance;
}
i also provide an example
part of example;
class ToDos {
Sandbox _sandbox;
DivElement _contentEl;
int _nextToDoId = 0;
UListElement _todoList;
ToDos ([Sandbox this._sandbox]);
start([Map options]) {
this._initLocalStorage();
var html = ['<div id="module-todos">',
'<form>',
'<input type="text" class="input-medium">',
'<button type="submit" class="btn">Add</button>',
'</form>',
'<ul>',
'</ul>',
'</div>'].join('');
this._contentEl = new Element.html(html);
this._todoList = this._contentEl.query('ul');
options['containerEl'].append(this._contentEl);
window.localStorage.keys.forEach((key) => this._renderToDo(key));
this._setupEvents();
this._sandbox.channel('navigationbar').topic('filter').listen((filterContent) {
this._filter(filterContent);
});
this._sandbox.channel('navigationbar').topic('clearfilter').listen((filterContent) {
this._todoList.queryAll('li span').forEach((element) => element.parent.classes.remove('hide'));
});
}
stop() {
this._contentEl.remove();
}
_initLocalStorage() {
if (window.localStorage.keys.length == 0) {
var map = {
"1": {
"subject": "Groceries: Banas and Apples",
"isDone": false
},
"2": {
"subject": "Taxes: take care of them",
"isDone": false
},
"3": {
"subject": "Bring out trash",
"isDone": false
}
};
for (var key in map.keys) {
window.localStorage[key] = stringify(map[key]);
this._nextToDoId++;
}
}
else {
for (var key in window.localStorage.keys) {
var intKey = int.parse(key);
if (intKey > this._nextToDoId) {
this._nextToDoId = intKey;
}
this._nextToDoId++;
}
}
}
_setupEvents() {
var input = this._contentEl.query('input');
input.onKeyDown.listen((event) {
if (event.keyCode == KeyCode.ENTER) {
event.preventDefault();
this._addToDo(input.value);
input.value = '';
}
});
this._contentEl.query('button[type="Submit"]').onClick.listen((event) {
event.preventDefault();
if (input.value.length > 0) {
this._addToDo(input.value);
input.value = '';
}
});
this._todoList.onClick.listen((MouseEvent event) {
var el = event.target;
if (el.classes.contains('icon-remove')) {
this._deleteToDo(el.parent);
}
else if (el.classes.contains('icon-ok')) {
this._toggleToDoDone(el.parent);
}
});
}
_renderToDo(id) {
var todoObject = parse(window.localStorage[id.toString()]);
var html = ['<li class="record-todo ', todoObject["isDone"]?"done":"",'" data-id="', id,'">',
'<span>', todoObject["subject"], '</span>',
'<i class="icon icon-ok"></i>',
'<i class="icon icon-remove"></i>',
'</li>'].join('');
this._todoList.append(new Element.html(html));
}
_addToDo(text) {
var todoJson = stringify({
"subject": text,
"isDone": false
});
window.localStorage[this._nextToDoId.toString()] = todoJson;
this._renderToDo(this._nextToDoId);
this._nextToDoId++;
}
_deleteToDo(todoLIElement) {
window.localStorage.remove(todoLIElement.dataset["id"]);
todoLIElement.remove();
}
_toggleToDoDone(todoLIElement) {
var done = !todoLIElement.classes.contains('done');
var id = todoLIElement.dataset["id"];
var todoObject = parse(window.localStorage[id]);
todoObject["isDone"] = done;
window.localStorage[id] = stringify(todoObject);
if (done) {
todoLIElement.classes.add('done');
}
else {
todoLIElement.classes.remove('done');
}
}
_filter(content) {
this._todoList.queryAll('li span').forEach((element) {
if (element.innerHtml.contains(content)) {
element.parent.classes.remove('hide');
}
else {
element.parent.classes.add('hide');
}
});
}
}
in my App.dart
library example;
import 'dart:html';
import 'dart:json';
import '../lib/dartscale.dart';
part 'dart/ToDos.dart';
main () {
var core = new Core();
core.register(new ToDos());
core.start("ToDos", "ToDos", {
"containerEl": query('body > .container')
});
}
bug in dart2js ?
Solution
Turns out that dart2js has problems with mirrored calls on Methods/Constructors which have optional positional Arguments.
So changing
class ToDos {
Sandbox _sandbox;
ToDos([Sandbox this._sandbox]);
}
to
class ToDos {
Sandbox _sandbox;
ToDos(Sandbox this._sandbox); //make the argument non-optional
}
solved my Problem
This isn't really an answer, since you don't state what's going wrong, but some general advice. Mostly, I'd avoid new Symbol() and mirrors if you can easily avoid them, and in this case you can.
First, you should figure out if you want to register module instances or produce instances on demand, you probably don't want both like you are here. If you register an instance, then can't you just reuse that instance? Does start() need to produce new instances as part of its spec? You turn around and try to make sure that an instance isn't already running anyway.
If you really do need to produce instances, a simple factory function will eliminate the need for mirrors. So instead of:
core.register(new ToDos());
You write:
core.register('ToDos', () => new ToDos());
If you still want to use mirrors, you can clean up the use of new Symbol(). Here's some recommendations:
Don't use Symbols as keys unless you're really getting them from reflective APIs like mirrors and noSuchMethod in the first place. Just use the String name or maybe the runtimeType. In your case you're mixing Symbols and Strings as keys in your _registeredModules map, which is probably causing some bugs, like modules will never appear to be registered. (are you testing in checked mode?)
Don't use new Symbol('name'), use const Symbol('name')
Don't use InstanceMirror.invoke, getField, or setField when you can just call the method directly. In your code you can replace
moduleInstance.invoke(new Symbol("start"), [options]);
with
moduleInstance.reflectee.start(options);
Factories aren't evil. It'd be nice to invoke a constructor from a type instance, but until then registering a factory is pretty lightweight in Dart.
Here's your code with those suggestions:
typedef Object Factory(Sandbox sandbox);
final Map<Symbol, Factory> _registeredModules = new Map<Type, Factory>();
register(Type type, Factory factory) {
if (_registeredModules.containsKey(type)) {
throw new StateError("Module $type already registered!");
}
_registeredModules[type] = factory;
}
start(Type type, options) {
if (!_registeredModules.containsKey(type)) {
throw new StateError("Module $type not registered!");
}
if (_runningModules.containsKey(type)) {
throw new StateError("Module $type already running!");
}
Sandbox sandbox = new Sandbox(this.mediator);
var module = _runningModules[type](sandbox)..start(options);
_runningModules[type] = module;
}

Multiple boolean checks or an invalids counter

What is your preferred way to implement actions based on the invalidity of multiple variables:
ie:
invalid_get() {
return a_invalid || b_invalid || c_invalid;
}
a_invalid_set(v) {
a_invalid=v;
if(v) {
validate_add();
} else {
validate_remove();
}
}
function validate_remove() {
if(!invalid_get()) {
validate_remove_do();
}
}
OR:
var invalids_num:Int;
function a_invalid_set(v) {
a_invalid=v;
if(v) {
++invalids_num;
validate_add();
} else {
--invalids_num;
validate_remove();
}
}
validate_remove() {
if(invalids_num==0) {
validate_remove_do();
}
}
I am guessing that a int check against 0 is faster and is without question the correct pattern, certainly for a large number of properties.

Resources