问:
StreamBuilder not correctly refreshing on new value
Probably it's my fault or a dumb error but this is what is happening to me:

authController.dart:

```<code>class AuthController {
BehaviorSubject _hometownController = BehaviorSubject();
Observable get hometown => _hometownController.stream;
void updateHometown(String hometown) {
    _hometownController.add(hometown);
    print(_hometownController.value); <- This always prints the expected value: "Hello!"`
}
}
</code>```

Login_screen.dart:

```<code>class Login2 extends StatelessWidget {
  AuthController authController = new AuthController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Builder(
        builder: (BuildContext context) =>
          Container(
            padding: EdgeInsets.all(32.0),
            child: Center(
              child:
                  //Hometown:
                  StreamBuilder(
                    stream: authController.hometown,
                    builder: (BuildContext context, AsyncSnapshot snap) {
                      return ListTile(
                        leading: Icon(Icons.map),
                        title: Text("Hometown:"),
                        subtitle: snap.hasData ? Text(snap.data) : Text("Not set"),
                        onTap: () {
                          authController.updateHometown("Hello!");
                        },
                      );
                    }
                  ),
  ))));}}
</code>```

And everything goes well.
But if I add an asynchronous function with async and await before authController.updateHometown:

Login_screen.dart:

```<code>                            onTap: () async {
                              var x = await something(); <- This always successfully completes
                              authController.updateHometown("Hello!");
                            },
</code>```

The stream never receives the new value and the StreamBuilder never rebuilds!

But if I use a statefulWidget class:

```<code>class Login2 extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => Login2State();
}

class Login2State extends State<Login2> {
  AuthController authController;

  @override
  void initState() {
    authController = new AuthController();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Builder(
        builder: (BuildContext context) =>
          Container(
            padding: EdgeInsets.all(32.0),
            child: Center(
              child:
                  //Hometown:
                  StreamBuilder(
                    stream: authController.hometown,
                    builder: (BuildContext context, AsyncSnapshot snap) {
                      return ListTile(
                        leading: Icon(Icons.map),
                        title: Text("Hometown:"),
                        subtitle: snap.hasData ? Text(snap.data) : Text("Not set"),
                        onTap: () async {
                          var x = await something();
                          authController.updateHometown("Hello!");
                        },
                      );
     }),))));}}
</code>```

Everything goes well, even if I never call setState
Why is this happening?

答:
From Framework.dart :

A StatelessWidget builds itself depending on data that has two conditions:

can be read synchronously when the widget is
built. And :

might change during the lifetime of the widget.

That's why when you make Login2 as StatelessWidget, and then change the data in authController synchronously it is immediately reflected because it satisfies both conditions. But when you use an async function inside onTap() you break the first one.

And why StatefulWidget works with async function is because its build function only needs a data change to trigger setState() implicitly irrespective of whether this info is available synchronously or asynchronously.

Body:
Probably it's my fault or a dumb error but this is what is happening to me:

authController.dart:

class AuthController {
BehaviorSubject _hometownController = BehaviorSubject();
Observable get hometown => _hometownController.stream;
void updateHometown(String hometown) {
    _hometownController.add(hometown);
    print(_hometownController.value); <- This always prints the expected value: "Hello!"`
}
}

Login_screen.dart:

class Login2 extends StatelessWidget {
  AuthController authController = new AuthController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Builder(
        builder: (BuildContext context) =>
          Container(
            padding: EdgeInsets.all(32.0),
            child: Center(
              child:
                  //Hometown:
                  StreamBuilder(
                    stream: authController.hometown,
                    builder: (BuildContext context, AsyncSnapshot snap) {
                      return ListTile(
                        leading: Icon(Icons.map),
                        title: Text("Hometown:"),
                        subtitle: snap.hasData ? Text(snap.data) : Text("Not set"),
                        onTap: () {
                          authController.updateHometown("Hello!");
                        },
                      );
                    }
                  ),
  ))));}}

And everything goes well.
But if I add an asynchronous function with async and await before authController.updateHometown:

Login_screen.dart:

                            onTap: () async {
                              var x = await something(); <- This always successfully completes
                              authController.updateHometown("Hello!");
                            },

The stream never receives the new value and the StreamBuilder never rebuilds!

But if I use a statefulWidget class:

class Login2 extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => Login2State();
}

class Login2State extends State<Login2> {
  AuthController authController;

  @override
  void initState() {
    authController = new AuthController();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Builder(
        builder: (BuildContext context) =>
          Container(
            padding: EdgeInsets.all(32.0),
            child: Center(
              child:
                  //Hometown:
                  StreamBuilder(
                    stream: authController.hometown,
                    builder: (BuildContext context, AsyncSnapshot snap) {
                      return ListTile(
                        leading: Icon(Icons.map),
                        title: Text("Hometown:"),
                        subtitle: snap.hasData ? Text(snap.data) : Text("Not set"),
                        onTap: () async {
                          var x = await something();
                          authController.updateHometown("Hello!");
                        },
                      );
     }),))));}}

Everything goes well, even if I never call setState
Why is this happening?


来源: stackexchange

问:
Function returns an error (ESLint) move function to body root
I have the following function.the code does what i need it to do,however its not structured correctly because of the declarations therefore it gives "(ESLint) move function to body root" error :

This is my code:

```<code>function onSuccess(result) {

            if (result) {
                 function GetTotal(result) {

                    var totBal = 0;
                    var str = 'R';
                    for (var i = 0; i < result.length; i++) {
                        totBal += result[i].Price;
                    }
                    str += totBal.toFixed(2);
                    return str;
                }
                var span = document.getElementById("Total");
                span.innerHTML = GetTotal(result);
            }
        }
</code>```

This is what i tried:

```<code>function onSuccess(result) {
        var fn;
        if (result) {
          fn=function GetTotal(result) {

                var totBal = 0;
                var str = 'R';
                for (var i = 0; i < result.length; i++) {
                    totBal += result[i].Price;
                }
                str += totBal.toFixed(2);
                return str;
            };
            var span = document.getElementById("Total");
            span.innerHTML = GetTotal(result);
        }
    }
</code>```

the "(ESLint) move function to body root" gets solved But with the above it returns an error saying "getTotal is not defined"

答:
Then function declaration is on right hand side. It becomes a local variable to the variable on left hand side. Use the name GetTotal instead of fn in the main function scope.

```<code>function onSuccess(result) {
        var GetTotal;
        if (result) {
          GetTotal = function(result) {

                var totBal = 0;
                var str = 'R';
                for (var i = 0; i < result.length; i++) {
                    totBal += result[i].Price;
                }
                str += totBal.toFixed(2);
                return str;
            };
            var span = document.getElementById("Total");
            span.innerHTML = GetTotal(result);
        }
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following function.the code does what i need it to do,however its not structured correctly because of the declarations therefore it gives "(ESLint) move function to body root" error :

This is my code:

function onSuccess(result) {

            if (result) {
                 function GetTotal(result) {

                    var totBal = 0;
                    var str = 'R';
                    for (var i = 0; i < result.length; i++) {
                        totBal += result[i].Price;
                    }
                    str += totBal.toFixed(2);
                    return str;
                }
                var span = document.getElementById("Total");
                span.innerHTML = GetTotal(result);
            }
        }

This is what i tried:

function onSuccess(result) {
        var fn;
        if (result) {
          fn=function GetTotal(result) {

                var totBal = 0;
                var str = 'R';
                for (var i = 0; i < result.length; i++) {
                    totBal += result[i].Price;
                }
                str += totBal.toFixed(2);
                return str;
            };
            var span = document.getElementById("Total");
            span.innerHTML = GetTotal(result);
        }
    }

the "(ESLint) move function to body root" gets solved But with the above it returns an error saying "getTotal is not defined"

Body:
Then function declaration is on right hand side. It becomes a local variable to the variable on left hand side. Use the name GetTotal instead of fn in the main function scope.

function onSuccess(result) {
        var GetTotal;
        if (result) {
          GetTotal = function(result) {

                var totBal = 0;
                var str = 'R';
                for (var i = 0; i < result.length; i++) {
                    totBal += result[i].Price;
                }
                str += totBal.toFixed(2);
                return str;
            };
            var span = document.getElementById("Total");
            span.innerHTML = GetTotal(result);
        }
    }


问:
CallSite <>p__site while decompiling large code base
I have large code base from a client whose developer refused to provide the code.

I have de-compiled major portion of it, although I am having problem with following

I am using dnSpy, Just Decompile, dotPeek to decompile the code. I have tried to google and looked over Stackoverflow as well but could not find any thing that could answer me. I would really appreciate if someone can point me in right direction.

Update: I have pasted complete function

```<code>public virtual string ParseDealerInventoryLink(string toParseLinkData)
        {
            string pattern = "{([^}]+)}";
            string text = toParseLinkData;
            RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled;
            if (this != null && !string.IsNullOrWhiteSpace(text))
            {
                object dyn = new PropertyBag(this);
                Regex regex = new Regex(pattern, options);
                Dictionary<string, DealerInventoryLinkPatternParam> linkPatternMap = DealerInventoryFeedUrlParser.GetLinkPatternParamValueMap();
                text = regex.Replace(text, delegate(Match mat)
                {
                    if (mat.Success && mat.Groups.Count > 0)
                    {
                        Group group = mat.Groups[mat.Groups.Count - 1];
                        if (group.Success)
                        {
                            string value = group.Value;
                            if (linkPatternMap.ContainsKey(value))
                            {
                                if (DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site1 == null)
                                {
                                    DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site1 = CallSite<Func<CallSite, object, string>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.Convert(CSharpBinderFlags.None, typeof(string), typeof(DealerInventoryFeedUrlParser)));
                                }
                                Func<CallSite, object, string> target = DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site1.Target;
                                CallSite <>p__Site = DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site1;
                                if (DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site2 == null)
                                {
                                    DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site2 = CallSite<Func<CallSite, Type, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "ToString", null, typeof(DealerInventoryFeedUrlParser), new CSharpArgumentInfo[]
                                    {
                                        CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType | CSharpArgumentInfoFlags.IsStaticType, null),
                                        CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)
                                    }));
                                }
                                Func<CallSite, Type, object, object> target2 = DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site2.Target;
                                CallSite <>p__Site2 = DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site2;
                                Type typeFromHandle = typeof(Convert);
                                if (DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site3 == null)
                                {
                                    DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site3 = CallSite<Func<CallSite, object, string, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(CSharpBinderFlags.None, typeof(DealerInventoryFeedUrlParser), new CSharpArgumentInfo[]
                                    {
                                        CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null),
                                        CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, null)
                                    }));
                                }
                                return target(<>p__Site, target2(<>p__Site2, typeFromHandle, DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site3.Target(DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site3, dyn, linkPatternMap[value].ColumnName)));
                            }
                        }
                    }
                    return mat.Value;
                });
            }
            return text;
        }
</code>```

答:
```<code>class DealerInventoryFeedUrlParser
{
    void ParseDealerInventoryLink()
    {
        dynamic input = new object();
        string link = input;
    }
}
</code>```

generates the following when compiled and then decompiled in ILSpy:

```<code>class DealerInventoryFeedUrlParser
{
    private void ParseDealerInventoryLink()
    {
        object input = new object();
        if (<>o__0.<>p__0 == null)
        {
            <>o__0.<>p__0 = CallSite<Func<CallSite, object, string>>.Create(Binder.Convert(CSharpBinderFlags.None, typeof(string), typeof(DealerInventoryFeedUrlParser)));
        }
        string link = <>o__0.<>p__0.Target(<>o__0.<>p__0, input);
    }
  }
</code>```

... which I would classify as "close enough".

There is no particular reason I chose new object() as the value assigned to dynamic. This could have been an int, string - anything. The CallSite ininitialisation code would look the same. T2 in CallSite<Func<T1, T2, TResult>> is always object, so you won't know what your real input value is unless you look at the location in your decompiled source where DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site1 is actually used.

EDIT

Now that the full source has been posted, let's try to put the pieces together:

```<code>class DealerInventoryFeedUrlParser
{
    static Dictionary<string, DealerInventoryLinkPatternParam> GetLinkPatternParamValueMap() => throw new NotImplementedException();

    public virtual string ParseDealerInventoryLink(string toParseLinkData)
    {
        string pattern = "{([^}]+)}";
        string text = toParseLinkData;
        RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled;
        if (/*this != null &&*/ !string.IsNullOrWhiteSpace(text))
        {
            dynamic dyn = new PropertyBag(this);
            Regex regex = new Regex(pattern, options);
            Dictionary<string, DealerInventoryLinkPatternParam> linkPatternMap = GetLinkPatternParamValueMap();
            text = regex.Replace(text, delegate (Match mat)
            {
                if (mat.Success && mat.Groups.Count > 0)
                {
                    Group group = mat.Groups[mat.Groups.Count - 1];
                    if (group.Success)
                    {
                        string value = group.Value;
                        if (linkPatternMap.ContainsKey(value))
                        {
                            return Convert.ToString(dyn[linkPatternMap[value].ColumnName]);
                        }
                    }
                }
                return mat.Value;
            });
        }
        return text;
    }
}

class PropertyBag
{
    private readonly object Owner;

    public PropertyBag(object obj)
    {
        Owner = obj;
    }
}

class DealerInventoryLinkPatternParam
{
    public string ColumnName { get; set; }
}
</code>```

ParseDealerInventoryLink compiled/decompiled:

```<code>public virtual string ParseDealerInventoryLink(string toParseLinkData)
{
    string pattern = "{([^}]+)}";
    string text = toParseLinkData;
    RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled;
    if (!string.IsNullOrWhiteSpace(text))
    {
        dynamic dyn = new PropertyBag(this);
        Regex regex = new Regex(pattern, options);
        Dictionary<string, DealerInventoryLinkPatternParam> linkPatternMap = DealerInventoryFeedUrlParser.GetLinkPatternParamValueMap();
        text = regex.Replace(text, delegate(Match mat)
        {
            if (mat.Success && mat.Groups.Count > 0)
            {
                Group group = mat.Groups[mat.Groups.Count - 1];
                if (group.Success)
                {
                    string value = group.Value;
                    if (linkPatternMap.ContainsKey(value))
                    {
                        if (<>o__1.<>p__2 == null)
                        {
                            <>o__1.<>p__2 = CallSite<Func<CallSite, object, string>>.Create(Binder.Convert(CSharpBinderFlags.None, typeof(string), typeof(DealerInventoryFeedUrlParser)));
                        }
                        Func<CallSite, object, string> target = <>o__1.<>p__2.Target;
                        CallSite<Func<CallSite, object, string>> <>p__ = <>o__1.<>p__2;
                        if (<>o__1.<>p__1 == null)
                        {
                            <>o__1.<>p__1 = CallSite<Func<CallSite, Type, object, object>>.Create(Binder.InvokeMember(CSharpBinderFlags.None, "ToString", null, typeof(DealerInventoryFeedUrlParser), new CSharpArgumentInfo[2]
                            {
                                CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType | CSharpArgumentInfoFlags.IsStaticType, null),
                                CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)
                            }));
                        }
                        Func<CallSite, Type, object, object> target2 = <>o__1.<>p__1.Target;
                        CallSite<Func<CallSite, Type, object, object>> <>p__2 = <>o__1.<>p__1;
                        Type typeFromHandle = typeof(Convert);
                        if (<>o__1.<>p__0 == null)
                        {
                            <>o__1.<>p__0 = CallSite<Func<CallSite, object, string, object>>.Create(Binder.GetIndex(CSharpBinderFlags.None, typeof(DealerInventoryFeedUrlParser), new CSharpArgumentInfo[2]
                            {
                                CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null),
                                CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, null)
                            }));
                        }
                        return target(<>p__, target2(<>p__2, typeFromHandle, <>o__1.<>p__0.Target(<>o__1.<>p__0, dyn, linkPatternMap[value].ColumnName)));
                    }
                }
            }
            return mat.Value;
        });
    }
    return text;
}
</code>```

You can substitute the compiler-generated names to check whether I've gotten everything right. What I made is an honest, but very, very quick attempt at guessing what I'm looking at based on my limited understanding of dynamic. Now it's up to you to check everything, verify correctness and fix if necessary.

P.S. The this != null check bit baffled me a little. Must be a quirk of the decompiler. I've commented it out as it didn't seem significant.

P.P.S. Decompiling and recompiling binaries is a pretty dirty and error-prone process. If the changes you need to make are small, consider looking into .NET binary patching (Google it), i.e. by using ILSpy + Reflexil.

Good luck.

Body:
I have large code base from a client whose developer refused to provide the code.

I have de-compiled major portion of it, although I am having problem with following

I am using dnSpy, Just Decompile, dotPeek to decompile the code. I have tried to google and looked over Stackoverflow as well but could not find any thing that could answer me. I would really appreciate if someone can point me in right direction.

Update: I have pasted complete function

public virtual string ParseDealerInventoryLink(string toParseLinkData)
        {
            string pattern = "{([^}]+)}";
            string text = toParseLinkData;
            RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled;
            if (this != null && !string.IsNullOrWhiteSpace(text))
            {
                object dyn = new PropertyBag(this);
                Regex regex = new Regex(pattern, options);
                Dictionary<string, DealerInventoryLinkPatternParam> linkPatternMap = DealerInventoryFeedUrlParser.GetLinkPatternParamValueMap();
                text = regex.Replace(text, delegate(Match mat)
                {
                    if (mat.Success && mat.Groups.Count > 0)
                    {
                        Group group = mat.Groups[mat.Groups.Count - 1];
                        if (group.Success)
                        {
                            string value = group.Value;
                            if (linkPatternMap.ContainsKey(value))
                            {
                                if (DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site1 == null)
                                {
                                    DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site1 = CallSite<Func<CallSite, object, string>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.Convert(CSharpBinderFlags.None, typeof(string), typeof(DealerInventoryFeedUrlParser)));
                                }
                                Func<CallSite, object, string> target = DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site1.Target;
                                CallSite <>p__Site = DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site1;
                                if (DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site2 == null)
                                {
                                    DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site2 = CallSite<Func<CallSite, Type, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(CSharpBinderFlags.None, "ToString", null, typeof(DealerInventoryFeedUrlParser), new CSharpArgumentInfo[]
                                    {
                                        CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType | CSharpArgumentInfoFlags.IsStaticType, null),
                                        CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)
                                    }));
                                }
                                Func<CallSite, Type, object, object> target2 = DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site2.Target;
                                CallSite <>p__Site2 = DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site2;
                                Type typeFromHandle = typeof(Convert);
                                if (DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site3 == null)
                                {
                                    DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site3 = CallSite<Func<CallSite, object, string, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(CSharpBinderFlags.None, typeof(DealerInventoryFeedUrlParser), new CSharpArgumentInfo[]
                                    {
                                        CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null),
                                        CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, null)
                                    }));
                                }
                                return target(<>p__Site, target2(<>p__Site2, typeFromHandle, DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site3.Target(DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site3, dyn, linkPatternMap[value].ColumnName)));
                            }
                        }
                    }
                    return mat.Value;
                });
            }
            return text;
        }

Body:
class DealerInventoryFeedUrlParser
{
    void ParseDealerInventoryLink()
    {
        dynamic input = new object();
        string link = input;
    }
}

generates the following when compiled and then decompiled in ILSpy:

class DealerInventoryFeedUrlParser
{
    private void ParseDealerInventoryLink()
    {
        object input = new object();
        if (<>o__0.<>p__0 == null)
        {
            <>o__0.<>p__0 = CallSite<Func<CallSite, object, string>>.Create(Binder.Convert(CSharpBinderFlags.None, typeof(string), typeof(DealerInventoryFeedUrlParser)));
        }
        string link = <>o__0.<>p__0.Target(<>o__0.<>p__0, input);
    }
  }

... which I would classify as "close enough".

There is no particular reason I chose new object() as the value assigned to dynamic. This could have been an int, string - anything. The CallSite ininitialisation code would look the same. T2 in CallSite<Func<T1, T2, TResult>> is always object, so you won't know what your real input value is unless you look at the location in your decompiled source where DealerInventoryFeedUrlParser.<ParseDealerInventoryLink>o__SiteContainer0.<>p__Site1 is actually used.

EDIT

Now that the full source has been posted, let's try to put the pieces together:

class DealerInventoryFeedUrlParser
{
    static Dictionary<string, DealerInventoryLinkPatternParam> GetLinkPatternParamValueMap() => throw new NotImplementedException();

    public virtual string ParseDealerInventoryLink(string toParseLinkData)
    {
        string pattern = "{([^}]+)}";
        string text = toParseLinkData;
        RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled;
        if (/*this != null &&*/ !string.IsNullOrWhiteSpace(text))
        {
            dynamic dyn = new PropertyBag(this);
            Regex regex = new Regex(pattern, options);
            Dictionary<string, DealerInventoryLinkPatternParam> linkPatternMap = GetLinkPatternParamValueMap();
            text = regex.Replace(text, delegate (Match mat)
            {
                if (mat.Success && mat.Groups.Count > 0)
                {
                    Group group = mat.Groups[mat.Groups.Count - 1];
                    if (group.Success)
                    {
                        string value = group.Value;
                        if (linkPatternMap.ContainsKey(value))
                        {
                            return Convert.ToString(dyn[linkPatternMap[value].ColumnName]);
                        }
                    }
                }
                return mat.Value;
            });
        }
        return text;
    }
}

class PropertyBag
{
    private readonly object Owner;

    public PropertyBag(object obj)
    {
        Owner = obj;
    }
}

class DealerInventoryLinkPatternParam
{
    public string ColumnName { get; set; }
}

ParseDealerInventoryLink compiled/decompiled:

public virtual string ParseDealerInventoryLink(string toParseLinkData)
{
    string pattern = "{([^}]+)}";
    string text = toParseLinkData;
    RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled;
    if (!string.IsNullOrWhiteSpace(text))
    {
        dynamic dyn = new PropertyBag(this);
        Regex regex = new Regex(pattern, options);
        Dictionary<string, DealerInventoryLinkPatternParam> linkPatternMap = DealerInventoryFeedUrlParser.GetLinkPatternParamValueMap();
        text = regex.Replace(text, delegate(Match mat)
        {
            if (mat.Success && mat.Groups.Count > 0)
            {
                Group group = mat.Groups[mat.Groups.Count - 1];
                if (group.Success)
                {
                    string value = group.Value;
                    if (linkPatternMap.ContainsKey(value))
                    {
                        if (<>o__1.<>p__2 == null)
                        {
                            <>o__1.<>p__2 = CallSite<Func<CallSite, object, string>>.Create(Binder.Convert(CSharpBinderFlags.None, typeof(string), typeof(DealerInventoryFeedUrlParser)));
                        }
                        Func<CallSite, object, string> target = <>o__1.<>p__2.Target;
                        CallSite<Func<CallSite, object, string>> <>p__ = <>o__1.<>p__2;
                        if (<>o__1.<>p__1 == null)
                        {
                            <>o__1.<>p__1 = CallSite<Func<CallSite, Type, object, object>>.Create(Binder.InvokeMember(CSharpBinderFlags.None, "ToString", null, typeof(DealerInventoryFeedUrlParser), new CSharpArgumentInfo[2]
                            {
                                CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType | CSharpArgumentInfoFlags.IsStaticType, null),
                                CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)
                            }));
                        }
                        Func<CallSite, Type, object, object> target2 = <>o__1.<>p__1.Target;
                        CallSite<Func<CallSite, Type, object, object>> <>p__2 = <>o__1.<>p__1;
                        Type typeFromHandle = typeof(Convert);
                        if (<>o__1.<>p__0 == null)
                        {
                            <>o__1.<>p__0 = CallSite<Func<CallSite, object, string, object>>.Create(Binder.GetIndex(CSharpBinderFlags.None, typeof(DealerInventoryFeedUrlParser), new CSharpArgumentInfo[2]
                            {
                                CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null),
                                CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, null)
                            }));
                        }
                        return target(<>p__, target2(<>p__2, typeFromHandle, <>o__1.<>p__0.Target(<>o__1.<>p__0, dyn, linkPatternMap[value].ColumnName)));
                    }
                }
            }
            return mat.Value;
        });
    }
    return text;
}

You can substitute the compiler-generated names to check whether I've gotten everything right. What I made is an honest, but very, very quick attempt at guessing what I'm looking at based on my limited understanding of dynamic. Now it's up to you to check everything, verify correctness and fix if necessary.

P.S. The this != null check bit baffled me a little. Must be a quirk of the decompiler. I've commented it out as it didn't seem significant.

P.P.S. Decompiling and recompiling binaries is a pretty dirty and error-prone process. If the changes you need to make are small, consider looking into .NET binary patching (Google it), i.e. by using ILSpy + Reflexil.

Good luck.


问:
Problem with saving php sessions in different directory
I'm trying really hard to save my sessions in different directory.
I have a shared server in OVH. Default session save path is /tmp, and I want to change it.

In my root directory I have www folder which is my main website folder. I created 'sessions' folder next to it, chmoded 777.
When I'm doing print_r(scandir('/home/expressptp/sessions/')); i'm getting files just fine, but when I try to session_save_path('/home/expressptp/sessions'); nothing ever appears there.

Full code looks something like this:

    session_save_path('/home/expressptp/sessions');
    session_start();

    echo session_id();
    $_SESSION["test"] = "test";

    echo session_save_path(); //that prints good path
```

But the problem is that in folder sessions there are no sessions :(

I tried everything. I put 'sessions' folder in 'www', chmod 777, setting path with realpath(dirname($_SERVER['DOCUMENT_ROOT']), etc.

If you have any ideas I will be grateful.

答:
Are you absolutely sure nothing in your code has begun outputting ("echo" or html tags or text) to the browser before you try this code?

Many times session/header/cookie functions do not work as expected just because of that...

Also, many host providers do restrict these kind of configurations, have you checked if the session_save_path() function is disabled, or if OVH explicitly prohibits this configuration change?

Body:
I'm trying really hard to save my sessions in different directory.
I have a shared server in OVH. Default session save path is /tmp, and I want to change it.

In my root directory I have www folder which is my main website folder. I created 'sessions' folder next to it, chmoded 777.
When I'm doing print_r(scandir('/home/expressptp/sessions/')); i'm getting files just fine, but when I try to session_save_path('/home/expressptp/sessions'); nothing ever appears there.

Full code looks something like this:

    session_save_path('/home/expressptp/sessions');
    session_start();

    echo session_id();
    $_SESSION["test"] = "test";

    echo session_save_path(); //that prints good path

But the problem is that in folder sessions there are no sessions :(

I tried everything. I put 'sessions' folder in 'www', chmod 777, setting path with realpath(dirname($_SERVER['DOCUMENT_ROOT']), etc.

If you have any ideas I will be grateful.


问:
How to call this function?
I have a function in Saves.java class and i want to call this function in the other Import.java class, how doing it ?
Here is the code of the function:

```<code>public void updatelv(Activity activity) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        String fileName = getResources().getString(R.string.fileName);
        fileDir = "" + preferences.getString("login", "") + "."+ preferences.getString("marque", "") + ".";
        list = myIO.ReadFilePerLine(getApplicationContext(), fileDir+fileName);
        ListView L = (ListView) findViewById(R.id.lv);

        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.list_item, list);
        L.setAdapter(adapter);
        }
</code>```

I think that i have to do this :  Saves save=new Saves();
And after, how to call the updatelv(activity) function ?

Thank you.

the import.java class called when pressed in a menu Import" button(in Saves.java class):

```<code>case R.id.importer:
  Import myImport = new Import(this);
  myImport.transfer();
</code>```

答:
```<code>Saves save=new Saves();
save.updatelv(this);
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to call this function?

Body:
I have a function in Saves.java class and i want to call this function in the other Import.java class, how doing it ?
Here is the code of the function:

public void updatelv(Activity activity) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        String fileName = getResources().getString(R.string.fileName);
        fileDir = "" + preferences.getString("login", "") + "."+ preferences.getString("marque", "") + ".";
        list = myIO.ReadFilePerLine(getApplicationContext(), fileDir+fileName);
        ListView L = (ListView) findViewById(R.id.lv);

        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.list_item, list);
        L.setAdapter(adapter);
        }

I think that i have to do this :  Saves save=new Saves();
And after, how to call the updatelv(activity) function ?

Thank you.

the import.java class called when pressed in a menu Import" button(in Saves.java class):

case R.id.importer:
  Import myImport = new Import(this);
  myImport.transfer();


问:
Access denied to S3 when using COPY command with IAM role
I have the following copy command:

```<code>copy ink.contact_trace_records
from 's3://mybucket/mykey'
iam_role 'arn:aws:iam::accountnum:role/rolename'
json 'auto';
</code>```

Where the role has the full access to S3 and full access to RS policies (I know this is not a good idea, but I'm just losing it here :) ). The cluster has the role attached. The cluster has VPC enhanced routing. I get the following:

```<code>[2019-05-28 14:07:34] [XX000][500310] [Amazon](500310) Invalid operation: S3ServiceException:Access Denied,Status 403,Error AccessDenied,Rid 370F75618922AFC0,ExtRid dp2mcnlofFzt4dz00Lcm188/+ta3OEKVpuFjnZSYsC0pJPMiULk7I6spOpiZwXc04VVRdxizIj4=,CanRetry 1
[2019-05-28 14:07:34] Details:
[2019-05-28 14:07:34] -----------------------------------------------
[2019-05-28 14:07:34] error:  S3ServiceException:Access Denied,Status 403,Error AccessDenied,Rid 370F75618922AFC0,ExtRid dp2mcnlofFzt4dz00Lcm188/+ta3OEKVpuFjnZSYsC0pJPMiULk7I6spOpiZwXc04VVRdxizIj4=,CanRetry 1
[2019-05-28 14:07:34] code:      8001
[2019-05-28 14:07:34] context:   S3 key being read : s3://redacted
[2019-05-28 14:07:34] query:     7794423
[2019-05-28 14:07:34] location:  table_s3_scanner.cpp:372
[2019-05-28 14:07:34] process:   query3_986_7794423 [pid=13695]
[2019-05-28 14:07:34] -----------------------------------------------;
</code>```

What am I missing here? The cluster has full access to S3, it is not even in a custom VPC, it is in the default one. Thoughts?

答:
Check the object owner. The object is likely owned by another account. This is the reason for S3 403s in many situations where objects cannot be accessed by a role or account that has full permissions. The typical indicator is that you can list the object(s) but cannot get or head them.

In the following example I'm trying to access a Redshift audit log from a 2nd account. The account 012345600000 is granted access to the bucket owned by 999999999999 using the following policy:

```<code>{"Version": "2012-10-17",
 "Statement": [
        {"Action": [
                "s3:Get*",
                "s3:ListBucket*"
            ],
          "Effect": "Allow",
          "Resource": [
                "arn:aws:s3:::my-audit-logs",
                "arn:aws:s3:::my-audit-logs/*"
            ],
          "Principal": {
                "AWS": [
                    "arn:aws:iam::012345600000:root"
                ]}}]
 }
</code>```

Now I try to list (s3 ls) then copy (s3 cp) a single log object:

```<code>aws --profile 012345600000 s3 ls s3://my-audit-logs/AWSLogs/999999999999/redshift/us-west-2/2019/05/25/
# 2019-05-28 14:49:46        376 …connectionlog_2019-05-25T19:03.gz
aws --profile 012345600000 s3 cp s3://my-audit-logs/AWSLogs/999999999999/redshift/us-west-2/2019/05/25/…connectionlog_2019-05-25T19:03.gz ~/Downloads/…connectionlog_2019-05-25T19:03.gz
# fatal error: An error occurred (403) when calling the HeadObject operation: Forbidden
</code>```

Then I check the object ownership from the account that owns the bucket.

```<code>aws --profile 999999999999 s3api get-object-acl --bucket my-audit-logs --key AWSLogs/999999999999/redshift/us-west-2/2019/05/25/…connectionlog_2019-05-25T19:03.gz
# "Owner": {
#    "DisplayName": "aws-cm-prod-auditlogs-uswest2", ## Not my account!
#    "ID": "b2b456ce30a967fb1877b3c9594773ae0275fee248e3ebdbff43d66907b89144"
# },
</code>```

I then copy the object in the same bucket with --acl bucket-owner-full-control. This makes me the owner of the new object. Note the changed SharedLogs/ prefix.

```<code>aws --profile 999999999999 s3 cp \
   s3://my-audit-logs/AWSLogs/999999999999/redshift/us-west-2/2019/05/25/…connectionlog_2019-05-25T19:03.gz \
   s3://my-audit-logs/SharedLogs/999999999999/redshift/us-west-2/2019/05/25/…connectionlog_2019-05-25T19:03.gz \
   --acl bucket-owner-full-control
</code>```

Now I can download (or load to Redshift!) the new object that is shared from the same bucket.

```<code>aws --profile 012345600000 s3 cp s3://my-audit-logs/SharedLogs/999999999999/redshift/us-west-2/2019/05/25/…connectionlog_2019-05-25T19:03.gz ~/Downloads/…connectionlog_2019-05-25T19:03.gz
# download: …
</code>```

Body:
I have the following copy command:

copy ink.contact_trace_records
from 's3://mybucket/mykey'
iam_role 'arn:aws:iam::accountnum:role/rolename'
json 'auto';

Where the role has the full access to S3 and full access to RS policies (I know this is not a good idea, but I'm just losing it here :) ). The cluster has the role attached. The cluster has VPC enhanced routing. I get the following:

[2019-05-28 14:07:34] [XX000][500310] [Amazon](500310) Invalid operation: S3ServiceException:Access Denied,Status 403,Error AccessDenied,Rid 370F75618922AFC0,ExtRid dp2mcnlofFzt4dz00Lcm188/+ta3OEKVpuFjnZSYsC0pJPMiULk7I6spOpiZwXc04VVRdxizIj4=,CanRetry 1
[2019-05-28 14:07:34] Details:
[2019-05-28 14:07:34] -----------------------------------------------
[2019-05-28 14:07:34] error:  S3ServiceException:Access Denied,Status 403,Error AccessDenied,Rid 370F75618922AFC0,ExtRid dp2mcnlofFzt4dz00Lcm188/+ta3OEKVpuFjnZSYsC0pJPMiULk7I6spOpiZwXc04VVRdxizIj4=,CanRetry 1
[2019-05-28 14:07:34] code:      8001
[2019-05-28 14:07:34] context:   S3 key being read : s3://redacted
[2019-05-28 14:07:34] query:     7794423
[2019-05-28 14:07:34] location:  table_s3_scanner.cpp:372
[2019-05-28 14:07:34] process:   query3_986_7794423 [pid=13695]
[2019-05-28 14:07:34] -----------------------------------------------;

What am I missing here? The cluster has full access to S3, it is not even in a custom VPC, it is in the default one. Thoughts?

Body:
Check the object owner. The object is likely owned by another account. This is the reason for S3 403s in many situations where objects cannot be accessed by a role or account that has full permissions. The typical indicator is that you can list the object(s) but cannot get or head them.

In the following example I'm trying to access a Redshift audit log from a 2nd account. The account 012345600000 is granted access to the bucket owned by 999999999999 using the following policy:

{"Version": "2012-10-17",
 "Statement": [
        {"Action": [
                "s3:Get*",
                "s3:ListBucket*"
            ],
          "Effect": "Allow",
          "Resource": [
                "arn:aws:s3:::my-audit-logs",
                "arn:aws:s3:::my-audit-logs/*"
            ],
          "Principal": {
                "AWS": [
                    "arn:aws:iam::012345600000:root"
                ]}}]
 }

Now I try to list (s3 ls) then copy (s3 cp) a single log object:

aws --profile 012345600000 s3 ls s3://my-audit-logs/AWSLogs/999999999999/redshift/us-west-2/2019/05/25/
# 2019-05-28 14:49:46        376 …connectionlog_2019-05-25T19:03.gz
aws --profile 012345600000 s3 cp s3://my-audit-logs/AWSLogs/999999999999/redshift/us-west-2/2019/05/25/…connectionlog_2019-05-25T19:03.gz ~/Downloads/…connectionlog_2019-05-25T19:03.gz
# fatal error: An error occurred (403) when calling the HeadObject operation: Forbidden

Then I check the object ownership from the account that owns the bucket.

aws --profile 999999999999 s3api get-object-acl --bucket my-audit-logs --key AWSLogs/999999999999/redshift/us-west-2/2019/05/25/…connectionlog_2019-05-25T19:03.gz
# "Owner": {
#    "DisplayName": "aws-cm-prod-auditlogs-uswest2", ## Not my account!
#    "ID": "b2b456ce30a967fb1877b3c9594773ae0275fee248e3ebdbff43d66907b89144"
# },

I then copy the object in the same bucket with --acl bucket-owner-full-control. This makes me the owner of the new object. Note the changed SharedLogs/ prefix.

aws --profile 999999999999 s3 cp \
   s3://my-audit-logs/AWSLogs/999999999999/redshift/us-west-2/2019/05/25/…connectionlog_2019-05-25T19:03.gz \
   s3://my-audit-logs/SharedLogs/999999999999/redshift/us-west-2/2019/05/25/…connectionlog_2019-05-25T19:03.gz \
   --acl bucket-owner-full-control

Now I can download (or load to Redshift!) the new object that is shared from the same bucket.

aws --profile 012345600000 s3 cp s3://my-audit-logs/SharedLogs/999999999999/redshift/us-west-2/2019/05/25/…connectionlog_2019-05-25T19:03.gz ~/Downloads/…connectionlog_2019-05-25T19:03.gz
# download: …


问:
I am getting an error - nib must contain exactly one top level object which must be a UITableViewCell instance'"
I am using a custom cell in my tableView but when I run i get the error which I have mentioned in my question.

```<code> self.districtTableView.register(UINib(nibName: "PlaceCollectionViewCell", bundle: nil), forCellReuseIdentifier: "placeCell")

 func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    return false
}

func textFieldDidEndEditing(_ textField: UITextField) {
    // TODO: Your app can do something when textField finishes editing

    print("The textField ended editing. Do something based on app requirements.")
}

func numberOfSections(in tableView: UITableView) -> Int {
     return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return districts.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "placeCell") as! PlaceTableViewCell
    // Set text from the data model
    cell.distLabel.text = districts[indexPath.row]
    cell.textLabel?.font = distTextField.font
    return cell
</code>```

How can I get rid of this error. I have used different methods for registering a cell in table view. But it does not works. please help

答: In my case it was a view which was added outside the cell. It shouldn't have been there

Body:
I am using a custom cell in my tableView but when I run i get the error which I have mentioned in my question.

 self.districtTableView.register(UINib(nibName: "PlaceCollectionViewCell", bundle: nil), forCellReuseIdentifier: "placeCell")

 func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    return false
}

func textFieldDidEndEditing(_ textField: UITextField) {
    // TODO: Your app can do something when textField finishes editing

    print("The textField ended editing. Do something based on app requirements.")
}

func numberOfSections(in tableView: UITableView) -> Int {
     return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return districts.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "placeCell") as! PlaceTableViewCell
    // Set text from the data model
    cell.distLabel.text = districts[indexPath.row]
    cell.textLabel?.font = distTextField.font
    return cell

How can I get rid of this error. I have used different methods for registering a cell in table view. But it does not works. please help


问:
Adding array into an array item
I am populating a json file and I have an array like this

```<code>[{ name: name, address: address, age: age }]

[{ name2: name2, address2: address2, age2: age2 }]
</code>```

Now, I want to merge these two arrays and I'm expecting a result like this

```<code>[
    { name: name, address: address, age: age },
    { name2: name2, address2: address2, age2: age2 }
]
</code>```

答:
    const a = [{ name: 'name1', address: 'address1', age: 22 }];

    const b = [{ name2: 'name2', address2: 'address2', age2: 23 }];

    const result = [...a, ...b];

    console.log(result);```

Title: Adding array into an array item

Body:
I am populating a json file and I have an array like this

[{ name: name, address: address, age: age }]

[{ name2: name2, address2: address2, age2: age2 }]

Now, I want to merge these two arrays and I'm expecting a result like this

[
    { name: name, address: address, age: age },
    { name2: name2, address2: address2, age2: age2 }
]


问:
Spring Boot 2.1.5 Java 11 Modules, Error assembling JAR: Could not create modular JAR file. The JDK jar tool exited with 1 -> [Help 1]
Upon running the command - mvn clean -Dmaven.test.skip=true package -X I am getting following error.

```<code>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-jar-plugin:3.1.2:jar (default-jar) on project my-module-one: Error assembling JAR: Could not create modular JAR file. The JDK jar tool exited with 1 -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-jar-plugin:3.1.2:jar (default-jar) on project my-module-one: Error assembling JAR
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:215)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:566)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
Caused by: org.apache.maven.plugin.MojoExecutionException: Error assembling JAR
    at org.apache.maven.plugins.jar.AbstractJarMojo.createArchive (AbstractJarMojo.java:269)
    at org.apache.maven.plugins.jar.AbstractJarMojo.execute (AbstractJarMojo.java:293)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:566)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
Caused by: org.codehaus.plexus.archiver.ArchiverException: Could not create modular JAR file. The JDK jar tool exited with 1
    at org.codehaus.plexus.archiver.jar.JarToolModularJarArchiver.postCreateArchive (JarToolModularJarArchiver.java:123)
    at org.codehaus.plexus.archiver.AbstractArchiver.createArchive (AbstractArchiver.java:1013)
    at org.apache.maven.archiver.MavenArchiver.createArchive (MavenArchiver.java:669)
    at org.apache.maven.plugins.jar.AbstractJarMojo.createArchive (AbstractJarMojo.java:262)
    at org.apache.maven.plugins.jar.AbstractJarMojo.execute (AbstractJarMojo.java:293)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:566)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
[ERROR]
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR]   mvn <goals> -rf :my-module-one
</code>```

Here is my pom.xml for my-module-one module

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>my-module-one</artifactId>
    <packaging>jar</packaging>

    <parent>
        <groupId>com.myparent</groupId>
        <artifactId>my-parent</artifactId>
        <version>0.1</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>
</code>```

Here is pom.xml for parent

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.myparent</groupId>
    <artifactId>my-parent</artifactId>
    <version>0.1</version>
    <packaging>pom</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/>
        <!-- lookup parent from repository -->
    </parent>

    <name>My App</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>11</java.version>

        <lombok.version>1.18.8</lombok.version>
        <rest.assured.version>4.0.0</rest.assured.version>
        <maven.compiler.version>3.8.1</maven.compiler.version>
        <spring-loaded.version>1.2.8.RELEASE</spring-loaded.version>

        <start-class>com.myparent.main.Main</start-class>
    </properties>

    <modules>
        <module>module-one</module>
        <module>module-two</module>
        <module>main</module>
    </modules>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>${rest.assured.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.version}</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                            <version>${lombok.version}</version>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <skip>true</skip>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.springframework</groupId>
                        <artifactId>springloaded</artifactId>
                        <version>${spring-loaded.version}</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

P.S. Running the application directly using mvn spring-boot:run works fine.

EDIT

There is one more line that comes up during the packaging of first module

```<code>jar: Package com.myparent.main missing from ModulePackages class file attribute
</code>```

答: try with:  mvn package -rf :my-module-one</p>

Body:
Upon running the command - mvn clean -Dmaven.test.skip=true package -X I am getting following error.

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-jar-plugin:3.1.2:jar (default-jar) on project my-module-one: Error assembling JAR: Could not create modular JAR file. The JDK jar tool exited with 1 -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-jar-plugin:3.1.2:jar (default-jar) on project my-module-one: Error assembling JAR
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:215)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:566)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
Caused by: org.apache.maven.plugin.MojoExecutionException: Error assembling JAR
    at org.apache.maven.plugins.jar.AbstractJarMojo.createArchive (AbstractJarMojo.java:269)
    at org.apache.maven.plugins.jar.AbstractJarMojo.execute (AbstractJarMojo.java:293)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:566)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
Caused by: org.codehaus.plexus.archiver.ArchiverException: Could not create modular JAR file. The JDK jar tool exited with 1
    at org.codehaus.plexus.archiver.jar.JarToolModularJarArchiver.postCreateArchive (JarToolModularJarArchiver.java:123)
    at org.codehaus.plexus.archiver.AbstractArchiver.createArchive (AbstractArchiver.java:1013)
    at org.apache.maven.archiver.MavenArchiver.createArchive (MavenArchiver.java:669)
    at org.apache.maven.plugins.jar.AbstractJarMojo.createArchive (AbstractJarMojo.java:262)
    at org.apache.maven.plugins.jar.AbstractJarMojo.execute (AbstractJarMojo.java:293)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:566)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
[ERROR]
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR]   mvn <goals> -rf :my-module-one

Here is my pom.xml for my-module-one module

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>my-module-one</artifactId>
    <packaging>jar</packaging>

    <parent>
        <groupId>com.myparent</groupId>
        <artifactId>my-parent</artifactId>
        <version>0.1</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

Here is pom.xml for parent

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.myparent</groupId>
    <artifactId>my-parent</artifactId>
    <version>0.1</version>
    <packaging>pom</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/>

    </parent>

    <name>My App</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>11</java.version>

        <lombok.version>1.18.8</lombok.version>
        <rest.assured.version>4.0.0</rest.assured.version>
        <maven.compiler.version>3.8.1</maven.compiler.version>
        <spring-loaded.version>1.2.8.RELEASE</spring-loaded.version>

        <start-class>com.myparent.main.Main</start-class>
    </properties>

    <modules>
        <module>module-one</module>
        <module>module-two</module>
        <module>main</module>
    </modules>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>${rest.assured.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.version}</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                            <version>${lombok.version}</version>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <skip>true</skip>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.springframework</groupId>
                        <artifactId>springloaded</artifactId>
                        <version>${spring-loaded.version}</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

P.S. Running the application directly using mvn spring-boot:run works fine.

EDIT

There is one more line that comes up during the packaging of first module

jar: Package com.myparent.main missing from ModulePackages class file attribute


问:
Is it possible to create an optional literal in Swift?
I have explained my query in the code snippet below. I am looking for this type of syntax for Obj-C interoperability. Specifically I see a difference in behaviour of aCoder.encode(count, forKey: "count") API when count is Int (non-optional) vs Int? (optional)

```<code>import Foundation

let num = 5
// Swift's type system will infer this as Int (non-optional)
print(type(of: num))
// Prints: Int

let optNum: Int? = 5
// This is explicitly typed as an optional Int
print(type(of: optNum))
// Prints Optional<Int>
</code>```

Is it possible to use a literal to implicitly type a var/let to optional?

```<code>// let imlicitOptional = 5?
// print(type(of: imlicitOptional))
// The above line should print: Optional<Int>

// or

// let imlicitOptional = num?
// print(type(of: imlicitOptional))
// The above line should print: Optional<Int>
</code>```

答:
I don't know why you need this but you can do like this

```<code>let opt = 5 as Int?
// or
let opt = Optional(5)
// or
let opt = 5 as Optional // thanks to vacawama for this
</code>```

Actually you can even create an operator that returns an optional but I think it's kinda useless.

postfix operator >?
postfix func >?<T>(value: T) -> T? {
    return Optional(value) // or return value as T?
}

let a = 5>?
```

Body:
I have explained my query in the code snippet below. I am looking for this type of syntax for Obj-C interoperability. Specifically I see a difference in behaviour of aCoder.encode(count, forKey: "count") API when count is Int (non-optional) vs Int? (optional)

import Foundation

let num = 5
// Swift's type system will infer this as Int (non-optional)
print(type(of: num))
// Prints: Int

let optNum: Int? = 5
// This is explicitly typed as an optional Int
print(type(of: optNum))
// Prints Optional<Int>

Is it possible to use a literal to implicitly type a var/let to optional?

// let imlicitOptional = 5?
// print(type(of: imlicitOptional))
// The above line should print: Optional<Int>

// or

// let imlicitOptional = num?
// print(type(of: imlicitOptional))
// The above line should print: Optional<Int>

Body:
I don't know why you need this but you can do like this

let opt = 5 as Int?
// or
let opt = Optional(5)
// or
let opt = 5 as Optional // thanks to vacawama for this

Actually you can even create an operator that returns an optional but I think it's kinda useless.

postfix operator >?
postfix func >?<T>(value: T) -> T? {
    return Optional(value) // or return value as T?
}

let a = 5>?


问:
How can I check if any of my boolean variable is false in VB.NET
Can I ask if is this is the only way to check if a variable is false in VB.net?

here is my code

```<code>if a = true and b = true and c = true then
     msgbox("ok")
else if a= true and b = true and c = false then
     msgbox("c has errors")
else if a= true and b = false and c = true then
     msgbox("b has errors")
else if a= false and b = true and c = true then
     msgbox("a has errors")
end if
</code>```

答:
It's more for the code review section, but I give the answers anyway...

For my aesthetics it is ugly to write If (a = True) Then or If (a = False) Then, I would rather use If (a) Then and If (Not a) Then.

In your code, if a + b have errors, nothing happens, as this case is not handled. A Rolls-Royce implementation could look like this:

```<code>Public Class Application

    Public Sub DoSomething()
        '... get the results from 3 calls to other methods
        Dim a As Boolean = MethodA()
        Dim b As Boolean = MethodB()
        Dim c As Boolean = MethodC()
        Dim myErrors As String = GetErrorMessage(a, b, c)
        If (myErrors Is Nothing) Then
            MsgBox("ok")
        Else
            MsgBox(myErrors)
            Environment.Exit(-1)
        End If
    End Sub

    Private Function GetErrorMessage(a As Boolean, b As Boolean, c As Boolean) As String
        If (a AndAlso b AndAlso c) Then Return Nothing
        Dim myList As New List(Of String)(3)
        If (Not a) Then myList.Add(NameOf(MethodA))
        If (Not b) Then myList.Add(NameOf(MethodB))
        If (Not c) Then myList.Add(NameOf(MethodC))
        Select Case myList.Count
            Case 1
                Return $"{myList(0)} has errors!"
            Case 2
                Return $"{myList(0)} and {myList(1)} have errors!"
            Case Else
                Return $"{String.Join(", ", myList.Take(myList.Count - 1))} and {myList(myList.Count - 1)} have errros!"
        End Select
    End Function

    Private Function MethodA() As Boolean
        'Does something
        Return True
    End Function

    Private Function MethodB() As Boolean
        'Does something
        Return False
    End Function

    Private Function MethodC() As Boolean
        'Does something
        Return False
    End Function

End Class
</code>```

As a general recommendation, I would not return a boolean from the 3 calls but implement them as Sub instead and throw an exception if something goes wrong, that allows you to give more accurate feedback and also to handle the error higher up the call stack if you prefere. Here an example of such an implementation:

```<code>Public Class Application

    Public Sub DoSomething()
        Dim myErrors As List(Of String) = Nothing
        Try
            MethodA()
        Catch ex As Exception
            If (myErrors Is Nothing) Then myErrors = New List(Of String)(3)
            myErrors.Add($"{NameOf(MethodA)}: {ex.Message}")
        End Try
        Try
            MethodB()
        Catch ex As Exception
            If (myErrors Is Nothing) Then myErrors = New List(Of String)(2)
            myErrors.Add($"{NameOf(MethodB)}: {ex.Message}")
        End Try
        Try
            MethodC()
        Catch ex As Exception
            If (myErrors Is Nothing) Then myErrors = New List(Of String)(1)
            myErrors.Add($"{NameOf(MethodC)}: {ex.Message}")
        End Try
        If (myErrors Is Nothing) Then
            MsgBox("OK")
        Else
            MsgBox($"The following errors occurred:{vbCrLf}{vbCrLf}{String.Join(vbCrLf, myErrors)}")
        End If
    End Sub

    Private Sub MethodA()
        'Does something
    End Sub

    Private Sub MethodB()
        'Does something
        Throw New NotImplementedException()
    End Sub

    Private Sub MethodC()
        'Does something
        Throw New NotSupportedException()
    End Sub

End Class
</code>```

Body:
Can I ask if is this is the only way to check if a variable is false in VB.net?

here is my code

if a = true and b = true and c = true then
     msgbox("ok")
else if a= true and b = true and c = false then
     msgbox("c has errors")
else if a= true and b = false and c = true then
     msgbox("b has errors")
else if a= false and b = true and c = true then
     msgbox("a has errors")
end if

Body:
It's more for the code review section, but I give the answers anyway...

For my aesthetics it is ugly to write If (a = True) Then or If (a = False) Then, I would rather use If (a) Then and If (Not a) Then.

In your code, if a + b have errors, nothing happens, as this case is not handled. A Rolls-Royce implementation could look like this:

Public Class Application

    Public Sub DoSomething()
        '... get the results from 3 calls to other methods
        Dim a As Boolean = MethodA()
        Dim b As Boolean = MethodB()
        Dim c As Boolean = MethodC()
        Dim myErrors As String = GetErrorMessage(a, b, c)
        If (myErrors Is Nothing) Then
            MsgBox("ok")
        Else
            MsgBox(myErrors)
            Environment.Exit(-1)
        End If
    End Sub

    Private Function GetErrorMessage(a As Boolean, b As Boolean, c As Boolean) As String
        If (a AndAlso b AndAlso c) Then Return Nothing
        Dim myList As New List(Of String)(3)
        If (Not a) Then myList.Add(NameOf(MethodA))
        If (Not b) Then myList.Add(NameOf(MethodB))
        If (Not c) Then myList.Add(NameOf(MethodC))
        Select Case myList.Count
            Case 1
                Return $"{myList(0)} has errors!"
            Case 2
                Return $"{myList(0)} and {myList(1)} have errors!"
            Case Else
                Return $"{String.Join(", ", myList.Take(myList.Count - 1))} and {myList(myList.Count - 1)} have errros!"
        End Select
    End Function

    Private Function MethodA() As Boolean
        'Does something
        Return True
    End Function

    Private Function MethodB() As Boolean
        'Does something
        Return False
    End Function

    Private Function MethodC() As Boolean
        'Does something
        Return False
    End Function

End Class

As a general recommendation, I would not return a boolean from the 3 calls but implement them as Sub instead and throw an exception if something goes wrong, that allows you to give more accurate feedback and also to handle the error higher up the call stack if you prefere. Here an example of such an implementation:

Public Class Application

    Public Sub DoSomething()
        Dim myErrors As List(Of String) = Nothing
        Try
            MethodA()
        Catch ex As Exception
            If (myErrors Is Nothing) Then myErrors = New List(Of String)(3)
            myErrors.Add($"{NameOf(MethodA)}: {ex.Message}")
        End Try
        Try
            MethodB()
        Catch ex As Exception
            If (myErrors Is Nothing) Then myErrors = New List(Of String)(2)
            myErrors.Add($"{NameOf(MethodB)}: {ex.Message}")
        End Try
        Try
            MethodC()
        Catch ex As Exception
            If (myErrors Is Nothing) Then myErrors = New List(Of String)(1)
            myErrors.Add($"{NameOf(MethodC)}: {ex.Message}")
        End Try
        If (myErrors Is Nothing) Then
            MsgBox("OK")
        Else
            MsgBox($"The following errors occurred:{vbCrLf}{vbCrLf}{String.Join(vbCrLf, myErrors)}")
        End If
    End Sub

    Private Sub MethodA()
        'Does something
    End Sub

    Private Sub MethodB()
        'Does something
        Throw New NotImplementedException()
    End Sub

    Private Sub MethodC()
        'Does something
        Throw New NotSupportedException()
    End Sub

End Class


问:
How to change dictionary keys only? Without change values swift
I have array like this.

```<code>var Array = [Int:[String:Any]]()
</code>```

I just update the values

```<code> let updateValue = ["Name":tripName!,"date":firstDate,"year":year,"startData":startDateValue,"endDate":endDateValue,"countryName":countrname!,"totelBudjet":totelBudjet,"backgroundImage":arrImages[randomItem],"code":getAddtripeAttibutes.code,"countryIcon":countryIcon] as [String : Any]

 Array.updateValue(updateValue, forKey: tripId)

 tripId = tripId + 1
</code>```

We have more Array data as mentioned below

trip keys like :

[0] [1] [2]

```<code>[0: ["year": "2019", "tripName": "Test", "backgroundImage": "Europe_Trip", "code": "DZD", "startData": 2019-05-30 10:14:11 +0000, "date": "May 30 - May 31", "endDate": 2019-05-31 10:14:11 +0000, "totelBudjet": "5000 DZD", "countryIcon": "dz", "countryName": "Algeria"], 1: ["date": "May 30 - May 31", "backgroundImage": "Europe_Trip", "endDate": 2019-05-31 10:14:43 +0000, "code": "DZD", "countryName": "Algeria", "tripName": "Gg", "countryIcon": "dz", "totelBudjet": "500 DZD", "startData": 2019-05-30 10:14:43 +0000, "year": "2019"], 2: ["year": "2019", "backgroundImage": "Asia_Trip", "endDate": 2019-05-31 10:15:00 +0000, "countryIcon": "al", "totelBudjet": "5800 ALL", "code": "ALL", "tripName": "Bb", "countryName": "Albania", "date": "May 30 - May 31", "startData": 2019-05-30 10:15:00 +0000]]
</code>```

I have updated tableview with above data

after i delete one array [1] it look like:
  this

[0] [2]

```<code> [0: ["year": "2019", "tripName": "Test", "backgroundImage": "Europe_Trip", "code": "DZD", "startData": 2019-05-30 10:14:11 +0000, "date": "May 30 - May 31", "endDate": 2019-05-31 10:14:11 +0000, "totelBudjet": "5000 DZD", "countryIcon": "dz", "countryName": "Algeria"], 2: ["year": "2019", "backgroundImage": "Asia_Trip", "endDate": 2019-05-31 10:15:00 +0000, "countryIcon": "al", "totelBudjet": "5800 ALL", "code": "ALL", "tripName": "Bb", "countryName": "Albania", "date": "May 30 - May 31", "startData": 2019-05-30 10:15:00 +0000]]
</code>```

But I want to update the keys as [0][1] not as [0][2]

Can any one please help me with this?

答:
it is not quite clear to me what's the use-case here, so I'm trying to cover the most possible.

using enumerated() on the array

if you need only to add the index, call the enumerated() method on an array, like e.g.

```<code>var array: [[String: Any]] = [["year": "2019", "tripName": "Trip#1"], ["year": "2020", "tripName": "Trip#2"], ["year": "2021", "tripName": "Trip#3"]]

array.enumerated().forEach { (arg0) in
    let (offset, element) = arg0
    debugPrint("\(offset) : \(element)")
}
</code>```

that would assign an offset to each element which you can print out or use otherwise, in my example the output on the console would look like this:

```<code>0 : ["tripName": "Trip#1", "year": "2019"]
1 : ["tripName": "Trip#2", "year": "2020"]
2 : ["tripName": "Trip#3", "year": "2021"]
</code>```

if you need to actually remove an item, like e.g.

```<code>array.remove(at: 1)
</code>```

and call the same snippet (above) again, it assigns the offset like this:

```<code>0 : ["tripName": "Trip#1", "year": "2019"]
1 : ["tripName": "Trip#3", "year": "2021"]
</code>```

that is quite similar to what you might looking for.

mapping an array from dictionary

if you need to actually map the dictionary first into an array (like e.g. during post-processing a JSON response), you may go for that as well like e.g.:

```<code>var dictionary: [Int: [String: Any]] = [0: ["year": "2019", "tripName": "Trip#1"], 1: ["year": "2020", "tripName": "Trip#2"], 2: ["year": "2021", "tripName": "Trip#3"]]

var array = dictionary.map { $0.value }
</code>```

then you can start dealing with the enumerated() method just like I shown it to you above.

NOTE: obviously if you do the mapping like I did, you will lose the information what the original key holds, and that will be replaced coincidently with the same number in my example, which may be misleading but if you are aware of that the offset and the key are two completely different values here, you may not have a huge surprise after you do the mapping.

Body:
I have array like this.

var Array = [Int:[String:Any]]()

I just update the values

 let updateValue = ["Name":tripName!,"date":firstDate,"year":year,"startData":startDateValue,"endDate":endDateValue,"countryName":countrname!,"totelBudjet":totelBudjet,"backgroundImage":arrImages[randomItem],"code":getAddtripeAttibutes.code,"countryIcon":countryIcon] as [String : Any]

 Array.updateValue(updateValue, forKey: tripId)

 tripId = tripId + 1

We have more Array data as mentioned below

trip keys like :

[0] [1] [2]

[0: ["year": "2019", "tripName": "Test", "backgroundImage": "Europe_Trip", "code": "DZD", "startData": 2019-05-30 10:14:11 +0000, "date": "May 30 - May 31", "endDate": 2019-05-31 10:14:11 +0000, "totelBudjet": "5000 DZD", "countryIcon": "dz", "countryName": "Algeria"], 1: ["date": "May 30 - May 31", "backgroundImage": "Europe_Trip", "endDate": 2019-05-31 10:14:43 +0000, "code": "DZD", "countryName": "Algeria", "tripName": "Gg", "countryIcon": "dz", "totelBudjet": "500 DZD", "startData": 2019-05-30 10:14:43 +0000, "year": "2019"], 2: ["year": "2019", "backgroundImage": "Asia_Trip", "endDate": 2019-05-31 10:15:00 +0000, "countryIcon": "al", "totelBudjet": "5800 ALL", "code": "ALL", "tripName": "Bb", "countryName": "Albania", "date": "May 30 - May 31", "startData": 2019-05-30 10:15:00 +0000]]

I have updated tableview with above data

after i delete one array [1] it look like:
  this

[0] [2]

 [0: ["year": "2019", "tripName": "Test", "backgroundImage": "Europe_Trip", "code": "DZD", "startData": 2019-05-30 10:14:11 +0000, "date": "May 30 - May 31", "endDate": 2019-05-31 10:14:11 +0000, "totelBudjet": "5000 DZD", "countryIcon": "dz", "countryName": "Algeria"], 2: ["year": "2019", "backgroundImage": "Asia_Trip", "endDate": 2019-05-31 10:15:00 +0000, "countryIcon": "al", "totelBudjet": "5800 ALL", "code": "ALL", "tripName": "Bb", "countryName": "Albania", "date": "May 30 - May 31", "startData": 2019-05-30 10:15:00 +0000]]

But I want to update the keys as [0][1] not as [0][2]

Can any one please help me with this?

Body:
it is not quite clear to me what's the use-case here, so I'm trying to cover the most possible.

using enumerated() on the array

if you need only to add the index, call the enumerated() method on an array, like e.g.

var array: [[String: Any]] = [["year": "2019", "tripName": "Trip#1"], ["year": "2020", "tripName": "Trip#2"], ["year": "2021", "tripName": "Trip#3"]]

array.enumerated().forEach { (arg0) in
    let (offset, element) = arg0
    debugPrint("\(offset) : \(element)")
}

that would assign an offset to each element which you can print out or use otherwise, in my example the output on the console would look like this:

0 : ["tripName": "Trip#1", "year": "2019"]
1 : ["tripName": "Trip#2", "year": "2020"]
2 : ["tripName": "Trip#3", "year": "2021"]

if you need to actually remove an item, like e.g.

array.remove(at: 1)

and call the same snippet (above) again, it assigns the offset like this:

0 : ["tripName": "Trip#1", "year": "2019"]
1 : ["tripName": "Trip#3", "year": "2021"]

that is quite similar to what you might looking for.

mapping an array from dictionary

if you need to actually map the dictionary first into an array (like e.g. during post-processing a JSON response), you may go for that as well like e.g.:

var dictionary: [Int: [String: Any]] = [0: ["year": "2019", "tripName": "Trip#1"], 1: ["year": "2020", "tripName": "Trip#2"], 2: ["year": "2021", "tripName": "Trip#3"]]

var array = dictionary.map { $0.value }

then you can start dealing with the enumerated() method just like I shown it to you above.

NOTE: obviously if you do the mapping like I did, you will lose the information what the original key holds, and that will be replaced coincidently with the same number in my example, which may be misleading but if you are aware of that the offset and the key are two completely different values here, you may not have a huge surprise after you do the mapping.


答:
You can try this:</p>

```<code>WITH CTE AS
(
    SELECT ROW_NUMBER() OVER (PARTITION BY fincode ORDER BY invdate) rn FROM yourtable
)
DELETE FROM cte WHERE rn > 1
</code>```

Title: how to delete the data from table for each scheme for fincode

Body:
i have table

|Schemecode  | Fincode |Invdate     |
|:-----------|--------:|:----------:|
|1           |    81   |  2019-03-31|
|1           |    81   |  2019-04-30|
|1           |    82   |  2019-04-30|
|4           |    34   |  2019-04-30|
|4           |    35   |  2019-04-30|
|6           |    38   |  2019-04-30|
|6           |    38   |  2019-03-31|
|6           |    81   |  2019-04-30|
|6           |    81   |  2019-03-31|
|6           |    42   |  2019-04-30|

i want to delete
all the duplicate rows having Fincode as duplicate for each Schemecode with Invdate older date i.e (2019-03-31)  Not with 2019-04-30.

i have tried query but unable to do

Expected output :

after delete

|Schemecode  | Fincode |Invdate     |
|:-----------|--------:|:----------:|
|1           |    81   |  2019-04-30|
|1           |    82   |  2019-04-30|
|4           |    34   |  2019-04-30|
|4           |    35   |  2019-04-30|
|6           |    38   |  2019-04-30|
|6           |    81   |  2019-04-30|
|6           |    42   |  2019-04-30|

Body:
You can try this:

WITH CTE AS
(
    SELECT ROW_NUMBER() OVER (PARTITION BY fincode ORDER BY invdate) rn FROM yourtable
)
DELETE FROM cte WHERE rn > 1


答:
Call it with the Saves object you just created (assuming you already have an Activity object named activity):</p>

```<code>save.updatelv(activity)
</code>```

Title: How to call this function?

Body:
Call it with the Saves object you just created (assuming you already have an Activity object named activity):

save.updatelv(activity)


问:
Query Sorting in firebase Swift
My realtime-database is structured like this:

```<code>   - Procedure001
        - Post0001
            - user_id: 00001
            - timestamp: 1559214445
</code>```

I would like to read the database and get only the posts that user0001 posted, and also sort them by most recent post (by timestamp).

Currently I am able to get only the posts by a certain user like so -

```<code>let ref = Database.database().reference().child("Procedure001").queryOrdered(byChild: "user_id").queryEqual(toValue: "0001")
</code>```

How can I also sort the by timestamp using firebase?

答: I ended up getting the posts and filtering them so I only get posts by a specific user using firebase, and sorting them according to timestamp afterwards using the new Swift 5 sort() function - I used the swift 5 answer on this thread Swift how to sort array of custom objects by property value</p>

Title: Query Sorting in firebase Swift

Body:
My realtime-database is structured like this:

   - Procedure001
        - Post0001
            - user_id: 00001
            - timestamp: 1559214445

I would like to read the database and get only the posts that user0001 posted, and also sort them by most recent post (by timestamp).

Currently I am able to get only the posts by a certain user like so -

let ref = Database.database().reference().child("Procedure001").queryOrdered(byChild: "user_id").queryEqual(toValue: "0001")

How can I also sort the by timestamp using firebase?