Consider the following parser:
class test
{
public:
static test from_string(const string &str); //throws!
};
template <typename Iterator = string::const_iterator>
struct test_parser : grammar<Iterator, test(), blank_type>
{
test_parser() : test_parser::base_type(query)
{
query = id[_val = phx::bind(&test::from_string, qi::_1)];
id = lexeme[*char_("a-zA-Z_0-9")];
}
rule<Iterator, test(), blank_type> query;
rule<Iterator, string(), blank_type> id;
};
I'd like to catch exceptions that test::from_string might throw and to fail the match on exception. I couldn't find direct way to do this, so I'm trying to use an "adapter" function that would accept the context explicitly. But how to access the context and how to attach such an action to the grammar? Please, see the questions within the code:
template<class Context>
void match_test(const string &attr, Context &context, bool &mFlag)
{
try
{
test t = test::from_string(attr);
// how do I access the context to put t into _val?
}
catch(...)
{
mFlag = false;
}
}
//...
test_parser() : test_parser::base_type(query)
{
query = id[?match_test<?>? /*how to instantiate and use the above semantic action?*/];
id = lexeme[*char_("a-zA-Z_0-9")];
}
Like the commenter said, use
query = id[
phx::try_ [
qi::_val = phx::bind(&test::from_string, qi::_1)
].catch_all [
qi::_pass = false
]
];
See it Live on Coliru
A version that compiles even with BOOST_SPIRIT_USE_PHOENIX_V3: Live on Coliru
query = id[
phx::try_ [
qi::_val = phx::bind(&test::from_string, qi::_1)
].catch_all [
qi::_pass = false
],
qi::_pass = qi::_pass // to appease the spirit expression compilation gods
];
Related
I have a need to update the user profile switch
ViewModel
class ProfileViewModel : BaseViewModel() {
var greet = mutableStateOf(user.pushSetting.greet)
var message = mutableStateOf(user.pushSetting.message)
var messageDetails = mutableStateOf(user.pushSetting.messageDetails)
var follow = mutableStateOf(user.pushSetting)
var like = mutableStateOf(user.pushSetting.like)
var comment = mutableStateOf(user.pushSetting.comment)
fun updateUser() {
println("--")
}
}
2.Composable
#Composable
fun SettingCard(viewModel: ProfileViewModel) {
Lists {
Section {
TextRow(text = "手机号码") { }
TextRow(text = "修改密码", line = false) { }
}
Section {
SwitchRow(text = "新好友通知", checkedState = viewModel.greet)
SwitchRow(text = "新消息通知", checkedState = viewModel.message)
SwitchRow(text = "消息显示详细", line = false, checkedState = viewModel.messageDetails)
}
}
}
3.SwitchRow
#Composable
fun SwitchRow(text: String, line: Boolean = true, checkedState: MutableState<Boolean>) {
ListItem(
text = { Text(text) },
trailing = {
Switch(
checked = checkedState.value,
onCheckedChange = { checkedState.value = it },
colors = SwitchDefaults.colors(checkedThumbColor = MaterialTheme.colors.primary)
)
}
)
}
How can I observe the change of the switch and call updateUser() in ViewModel
I know this is a way, but it is not ideal. The network update will be called every time it is initialized. Is there a better solution?
LaunchedEffect(viewModel.greet) {
viewModel.updateUser()
}
The best solution for this would be to have unidirectional flow with SwitchRow with a lambda as #Codecameo advised.
But if you want to observe a MutableState inside your Viewmodel you can use snapshotFlows as
var greet: MutableState<Boolean> = mutableStateOf(user.pushSetting.greet)
init {
snapshotFlow { greet.value }
.onEach {
updateUser()
}
.launchIn(viewModelScope)
//...
}
Create a Flow from observable Snapshot state. (e.g. state holders
returned by mutableStateOf.) snapshotFlow creates a Flow that runs
block when collected and emits the result, recording any snapshot
state that was accessed. While collection continues, if a new Snapshot
is applied that changes state accessed by block, the flow will run
block again, re-recording the snapshot state that was accessed. If the
result of block is not equal to the previous result, the flow will
emit that new result. (This behavior is similar to that of
Flow.distinctUntilChanged.) Collection will continue indefinitely
unless it is explicitly cancelled or limited by the use of other Flow
operators.
Add a callback lamba in SwitchRow and call it upon any state change
#Composable
fun SettingCard(viewModel: ProfileViewModel) {
Lists {
Section {
TextRow(text = "手机号码") { }
TextRow(text = "修改密码", line = false) { }
}
Section {
SwitchRow(text = "新好友通知", checkedState = viewModel.greet) {
viewModel.updateUser()
}
SwitchRow(text = "新消息通知", checkedState = viewModel.message) {
viewModel.updateUser()
}
SwitchRow(text = "消息显示详细", line = false, checkedState = viewModel.messageDetails) {
viewModel.updateUser()
}
}
}
}
#Composable
fun SwitchRow(
text: String,
line: Boolean = true,
checkedState: MutableState<Boolean>,
onChange: (Boolean) -> Unit
) {
ListItem(
text = { Text(text) },
trailing = {
Switch(
checked = checkedState.value,
onCheckedChange = {
onChange(it)
checkedState.value = it
},
colors = SwitchDefaults.colors(checkedThumbColor = MaterialTheme.colors.primary)
)
}
)
}
Another approach:
You can keep MutableStateFlow<T> in your viewmodel and start observing it in init method and send a value to it from SwitchRow, like viewModel.stateFlow.value = value.
Remember, MutableStateFlow will only trigger in the value changes. If you set same value twice it will discard second value and will execute for first one.
val stateFlow = MutableStateFlow<Boolean?>(null)
init {
stateFlow
.filterNotNull()
.onEach { updateUser() }
.launchIn(viewModelScope)
}
In switchRow
viewmodel.stateFlow.value = !(viewmodel.stateFlow.value?: false)
This could be one potential solution. You can implement it in your convenient way.
Using DescribeInstancesRequest (c++ sdk) to get response about a particular instance_id. I am having a problem constructing the filter.
I am adapting the example code provided by the aws-doc-sdk-examples c++ example code describe_instances.cpp. I have added code to filter the response to use a known valid (now hard coded) instance ID.
I have tried multiple variations to set up the filter, but the docs aren't clear to me about the "value pair" format for the filter.
Here is the complete code. It compiles just find, but always responds with the "Could not find: ..."
Please let me know what I am getting wrong with the filter syntax! (See commented section Filter an instance id)
Thanks
void Server::set_instance_info()
{
// Get server instance information via aws sdk
Aws::SDKOptions options;
Aws::InitAPI(options);
{
/* #TODO Make this a startup config value */
Aws::Client::ClientConfiguration clientConfig;
clientConfig.region = "us-west-2";
Aws::EC2::EC2Client ec2(clientConfig);
Aws::EC2::Model::DescribeInstancesRequest request;
// Filter an instance_id
Aws::EC2::Model::Filter filter;
filter.SetName("instance_id");
Aws::String filter_val{"Name=instance_id,Values=i-0e120b44acc929946"};
Aws::Vector<Aws::String> filter_values;
filter_values.push_back(filter_val);
filter.SetValues(filter_values);
Aws::Vector<Aws::EC2::Model::Filter> DIRFilter;
DIRFilter.push_back(filter);
request.SetFilters(DIRFilter);
auto outcome = ec2.DescribeInstances(request);
if (outcome.IsSuccess())
{
const auto &reservations =
outcome.GetResult().GetReservations();
for (const auto &reservation : reservations)
{
const auto &instances = reservation.GetInstances();
for (const auto &instance : instances)
{
Aws::String instanceStateString =
Aws::EC2::Model::InstanceStateNameMapper::GetNameForInstanceStateName(
instance.GetState().GetName());
Aws::String type_string =
Aws::EC2::Model::InstanceTypeMapper::GetNameForInstanceType(
instance.GetInstanceType());
Aws::String name = "Unknown";
const auto &tags = instance.GetTags();
auto nameIter = std::find_if(tags.cbegin(), tags.cend(),
[](const Aws::EC2::Model::Tag &tag)
{
return tag.GetKey() == "Name";
});
if (nameIter != tags.cend())
{
name = nameIter->GetValue();
}
Server::id_ = instance.GetInstanceId();
Server::name_ = name;
Server::type_ = type_string;
Server::dn_ = "Not implemented";
Server::ip_ = "Not implmented";
}
}
} else {
Server::id_ = "Could not find: " + filter_val;;
Server::name_ = "";
Server::type_ = "";
Server::dn_ = "";
Server::ip_ = "";
}
}
return;
}
I just couldn't get the filter to work. Any input would be appreciated. However, there is an alternate method using the WithInstanceIds member function. Reading the API docs is always a good idea!!
Here is the subroutine that works:
void Server::set_instance_info()
{
// Get server instance information via aws sdk
Aws::SDKOptions options;
Aws::InitAPI(options);
{
/* #TODO Make this a startup config value */
Aws::Client::ClientConfiguration clientConfig;
clientConfig.region = "us-west-2";
Aws::EC2::EC2Client ec2(clientConfig);
Aws::EC2::Model::DescribeInstancesRequest request;
/* #TODO Make this a startup config value */
const Aws::String instanceId{"i-0e120b44acc929946"};
Aws::Vector<Aws::String> instances;
instances.push_back(instanceId);
request.WithInstanceIds(instances);
auto outcome = ec2.DescribeInstances(request);
if (outcome.IsSuccess())
{
const auto &reservations =
outcome.GetResult().GetReservations();
for (const auto &reservation : reservations)
{
const auto &instances = reservation.GetInstances();
for (const auto &instance : instances)
{
Aws::String instanceStateString =
Aws::EC2::Model::InstanceStateNameMapper::GetNameForInstanceStateName(
instance.GetState().GetName());
Aws::String type_string =
Aws::EC2::Model::InstanceTypeMapper::GetNameForInstanceType(
instance.GetInstanceType());
Aws::String name = "Unknown";
const auto &tags = instance.GetTags();
auto nameIter = std::find_if(tags.cbegin(), tags.cend(),
[](const Aws::EC2::Model::Tag &tag)
{
return tag.GetKey() == "Name";
});
if (nameIter != tags.cend())
{
name = nameIter->GetValue();
}
Server::id_ = instance.GetInstanceId();
Server::name_ = name;
Server::type_ = type_string;
Server::dn_ = "Not implemented";
Server::ip_ = "Not implmented";
}
}
} else {
Server::id_ = "Could not find: "+ instanceId;
Server::name_ = "";
Server::type_ = "";
Server::dn_ = "";
Server::ip_ = "";
}
}
return;
}
I want to force all my DateTime in my domain to be datetime2 on sql server. I know I can use:
Property(x => x.Field).HasColumnType("datetime2");
In my EntityTypeConfiguration derived classes.
But I would like to code something less "verbose". I try the following:
public static void SetDateTimeColumnType<T>(EntityTypeConfiguration<T> etc) where T : class {
Type t = typeof(T);
foreach (PropertyInfo pi in t.GetProperties(BindingFlags.Public | BindingFlags.Instance)) {
if (pi.PropertyType.Name == "DateTime") {
etc.Property(x => (DateTime)pi.GetValue(x)).HasColumnType("datetime2");
}
}
}
But I get the following exception :
The expression 'x => Convert(value(EFVIPRepository.ContextUtilities+<>c__DisplayClass0`1[ValkirIP.Domain.Entities.IPRight]).pi.GetValue(x))'
is not a valid property expression.
The expression should represent a property: C#: 't => t.MyProperty' VB.Net: 'Function(t) t.MyProperty'.
Use dotted paths for nested properties: C#: 't => t.MyProperty.MyProperty' VB.Net: 'Function(t) t.MyProperty.MyProperty'.
I think my real question is how to build a "property expresssion" from the name of the property, if possible.
Thank you in advance
===== EDIT =====
I also try
Expression expr = Expression.Property(System.Linq.Expressions.Expression.Variable(t), pi);
etc.Property((Expression<Func<T, DateTime>>)expr).HasColumnType("datetime2");
with the following exception:
Impossible d'effectuer un cast d'un objet de type 'System.Linq.Expressions.PropertyExpression' en type 'System.Linq.Expressions.Expression`1[System.Func`2[ValkirIP.Domain.Entities.IPRight,System.DateTime]]'.
You must build correct Expression Tree.
Try this:
public static void SetDateTimeColumnType<T>(EntityTypeConfiguration<T> etc) where T : class
{
Type t = typeof(T);
foreach (PropertyInfo pi in t.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (pi.PropertyType.Name == "DateTime")
{
var parameter = Expression.Parameter(t, "x");
var property = Expression.Property(parameter, pi.Name);
var lmbd Expression.Lambda<Func<T, DateTime>>(property, parameter);
etc.Property(lmbd).HasColumnType("datetime2");
}
}
}
I've got a really strange problem. MSVC doesn't have initializer lists, so I've used a lambda to approximate them.
static const std::unordered_map<std::wstring, LexedFile::Token> reserved_words =
[]() -> std::unordered_map<std::wstring, LexedFile::Token> {
std::unordered_map<std::wstring, LexedFile::Token> retval;
// Do stuff with retval
return retval;
}();
MSVC throws a compiler error.
error C2440: 'initializing' : cannot convert from 'int' to
'std::tr1::unordered_map<_Kty,_Ty>'
Unless I'm quite blind, there's no "int" anywhere near this. I don't see what's wrong. Any suggestions?
Edit:
There's nothing funky about // Do stuff with retval, it's just a bunch of insertions, and this is a function-scope static variable in a lambda in a member function.
auto next = [&] {
static const std::unordered_map<std::wstring, LexedFile::Token> reserved_words =
[]() -> std::unordered_map<std::wstring, LexedFile::Token> {
std::unordered_map<std::wstring, LexedFile::Token> retval;
retval[L"namespace"] = LexedFile::Token::Namespace;
retval[L"for"] = LexedFile::Token::For;
retval[L"while"] = LexedFile::Token::While;
retval[L"do"] = LexedFile::Token::Do;
retval[L"switch"] = LexedFile::Token::Switch;
retval[L"case"] = LexedFile::Token::Case;
retval[L"default"] = LexedFile::Token::Default;
retval[L"try"] = LexedFile::Token::Try;
retval[L"catch"] = LexedFile::Token::Catch;
retval[L"auto"] = LexedFile::Token::Auto;
retval[L"type"] = LexedFile::Token::Type;
retval[L"break"] = LexedFile::Token::Break;
retval[L"continue"] = LexedFile::Token::Continue;
retval[L"return"] = LexedFile::Token::Return;
retval[L"static"] = LexedFile::Token::Static;
retval[L"sizeof"] = LexedFile::Token::Sizeof;
retval[L"decltype"] = LexedFile::Token::Decltype;
retval[L"if"] = LexedFile::Token::If;
retval[L"else"] = LexedFile::Token::Else;
return retval;
}();
if (stack.empty())
return;
std::wstring token(stack.begin(), stack.end());
stack.clear();
if (reserved_words.find(token) != reserved_words.end()) {
l.tokens.push_back(reserved_words.find(token)->second);
return;
}
l.tokens.push_back(LexedFile::Identifier);
};
The compiler will accept it if I use the constructor directly not initialization, which seems very strange. Probably a compiler bug.
Calling the constructor with () instead of using = works just fine, so I'm marking this one as a compiler error.
I'm building a LINQ-based query generator.
One of the features is being able to specify an arbitrary server-side projection as part of the query definition. For example:
class CustomerSearch : SearchDefinition<Customer>
{
protected override Expression<Func<Customer, object>> GetProjection()
{
return x => new
{
Name = x.Name,
Agent = x.Agent.Code
Sales = x.Orders.Sum(o => o.Amount)
};
}
}
Since the user must then be able to sort on the projection properties (as opposed to Customer properties), I recreate the expression as a Func<Customer,anonymous type> instead of Func<Customer, object>:
//This is a method on SearchDefinition
IQueryable Transform(IQueryable source)
{
var projection = GetProjection();
var properProjection = Expression.Lambda(projection.Body,
projection.Parameters.Single());
In order to return the projected query, I'd love to be able to do this (which, in fact, works in an almost identical proof of concept):
return Queryable.Select((IQueryable<TRoot>)source, (dynamic)properProjection);
TRoot is the type parameter in SearchDefinition. This results in the following exception:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:
The best overloaded method match for
'System.Linq.Queryable.Select<Customer,object>(System.Linq.IQueryable<Customer>,
System.Linq.Expressions.Expression<System.Func<Customer,object>>)'
has some invalid arguments
at CallSite.Target(Closure , CallSite , Type , IQueryable`1 , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecute3[T0,T1,T2,TRet]
(CallSite site, T0 arg0, T1 arg1, T2 arg2)
at SearchDefinition`1.Transform(IQueryable source) in ...
If you look closely, it's inferring the generic parameters incorrectly: Customer,object instead of Customer,anonymous type, which is the actual type of the properProjection expression (double-checked)
My workaround is using reflection. But with generic arguments, it's a real mess:
var genericSelectMethod = typeof(Queryable).GetMethods().Single(
x => x.Name == "Select" &&
x.GetParameters()[1].ParameterType.GetGenericArguments()[0]
.GetGenericArguments().Length == 2);
var selectMethod = genericSelectMethod.MakeGenericMethod(source.ElementType,
projectionBody.Type);
return (IQueryable)selectMethod.Invoke(null, new object[]{ source, projection });
Does anyone know of a better way?
Update: the reason why dynamic fails is that anonymous types are defined as internal. That's why it worked using a proof-of-concept project, where everything was in the same assembly.
I'm cool with that. I'd still like to find a cleaner way to find the right Queryable.Select overload.
The fix is so simple it hurts:
[assembly: InternalsVisibleTo("My.Search.Lib.Assembly")]
Here's my test as requested. This on a Northwind database and this works fine for me.
static void Main(string[] args)
{
var dc = new NorthwindDataContext();
var source = dc.Categories;
Expression<Func<Category, object>> expr =
c => new
{
c.CategoryID,
c.CategoryName,
};
var oldParameter = expr.Parameters.Single();
var parameter = Expression.Parameter(oldParameter.Type, oldParameter.Name);
var body = expr.Body;
body = RebindParameter(body, oldParameter, parameter);
Console.WriteLine("Parameter Type: {0}", parameter.Type);
Console.WriteLine("Body Type: {0}", body.Type);
var newExpr = Expression.Lambda(body, parameter);
Console.WriteLine("Old Expression Type: {0}", expr.Type);
Console.WriteLine("New Expression Type: {0}", newExpr.Type);
var query = Queryable.Select(source, (dynamic)newExpr);
Console.WriteLine(query);
foreach (var item in query)
{
Console.WriteLine(item);
Console.WriteLine("\t{0}", item.CategoryID.GetType());
Console.WriteLine("\t{0}", item.CategoryName.GetType());
}
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
Console.WriteLine();
}
static Expression RebindParameter(Expression expr, ParameterExpression oldParam, ParameterExpression newParam)
{
switch (expr.NodeType)
{
case ExpressionType.Parameter:
var parameterExpression = expr as ParameterExpression;
return (parameterExpression.Name == oldParam.Name)
? newParam
: parameterExpression;
case ExpressionType.MemberAccess:
var memberExpression = expr as MemberExpression;
return memberExpression.Update(
RebindParameter(memberExpression.Expression, oldParam, newParam));
case ExpressionType.AndAlso:
case ExpressionType.OrElse:
case ExpressionType.Equal:
case ExpressionType.NotEqual:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
var binaryExpression = expr as BinaryExpression;
return binaryExpression.Update(
RebindParameter(binaryExpression.Left, oldParam, newParam),
binaryExpression.Conversion,
RebindParameter(binaryExpression.Right, oldParam, newParam));
case ExpressionType.New:
var newExpression = expr as NewExpression;
return newExpression.Update(
newExpression.Arguments
.Select(arg => RebindParameter(arg, oldParam, newParam)));
case ExpressionType.Call:
var methodCallExpression = expr as MethodCallExpression;
return methodCallExpression.Update(
RebindParameter(methodCallExpression.Object, oldParam, newParam),
methodCallExpression.Arguments
.Select(arg => RebindParameter(arg, oldParam, newParam)));
default:
return expr;
}
}
Also, dynamic method resolution doesn't really do much for you in this case as there are only two very distinct overloads of Select(). Ultimately you just need to remember that you won't have any static type checking on your results since you don't have any static type information. With that said, this will also work for you (using the above code example):
var query = Queryable.Select(source, expr).Cast<dynamic>();
Console.WriteLine(query);
foreach (var item in query)
{
Console.WriteLine(item);
Console.WriteLine("\t{0}", item.CategoryID.GetType());
Console.WriteLine("\t{0}", item.CategoryName.GetType());
}