问:
How to make a custom attribute in C# for mapping intents in Microsoft Bot Framework?

The [LuisIntent("")] attribute uses the ILuisService to query
  the LUIS based on LUISModel attributes' value, then finds out the
  top scoring intent and matches the IntentHandler Delegate in the
  overridden MessageRecievedAsync method and loads the
  LUISResult dynamically in the following method while debugging a class which inherits from LuisDialog.

```<code>public async Task None(IDialogContext context, LuisResult result)
{
  //some stuff
}
</code>```

My question is how to make a custom attribute which maps it to the correct intent handler.

I am trying to use RASA NLU Service as my NLP engine along with Microsoft Bot Framework in C#.

I am trying to map LUISEmulatedResult which I get from HttpClient.GetAsync() method which queries RASA NLU to get LUISResult type JSON to a method which follows this delegate.

Progress I have done:

The [RASAIntentAttribute("IntentName")]

```<code>using Microsoft.Bot.Builder.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;

namespace DemoFlightRASA.Models
{
    public class RASAIntentAttribute : Attribute
    {
        private readonly string _intentName;

        public RASAIntentAttribute(string IntentName)
        {
            this._intentName = IntentName;
        }

        //The intent handler delegate
        //Now I want to map LUISEmulatedResult which I get from HttpClient.GetAsync() method to a method which follows this delegate
        public delegate Task RASAIntentHandler(IDialogContext context, LUISEmulatedResult result);

    }
}
</code>```

The LUISEmulatedResult model class:

```<code>namespace DemoFlightRASA.Models
{
    public class LUISEmulatedResult
    {
        public string query { get; set; }
        public Topscoringintent topScoringIntent { get; set; }
        public Intent[] intents { get; set; }
        public Entity[] entities { get; set; }
    }

    public class Topscoringintent
    {
        public string intent { get; set; }
        public float score { get; set; }
    }

    public class Intent
    {
        public string intent { get; set; }
        public float score { get; set; }
    }

    public class Entity
    {
        public string entity { get; set; }
        public string type { get; set; }
        public int startIndex { get; set; }
        public int endIndex { get; set; }
        public Resolution resolution { get; set; }
        public float score { get; set; }
    }

    public class Resolution
    {
        public string[] values { get; set; }
    }

}
</code>```

Also I tried this one, but this doesn't seem to work

I want to create a end-to-end flow which uses RASA NLU opposed to LUIS in bot framework. I have the RASA NLU endpoint ready, just not able to make the RASAIntentAttribute.

Any pointers, tips, tutorials, code snippets as to how to map the delegate to the method will be greatly appreciated. Thank you.

答:
Note: I don't think you can have a delegate as an attribute parameter: Is it possible to have a delegate as attribute parameter? How are you planning to use the RASAIntentHandler delegate?

The .net Bot Framework sdk uses reflection to determine which methods in the LuisDialog are intent handlers: https://github.com/Microsoft/BotBuilder/blob/b6cd3ff85e8dc57ac586a11db489a0c75c635ae2/CSharp/Library/Microsoft.Bot.Builder/Dialogs/LuisDialog.cs#L362

```<code>public static IEnumerable<KeyValuePair<string, IntentActivityHandler>> EnumerateHandlers(object dialog)
        {
            var type = dialog.GetType();
            var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
            foreach (var method in methods)
            {
                var intents = method.GetCustomAttributes<LuisIntentAttribute>(inherit: true).ToArray();
                IntentActivityHandler intentHandler = null;

                try
                {
                    intentHandler = (IntentActivityHandler)Delegate.CreateDelegate(typeof(IntentActivityHandler), dialog, method, throwOnBindFailure: false);
                }
                catch (ArgumentException)
                {
                    // "Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type."
                    // https://github.com/Microsoft/BotBuilder/issues/634
                    // https://github.com/Microsoft/BotBuilder/issues/435
                }

                // fall back for compatibility
                if (intentHandler == null)
                {
                    try
                    {
                        var handler = (IntentHandler)Delegate.CreateDelegate(typeof(IntentHandler), dialog, method, throwOnBindFailure: false);

                        if (handler != null)
                        {
                            // thunk from new to old delegate type
                            intentHandler = (context, message, result) => handler(context, result);
                        }
                    }
                    catch (ArgumentException)
                    {
                        // "Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type."
                        // https://github.com/Microsoft/BotBuilder/issues/634
                        // https://github.com/Microsoft/BotBuilder/issues/435
                    }
                }

                if (intentHandler != null)
                {
                    var intentNames = intents.Select(i => i.IntentName).DefaultIfEmpty(method.Name);

                    foreach (var intentName in intentNames)
                    {
                        var key = string.IsNullOrWhiteSpace(intentName) ? string.Empty : intentName;
                        yield return new KeyValuePair<string, IntentActivityHandler>(intentName, intentHandler);
                    }
                }
                else
                {
                    if (intents.Length > 0)
                    {
                        throw new InvalidIntentHandlerException(string.Join(";", intents.Select(i => i.IntentName)), method);
                    }
                }
            }
        }
</code>```

Here is the code in LuisDialog that calls the handler that corresponds to the best intent in the IntentRecommendation returned from LUISs: https://github.com/Microsoft/BotBuilder/blob/b6cd3ff85e8dc57ac586a11db489a0c75c635ae2/CSharp/Library/Microsoft.Bot.Builder/Dialogs/LuisDialog.cs#L252

```<code>protected virtual async Task DispatchToIntentHandler(IDialogContext context,
                                                            IAwaitable<IMessageActivity> item,
                                                            IntentRecommendation bestIntent,
                                                            LuisResult result)
        {
            if (this.handlerByIntent == null)
            {
                this.handlerByIntent = new Dictionary<string, IntentActivityHandler>(GetHandlersByIntent());
            }

            IntentActivityHandler handler = null;
            if (result == null || !this.handlerByIntent.TryGetValue(bestIntent.Intent, out handler))
            {
                handler = this.handlerByIntent[string.Empty];
            }

            if (handler != null)
            {
                await handler(context, item, result);
            }
            else
            {
                var text = $"No default intent handler found.";
                throw new Exception(text);
            }
        }
</code>```

This is how LUIS results are mapped to methods marked with the LUISIntentAttribute on LUISDialogs.  This functionality, or something similar, will need to be in the RASA implementation.

Body:
The [LuisIntent("")] attribute uses the ILuisService to query
  the LUIS based on LUISModel attributes' value, then finds out the
  top scoring intent and matches the IntentHandler Delegate in the
  overridden MessageRecievedAsync method and loads the
  LUISResult dynamically in the following method while debugging a class which inherits from LuisDialog.

public async Task None(IDialogContext context, LuisResult result)
{
  //some stuff
}

My question is how to make a custom attribute which maps it to the correct intent handler.

I am trying to use RASA NLU Service as my NLP engine along with Microsoft Bot Framework in C#.

I am trying to map LUISEmulatedResult which I get from HttpClient.GetAsync() method which queries RASA NLU to get LUISResult type JSON to a method which follows this delegate.

Progress I have done:

The [RASAIntentAttribute("IntentName")]

using Microsoft.Bot.Builder.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;

namespace DemoFlightRASA.Models
{
    public class RASAIntentAttribute : Attribute
    {
        private readonly string _intentName;

        public RASAIntentAttribute(string IntentName)
        {
            this._intentName = IntentName;
        }

        //The intent handler delegate
        //Now I want to map LUISEmulatedResult which I get from HttpClient.GetAsync() method to a method which follows this delegate
        public delegate Task RASAIntentHandler(IDialogContext context, LUISEmulatedResult result);

    }
}

The LUISEmulatedResult model class:

namespace DemoFlightRASA.Models
{
    public class LUISEmulatedResult
    {
        public string query { get; set; }
        public Topscoringintent topScoringIntent { get; set; }
        public Intent[] intents { get; set; }
        public Entity[] entities { get; set; }
    }

    public class Topscoringintent
    {
        public string intent { get; set; }
        public float score { get; set; }
    }

    public class Intent
    {
        public string intent { get; set; }
        public float score { get; set; }
    }

    public class Entity
    {
        public string entity { get; set; }
        public string type { get; set; }
        public int startIndex { get; set; }
        public int endIndex { get; set; }
        public Resolution resolution { get; set; }
        public float score { get; set; }
    }

    public class Resolution
    {
        public string[] values { get; set; }
    }

}

Also I tried this one, but this doesn't seem to work

I want to create a end-to-end flow which uses RASA NLU opposed to LUIS in bot framework. I have the RASA NLU endpoint ready, just not able to make the RASAIntentAttribute.

Any pointers, tips, tutorials, code snippets as to how to map the delegate to the method will be greatly appreciated. Thank you.

Body:
Note: I don't think you can have a delegate as an attribute parameter: Is it possible to have a delegate as attribute parameter? How are you planning to use the RASAIntentHandler delegate?

The .net Bot Framework sdk uses reflection to determine which methods in the LuisDialog are intent handlers: https://github.com/Microsoft/BotBuilder/blob/b6cd3ff85e8dc57ac586a11db489a0c75c635ae2/CSharp/Library/Microsoft.Bot.Builder/Dialogs/LuisDialog.cs#L362

public static IEnumerable<KeyValuePair<string, IntentActivityHandler>> EnumerateHandlers(object dialog)
        {
            var type = dialog.GetType();
            var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
            foreach (var method in methods)
            {
                var intents = method.GetCustomAttributes<LuisIntentAttribute>(inherit: true).ToArray();
                IntentActivityHandler intentHandler = null;

                try
                {
                    intentHandler = (IntentActivityHandler)Delegate.CreateDelegate(typeof(IntentActivityHandler), dialog, method, throwOnBindFailure: false);
                }
                catch (ArgumentException)
                {
                    // "Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type."
                    // https://github.com/Microsoft/BotBuilder/issues/634
                    // https://github.com/Microsoft/BotBuilder/issues/435
                }

                // fall back for compatibility
                if (intentHandler == null)
                {
                    try
                    {
                        var handler = (IntentHandler)Delegate.CreateDelegate(typeof(IntentHandler), dialog, method, throwOnBindFailure: false);

                        if (handler != null)
                        {
                            // thunk from new to old delegate type
                            intentHandler = (context, message, result) => handler(context, result);
                        }
                    }
                    catch (ArgumentException)
                    {
                        // "Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type."
                        // https://github.com/Microsoft/BotBuilder/issues/634
                        // https://github.com/Microsoft/BotBuilder/issues/435
                    }
                }

                if (intentHandler != null)
                {
                    var intentNames = intents.Select(i => i.IntentName).DefaultIfEmpty(method.Name);

                    foreach (var intentName in intentNames)
                    {
                        var key = string.IsNullOrWhiteSpace(intentName) ? string.Empty : intentName;
                        yield return new KeyValuePair<string, IntentActivityHandler>(intentName, intentHandler);
                    }
                }
                else
                {
                    if (intents.Length > 0)
                    {
                        throw new InvalidIntentHandlerException(string.Join(";", intents.Select(i => i.IntentName)), method);
                    }
                }
            }
        }

Here is the code in LuisDialog that calls the handler that corresponds to the best intent in the IntentRecommendation returned from LUISs: https://github.com/Microsoft/BotBuilder/blob/b6cd3ff85e8dc57ac586a11db489a0c75c635ae2/CSharp/Library/Microsoft.Bot.Builder/Dialogs/LuisDialog.cs#L252

protected virtual async Task DispatchToIntentHandler(IDialogContext context,
                                                            IAwaitable<IMessageActivity> item,
                                                            IntentRecommendation bestIntent,
                                                            LuisResult result)
        {
            if (this.handlerByIntent == null)
            {
                this.handlerByIntent = new Dictionary<string, IntentActivityHandler>(GetHandlersByIntent());
            }

            IntentActivityHandler handler = null;
            if (result == null || !this.handlerByIntent.TryGetValue(bestIntent.Intent, out handler))
            {
                handler = this.handlerByIntent[string.Empty];
            }

            if (handler != null)
            {
                await handler(context, item, result);
            }
            else
            {
                var text = $"No default intent handler found.";
                throw new Exception(text);
            }
        }

This is how LUIS results are mapped to methods marked with the LUISIntentAttribute on LUISDialogs.  This functionality, or something similar, will need to be in the RASA implementation.


来源: stackexchange

问:
How to make UINavigationBar background transparent?
First of all,
I've seen all the answers at How to make UINavigationBar Transparent in IOS 8? Transparent UINavigationBar and Make UINavigationBar transparent.

They just don't seem to work for me.

My regular view controller (before trying to make the navigation bar transparent) doesn't have any issues:

I'm using (tried both in viewDidLoad and viewWillAppear:):

```<code>[self.navigationController.navigationBar setBackgroundImage:[UIImage new]
                                              forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.shadowImage = [UIImage new];
self.navigationController.navigationBar.translucent = YES;
self.navigationController.view.backgroundColor = [UIColor clearColor];
</code>```

I'm getting this:

Gray status bar background, completely white navigation bar which doesn't blend with the status bar, and then the view starts. All the 'solutions' at the other questions' answers' yield the same result for me.

I've also tried setting self.edgesForExtendedLayout = UIRectEdgeNone; or self.edgesForExtendedLayout = UIRectEdgeAll; but that also didn't have any impact.

How can I make my navigation bar transparent without messing up everything?

UPDATE: Following Warif Akhand Rishi's answer, I've changed self.navigationController.view.backgroundColor = [UIColor clearColor]; to self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];, now I'm getting a gray, unified status/navbar, but still not transparent:

UPDATE 2: I've hooked up the view debugger, and that gray background seems to come from deep down from the roots of view hierarchy, and my view's content is not extending up. I've tried self.edgesForExtendedLayout = UIRectEdgeAll; again with the latest code but still no avail:

答:
swift 4 transparent nav bar:
(be sure view extends behind nav bar to show through, otherwise will just be black)

```<code>navigationController?.navigationBar.isTranslucent = true
navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationController?.navigationBar.shadowImage = UIImage() //remove pesky 1 pixel line
</code>```

or just match navbar color to color of your current vc, but keep it opaque. with translucent set to false child views will line up with navbar instead of going under it.

```<code>navigationController?.navigationBar.isTranslucent = false
navigationController?.navigationBar.barTintColor = UIColor.yourColor
navigationController?.navigationBar.shadowImage = UIImage() //remove pesky 1 pixel line
</code>```

ContentLicense: CC BY-SA 3.0

Body:
First of all,
I've seen all the answers at How to make UINavigationBar Transparent in IOS 8? Transparent UINavigationBar and Make UINavigationBar transparent.

They just don't seem to work for me.

My regular view controller (before trying to make the navigation bar transparent) doesn't have any issues:

I'm using (tried both in viewDidLoad and viewWillAppear:):

[self.navigationController.navigationBar setBackgroundImage:[UIImage new]
                                              forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.shadowImage = [UIImage new];
self.navigationController.navigationBar.translucent = YES;
self.navigationController.view.backgroundColor = [UIColor clearColor];

I'm getting this:

Gray status bar background, completely white navigation bar which doesn't blend with the status bar, and then the view starts. All the 'solutions' at the other questions' answers' yield the same result for me.

I've also tried setting self.edgesForExtendedLayout = UIRectEdgeNone; or self.edgesForExtendedLayout = UIRectEdgeAll; but that also didn't have any impact.

How can I make my navigation bar transparent without messing up everything?

UPDATE: Following Warif Akhand Rishi's answer, I've changed self.navigationController.view.backgroundColor = [UIColor clearColor]; to self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];, now I'm getting a gray, unified status/navbar, but still not transparent:

UPDATE 2: I've hooked up the view debugger, and that gray background seems to come from deep down from the roots of view hierarchy, and my view's content is not extending up. I've tried self.edgesForExtendedLayout = UIRectEdgeAll; again with the latest code but still no avail:

Body:
swift 4 transparent nav bar:
(be sure view extends behind nav bar to show through, otherwise will just be black)

navigationController?.navigationBar.isTranslucent = true
navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationController?.navigationBar.shadowImage = UIImage() //remove pesky 1 pixel line

or just match navbar color to color of your current vc, but keep it opaque. with translucent set to false child views will line up with navbar instead of going under it.

navigationController?.navigationBar.isTranslucent = false
navigationController?.navigationBar.barTintColor = UIColor.yourColor
navigationController?.navigationBar.shadowImage = UIImage() //remove pesky 1 pixel line


问:
API's not showing after migrating WSO2 API Manager to 2.1.0
I have done the migration of API Manager from 2.0.0 to 2.1.0
by following https://docs.wso2.com/display/AM210/Upgrading+from+the+Previous+Release#UpgradingfromthePreviousRelease-Step2-UpgradeAPIManagerto2.1.0

It looked fine and I dont see any errors in logs.
But none of my API's are visible in the publisher.
But in the store ,I can see the existing Applications.

Also in the logs ,I can see my API's are getting mapped ;but now showing up in API Manager

```<code>[2017-11-13 23:07:43,538]  INFO - SynapseControllerFactory The timeout handler will run every : 15s
[2017-11-13 23:07:43,544]  INFO - Axis2SynapseController Initializing Synapse at : Mon Nov 13 23:07:43 UTC 2017
[2017-11-13 23:07:43,551]  INFO - CarbonSynapseController Loading the mediation configuration from the file system
[2017-11-13 23:07:43,553]  INFO - MultiXMLConfigurationBuilder Building synapse configuration from the synapse artifact repository at : ././repository/deployment/server/synapse-configs/default
[2017-11-13 23:07:43,554]  INFO - XMLConfigurationBuilder Generating the Synapse configuration model by parsing the XML configuration
[2017-11-13 23:07:43,608]  INFO - DependencyTracker Sequence : _sandbox_key_error_ was added to the Synapse configuration successfully
[2017-11-13 23:07:43,610]  INFO - DependencyTracker Sequence : _resource_mismatch_handler_ was added to the Synapse configuration successfully
[2017-11-13 23:07:43,618]  INFO - DependencyTracker Sequence : _cors_request_handler_ was added to the Synapse configuration successfully
[2017-11-13 23:07:43,646]  INFO - DependencyTracker Sequence : fault was added to the Synapse configuration successfully
[2017-11-13 23:07:43,649]  INFO - DependencyTracker Sequence : _production_key_error_ was added to the Synapse configuration successfully
[2017-11-13 23:07:43,651]  INFO - DependencyTracker Sequence : _build_ was added to the Synapse configuration successfully
[2017-11-13 23:07:43,653]  INFO - DependencyTracker Sequence : outDispatchSeq was added to the Synapse configuration successfully
[2017-11-13 23:07:43,658]  INFO - DependencyTracker Sequence : main was added to the Synapse configuration successfully
[2017-11-13 23:07:43,659]  INFO - DependencyTracker Sequence : _auth_failure_handler_ was added to the Synapse configuration successfully
[2017-11-13 23:07:43,664]  INFO - DependencyTracker Sequence : _token_fault_ was added to the Synapse configuration successfully
[2017-11-13 23:07:43,675]  INFO - DependencyTracker Sequence : dispatchSeq was added to the Synapse configuration successfully
[2017-11-13 23:07:43,676]  INFO - DependencyTracker Sequence : _throttle_out_handler_ was added to the Synapse configuration successfully
[2017-11-13 23:07:43,684]  INFO - DependencyTracker Proxy service : WorkflowCallbackService was added to the Synapse configuration successfully
[2017-11-13 23:07:44,157]  INFO - DependencyTracker API : admin--Auth:vv1 was added to the Synapse configuration successfully
[2017-11-13 23:07:44,160]  INFO - DependencyTracker API : _WSO2AMAuthorizeAPI_ was added to the Synapse configuration successfully
***
</code>```

[2017-11-13 23:07:44,193]  INFO - DependencyTracker API :
  admin--MenuProfileAPIs:vv1 was added to the Synapse configuration
  successfully
      [2017-11-13 23:07:44,194]  INFO - DependencyTracker API : admin--testGroup:vv1 was added to the Synapse configuration
  successfully
      [2017-11-13 23:07:44,640]  INFO - DependencyTracker API : admin--SettingsAPIs:vv1 was added to the Synapse configuration
  successfully

```<code>[2017-11-13 23:07:44,642]  INFO - DependencyTracker Inbound Endpoint : WebSocketInboundEndpoint was added to the Synapse configuration successfully
[2017-11-13 23:07:44,642]  INFO - SynapseConfigurationBuilder Loaded Synapse configuration from the artifact repository at : ././repository/deployment/server/synapse-configs/default
[2017-11-13 23:07:44,643]  INFO - DependencyTracker Local entry : SERVER_HOST was added to the Synapse configuration successfully
[2017-11-13 23:07:44,643]  INFO - DependencyTracker Local entry : SERVER_IP was added to the Synapse configuration successfully
[2017-11-13 23:07:44,645]  INFO - Axis2SynapseController Loading mediator extensions...
[2017-11-13 23:07:44,747]  INFO - DeploymentInterceptor Deploying Axis2 service: echo {super-tenant}
[2017-11-13 23:07:44,747]  INFO - DeploymentEngine Deploying Web service: Echo.aar -
</code>```

How Can i debug this issue?What could be the possible causes for this.

I tried to create a new API with the same name of an existing API.Its not letting me create .It says duplicate.So it feels the API is existing ; but not shown in the UI.
I went to Manage Subscriptions in the Publisher and I can see the API's listed there. If I click the API's , I can see them.EVerything looks intact.But its not listing.

答:
Please check followings

Verify whether same APIM and Registry databases from the 2.0.0 deployment is pointed to 2.1.0.

Re-index the API data as stated in step 4 of "https://docs.wso2.com/display/AM210/Upgrading+from+the+Previous+Release#UpgradingfromthePreviousRelease-Step2-UpgradeAPIManagerto2.1.0"

Body:
I have done the migration of API Manager from 2.0.0 to 2.1.0
by following https://docs.wso2.com/display/AM210/Upgrading+from+the+Previous+Release#UpgradingfromthePreviousRelease-Step2-UpgradeAPIManagerto2.1.0

It looked fine and I dont see any errors in logs.
But none of my API's are visible in the publisher.
But in the store ,I can see the existing Applications.

Also in the logs ,I can see my API's are getting mapped ;but now showing up in API Manager

[2017-11-13 23:07:43,538]  INFO - SynapseControllerFactory The timeout handler will run every : 15s
[2017-11-13 23:07:43,544]  INFO - Axis2SynapseController Initializing Synapse at : Mon Nov 13 23:07:43 UTC 2017
[2017-11-13 23:07:43,551]  INFO - CarbonSynapseController Loading the mediation configuration from the file system
[2017-11-13 23:07:43,553]  INFO - MultiXMLConfigurationBuilder Building synapse configuration from the synapse artifact repository at : ././repository/deployment/server/synapse-configs/default
[2017-11-13 23:07:43,554]  INFO - XMLConfigurationBuilder Generating the Synapse configuration model by parsing the XML configuration
[2017-11-13 23:07:43,608]  INFO - DependencyTracker Sequence : _sandbox_key_error_ was added to the Synapse configuration successfully
[2017-11-13 23:07:43,610]  INFO - DependencyTracker Sequence : _resource_mismatch_handler_ was added to the Synapse configuration successfully
[2017-11-13 23:07:43,618]  INFO - DependencyTracker Sequence : _cors_request_handler_ was added to the Synapse configuration successfully
[2017-11-13 23:07:43,646]  INFO - DependencyTracker Sequence : fault was added to the Synapse configuration successfully
[2017-11-13 23:07:43,649]  INFO - DependencyTracker Sequence : _production_key_error_ was added to the Synapse configuration successfully
[2017-11-13 23:07:43,651]  INFO - DependencyTracker Sequence : _build_ was added to the Synapse configuration successfully
[2017-11-13 23:07:43,653]  INFO - DependencyTracker Sequence : outDispatchSeq was added to the Synapse configuration successfully
[2017-11-13 23:07:43,658]  INFO - DependencyTracker Sequence : main was added to the Synapse configuration successfully
[2017-11-13 23:07:43,659]  INFO - DependencyTracker Sequence : _auth_failure_handler_ was added to the Synapse configuration successfully
[2017-11-13 23:07:43,664]  INFO - DependencyTracker Sequence : _token_fault_ was added to the Synapse configuration successfully
[2017-11-13 23:07:43,675]  INFO - DependencyTracker Sequence : dispatchSeq was added to the Synapse configuration successfully
[2017-11-13 23:07:43,676]  INFO - DependencyTracker Sequence : _throttle_out_handler_ was added to the Synapse configuration successfully
[2017-11-13 23:07:43,684]  INFO - DependencyTracker Proxy service : WorkflowCallbackService was added to the Synapse configuration successfully
[2017-11-13 23:07:44,157]  INFO - DependencyTracker API : admin--Auth:vv1 was added to the Synapse configuration successfully
[2017-11-13 23:07:44,160]  INFO - DependencyTracker API : _WSO2AMAuthorizeAPI_ was added to the Synapse configuration successfully
***

[2017-11-13 23:07:44,193]  INFO - DependencyTracker API :
  admin--MenuProfileAPIs:vv1 was added to the Synapse configuration
  successfully
      [2017-11-13 23:07:44,194]  INFO - DependencyTracker API : admin--testGroup:vv1 was added to the Synapse configuration
  successfully
      [2017-11-13 23:07:44,640]  INFO - DependencyTracker API : admin--SettingsAPIs:vv1 was added to the Synapse configuration
  successfully

[2017-11-13 23:07:44,642]  INFO - DependencyTracker Inbound Endpoint : WebSocketInboundEndpoint was added to the Synapse configuration successfully
[2017-11-13 23:07:44,642]  INFO - SynapseConfigurationBuilder Loaded Synapse configuration from the artifact repository at : ././repository/deployment/server/synapse-configs/default
[2017-11-13 23:07:44,643]  INFO - DependencyTracker Local entry : SERVER_HOST was added to the Synapse configuration successfully
[2017-11-13 23:07:44,643]  INFO - DependencyTracker Local entry : SERVER_IP was added to the Synapse configuration successfully
[2017-11-13 23:07:44,645]  INFO - Axis2SynapseController Loading mediator extensions...
[2017-11-13 23:07:44,747]  INFO - DeploymentInterceptor Deploying Axis2 service: echo {super-tenant}
[2017-11-13 23:07:44,747]  INFO - DeploymentEngine Deploying Web service: Echo.aar -

How Can i debug this issue?What could be the possible causes for this.

I tried to create a new API with the same name of an existing API.Its not letting me create .It says duplicate.So it feels the API is existing ; but not shown in the UI.
I went to Manage Subscriptions in the Publisher and I can see the API's listed there. If I click the API's , I can see them.EVerything looks intact.But its not listing.


问:
Passport.js practical for simple login
I'm designing my user authentication system using Node.js/Express, and as I've been searching the web for authentication strategies, I noticed that a lot of developers recommend passport.js for helping with authentication.

My authentication will only ever use a username/password strategy with JSON web tokens.  Under that assumption, it seems like I have to manage the entire authentication myself: I check the username and password against the database, and I check and attach JWTs.  It seems like Passport only wraps my work inside it's own functions.

With only a username/password strategy, what use is Passport? What does Passport provide in this scenario that is of any real benefit over me just performing the authentication without it?

答:
Never. Ever. Implement. Your. Own. Security. Framework

Unless you actually want to implement a framework and you have all the resources in the world to do that, all the required knowledge and the key people ( like OWASP ) & etc etc.

Use existing lib for your project

Use a library, or a framework, that's open source and battle tested. Yes it will not be perfect and will have limitations. Yes it may not be the most secure code ever. BUT it will be much better than your own, especially if you're starting from scratch.

Then follow best practices for CSRF, XSS, DDoS & other kind of attack prevention.

Title: Passport.js practical for simple login


问:
EF6 Cannot insert duplicate key row
I got error when i try to update entity with unique constraint
I checked the form and there were a couple of similar post but none has answer.

```<code>    public class Car
    {
         [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int IdCar { get;set; }

        public string ColorCode { get; set; }

        [Index(IsUnique = true)]
        public string MotorId { get; set; }
    }

     private static int UpsertCar(Car checkCar, IUow uow)
    {
        var car =
           uow.Cars.GetAll().FirstOrDefault(x => x.MotorId.Trim()
               .Equals(checkCar.MotorId.Trim(),
                   StringComparison.CurrentCultureIgnoreCase));

        if (car == null)
        {
            uow.Cars.Add(checkCar);
            uow.Commit();
            return checkCar.IdCar;
        }
        else
        {
            car.ColorCode = checkCar.ColorCode;
            uow.Cars.Update(car);
            uow.Commit(); // Issue when i try to save
            return car.IdCar;
        }
    }
</code>```

Here is the update function

```<code> public virtual void Update(T entity)
    {
        DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
        if (dbEntityEntry.State == EntityState.Detached)
        {

            DbSet.Attach(entity);
        }
        dbEntityEntry.State = EntityState.Modified;
    }
</code>```

Error

Cannot insert duplicate key row in object 'dbo.Car' with unique index 'IX_MotorId’.
  The statement has been terminated.

答:
The problem here is that you chose to use the Repository pattern over the top of Entity Framework - an architecture problem. This isn't the only problem you'll have in your solution.

EF6 is very powerful, and the repository pattern hides all that power.

A standard way to code this whole upsert concept involves loading the original record from the context:

```<code>public class Car
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int IdCar { get;set; }

    public string ColorCode { get; set; }

    [Index(IsUnique = true)]
    public string MotorId { get; set; }

    //By having this update function alongside the members, it's easy to see whether it's up to date.
    public void Update(Car original)
    {
        original.ColorCode = ColorCode;
        original.MotorId = MotorId;
    }
}

public static int UpsertCar(Car checkCar, MyContext db)
{
    var original = db.Cars.SingleOrDefault(c => c.IdCar == checkCar.IdCar);

    if (original == null)
    {
        db.Cars.Add(checkCar);
    }
    else
    {
        checkCar.Update(original);
    }
    db.SaveChanges();
}
</code>```

Here you can see how simple it is when using EntityFramework directly.

Importantly, you can also see how simple it is to create your own Update function (keeping your current ORM architecture). Often, business rules will restrict what is able to be updated, and your own Update function won't allow update of all fields.

You should never need to use dbEntityEntry.State = EntityState.Modified; and if you do, you're probably approaching the code incorrectly.

Title: EF6 Cannot insert duplicate key row

Body:
I got error when i try to update entity with unique constraint
I checked the form and there were a couple of similar post but none has answer.

    public class Car
    {
         [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int IdCar { get;set; }

        public string ColorCode { get; set; }

        [Index(IsUnique = true)]
        public string MotorId { get; set; }
    }

     private static int UpsertCar(Car checkCar, IUow uow)
    {
        var car =
           uow.Cars.GetAll().FirstOrDefault(x => x.MotorId.Trim()
               .Equals(checkCar.MotorId.Trim(),
                   StringComparison.CurrentCultureIgnoreCase));

        if (car == null)
        {
            uow.Cars.Add(checkCar);
            uow.Commit();
            return checkCar.IdCar;
        }
        else
        {
            car.ColorCode = checkCar.ColorCode;
            uow.Cars.Update(car);
            uow.Commit(); // Issue when i try to save
            return car.IdCar;
        }
    }

Here is the update function

 public virtual void Update(T entity)
    {
        DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
        if (dbEntityEntry.State == EntityState.Detached)
        {

            DbSet.Attach(entity);
        }
        dbEntityEntry.State = EntityState.Modified;
    }

Error

Cannot insert duplicate key row in object 'dbo.Car' with unique index 'IX_MotorId’.
  The statement has been terminated.

Body:
The problem here is that you chose to use the Repository pattern over the top of Entity Framework - an architecture problem. This isn't the only problem you'll have in your solution.

EF6 is very powerful, and the repository pattern hides all that power.

A standard way to code this whole upsert concept involves loading the original record from the context:

public class Car
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int IdCar { get;set; }

    public string ColorCode { get; set; }

    [Index(IsUnique = true)]
    public string MotorId { get; set; }

    //By having this update function alongside the members, it's easy to see whether it's up to date.
    public void Update(Car original)
    {
        original.ColorCode = ColorCode;
        original.MotorId = MotorId;
    }
}

public static int UpsertCar(Car checkCar, MyContext db)
{
    var original = db.Cars.SingleOrDefault(c => c.IdCar == checkCar.IdCar);

    if (original == null)
    {
        db.Cars.Add(checkCar);
    }
    else
    {
        checkCar.Update(original);
    }
    db.SaveChanges();
}

Here you can see how simple it is when using EntityFramework directly.

Importantly, you can also see how simple it is to create your own Update function (keeping your current ORM architecture). Often, business rules will restrict what is able to be updated, and your own Update function won't allow update of all fields.

You should never need to use dbEntityEntry.State = EntityState.Modified; and if you do, you're probably approaching the code incorrectly.


问:
Dismiss keyboard by touching background of UITableView
I have a UITableView with UITextFields as cells.  I would like to dismiss the keyboard when the background of the UITableView is touched.  I'm trying to do this by creating a UIButton the size of the UITableView and placing it behind the UITableView.  The only problem is the UIButton is catching all the touches even when the touch is on the UITableView.  What am I doing wrong?

Thanks!

答:
The UITapGestureRecognizer solution works with table cell selection if you set:</p>

```<code>gestureRecognizer.cancelsTouchesInView = NO;</code>```

Body:
The UITapGestureRecognizer solution works with table cell selection if you set:

gestureRecognizer.cancelsTouchesInView = NO;

ContentLicense: CC BY-SA 2.5


问:
Is there a list of ghci abbreviated commands?
The document wrote,

The command name may be abbreviated, with ambiguities being resolved in favour of the more commonly used commands

but I can't find exact list.

I know some of them but I want to know if there is the full list available. The command with ? means ther are more than one suggesstions when tab-completion.

```<code>:a -> ?
:b -> ?
:c -> ?
:de -> ?
:e -> :edit
:for -> ?
:h -> :help
:i -> :info
:l -> :load
:m -> :module
:r -> :reload
:s -> :script
:t -> :type
:un -> ?
:where -> undocumented, found by completion, don't know what it is for
</code>```

答:
I checked ghc source file, and found stdin input is processed by

```<code>runGHIC -> runGHCiInput -> ghciCompleteWord -> lookupCompletion -> lookupCommand'
</code>```

At the end of lookupCommand

```<code>  -- first, look for exact match (while preferring macros); then, look
  -- for first prefix match (preferring builtins), *unless* a macro
  -- overrides the builtin; see #8305 for motivation
  return $ lookupExact str xcmds <|>
           lookupExact str ghci_cmds <|>
           (builtinPfxMatch >>= \c -> lookupExact (cmdName c) xcmds) <|>
           builtinPfxMatch <|>
           lookupPrefix str xcmds
</code>```

Basically, it first lookup exact match, then prefix match in order. So for normal :xxx command, it follows ghci_cmds order, which is availableCommands in GhciSettings, i.e.

```<code>  ("?",         keepGoing help,                 noCompletion),
  ("add",       keepGoingPaths addModule,       completeFilename),
  ("abandon",   keepGoing abandonCmd,           noCompletion),
  ("break",     keepGoing breakCmd,             completeIdentifier),
  ("back",      keepGoing backCmd,              noCompletion),
  ("browse",    keepGoing' (browseCmd False),   completeModule),
  ("browse!",   keepGoing' (browseCmd True),    completeModule),
  ("cd",        keepGoing' changeDirectory,     completeFilename),
  ("check",     keepGoing' checkModule,         completeHomeModule),
  ("continue",  keepGoing continueCmd,          noCompletion),
  ("cmd",       keepGoing cmdCmd,               completeExpression),
  ("ctags",     keepGoing createCTagsWithLineNumbersCmd, completeFilename),
  ("ctags!",    keepGoing createCTagsWithRegExesCmd, completeFilename),
  ("def",       keepGoing (defineMacro False),  completeExpression),
  ("def!",      keepGoing (defineMacro True),   completeExpression),
  ("delete",    keepGoing deleteCmd,            noCompletion),
  ("edit",      keepGoing' editFile,            completeFilename),
  ("etags",     keepGoing createETagsFileCmd,   completeFilename),
  ("force",     keepGoing forceCmd,             completeExpression),
  ("forward",   keepGoing forwardCmd,           noCompletion),
  ("help",      keepGoing help,                 noCompletion),
  ("history",   keepGoing historyCmd,           noCompletion),
  ("info",      keepGoing' (info False),        completeIdentifier),
  ("info!",     keepGoing' (info True),         completeIdentifier),
  ("issafe",    keepGoing' isSafeCmd,           completeModule),
  ("kind",      keepGoing' (kindOfType False),  completeIdentifier),
  ("kind!",     keepGoing' (kindOfType True),   completeIdentifier),
  ("load",      keepGoingPaths loadModule_,     completeHomeModuleOrFile),
  ("load!",     keepGoingPaths loadModuleDefer, completeHomeModuleOrFile),
  ("list",      keepGoing' listCmd,             noCompletion),
  ("module",    keepGoing moduleCmd,            completeSetModule),
  ("main",      keepGoing runMain,              completeFilename),
  ("print",     keepGoing printCmd,             completeExpression),
  ("quit",      quit,                           noCompletion),
  ("reload",    keepGoing' reloadModule,        noCompletion),
  ("reload!",   keepGoing' reloadModuleDefer,   noCompletion),
  ("run",       keepGoing runRun,               completeFilename),
  ("script",    keepGoing' scriptCmd,           completeFilename),
  ("set",       keepGoing setCmd,               completeSetOptions),
  ("seti",      keepGoing setiCmd,              completeSeti),
  ("show",      keepGoing showCmd,              completeShowOptions),
  ("showi",     keepGoing showiCmd,             completeShowiOptions),
  ("sprint",    keepGoing sprintCmd,            completeExpression),
  ("step",      keepGoing stepCmd,              completeIdentifier),
  ("steplocal", keepGoing stepLocalCmd,         completeIdentifier),
  ("stepmodule",keepGoing stepModuleCmd,        completeIdentifier),
  ("type",      keepGoing' typeOfExpr,          completeExpression),
  ("trace",     keepGoing traceCmd,             completeExpression),
  ("undef",     keepGoing undefineMacro,        completeMacro),
  ("unset",     keepGoing unsetOptions,         completeSetOptions),
  ("where",     keepGoing whereCmd,             noCompletion)
</code>```

so :c means :cd, :d means :def, follow the order.

Body:
The document wrote,

The command name may be abbreviated, with ambiguities being resolved in favour of the more commonly used commands

but I can't find exact list.

I know some of them but I want to know if there is the full list available. The command with ? means ther are more than one suggesstions when tab-completion.

:a -> ?
:b -> ?
:c -> ?
:de -> ?
:e -> :edit
:for -> ?
:h -> :help
:i -> :info
:l -> :load
:m -> :module
:r -> :reload
:s -> :script
:t -> :type
:un -> ?
:where -> undocumented, found by completion, don't know what it is for

Body:
I checked ghc source file, and found stdin input is processed by

runGHIC -> runGHCiInput -> ghciCompleteWord -> lookupCompletion -> lookupCommand'

At the end of lookupCommand

  -- first, look for exact match (while preferring macros); then, look
  -- for first prefix match (preferring builtins), *unless* a macro
  -- overrides the builtin; see #8305 for motivation
  return $ lookupExact str xcmds <|>
           lookupExact str ghci_cmds <|>
           (builtinPfxMatch >>= \c -> lookupExact (cmdName c) xcmds) <|>
           builtinPfxMatch <|>
           lookupPrefix str xcmds

Basically, it first lookup exact match, then prefix match in order. So for normal :xxx command, it follows ghci_cmds order, which is availableCommands in GhciSettings, i.e.

  ("?",         keepGoing help,                 noCompletion),
  ("add",       keepGoingPaths addModule,       completeFilename),
  ("abandon",   keepGoing abandonCmd,           noCompletion),
  ("break",     keepGoing breakCmd,             completeIdentifier),
  ("back",      keepGoing backCmd,              noCompletion),
  ("browse",    keepGoing' (browseCmd False),   completeModule),
  ("browse!",   keepGoing' (browseCmd True),    completeModule),
  ("cd",        keepGoing' changeDirectory,     completeFilename),
  ("check",     keepGoing' checkModule,         completeHomeModule),
  ("continue",  keepGoing continueCmd,          noCompletion),
  ("cmd",       keepGoing cmdCmd,               completeExpression),
  ("ctags",     keepGoing createCTagsWithLineNumbersCmd, completeFilename),
  ("ctags!",    keepGoing createCTagsWithRegExesCmd, completeFilename),
  ("def",       keepGoing (defineMacro False),  completeExpression),
  ("def!",      keepGoing (defineMacro True),   completeExpression),
  ("delete",    keepGoing deleteCmd,            noCompletion),
  ("edit",      keepGoing' editFile,            completeFilename),
  ("etags",     keepGoing createETagsFileCmd,   completeFilename),
  ("force",     keepGoing forceCmd,             completeExpression),
  ("forward",   keepGoing forwardCmd,           noCompletion),
  ("help",      keepGoing help,                 noCompletion),
  ("history",   keepGoing historyCmd,           noCompletion),
  ("info",      keepGoing' (info False),        completeIdentifier),
  ("info!",     keepGoing' (info True),         completeIdentifier),
  ("issafe",    keepGoing' isSafeCmd,           completeModule),
  ("kind",      keepGoing' (kindOfType False),  completeIdentifier),
  ("kind!",     keepGoing' (kindOfType True),   completeIdentifier),
  ("load",      keepGoingPaths loadModule_,     completeHomeModuleOrFile),
  ("load!",     keepGoingPaths loadModuleDefer, completeHomeModuleOrFile),
  ("list",      keepGoing' listCmd,             noCompletion),
  ("module",    keepGoing moduleCmd,            completeSetModule),
  ("main",      keepGoing runMain,              completeFilename),
  ("print",     keepGoing printCmd,             completeExpression),
  ("quit",      quit,                           noCompletion),
  ("reload",    keepGoing' reloadModule,        noCompletion),
  ("reload!",   keepGoing' reloadModuleDefer,   noCompletion),
  ("run",       keepGoing runRun,               completeFilename),
  ("script",    keepGoing' scriptCmd,           completeFilename),
  ("set",       keepGoing setCmd,               completeSetOptions),
  ("seti",      keepGoing setiCmd,              completeSeti),
  ("show",      keepGoing showCmd,              completeShowOptions),
  ("showi",     keepGoing showiCmd,             completeShowiOptions),
  ("sprint",    keepGoing sprintCmd,            completeExpression),
  ("step",      keepGoing stepCmd,              completeIdentifier),
  ("steplocal", keepGoing stepLocalCmd,         completeIdentifier),
  ("stepmodule",keepGoing stepModuleCmd,        completeIdentifier),
  ("type",      keepGoing' typeOfExpr,          completeExpression),
  ("trace",     keepGoing traceCmd,             completeExpression),
  ("undef",     keepGoing undefineMacro,        completeMacro),
  ("unset",     keepGoing unsetOptions,         completeSetOptions),
  ("where",     keepGoing whereCmd,             noCompletion)

so :c means :cd, :d means :def, follow the order.


问:
Javascript function not working when performing actions on a different HTML page
I have a button that if clicked calls a js function that should change the current page and display a simple hello world message, but all that happens is that the page gets changed but nothing is being displayed

Atalanta.html

```<code><button class="btn btn-info" onclick = "Atalanta1();">Read More </button>
</code>```

Article.html

```<code><div id = "NewsArticle">

</div>
</code>```

javascript file

```<code>function Atalanta1() {
    document.location.href = "../Article.html";
    var article = document.querySelector("#NewsArticle");
    var title = "";

    title += "<h2>" + "Hello World" + "</h2>";

    article.innerHTML = title;
}
</code>```

答:
Change your button to :

```<code><a class="btn btn-info" href="Article.html">Read More </a>
</code>```

On Article.html add this script :

```<code>window.onload = function() {
    var title = "";
    var article = document.querySelector("#NewsArticle");

    title += "<h2>" + "Hello World" + "</h2>";

    article.innerHTML = title;
}
</code>```

Body:
I have a button that if clicked calls a js function that should change the current page and display a simple hello world message, but all that happens is that the page gets changed but nothing is being displayed

Atalanta.html

<button class="btn btn-info" onclick = "Atalanta1();">Read More </button>

Article.html

javascript file

function Atalanta1() {
    document.location.href = "../Article.html";
    var article = document.querySelector("#NewsArticle");
    var title = "";

    title += "
" + "Hello World" + "
";

    article.innerHTML = title;
}

Body:
Change your button to :

<a class="btn btn-info" href="Article.html">Read More </a>

On Article.html add this script :

window.onload = function() {
    var title = "";
    var article = document.querySelector("#NewsArticle");

    title += "<h2>" + "Hello World" + "</h2>";

    article.innerHTML = title;
}


问:
How can I execute a command inside another folder and return to original directory?
I use this command to make inside a folder:

```<code>cd build/ && make
</code>```

But I want to return to original directory after the command

I tried this:

```<code>cd build/ && make && cd ..
</code>```

But this doesn't work. How can I do it? Would help in quick testing...

答:
Use a subshell, like so:

```<code>$ pwd
/tmp

$ (cd build && make)

$ pwd
/tmp
</code>```

The shell forks before running the commands in brackets, so once it completes it's as if you never left the current directory.

Body:
I use this command to make inside a folder:

cd build/ && make

But I want to return to original directory after the command

I tried this:

cd build/ && make && cd ..

But this doesn't work. How can I do it? Would help in quick testing...

Body:
Use a subshell, like so:

$ pwd
/tmp

$ (cd build && make)

$ pwd
/tmp

The shell forks before running the commands in brackets, so once it completes it's as if you never left the current directory.

ContentLicense: CC BY-SA 4.0


问:
Acceptance-rejection for beta distribution R code
I’m using the acceptance-rejection method for beta distribution with g(x) = 1, 0 ≤ x ≤ 1.
The function is:
f(x) = 100x^3(1-x)^2.

I want to create an algorithm to generate data from this density function.

How can I estimate P(0 ≤ X ≤ 0.8) with k = 1000 repetitions (n=1000)? How can I solve this in R?

I already have:

```<code>beta.rejection <- function(f, c, g, n) {
naccepts <- 0
result.sample <- rep(NA, n)

  while (naccepts < n) {
    y <- runif(1, 0, 0.8)
    u <- runif(1, 0, 0.8)

    if ( u <= f(y) / (c*g(y)) ) {
      naccepts <- naccepts + 1
      result.sample[n.accepts] = y
    }
  }

  result.sample
}

f <- function(x) 100*(x^3)*(1-x)^2
g <- function(x) x/x
c <- 2

result <- beta.rejection(f, c, g, 10000)

for (i in 1:1000){ # k = 1000 reps
  result[i] <- result[i] / n
}

print(mean(result))
</code>```

答:
You are close, but a few problems:

1) typo with naccepts vs. n.accepts

2) If you aren't going to hard-wire in g then you shouldn't hard-wire in runif() as the function which generates random variables which are distributed according to g. The function rejection (why hard-wire in beta?) should also be passed a function which is capable of generating the appropriate random variables.

3) u should be drawn from [0,1] not [0,0.8]. The 0.8 should have no part in the generation of the values, just their interpretation.

4) c need to be an upper bound for f(y)/g(y). 2 is too small. Why not take the derivative of f to find it's max? 3.5 works. Also -- c isn't a good name for a variable in R (because of the function c()). Why not call it M?

Making these changes yields:

```<code>rejection <- function(f, M, g, rg,n) {
  naccepts <- 0
  result.sample <- rep(NA, n)

  while (naccepts < n) {
    y <- rg(1)
    u <- runif(1)

    if ( u <= f(y) / (M*g(y)) ) {
      naccepts <- naccepts + 1
      result.sample[naccepts] = y
    }
  }

  result.sample
}

f <- function(x) 100*(x^3)*(1-x)^2
g <- function(x) 1
rg <- runif
M <- 3.5 #upper bound on f (via basic calculus)

result <- rejection(f, M, g,rg, 10000)

print(length(result[result <= 0.8])/10000)
</code>```

Typical output: 0.9016

You can also make a density histogram of result and compare it to the theoretical beta distribution:

```<code>> hist(result,freq = FALSE)
> points(seq(0,1,0.01),dbeta(seq(0,1,0.01),4,3),type = "l")
</code>```

The match is quite good:

Body:
I’m using the acceptance-rejection method for beta distribution with g(x) = 1, 0 ≤ x ≤ 1.
The function is:
f(x) = 100x^3(1-x)^2.

I want to create an algorithm to generate data from this density function.

How can I estimate P(0 ≤ X ≤ 0.8) with k = 1000 repetitions (n=1000)? How can I solve this in R?

I already have:

beta.rejection <- function(f, c, g, n) {
naccepts <- 0
result.sample <- rep(NA, n)

  while (naccepts < n) {
    y <- runif(1, 0, 0.8)
    u <- runif(1, 0, 0.8)

    if ( u <= f(y) / (c*g(y)) ) {
      naccepts <- naccepts + 1
      result.sample[n.accepts] = y
    }
  }

  result.sample
}

f <- function(x) 100*(x^3)*(1-x)^2
g <- function(x) x/x
c <- 2

result <- beta.rejection(f, c, g, 10000)

for (i in 1:1000){ # k = 1000 reps
  result[i] <- result[i] / n
}

print(mean(result))

Body:
You are close, but a few problems:

1) typo with naccepts vs. n.accepts

2) If you aren't going to hard-wire in g then you shouldn't hard-wire in runif() as the function which generates random variables which are distributed according to g. The function rejection (why hard-wire in beta?) should also be passed a function which is capable of generating the appropriate random variables.

3) u should be drawn from [0,1] not [0,0.8]. The 0.8 should have no part in the generation of the values, just their interpretation.

4) c need to be an upper bound for f(y)/g(y). 2 is too small. Why not take the derivative of f to find it's max? 3.5 works. Also -- c isn't a good name for a variable in R (because of the function c()). Why not call it M?

Making these changes yields:

rejection <- function(f, M, g, rg,n) {
  naccepts <- 0
  result.sample <- rep(NA, n)

  while (naccepts < n) {
    y <- rg(1)
    u <- runif(1)

    if ( u <= f(y) / (M*g(y)) ) {
      naccepts <- naccepts + 1
      result.sample[naccepts] = y
    }
  }

  result.sample
}

f <- function(x) 100*(x^3)*(1-x)^2
g <- function(x) 1
rg <- runif
M <- 3.5 #upper bound on f (via basic calculus)

result <- rejection(f, M, g,rg, 10000)

print(length(result[result <= 0.8])/10000)

Typical output: 0.9016

You can also make a density histogram of result and compare it to the theoretical beta distribution:

> hist(result,freq = FALSE)
> points(seq(0,1,0.01),dbeta(seq(0,1,0.01),4,3),type = "l")

The match is quite good:


问:
Colorplot of 2D array matplotlib
So, I thought this was going to be really simple, but I've been having a lot of difficult finding exactly what I'm looking for in a comprehensible example.

Basically I want to make phase plots, so assuming I have a 2d array, how can I get matplotlib to convert this to a plot that I can attach titles, axes, and legends (color bars) to.

I'm looking for an extremely simple bare bones solution that only uses what is required that will work with any 2D array.

I'm certain this is simple and I'm just being thick somehow, but I'm really having a lot of trouble with this.

I have been tooling with the examples, but they don't seem well suited to what I'm trying to do: I like the general appearance of this graph, I'd just like to be able to pass in a 2dArray and have this same result:

```<code>import numpy as np
import matplotlib as ml
import matplotlib.pyplot as plt

H = [[1,2,3,4][5,6,7,8][9,10,11,12][13,14,15,16]]

fig = plt.figure(figsize=(6, 3.2))

ax = fig.add_subplot(111)
ax.set_title('colorMap')
X,Y = np.meshgrid(xedges, yedges)
plt.pcolormesh(X, Y, H)
ax.set_aspect('equal')

cax = fig.add_axes([0.12, 0.1, 0.78, 0.8])
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
cax.patch.set_alpha(0)
cax.set_frame_on(False)
plt.colorbar(orientation='vertical')
plt.show()
</code>```

答:
Here is the simplest example that has the key lines of code:

```<code>import numpy as np
import matplotlib.pyplot as plt

H = np.array([[1, 2, 3, 4],
          [5, 6, 7, 8],
          [9, 10, 11, 12],
          [13, 14, 15, 16]])

plt.imshow(H, interpolation='none')
plt.show()
</code>```

EDIT: (1/2023) Still working with Python 3.9.13

Title: Colorplot of 2D array matplotlib

Body:
So, I thought this was going to be really simple, but I've been having a lot of difficult finding exactly what I'm looking for in a comprehensible example.

Basically I want to make phase plots, so assuming I have a 2d array, how can I get matplotlib to convert this to a plot that I can attach titles, axes, and legends (color bars) to.

I'm looking for an extremely simple bare bones solution that only uses what is required that will work with any 2D array.

I'm certain this is simple and I'm just being thick somehow, but I'm really having a lot of trouble with this.

I have been tooling with the examples, but they don't seem well suited to what I'm trying to do: I like the general appearance of this graph, I'd just like to be able to pass in a 2dArray and have this same result:

import numpy as np
import matplotlib as ml
import matplotlib.pyplot as plt

H = [[1,2,3,4][5,6,7,8][9,10,11,12][13,14,15,16]]

fig = plt.figure(figsize=(6, 3.2))

ax = fig.add_subplot(111)
ax.set_title('colorMap')
X,Y = np.meshgrid(xedges, yedges)
plt.pcolormesh(X, Y, H)
ax.set_aspect('equal')

cax = fig.add_axes([0.12, 0.1, 0.78, 0.8])
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
cax.patch.set_alpha(0)
cax.set_frame_on(False)
plt.colorbar(orientation='vertical')
plt.show()

Body:
Here is the simplest example that has the key lines of code:

import numpy as np
import matplotlib.pyplot as plt

H = np.array([[1, 2, 3, 4],
          [5, 6, 7, 8],
          [9, 10, 11, 12],
          [13, 14, 15, 16]])

plt.imshow(H, interpolation='none')
plt.show()

EDIT: (1/2023) Still working with Python 3.9.13


问:
Slight zoom on MKCoordinateRegion?
I am zooming an MKMapView to fit the bounding region of a collection of pins, however when the pins are displayed I have noticed that the zoom could ideally do with being a little tighter. My proposed solution to this was to make the region deltas slightly smaller:

```<code>// SMALL ZOOM
region.span.latitudeDelta = (upper.latitude - lower.latitude) * 0.9;
region.span.longitudeDelta = (upper.longitude - lower.longitude) * 0.9;
</code>```

However I have noticed that fine adjustments don't seem to translate to a small zoom increase, is there some form of snapping on the zoom? Really small values work, as do really big ones, but just adjusting the region size by a few percent does not seem to work with the view nearly always jumping/zooming in to far and clipping my pins.

EDIT:

Quick tests showing the results of different scaling factors on the region:

```<code> //                                                             SCALE FACTOR
 //                                                                  V
 region.span.latitudeDelta  =   (upper.latitude - lower.latitude) * 0.9;
 region.span.longitudeDelta = (upper.longitude - lower.longitude) * 0.9;
</code>```

Here are the results:

x0.5 region too small, some annotations off screen

x0.6 Same as using 1.0

x0.7 Same as using 1.0

x0.8 Same as using 1.0

x0.9 Same as using 1.0

x1.0 Original fit

x1.1 region too big, annotations too small on screen

My point is that very small adjustments (e.g. 0.6 to 0.9) don't seem to make any difference.

答:
I have found this method to be extremely useful. All you need to do is call it and pass your MKMapView as the argument, and it will determine the best zoom level to fit all of your annotations. The "tightness" can be adjusted by modifying the constant multiplier on the commented lines (currently 1.1).

What's the best way to zoom out and fit all annotations in MapKit

```<code>- (void)zoomToFitMapAnnotations:(MKMapView *)mapView
{
    if ([mapView.annotations count] == 0)
        return;

    CLLocationCoordinate2D topLeftCoord;
    topLeftCoord.latitude = -90;
    topLeftCoord.longitude = 180;

    CLLocationCoordinate2D bottomRightCoord;
    bottomRightCoord.latitude = 90;
    bottomRightCoord.longitude = -180;

    for (MapAnnotation *annotation in mapView.annotations)
    {
        topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
        topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);

        bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
        bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
    }

    MKCoordinateRegion region;
    region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;
    region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
    region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1; // Add a little extra space on the sides
    region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1; // Add a little extra space on the sides

    region = [mapView regionThatFits:region];
    [mapView setRegion:region animated:YES];
}
</code>```

Title: Slight zoom on MKCoordinateRegion?

Body:
I am zooming an MKMapView to fit the bounding region of a collection of pins, however when the pins are displayed I have noticed that the zoom could ideally do with being a little tighter. My proposed solution to this was to make the region deltas slightly smaller:

// SMALL ZOOM
region.span.latitudeDelta = (upper.latitude - lower.latitude) * 0.9;
region.span.longitudeDelta = (upper.longitude - lower.longitude) * 0.9;

However I have noticed that fine adjustments don't seem to translate to a small zoom increase, is there some form of snapping on the zoom? Really small values work, as do really big ones, but just adjusting the region size by a few percent does not seem to work with the view nearly always jumping/zooming in to far and clipping my pins.

EDIT:

Quick tests showing the results of different scaling factors on the region:

 //                                                             SCALE FACTOR
 //                                                                  V
 region.span.latitudeDelta  =   (upper.latitude - lower.latitude) * 0.9;
 region.span.longitudeDelta = (upper.longitude - lower.longitude) * 0.9;

Here are the results:

x0.5 region too small, some annotations off screen

x0.6 Same as using 1.0

x0.7 Same as using 1.0

x0.8 Same as using 1.0

x0.9 Same as using 1.0

x1.0 Original fit

x1.1 region too big, annotations too small on screen

My point is that very small adjustments (e.g. 0.6 to 0.9) don't seem to make any difference.

Body:
I have found this method to be extremely useful. All you need to do is call it and pass your MKMapView as the argument, and it will determine the best zoom level to fit all of your annotations. The "tightness" can be adjusted by modifying the constant multiplier on the commented lines (currently 1.1).

What's the best way to zoom out and fit all annotations in MapKit

- (void)zoomToFitMapAnnotations:(MKMapView *)mapView
{
    if ([mapView.annotations count] == 0)
        return;

    CLLocationCoordinate2D topLeftCoord;
    topLeftCoord.latitude = -90;
    topLeftCoord.longitude = 180;

    CLLocationCoordinate2D bottomRightCoord;
    bottomRightCoord.latitude = 90;
    bottomRightCoord.longitude = -180;

    for (MapAnnotation *annotation in mapView.annotations)
    {
        topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
        topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);

        bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
        bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
    }

    MKCoordinateRegion region;
    region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;
    region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
    region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1; // Add a little extra space on the sides
    region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1; // Add a little extra space on the sides

    region = [mapView regionThatFits:region];
    [mapView setRegion:region animated:YES];
}


问:
What are the functional benefits of recursive scheduling in System.Reactive?
I'm current reading http://www.introtorx.com/ and I'm getting really interested in stripping Subject<T> out of my reactive code. I'm starting to understand how to encapsulate sequence generation so that I can reason better about a given sequence. I read a few SO questions and ended up reading about scheduling. Of particular interest is recursive scheduling, using the Schedule(this IScheduler scheduler, Action<TState,Action<TState>>)overloads - like this one.

The book is starting to show its age in a few areas, and the biggest i see is that it never compares its techniques to alternatives that may be achieved using the Task and async/await language features. I always end up feeling like I could write less code by ignoring the book advice and using the asynchronous toys, but the back of my mind nags me about being lazy and not learning the pattern properly.

With that, here is my question. If I wanted to schedule a sequence at an interval, support cancellation and perform work on a background thread, I might do this:

```<code>    static void Main(string[] args)
    {
        var sequence = Observable.Create<object>(o =>
        {
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            DoWerk(o, cancellationTokenSource);

            return cancellationTokenSource.Cancel;
        });

        sequence.Subscribe(p => Console.Write(p));

        Console.ReadLine();
    }

    private static async void DoWerk(IObserver<object> o, CancellationTokenSource cancellationTokenSource)
    {
        string message =  "hello world!";
        for (int i = 0; i < message.Length; i++)
        {
            await Task.Delay(250, cancellationTokenSource.Token);
            o.OnNext(message[i]);

            if (cancellationTokenSource.IsCancellationRequested)
            {
                break;
            }
        }

        o.OnCompleted();
    }
</code>```

Note the use of async void to create concurrency without explicitly borrowing a thread pool thread with Task.Run(). await Task.Delay() will, however, do just that but it will not lease the thread for long.

What are the limitations and pitfalls here? What are the reasons that you might prefer to use recursive scheduling?

答:
I personally wouldn't use await Task.Delay(250, cancellationTokenSource.Token); as a way to slow down a loop. It's better than Thread.Sleep(250), but it's still code smell to me.

I would look at it that you should use a built-in operator in preference to a roll-your-own solution like this.

The operator you need is one of the most powerful, but often overlooked. Try Observable.Generate. He's how:

```<code>static void Main(string[] args)
{
    IObservable<char> sequence = Observable.Create<char>(o =>
    {
        string message =  "hello world!";
        return
            Observable
                .Generate(
                    0,
                    n => n < message.Length,
                    n => n + 1,
                    n => message[n],
                    n => TimeSpan.FromMilliseconds(250.0))
                .Subscribe(o);
    });

    using (sequence.Subscribe(p => Console.Write(p)))
    {
        Console.ReadLine();
    }
}
</code>```

This is self-cancelling (when you call .Dispose() on the subscription) and produces values every 250.0 milliseconds.

I've continued to use the Observable.Create operator to ensure that the message variable is encapsulated within the observable - otherwise it is possible for someone to change the value of message as the observable is working with it and thus break it.

As an alternative, that might not be as efficient with memory, but is self-encapsulating, try this:

```<code>IObservable<char> sequence =
    Observable
        .Generate(
            "hello world!",
            n => !String.IsNullOrEmpty(n),
            n => n.Substring(1),
            n => n[0],
            n => TimeSpan.FromMilliseconds(250.0));
</code>```

And, finally, there's nothing "recursive" about the scheduling in your question. What did you mean by that?

I finally figured out what you're looking at. I missed it in the question.

Here's an example using the recursive scheduling:

```<code>IObservable<char> sequence = Observable.Create<char>(o =>
{
    string message = "hello world!";
    return Scheduler.Default.Schedule<string>(message, TimeSpan.FromMilliseconds(250.0), (state, schedule) =>
    {
        if (!String.IsNullOrEmpty(state))
        {
            o.OnNext(state[0]);
            schedule(state.Substring(1), TimeSpan.FromMilliseconds(250.0));
        }
        else
        {
            o.OnCompleted();
        }
    });
});
</code>```

Body:
I'm current reading http://www.introtorx.com/ and I'm getting really interested in stripping Subject<T> out of my reactive code. I'm starting to understand how to encapsulate sequence generation so that I can reason better about a given sequence. I read a few SO questions and ended up reading about scheduling. Of particular interest is recursive scheduling, using the Schedule(this IScheduler scheduler, Action<TState,Action<TState>>)overloads - like this one.

The book is starting to show its age in a few areas, and the biggest i see is that it never compares its techniques to alternatives that may be achieved using the Task and async/await language features. I always end up feeling like I could write less code by ignoring the book advice and using the asynchronous toys, but the back of my mind nags me about being lazy and not learning the pattern properly.

With that, here is my question. If I wanted to schedule a sequence at an interval, support cancellation and perform work on a background thread, I might do this:

    static void Main(string[] args)
    {
        var sequence = Observable.Create<object>(o =>
        {
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            DoWerk(o, cancellationTokenSource);

            return cancellationTokenSource.Cancel;
        });

        sequence.Subscribe(p => Console.Write(p));

        Console.ReadLine();
    }

    private static async void DoWerk(IObserver<object> o, CancellationTokenSource cancellationTokenSource)
    {
        string message =  "hello world!";
        for (int i = 0; i < message.Length; i++)
        {
            await Task.Delay(250, cancellationTokenSource.Token);
            o.OnNext(message[i]);

            if (cancellationTokenSource.IsCancellationRequested)
            {
                break;
            }
        }

        o.OnCompleted();
    }

Note the use of async void to create concurrency without explicitly borrowing a thread pool thread with Task.Run(). await Task.Delay() will, however, do just that but it will not lease the thread for long.

What are the limitations and pitfalls here? What are the reasons that you might prefer to use recursive scheduling?

Body:
I personally wouldn't use await Task.Delay(250, cancellationTokenSource.Token); as a way to slow down a loop. It's better than Thread.Sleep(250), but it's still code smell to me.

I would look at it that you should use a built-in operator in preference to a roll-your-own solution like this.

The operator you need is one of the most powerful, but often overlooked. Try Observable.Generate. He's how:

static void Main(string[] args)
{
    IObservable<char> sequence = Observable.Create<char>(o =>
    {
        string message =  "hello world!";
        return
            Observable
                .Generate(
                    0,
                    n => n < message.Length,
                    n => n + 1,
                    n => message[n],
                    n => TimeSpan.FromMilliseconds(250.0))
                .Subscribe(o);
    });

    using (sequence.Subscribe(p => Console.Write(p)))
    {
        Console.ReadLine();
    }
}

This is self-cancelling (when you call .Dispose() on the subscription) and produces values every 250.0 milliseconds.

I've continued to use the Observable.Create operator to ensure that the message variable is encapsulated within the observable - otherwise it is possible for someone to change the value of message as the observable is working with it and thus break it.

As an alternative, that might not be as efficient with memory, but is self-encapsulating, try this:

IObservable<char> sequence =
    Observable
        .Generate(
            "hello world!",
            n => !String.IsNullOrEmpty(n),
            n => n.Substring(1),
            n => n[0],
            n => TimeSpan.FromMilliseconds(250.0));

And, finally, there's nothing "recursive" about the scheduling in your question. What did you mean by that?

I finally figured out what you're looking at. I missed it in the question.

Here's an example using the recursive scheduling:

IObservable<char> sequence = Observable.Create<char>(o =>
{
    string message = "hello world!";
    return Scheduler.Default.Schedule<string>(message, TimeSpan.FromMilliseconds(250.0), (state, schedule) =>
    {
        if (!String.IsNullOrEmpty(state))
        {
            o.OnNext(state[0]);
            schedule(state.Substring(1), TimeSpan.FromMilliseconds(250.0));
        }
        else
        {
            o.OnCompleted();
        }
    });
});


问:
Excel VBA, cleaning data using if statement and bad email list
I'm wanting to use an if statement in VBA to help me clean CSV files i have a list of emails that are "bad" and want to add them into the statement so when the program runs it picks up email x, y and z.

I found a youtube video that explained out to remove rows with blank or 0 values, but havent been able to work out if i can expand it.

```<code>Sub CleanData()

' Disable certain Excel Features, whilst the macro is running
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = False
Application.ScreenUpdating = False

    ' Decalare Variables
    Dim DeleteRow As Long
    Dim ws As Worksheet

    ' Set objects
    Set ws = ActiveSheet

        ' Loop through the rows of data, in order to delete rows with a
        ' zero value in column O. Our data commences of row 5
        For DeleteRow = ws.Range("O" & Rows.Count).End(xlUp).Row To 2 Step -1

            ' Identify values in col O, which are zero & delete entire row
            If ws.Range("O" & DeleteRow).Value = 0 Then
            Rows(DeleteRow).EntireRow.Delete
            End If

        'Move to next cell in the range, whitch is being looped
        Next DeleteRow

    ' Re-enable the above Excel Features, Whitch were disabled whilst the macro ran
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub
</code>```

in the below section I'd like to add other "bad/unwanted" emails

```<code>' Identify values in col O, which are zero & delete entire row
If ws.Range("O" & DeleteRow).Value = 0 Then
    Rows(DeleteRow).EntireRow.Delete
End If
</code>```

Any reading or help to point me in the right direction much appreciated.

答:
See if this works for you.

```<code>Option Explicit

Sub CleanData()

    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False
    Application.ScreenUpdating = False

    Dim ws As Worksheet, delCollection As Range, ckRng As Range, cel As Range
    Dim TestArr(4)  '< Set this to number of strings you have starting at 0

    'Create your array of search values to delete
    TestArr(0) = 0
    TestArr(1) = ""
    TestArr(2) = "a String"
    TestArr(3) = "a String with wildcard*"
    TestArr(4) = "*String with multiple wildcards*"

    Set ws = ThisWorkbook.ActiveSheet
    Set ckRng = ws.UsedRange.Columns("O")

    For Each cel In ckRng.Cells
        If OrLikeArr(cel.Value, TestArr) Then
            If delCollection Is Nothing Then
                Set delCollection = cel.EntireRow
            Else
                Set delCollection = Application.Union(cel, delCollection)
            End If
        End If
    Next cel

    If Not delCollection Is Nothing Then delCollection.EntireRow.Delete

    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True
    Application.ScreenUpdating = True

End Sub
</code>```

Also, make sure to add the following function to your module:

```<code>Function OrLikeArr(ByVal compareStr As String, _
    ParamArray compareArr() As Variant) As Boolean

    Dim i As Long, TestArr
    OrLikeArr = False
    TestArr = compareArr(0)

    For i = LBound(TestArr) To UBound(TestArr)
        Debug.Print "Testing [" & compareStr & "] to [" & TestArr(i) & "] ";
        If compareStr Like TestArr(i) Then
            OrLikeArr = True
            Debug.Print OrLikeArr
            Exit Function
        End If
        Debug.Print OrLikeArr
    Next i

End Function
</code>```

There are many ways of accomplishing your goal, but in the one I suggested, you are adding all the rows that meet your criteria - in this case = 0 - to the range delCollection. You can do this by using the Union method.

After all the items that meet your criteria are found and added to this range, you will then proceed to delete the range in one hit, as opposed to deleting it line-by-line. This will give you a performance boost by doing it this way.

EDIT

I just realized that you had set calculation to xlCalculationAutomatic at the beginning and end of your code. Updated my code to correct that.

EDIT #2

I added the function OrLikeArr to the answer. You can use this instead of typing out cel.Value like x or cel.Value like y or cel.Value like z. This function make the code much cleaner.

But with this being said, I also made a modification to the original code. I added an array, and in that array you will need to input your custom values. One value you stated was 0, which you can see I added as TestArr(0) = 0.

Once you have added all your values to this array, make sure your declaration on TestArr(i) is correct. i needs to be the total of your test strings - as you can see I stopped with TestArr(4), so thats why it says Dim TestArr(4).

Body:
I'm wanting to use an if statement in VBA to help me clean CSV files i have a list of emails that are "bad" and want to add them into the statement so when the program runs it picks up email x, y and z.

I found a youtube video that explained out to remove rows with blank or 0 values, but havent been able to work out if i can expand it.

Sub CleanData()

' Disable certain Excel Features, whilst the macro is running
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = False
Application.ScreenUpdating = False

    ' Decalare Variables
    Dim DeleteRow As Long
    Dim ws As Worksheet

    ' Set objects
    Set ws = ActiveSheet

        ' Loop through the rows of data, in order to delete rows with a
        ' zero value in column O. Our data commences of row 5
        For DeleteRow = ws.Range("O" & Rows.Count).End(xlUp).Row To 2 Step -1

            ' Identify values in col O, which are zero & delete entire row
            If ws.Range("O" & DeleteRow).Value = 0 Then
            Rows(DeleteRow).EntireRow.Delete
            End If

        'Move to next cell in the range, whitch is being looped
        Next DeleteRow

    ' Re-enable the above Excel Features, Whitch were disabled whilst the macro ran
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub

in the below section I'd like to add other "bad/unwanted" emails

' Identify values in col O, which are zero & delete entire row
If ws.Range("O" & DeleteRow).Value = 0 Then
    Rows(DeleteRow).EntireRow.Delete
End If

Any reading or help to point me in the right direction much appreciated.

Body:
See if this works for you.

Option Explicit

Sub CleanData()

    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False
    Application.ScreenUpdating = False

    Dim ws As Worksheet, delCollection As Range, ckRng As Range, cel As Range
    Dim TestArr(4)  '< Set this to number of strings you have starting at 0

    'Create your array of search values to delete
    TestArr(0) = 0
    TestArr(1) = ""
    TestArr(2) = "a String"
    TestArr(3) = "a String with wildcard*"
    TestArr(4) = "*String with multiple wildcards*"

    Set ws = ThisWorkbook.ActiveSheet
    Set ckRng = ws.UsedRange.Columns("O")

    For Each cel In ckRng.Cells
        If OrLikeArr(cel.Value, TestArr) Then
            If delCollection Is Nothing Then
                Set delCollection = cel.EntireRow
            Else
                Set delCollection = Application.Union(cel, delCollection)
            End If
        End If
    Next cel

    If Not delCollection Is Nothing Then delCollection.EntireRow.Delete

    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True
    Application.ScreenUpdating = True

End Sub

Also, make sure to add the following function to your module:

Function OrLikeArr(ByVal compareStr As String, _
    ParamArray compareArr() As Variant) As Boolean

    Dim i As Long, TestArr
    OrLikeArr = False
    TestArr = compareArr(0)

    For i = LBound(TestArr) To UBound(TestArr)
        Debug.Print "Testing [" & compareStr & "] to [" & TestArr(i) & "] ";
        If compareStr Like TestArr(i) Then
            OrLikeArr = True
            Debug.Print OrLikeArr
            Exit Function
        End If
        Debug.Print OrLikeArr
    Next i

End Function

There are many ways of accomplishing your goal, but in the one I suggested, you are adding all the rows that meet your criteria - in this case = 0 - to the range delCollection. You can do this by using the Union method.

After all the items that meet your criteria are found and added to this range, you will then proceed to delete the range in one hit, as opposed to deleting it line-by-line. This will give you a performance boost by doing it this way.

EDIT

I just realized that you had set calculation to xlCalculationAutomatic at the beginning and end of your code. Updated my code to correct that.

EDIT #2

I added the function OrLikeArr to the answer. You can use this instead of typing out cel.Value like x or cel.Value like y or cel.Value like z. This function make the code much cleaner.

But with this being said, I also made a modification to the original code. I added an array, and in that array you will need to input your custom values. One value you stated was 0, which you can see I added as TestArr(0) = 0.

Once you have added all your values to this array, make sure your declaration on TestArr(i) is correct. i needs to be the total of your test strings - as you can see I stopped with TestArr(4), so thats why it says Dim TestArr(4).


问:
Passing a function pointer as non-type template parameter
I have this template function, which is working well:

```<code>    template<typename RES, typename... PARMS> SQInteger GlobalBind(RES(*fn)(PARMS... parms), const char *sqName, HSQUIRRELVM v)
</code>```

Which is called like this :

```<code>GlobalBind(aFunction, "aName", vm);
</code>```

Its scope is binding function fn to a scripting engine.

Using it in this way, I must keep the fn pointer AND a proxy template pointer inside of the scripting engine; the proxy template (not shown here) is called with fn as parameter, does some stuff, and then calls fn.

What I'd like to achieve is to remove the fn pointer from the function call, and put it into the template as a parameter, something like this:

```<code>template<typename RES, typename... PARMS, RES(*fn)(PARMS...)> SQInteger GlobalBind(const char *sqName, HSQUIRRELVM v)
</code>```

So, a specific template is instantiated for each different fn, which means that I could avoid the fn pointer in the scripting language; the call should be:

```<code>GlobalBind<aFunction>("aName", vm);
</code>```

The template declaration is accepted by the compiler, but the call brings errors, even adding the parameter types before aFunction, like this (assuming aFunction returns and int and has const char * as a parameter):

```<code>GlobalBind<int, const char *, aFunction>("aName", vm);
</code>```

Is there a way to achieve this result (the former, without a parameters list)?

EDIT:
to simplify the question, is the template

```<code>template<typename RES, typename... PARMS, RES(*fn)(PARMS...)> RES TEST(PARMS... parms) {
    return fn(parms...);
}
</code>```

a valid one ? And if yes... how should it be called ?
I tried this :

```<code>int testfn(const char *s) { return strlen(s); }
TEST<testfn>("aString");   << ERROR
TEST<int, const char *, testfn>("aString");  << ERROR
</code>```

EDIT2:
This one :

```<code>template<int (*fn)(const char *)> int TEST2(const char *s) {
    return fn(s);
}
TEST2<testfn>("aString");
</code>```

works, but it's not useful for my purpose

答:
```<code>template<class T, T t>
struct constant_t:std::integral_constant<T,t>{
  constexpr operator T()const { return t; }
  constexpr constant_t(){}
};

#define TYPEDARG(...) \
  typename std::decay<decltype(__VA_ARGS__)>::type, \
  __VA_ARGS__
</code>```

Now constant_t<TYPEDARG(foo)> is a type whose instances can be invoked if foo is a non-overloaded function and they call foo.

In c++17 this becomes:

```<code>template<auto x>
using constant_t=std::integral_constant<std::decay_t<decltype(x)>,x>;
</code>```

and use is simply constant_t<foo>, without all that extra noise.

```<code>template<class Fn, class R, class... Args>
R test(Args&&... args) {
  return Fn{}(std::forward<Args>(args)...);
}

int foo( int a, int b ) { return a+b; }

int r = test< constant_t<TYPEDARG(foo)>, int, int, int >( 3, 4 );
</code>```

Body:
I have this template function, which is working well:

    template<typename RES, typename... PARMS> SQInteger GlobalBind(RES(*fn)(PARMS... parms), const char *sqName, HSQUIRRELVM v)

Which is called like this :

GlobalBind(aFunction, "aName", vm);

Its scope is binding function fn to a scripting engine.

Using it in this way, I must keep the fn pointer AND a proxy template pointer inside of the scripting engine; the proxy template (not shown here) is called with fn as parameter, does some stuff, and then calls fn.

What I'd like to achieve is to remove the fn pointer from the function call, and put it into the template as a parameter, something like this:

template<typename RES, typename... PARMS, RES(*fn)(PARMS...)> SQInteger GlobalBind(const char *sqName, HSQUIRRELVM v)

So, a specific template is instantiated for each different fn, which means that I could avoid the fn pointer in the scripting language; the call should be:

GlobalBind<aFunction>("aName", vm);

The template declaration is accepted by the compiler, but the call brings errors, even adding the parameter types before aFunction, like this (assuming aFunction returns and int and has const char * as a parameter):

GlobalBind<int, const char *, aFunction>("aName", vm);

Is there a way to achieve this result (the former, without a parameters list)?

EDIT:
to simplify the question, is the template

template<typename RES, typename... PARMS, RES(*fn)(PARMS...)> RES TEST(PARMS... parms) {
    return fn(parms...);
}

a valid one ? And if yes... how should it be called ?
I tried this :

int testfn(const char *s) { return strlen(s); }
TEST<testfn>("aString");   << ERROR
TEST<int, const char *, testfn>("aString");  << ERROR

EDIT2:
This one :

template<int (*fn)(const char *)> int TEST2(const char *s) {
    return fn(s);
}
TEST2<testfn>("aString");

works, but it's not useful for my purpose

Body:
template<class T, T t>
struct constant_t:std::integral_constant<T,t>{
  constexpr operator T()const { return t; }
  constexpr constant_t(){}
};

#define TYPEDARG(...) \
  typename std::decay<decltype(__VA_ARGS__)>::type, \
  __VA_ARGS__

Now constant_t<TYPEDARG(foo)> is a type whose instances can be invoked if foo is a non-overloaded function and they call foo.

In c++17 this becomes:

template<auto x>
using constant_t=std::integral_constant<std::decay_t<decltype(x)>,x>;

and use is simply constant_t<foo>, without all that extra noise.

template<class Fn, class R, class... Args>
R test(Args&&... args) {
  return Fn{}(std::forward<Args>(args)...);
}

int foo( int a, int b ) { return a+b; }

int r = test< constant_t<TYPEDARG(foo)>, int, int, int >( 3, 4 );


问:
Regex: Disable Symbols
Is there any way to disable all symbols, punctuations, block elements, geometric shapes and dingbats such like these:

✁ ✂ ✃ ✄ ✆ ✇ ✈ ✉ ✌ ✍ ✎ ✏ ✐ ✑ ✒ ✓ ✔ ✕  ⟻ ⟼ ⟽ ⟾ ⟿  ⟻ ⟼ ⟽ ⟾ ⟿ ▚ ▛ ▜ ▝ ▞ ▟

without writing down all of them in the Regular Expression Pattern, while enable all other normal language characters such like chinese, arabic etc.. such like these:

文化中国 الجزيرة نت

?

I'm building a javascript validation function and my real problem is that I can't use:

```<code>[a-zA-Z0-9]
</code>```

Because this ignores a lots of languages too not just the symbols.

答: The Unicode standard divides up all the possible characters into code charts. Each code chart contains related characters. If you want to exclude (or include) only certain classes of characters, you will have to make a suitable list of exclusions (or inclusions). Unicode is big, so this might be a lot of work.</p>

Title: Regex: Disable Symbols

Body:
Is there any way to disable all symbols, punctuations, block elements, geometric shapes and dingbats such like these:

✁ ✂ ✃ ✄ ✆ ✇ ✈ ✉ ✌ ✍ ✎ ✏ ✐ ✑ ✒ ✓ ✔ ✕  ⟻ ⟼ ⟽ ⟾ ⟿  ⟻ ⟼ ⟽ ⟾ ⟿ ▚ ▛ ▜ ▝ ▞ ▟

without writing down all of them in the Regular Expression Pattern, while enable all other normal language characters such like chinese, arabic etc.. such like these:

文化中国 الجزيرة نت

?

I'm building a javascript validation function and my real problem is that I can't use:

[a-zA-Z0-9]

Because this ignores a lots of languages too not just the symbols.


问:
disable right click without js and css
This is a random Chinese website http://www.soap-china.com/index.asp

I noticed that right click is disabled. I always have JavaScript off, so I started delete node by node, css line by line in Firebag, but didn't find out what is disabling right click.

How does it work?

This is not first time I see this, so I am curious about this trick.

答:
The best way to do this :

```<code><script type="text/javascript">
document.oncontextmenu =new Function("return false;")
document.onselectstart =new Function("return false;")
</script>
</code>```

Good luck.

Title: disable right click without js and css

Body:
The best way to do this :

<script type="text/javascript">
document.oncontextmenu =new Function("return false;")
document.onselectstart =new Function("return false;")
</script>

Good luck.