text:
Q: Segmentation fault with a linked stack trying to evaluate postfix expressions I am attempting to implement a linked stack to evaluate post fix expressions however I keep getting a segmentation fault and not sure how to go about fixing it. I'm new to c programming which is different from OOD so any advice is welcomed. Thank you & please excuse my comments and spacing.
 #include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

struct node {
int data;
struct node *next;
};
 struct node *top = NULL;

void push(int data);
int pop();
int evaluatePostfix(char* exp);

void main() {
     char postfixExp[256];

     printf("What is your Postfix Expression? : \n");

     fgets(postfixExp, sizeof(postfixExp), stdin);
     printf("%d\n", evaluatePostfix(postfixExp));
}

//done
void push(int data) {
     struct node *newNode;
     newNode = (struct node*)malloc(sizeof(struct node));;
     (*newNode).data = data;
     (*newNode).next = NULL;
     //use isEmpty if can
     if (top != NULL) {
         (*newNode).next = top;
     }
     top = newNode;
}
//done
int pop() {
    struct node *temp = top;
    int *remove;
    //use isEmpty if can
    if (top != NULL) {
        *remove = (*top).data;
        top = (*top).next;
        free(temp);
    }
return *remove;

}

 int evaluatePostfix(char* exp) {
     struct node *top = NULL;
     for (int i = 0; i < sizeof(exp); i++) {
      if (isdigit(exp[i])) {
        push(exp[i]);
    } else {
        int val1 = pop();
        int val2 = pop();
        switch(exp[i]) {
            case '+':
                push(val2+val1);
                break;
            case '-':
                push(val2-val1);
                break;
            case '*':
                push(val2*val1);
                break;
            case '/':
                push(val2/val1);
                break;
        }
    }
}
return pop();

}

A: I have fully undestood your error the error in value is attributed to many factors

*

*pointed out by @Eugene Sh. int remove change it data type to integer

*the loop you are iterating is twice the size of expression since you are using constant literal you should use for (int i = 0; i < strlen(exp)-1; i++) subtracting 1 because of \0

*what you are doing here is

   if (isdigit(exp[i])) {
    push(exp[i]);
} else {
    int val1 = pop();
    int val2 = pop();

since 34+ be an expression then you checked using isdigit(exp[i])

isdigit(exp[i]) only check the passed character is a decimal digit character.

subtract (exp[i]) with 48 ascii value of 0 to convert decimal ascii character to integer
modify your code like this

*

*

 int pop() {
struct node *temp = top;
int removed;
//use isEmpty if can
if (top != NULL) {
    removed = (*top).data;
    top = (*top).next;
    free(temp);
 }
 return removed;
}

2&3.

for (int i = 0; i < strlen(exp)-1; i++) {
  if (isdigit(exp[i])) {
    push(exp[i]-48);
} else {
    int val1 = pop();
    int val2 = pop();
printf("val1%d\n",val1);
printf("val2%d\n",val2);

your working code
    http://ideone.com/z58Phy


text:
Q: WCF Routing Service - Dynamic Error Handling I'm learning about what can be done with the WCF Routing Service. Still at the 'screwing around with it to see what it can do' phase.
My understanding of the Routing Service is that when a message comes through, the service will try to pass it on to whichever endpoint appears first in the backup list. If that fails, it will then go on to try the next, and then the next, until either something works or there's nothing left to try.
What I would like to do is get access to that failure event so that I can:

*

*Log the failure

*Send a notification via email that the endpoint is failing

*Optionally remove the endpoint from the backup list so that it won't slow down future messages from flowing through the system

Having trouble finding how to extend the WCF framework to get at this particular event.
Is this a thing that the WCF Routing Service can do? Any nudge in the right direction would be greatly appreciated.

At the moment I have 30-ish dynamically generated routing services hosted under IIS (or to be more precise, the ASP.NET Development Server for Visual Studio 2010). I'm setting up the routes to the services in Global.asax as below.
    protected void Application_Start(object sender, EventArgs e)
    {
        List<Type> serviceTypes = ServiceUtility.GetServiceTypes();
        foreach (Type st in serviceTypes)
        {
            string route = String.Format("Services/{0}.svc", ServiceUtility.GetServiceName(st));
            RouteTable.Routes.Add(new ServiceRoute(route, new RoutingServiceHostFactory(st), typeof(System.ServiceModel.Routing.RoutingService)));
        }
    }

ServiceUtility and RoutingServiceHostFactory are custom classes. Note that IPolicyService is a WCF service contract interface in the assembly that I'm interested in.
public static class ServiceUtility
{
    public static List<Type> GetServiceTypes()
    {
        Type policyInterfaceType = typeof(IPolicyService);
        Assembly serviceContractsAssembly = Assembly.GetAssembly(policyInterfaceType);
        Type[] serviceContractsAssemblyTypes = serviceContractsAssembly.GetTypes();

        List<Type> serviceTypes = new List<Type>();
        foreach (Type t in serviceContractsAssemblyTypes)
        {
            if (!t.IsInterface)
                continue;

            object[] attrib = t.GetCustomAttributes(typeof(ServiceContractAttribute), false);
            if (attrib == null || attrib.Length <= 0)
                continue;

            serviceTypes.Add(t);
        }

        return serviceTypes;
    }

    // Other stuff
}

I'm generating my ServiceHosts as follows. I've omitted some of my helper methods for brevity.
public class RoutingServiceHostFactory : ServiceHostFactory
{
    private Type BackendServiceType { get; set; }
    private Binding BackendServiceBinding { get; set; }

    public RoutingServiceHostFactory(Type backendServiceType)
    {
        this.BackendServiceType = backendServiceType;
        this.BackendServiceBinding = ServiceUtility.GetBinding(this.BackendServiceType);
    }

    private const string DOMAIN_LIVE = "http://localhost:2521/";
    private const string DOMAIN_DEAD_1 = "http://localhost:2522/";
    private const string DOMAIN_DEAD_2 = "http://localhost:2524/";
    private const string DOMAIN_DEAD_3 = "http://localhost:2525/";
    private const string DOMAIN_DEAD_4 = "http://localhost:2526/";
    private const string DOMAIN_DEAD_5 = "http://localhost:2527/";

    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        ServiceHost host = base.CreateServiceHost(serviceType, baseAddresses);

        this.BindEndpoints(host, baseAddresses);
        this.ConfigureRoutingBehavior(host);
        this.ConfigureServiceMetadataBehavior(host);
        this.ConfigureDebugBehavior(host);

        host.Description.Behaviors.Add(new RoutingServiceErrorHandlerInjector());

        return host;
    }

    // Other Stuff

    private void ConfigureRoutingBehavior(ServiceHost host)
    {
        string deadAddress1 = ServiceUtility.GetServiceUrl(DOMAIN_DEAD_1, this.BackendServiceType);
        string deadAddress2 = ServiceUtility.GetServiceUrl(DOMAIN_DEAD_2, this.BackendServiceType);
        string deadAddress3 = ServiceUtility.GetServiceUrl(DOMAIN_DEAD_3, this.BackendServiceType);
        string deadAddress4 = ServiceUtility.GetServiceUrl(DOMAIN_DEAD_4, this.BackendServiceType);
        string deadAddress5 = ServiceUtility.GetServiceUrl(DOMAIN_DEAD_5, this.BackendServiceType);
        string realAddress = ServiceUtility.GetServiceUrl(DOMAIN_LIVE, this.BackendServiceType);

        RoutingConfiguration rc = new RoutingConfiguration();

        ContractDescription contract = new ContractDescription("IRequestReplyRouter");
        ServiceEndpoint deadDestination1 = new ServiceEndpoint(contract, this.BackendServiceBinding, new EndpointAddress(deadAddress1));
        ServiceEndpoint deadDestination2 = new ServiceEndpoint(contract, this.BackendServiceBinding, new EndpointAddress(deadAddress2));
        ServiceEndpoint deadDestination3 = new ServiceEndpoint(contract, this.BackendServiceBinding, new EndpointAddress(deadAddress3));
        ServiceEndpoint deadDestination4 = new ServiceEndpoint(contract, this.BackendServiceBinding, new EndpointAddress(deadAddress4));
        ServiceEndpoint deadDestination5 = new ServiceEndpoint(contract, this.BackendServiceBinding, new EndpointAddress(deadAddress5));
        ServiceEndpoint realDestination = new ServiceEndpoint(contract, this.BackendServiceBinding, new EndpointAddress(realAddress));

        List<ServiceEndpoint> backupList = new List<ServiceEndpoint>();
        backupList.Add(deadDestination1);
        backupList.Add(deadDestination2);
        backupList.Add(deadDestination3);
        backupList.Add(deadDestination4);
        backupList.Add(deadDestination5);
        backupList.Add(realDestination);

        rc.FilterTable.Add(new MatchAllMessageFilter(), backupList);

        RoutingBehavior rb = new RoutingBehavior(rc);

        host.Description.Behaviors.Add(rb);
    }

    // Other Stuff
}

Port 2521 has an actual website on the other end that is hosting some WCF services. The other ports referenced above have nothing listening.
For context, here's my Web.config for the routing site. Note that the time-outs and such are just the result of my screwing around, don't take them too seriously.
<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>

  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
    <bindings>
      <wsHttpBinding>
        <binding
          name="TestBinding"
          allowCookies="True"
          closeTimeout="00:04:00"
          openTimeout="00:00:10"
          receiveTimeout="00:05:00"
          sendTimeout="00:05:00"
          maxReceivedMessageSize="15728640">
          <security>
            <message establishSecurityContext="true" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
  </system.serviceModel>
</configuration>

EDIT
In response to TheDoctor's answer below, I thought I should expand on what I've been doing with this attempted solution since I originally posted. I've tried implementing the IErrorHandler interface. However, I haven't had much luck with it.
Note that in the example above, my RoutingServiceHostFactory has changed slightly. I am now adding on the RoutingServiceErrorHandlerInjector behaviour to the service description. Note that I have also added extra dead endpoints to my backup list for the purpose of illustration.
public class RoutingServiceErrorHandlerInjector : IServiceBehavior
{
    #region IServiceBehavior Members

    public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
    {

    }

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
    {
        foreach (ChannelDispatcher chanDisp in serviceHostBase.ChannelDispatchers)
        {
            chanDisp.ErrorHandlers.Add(new RoutingServiceErrorHandler());
        }
    }

    public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
    {

    }

    #endregion
}

public class RoutingServiceErrorHandler : IErrorHandler
{
    #region IErrorHandler Members

    public bool HandleError(Exception error)
    {
        throw new NotImplementedException(error.Message, error);

    }

    public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
    {
        throw new NotImplementedException(error.Message, error);
    }

    #endregion
}

My expectation was that I should trigger a ProvideFault or a HandleError event for deadDestination1 through to deadDestination5. I have breakpoints in place on the NotImplementedExceptions above in my debugger. But that code is never activated. The calls eventually make it through to the real address at the end of the backup list, and the client/server application I'm using to test this RoutingService runs fine. Communication is slower but still well within the timeout limits.
However, if I comment out the line backupList.Add(realDestination); from the ConfigureRoutingBehavior method above, then the RoutingServiceErrorHandler.ProvideFault method IS excercised... But it only contains the information relating to deadDestination5. Any exceptions or errors that may have been generated for deadDestination1 through deadDestination4 just disappear on me.
Furthermore, I've had a go with the RedGate debugger stepping through the reflected code for RoutingService. It was tricky for me as I'm not used to debugging optimized code, so there were hardly any variables available for me to actually read. But from eyeballing the stepthrough of the logic below:
// This has been taken from System.ServiceModel.Routing.RoutingService
// via the RedGate decompiler - unsure about it's ultimate accuracy.
[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed), ServiceBehavior(AddressFilterMode=AddressFilterMode.Any, InstanceContextMode=InstanceContextMode.PerSession, UseSynchronizationContext=false, ValidateMustUnderstand=false)]
public sealed class RoutingService : ISimplexDatagramRouter, ISimplexSessionRouter, IRequestReplyRouter, IDuplexSessionRouter, IDisposable
{
    [OperationBehavior(Impersonation=ImpersonationOption.Allowed), TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
    IAsyncResult IRequestReplyRouter.BeginProcessRequest(Message message, AsyncCallback callback, object state)
    {
        return this.BeginProcessRequest<IRequestReplyRouter>(message, callback, state);
    }

    private IAsyncResult BeginProcessRequest<TContract>(Message message, AsyncCallback callback, object state)
    {
        IAsyncResult result;
        try
        {
            System.ServiceModel.Routing.FxTrace.Trace.SetAndTraceTransfer(this.ChannelExtension.ActivityID, true);
            result = new ProcessRequestAsyncResult<TContract>(this, message, callback, state);
        }
        catch (Exception exception)
        {
            if (TD.RoutingServiceProcessingFailureIsEnabled())
            {
                TD.RoutingServiceProcessingFailure(this.eventTraceActivity, OperationContext.Current.Channel.LocalAddress.ToString(), exception);
            }
            throw;
        }
        return result;
    }
}

Relevant sections from System.ServiceModel.Routing.ProcessRequestAsyncResult shown below. These are also from debugging via RedGate, so cannot modify. I'm trusting that RedGate and the released source from Microsoft are accurate. #hesaiddubiously
internal class ProcessRequestAsyncResult<TContract> : TransactedAsyncResult
{
    public ProcessRequestAsyncResult(RoutingService service, Message message, AsyncCallback callback, object state) : base(callback, state)
    {
        this.allCompletedSync = true;
        this.service = service;
        this.messageRpc = new System.ServiceModel.Routing.MessageRpc(message, OperationContext.Current, service.ChannelExtension.ImpersonationRequired);
        if (TD.RoutingServiceProcessingMessageIsEnabled())
        {
            TD.RoutingServiceProcessingMessage(this.messageRpc.EventTraceActivity, this.messageRpc.UniqueID, message.Headers.Action, this.messageRpc.OperationContext.EndpointDispatcher.EndpointAddress.Uri.ToString(), (this.messageRpc.Transaction != null) ? "True" : "False");
        }
        try
        {
            EndpointNameMessageFilter.Set(this.messageRpc.Message.Properties, service.ChannelExtension.EndpointName);
            this.messageRpc.RouteToSingleEndpoint<TContract>(this.service.RoutingConfig);
        }
        catch (MultipleFilterMatchesException exception)
        {
            throw System.ServiceModel.Routing.FxTrace.Exception.AsError(new ConfigurationErrorsException(System.ServiceModel.Routing.SR.ReqReplyMulticastNotSupported(this.messageRpc.OperationContext.Channel.LocalAddress), exception));
        }
        while (this.StartProcessing())
        {
        }
    }

    private bool StartProcessing()
    {
        bool flag = false;
        SendOperation operation = this.messageRpc.Operations[0];
        this.currentClient = this.service.GetOrCreateClient<TContract>(operation.CurrentEndpoint, this.messageRpc.Impersonating);
        if (TD.RoutingServiceTransmittingMessageIsEnabled())
        {
            TD.RoutingServiceTransmittingMessage(this.messageRpc.EventTraceActivity, this.messageRpc.UniqueID, "0", this.currentClient.Key.ToString());
        }
        try
        {
            Message message;
            if ((this.messageRpc.Transaction != null) && operation.HasAlternate)
            {
                throw System.ServiceModel.Routing.FxTrace.Exception.AsError(new ConfigurationErrorsException(System.ServiceModel.Routing.SR.ErrorHandlingNotSupportedReqReplyTxn(this.messageRpc.OperationContext.Channel.LocalAddress)));
            }
            if (operation.AlternateEndpointCount > 0)
            {
                message = this.messageRpc.CreateBuffer().CreateMessage();
            }
            else
            {
                message = this.messageRpc.Message;
            }
            operation.PrepareMessage(message);
            IAsyncResult result = null;
            using (base.PrepareTransactionalCall(this.messageRpc.Transaction))
            {
                using (IDisposable disposable = null)
                {
                    try
                    {
                    }
                    finally
                    {
                        disposable = this.messageRpc.PrepareCall();
                    }
                    result = this.currentClient.BeginOperation(message, this.messageRpc.Transaction, base.PrepareAsyncCompletion(ProcessRequestAsyncResult<TContract>.operationCallback), this);
                }
            }
            if (!base.CheckSyncContinue(result))
            {
                return flag;
            }
            if (this.OperationComplete(result))
            {
                base.Complete(this.allCompletedSync);
                return flag;
            }
            return true;
        }
        catch (Exception exception)
        {
            if (Fx.IsFatal(exception))
            {
                throw;
            }
            if (!this.HandleClientOperationFailure(exception))
            {
                throw;
            }
            return true;
        }
    }
}

To my superficial reading, it appears to me that the ProcessRequestAsyncResult is doing the work of stepping through the backup list via the ProcessRequestAsyncResult.StartProcessing method. However, StartProcess() doesn't appear to be throwing every single exception, but rather it selectively chooses whether or not to throw exceptions.
It seems that only the exception for the final dead address is actually being thrown by StartProcess(), then passed up by the RoutingService.BeginProcessRequest catch clause, only to then finally make it all the way to an activation in my IErrorHandler implementation.
This strongly suggests to me that what I'm trying to do here cannot be done with the current implementation of the System.ServiceModel.Routing namespace. Note that RoutingService is a sealed class, so I cannot extend it with a base class of my own to change this behaviour even if I thought that was a good idea (which I don't).
But then again, note that this is a superficial reading. I could easily be wrong. In fact, I would very much like to be proven wrong. I'd vastly prefer to find a way to get the RoutingService to do what I want it to do rather than having to roll my own.

A: WCF provides error handling (http://msdn.microsoft.com/en-us/library/ee517422.aspx), so you could create a function that activates on a CommunicationException (http://msdn.microsoft.com/en-us/library/system.servicemodel.communicationexception.aspx) and logs the error codes from the data passed to the function. You could the go from there to a mail rooting service and whatever else you need.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why do we believe space and time are intertwined? What is the idea behind it? And how do we arrive at this conclusion? What led us to believe that space and time are actually interconnected? How did the idea actually originate? why do we believe that this concept is true?

A: Relativity tells us that when under high enough gravitational fields or high enough speeds, the dynamic nature of time arises. That means that for an observer, you could be in some place in space (that seems normal) but also in some place in time (which is the counterintuitive part).
Therefore, you would have coordinates not only for space, but also in time (search for "spacetime diagram").
Having another coordinate means having another dimension, so we consider time to be another dimension, all of that is motivated by it's dynamic nature.
On the other hand, Newton considered time to be absolute for everybody, that means that everybody would have the same coordinate in time, thus, it makes no sense to consider it another dimension.


text:
Q: Debug failed kubernetes deployment I am experimenting with Kubernetes on Digital Ocean.
As a testcase, i am trying to deploy a Jenkins instance to my cluster with a persistent volume.
My deployment yaml:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: jenkins-deployment
  labels:
    app: jenkins
spec:
  replicas: 1
  selector:
    matchLabels:
      app: jenkins
  template:
    metadata:
      labels:
        app: jenkins
    spec:
      containers:
      - name: jenkins
        image: jenkins/jenkins:lts
        ports:
          - containerPort: 8080
        volumeMounts:
          - name: jenkins-home
            mountPath: /var/jenkins_home
      volumes:
        - name: jenkins-home
          persistentVolumeClaim:
            claimName: jenkins-pvc

My PV Claim
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: jenkins-pvc
spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: do-block-storage
  resources:
    requests:
      storage: 30Gi

For some reason the pod keeps ending up in a CrashLoopBackOff state.
kubectl describe pod <podname> gives me
Name:           jenkins-deployment-bb5857d76-j2f2w
Namespace:      default
Priority:       0
Node:           cc-pool-bg6c/10.138.123.186
Start Time:     Sun, 15 Sep 2019 22:18:56 +0200
Labels:         app=jenkins
                pod-template-hash=bb5857d76
Annotations:    <none>
Status:         Running
IP:             10.244.0.166
Controlled By:  ReplicaSet/jenkins-deployment-bb5857d76
Containers:
  jenkins:
    Container ID:   docker://4eaadebb917001d8d3eaaa3b043e1b58b6269f929b9e95c4b08d88b0098d29d6
    Image:          jenkins/jenkins:lts
    Image ID:       docker-pullable://jenkins/jenkins@sha256:7cfe34701992434cc08bfd40e80e04ab406522214cf9bbefa57a5432a123b340
    Port:           8080/TCP
    Host Port:      0/TCP
    State:          Waiting
      Reason:       CrashLoopBackOff
    Last State:     Terminated
      Reason:       Error
      Exit Code:    1
      Started:      Sun, 15 Sep 2019 22:35:14 +0200
      Finished:     Sun, 15 Sep 2019 22:35:14 +0200
    Ready:          False
    Restart Count:  8
    Environment:    <none>
    Mounts:
      /var/jenkins_home from jenkins-home (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-wd6p7 (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   False
  PodScheduled      True
Volumes:
  jenkins-home:
    Type:       PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
    ClaimName:  jenkins-pvc
    ReadOnly:   false
  default-token-wd6p7:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-wd6p7
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason                  Age                  From                     Message
  ----     ------                  ----                 ----                     -------
  Normal   Scheduled               19m                  default-scheduler        Successfully assigned default/jenkins-deployment-bb5857d76-j2f2w to cc-pool-bg6c
  Normal   SuccessfulAttachVolume  19m                  attachdetach-controller  AttachVolume.Attach succeeded for volume "pvc-cb772fdb-492b-4ef5-a63e-4e483b8798fd"
  Normal   Pulled                  17m (x5 over 19m)    kubelet, cc-pool-bg6c    Container image "jenkins/jenkins:lts" already present on machine
  Normal   Created                 17m (x5 over 19m)    kubelet, cc-pool-bg6c    Created container jenkins
  Normal   Started                 17m (x5 over 19m)    kubelet, cc-pool-bg6c    Started container jenkins
  Warning  BackOff                 4m8s (x72 over 19m)  kubelet, cc-pool-bg6c    Back-off restarting failed container

Could anyone help me point out what is wrong here, or where to look for that matter?
Many thanks in advance.

A: Looks like you don't have permission to write to the volume.
Try running the container as root using security contexts:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: jenkins-deployment
  labels:
    app: jenkins
spec:
  replicas: 1
  selector:
    matchLabels:
      app: jenkins
  template:
    metadata:
      labels:
        app: jenkins
    spec:
      securityContext:
        fsGroup: 1000
        runAsUser: 0
      containers:
      - name: jenkins
        image: jenkins/jenkins:lts
        ports:
          - containerPort: 8080
        volumeMounts:
          - name: jenkins-home
            mountPath: /var/jenkins_home
      volumes:
        - name: jenkins-home
          persistentVolumeClaim:
            claimName: jenkins-pvc

A: I cannot add comment (not enough reputation :D)
Looking at the pod logs may give some idea kubectl logs <podname>
PVC seems to be allocated and attached without issues. I had similar issues deploying nginx container a while ago, the issue was nginx container requires specific UID on host to work. Check if jenkins container needs specific UID.
Also, you may need to set required permissions on the volume (depending on jenkins requirement).


text:
Q: Virtual Functions: Iterating over a vector that is populated with subclass objects Short Description:
I am iterating over a vector calling a virtual function on every object in the vector in order to execute a sequence of actions.  The vector is of the base class as is the iterator.  All the objects are children.  When the virtual function is called it executes the base class's function.
(Really) Long Description:
I am attempting to model a creature that has a set of behaviors.  My base class is abstract with only two functions (virtual) which all the subclasses have overridden:
class Behavior
{
public:
     Behavior();
    ~Behavior(void){}
 virtual void execute(){}
 virtual BEHAVIOR_TYPE getType() {return m_Type;}

protected:
BEHAVIOR_TYPE m_Type;
};

I have created a number of children behaviors, such as move, consume, scout, etc.
class Move :
    public Behavior
{
public:
BEHAVIOR_TYPE getType() {return m_Type;}
    enum Direction {N, NE, E, SE, S, SW, W, NW};
Move(DOCO * d);
~Move(void);
void execute() ;
    Direction chooseDirection();
    void setDirection(Direction newDirection);
private:
    Direction m_Direction;
    DOCO *I;
BEHAVIOR_TYPE m_Type;

};

I created a vector onto which I pushed instances of each Behavior subclass as well as an iterator to traverse it:
vector<Behavior> m_Behavior;
vector<Behavior>::iterator bIt;

When the creature gets an action sequence, I try to iterate over the vector, dereference the iterator, and call the execute function:
void World::justDoIt()
{
    for(dIt=myDOCO.begin(); dIt!=myDOCO.end(); ++dIt)
{
    vector<Behavior>::iterator myBehavior=(dIt)->getFirstBehavior();
    vector<Behavior>::iterator end=(dIt)->getLastBehavior();
    for(myBehavior; myBehavior!=end; ++myBehavior)

        (*myBehavior).execute();
}
}

The problem is that it executes the parent's function rather than the child's function.
In my understanding of late binding it should automatically call the appropriate function based on the type of object that was calling it rather than the type of pointer with which it was called, and in my code I anticipated it would be pointing to the child object.
Obviously I have made an error and somehow told the program that I want these to be treated as parents instead of children, but I cannot find my error.
A second symptom is that it will not let me make the parents function pure virtual, because it says it cannot instantiate an abstract class.  I am not instantiating it explicitly anywhere in my code, but there must be somewhere I am doing it implicitly.  I cannot find where, however.  Certainly creating a vector to hold objects of the parent class does not require instantiating the parent, and that is the only time I reference the parent class directly.
Any help would be greatly appreciated.

A: You are adding instances of classes to the vector. This results in slicing.
What you need to do is add pointers to instances of behaviors, and modify the loop to do
(*myBehavior)->execute();

A: The class vector<Behavior> makes copies of whatever you store inside it, using the copy constructor Behavior::Behavior(const Behavior&);.  This destroys the polymorphism.  You need to use a pointer or smart pointer in the container instead:
vector<Behavior*> m_Behavior; // I will take care of new and delete
vector<shared_ptr<Behavior> > m_Behavior; // easier

If you don't have std::shared_ptr or std::tr1::shared_ptr in #include <memory> or similar, maybe you can use Boost's.


text:
Q: Custom Splash screen Silverlight issue I created a simple splash screen using Blend and then copied the contents to Splash.xaml in my Web project. This is the xaml :-
<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:ed="http://schemas.microsoft.com/expression/2010/drawing"

    d:DesignHeight="600" d:DesignWidth="800" mc:Ignorable="d">
    <Grid.Resources>
        <Storyboard x:Name="SplashStoryboard" RepeatBehavior="Forever" AutoReverse="True">
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Arc.StartAngle)" Storyboard.TargetName="arc">
                <EasingDoubleKeyFrame KeyTime="0:0:1.6" Value="90"/>
                <EasingDoubleKeyFrame KeyTime="0:0:3.5" Value="180"/>
            </DoubleAnimationUsingKeyFrames>
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Arc.EndAngle)" Storyboard.TargetName="arc">
                <EasingDoubleKeyFrame KeyTime="0:0:1.6" Value="180"/>
                <EasingDoubleKeyFrame KeyTime="0:0:3.5" Value="270"/>
            </DoubleAnimationUsingKeyFrames>
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Arc.StartAngle)" Storyboard.TargetName="arc1">
                <EasingDoubleKeyFrame KeyTime="0:0:1.6" Value="180"/>
                <EasingDoubleKeyFrame KeyTime="0:0:3.5" Value="270"/>
            </DoubleAnimationUsingKeyFrames>
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Arc.EndAngle)" Storyboard.TargetName="arc1">
                <EasingDoubleKeyFrame KeyTime="0:0:1.6" Value="270"/>
                <EasingDoubleKeyFrame KeyTime="0:0:3.5" Value="360"/>
            </DoubleAnimationUsingKeyFrames>
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Arc.StartAngle)" Storyboard.TargetName="arc2">
                <EasingDoubleKeyFrame KeyTime="0:0:1.6" Value="270"/>
                <EasingDoubleKeyFrame KeyTime="0:0:3.5" Value="0"/>
            </DoubleAnimationUsingKeyFrames>
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Arc.EndAngle)" Storyboard.TargetName="arc2">
                <EasingDoubleKeyFrame KeyTime="0:0:1.6" Value="360"/>
                <EasingDoubleKeyFrame KeyTime="0:0:3.5" Value="90"/>
            </DoubleAnimationUsingKeyFrames>
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Arc.StartAngle)" Storyboard.TargetName="arc3">
                <EasingDoubleKeyFrame KeyTime="0:0:1.6" Value="0"/>
                <EasingDoubleKeyFrame KeyTime="0:0:3.5" Value="90"/>
            </DoubleAnimationUsingKeyFrames>
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Arc.EndAngle)" Storyboard.TargetName="arc3">
                <EasingDoubleKeyFrame KeyTime="0:0:1.6" Value="90"/>
                <EasingDoubleKeyFrame KeyTime="0:0:3.5" Value="180"/>
            </DoubleAnimationUsingKeyFrames>
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Arc.StartAngle)" Storyboard.TargetName="arc4">
                <EasingDoubleKeyFrame KeyTime="0:0:1.6" Value="0"/>
                <EasingDoubleKeyFrame KeyTime="0:0:3.5" Value="90"/>
            </DoubleAnimationUsingKeyFrames>
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Arc.EndAngle)" Storyboard.TargetName="arc4">
                <EasingDoubleKeyFrame KeyTime="0:0:1.6" Value="90"/>
                <EasingDoubleKeyFrame KeyTime="0:0:3.5" Value="180"/>
            </DoubleAnimationUsingKeyFrames>
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Arc.StartAngle)" Storyboard.TargetName="arc5">
                <EasingDoubleKeyFrame KeyTime="0:0:1.6" Value="180"/>
                <EasingDoubleKeyFrame KeyTime="0:0:3.5" Value="270"/>
            </DoubleAnimationUsingKeyFrames>
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Arc.EndAngle)" Storyboard.TargetName="arc5">
                <EasingDoubleKeyFrame KeyTime="0:0:1.6" Value="270"/>
                <EasingDoubleKeyFrame KeyTime="0:0:3.5" Value="360"/>
            </DoubleAnimationUsingKeyFrames>
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Arc.StartAngle)" Storyboard.TargetName="arc7">
                <EasingDoubleKeyFrame KeyTime="0:0:1.6" Value="180"/>
                <EasingDoubleKeyFrame KeyTime="0:0:3.5" Value="0"/>
            </DoubleAnimationUsingKeyFrames>
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Arc.EndAngle)" Storyboard.TargetName="arc7">
                <EasingDoubleKeyFrame KeyTime="0:0:1.6" Value="360"/>
                <EasingDoubleKeyFrame KeyTime="0:0:3.5" Value="180"/>
            </DoubleAnimationUsingKeyFrames>
        </Storyboard>
    </Grid.Resources>

    <Grid x:Name="LayoutRoot" Background="White">
        <Image Source="ServerImages/Orange.jpg" Stretch="Fill"/>
        <ed:Arc x:Name="arc" ArcThickness="0" ArcThicknessUnit="Pixel" Fill="#FFF4F4F5" Margin="0" Stretch="None" Stroke="#FF811902" StartAngle="0" UseLayoutRounding="False" Width="400" Height="400" HorizontalAlignment="Center" VerticalAlignment="Center" StrokeThickness="4" StrokeStartLineCap="Round" StrokeEndLineCap="Round"/>
        <ed:Arc x:Name="arc1" ArcThickness="0" ArcThicknessUnit="Pixel" EndAngle="180" Fill="#FFF4F4F5" Margin="0" Stretch="None" Stroke="#FF811902" StartAngle="90" UseLayoutRounding="False" Width="350" Height="350" HorizontalAlignment="Center" VerticalAlignment="Center" StrokeThickness="4" StrokeStartLineCap="Round" StrokeEndLineCap="Round"/>
        <ed:Arc x:Name="arc2" ArcThickness="0" ArcThicknessUnit="Pixel" EndAngle="270" Fill="#FFF4F4F5" Margin="0" Stretch="None" Stroke="#FF811902" StartAngle="180" UseLayoutRounding="False" Width="450" Height="450" HorizontalAlignment="Center" VerticalAlignment="Center" StrokeThickness="4" StrokeStartLineCap="Round" StrokeEndLineCap="Round"/>
        <ed:Arc x:Name="arc3" ArcThickness="0" ArcThicknessUnit="Pixel" EndAngle="360" Fill="#FFF4F4F5" Margin="0" Stretch="None" Stroke="#FF811902" StartAngle="270" UseLayoutRounding="False" Width="300" Height="300" HorizontalAlignment="Center" VerticalAlignment="Center" StrokeThickness="4" StrokeStartLineCap="Round" StrokeEndLineCap="Round"/>
        <ed:Arc x:Name="arc4" ArcThickness="0" ArcThicknessUnit="Pixel" EndAngle="360" Fill="#FFF4F4F5" Margin="0" Stretch="None" Stroke="#FF811902" StartAngle="270" UseLayoutRounding="False" Width="500" Height="500" HorizontalAlignment="Center" VerticalAlignment="Center" StrokeThickness="4" StrokeStartLineCap="Round" StrokeEndLineCap="Round"/>
        <ed:Arc x:Name="arc5" ArcThickness="0" ArcThicknessUnit="Pixel" EndAngle="180" Fill="#FFF4F4F5" Margin="0" Stretch="None" Stroke="#FF811902" StartAngle="90" UseLayoutRounding="False" Width="500" Height="500" HorizontalAlignment="Center" VerticalAlignment="Center" StrokeThickness="4" StrokeStartLineCap="Round" StrokeEndLineCap="Round"/>
        <ed:Arc x:Name="arc7" ArcThickness="0" ArcThicknessUnit="Pixel" Fill="#FFF4F4F5" Margin="0" Stretch="None" Stroke="#FF811902" UseLayoutRounding="False" Width="250" Height="250" HorizontalAlignment="Center" VerticalAlignment="Center" StrokeThickness="4" StrokeStartLineCap="Round" StrokeEndLineCap="Round" EndAngle="270"/>
        <TextBlock x:Name="tbProgress" Margin="0" TextWrapping="Wrap" Text="0" d:LayoutOverrides="Width, Height" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="64" FontWeight="Bold" Foreground="#FF451701"/>
    </Grid>
</Grid>

Problem however is xmlns:ed="http://schemas.microsoft.com/expression/2010/drawing" is not recognized because it inside SDK's folder. How do i get pass this issue? Where should i add this reference of dll. Put in other words i won't be able to use shapes in splash screen?
Thanks in advance :)

A: In this video it mentions that you can only use functionality that's part of the core Silverlight runtime.  I'm guessing that's the problem here.


text:
Q: How to speed up simulation time of simulink for fuzzy controllers I have implemented fuzzy controller in simulink as shown below. Fuzzy controller has two inputs with three membership functions and 9 rules.The issue is that; that the simulink is taking too long time to run it. What could be the issue. Any guidance.

A: go to configuration parameters --> solver --> zero crossing option and turn it to disable, it would help you.


text:
Q: Move Product to draft automatically if published in a specific category I need if a Product published in a specific category in woocommerce, to move to draft automatically.
I need this operation to be done  in the background and work if product added from api
I used this code and it worked but not if product added from API:
add_action( 'transition_post_status', 'auto_draft_on_category', 10, 3 );

function auto_draft_on_category( $new_status, $old_status, $post ) {
    if ( $post->post_type == 'product' && has_term( 'your-category-slug', 'product_cat', $post ) && $new_status == 'publish' ) {
        wp_update_post( array(
            'ID' => $post->ID,
            'post_status' => 'draft'
        ) );
    }
}


text:
Q: Android asynchronous Task finishes before Firebasequery completed I want to execute some Firebasequery in an asynchronous Task. The Problem is that i have to call Thread.sleep(5000); to get the expected resultlist. Otherwise the List is always empty because the Task ends without waiting for completion of the Firebasequery.
The task is called from a backgroundservice and waits for the result via Task.execute().get();
Are there any possibilities to get the asynch Tasks result without calling Thread.sleep()?
     @Override
protected ArrayList<Product> doInBackground(InventoryCheckService... params) {
    this.service = params[0];
    result = new ArrayList<>();
    DatabaseReference userReference = DatabaseAdapter.getInstance().getUserReference();
    if(userReference != null){
        userReference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                HashMap<String, Product> changedProducts = dataSnapshot.getValue(new GenericTypeIndicator<HashMap<String, Product>>() {
                });
                if(changedProducts != null){
                    Iterator<String> iterator = changedProducts.keySet().iterator();
                    String nextExpirationDate = getDateForTommorow();
                    while (iterator.hasNext()) {
                        String nextKey = iterator.next();
                        Product product = changedProducts.get(nextKey);
                        if (product.getBestBeforeDate().containsKey(nextExpirationDate)) {
                            result.add(product);
                        }
                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    return result;
}

Thanks in advance for help! :)

A: Finally I solved my Issue. I wanted to raise an Intent after Taskexecution. Instead of starting the Intent from the Service, I used to put the Code into the asynchronous Task:
 @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            HashMap<String, Product> changedProducts = dataSnapshot.getValue(new GenericTypeIndicator<HashMap<String, Product>>() {
            });
            if(changedProducts != null){
                Iterator<String> iterator = changedProducts.keySet().iterator();
                String nextExpirationDate = getDateForTommorow();
                while (iterator.hasNext()) {
                    String nextKey = iterator.next();
                    Product product = changedProducts.get(nextKey);
                    if (product.getBestBeforeDate().containsKey(nextExpirationDate)) {
                        result.add(product);
                    }
                }
                 // start Intent here...
            }

Now I dont have to sleep until the Task is completed, because it is part of the Task to start the Intent.


text:
Q: Converting control characters to XML? The JPEG-2000 standard says that the file type box contains a series of compatibility list fields. It says this about each field:

This field is encoded as a four-byte string of ISO/IEC 646 characters.

Here is a compatibility list field from one JPEG-2000 file (hex bytes):
00 00 00 B5

How is that four-byte encoding of a string represented in XML, given that hex 00 (nul) is not a valid character in XML?


text:
Q: How to reshape the data in stacked format by merging two dataframes in r? Is there any function in R which can reshape the data in stacked format by merging two dataframes?
Table1
Vegetables|Onion|Potato|Tomato|
Cheap     |  20 |  30  |  40  |

Table2
Vegetables|Cabbage|Carrot|Cauliflower|Eggplant
Mid       |  20   |  30  |     40    |   30

Required Output
   Vegetables |  Type     |Quantity|
    Cheap     |  Onion    |   20   |
    Cheap     |  Potato   |   30   |
    Cheap     |  Tomato   |   40   |
    Mid       |  Cabbage  |   20   |
    Mid       |  Carrot   |   30   |
    Mid       |Cauliflower|   40   |
    Mid       |  Eggplant |   30   |

Thanks in advance for your help! you are awesome.

A: The name of the parameter you're trying to use is id.vars instead of id. Try melt(Table1,id.vars="Vegetable")
library(reshape2)
df1 <- data.frame(Vegetables="Cheap", Onion=20,Potato=30,Tomato=40)
df2 <- data.frame(Vegetables="Mid", Cabbage=20, Carrot=30,Cauliflower=40, Eggplant=30)
do.call("rbind", lapply(list(df1,df2),function(d){melt(d,id.vars="Vegetables", variable.name="Type", value.name="Quantity")}))

You can then insert all your tables into a list and simply use lapply. (The do.call then combines melted datasets into one)


text:
Q: Proof Verification: $\int_0^{2\pi}|\sin{((n-1)x)}|dx = 4$. Last year, I was trying to solve a trigonometric integral with absolute values depending on any positive integer $n$. After trying multiple methods, I decided to go with a slightly easier integral to see if I could gain some useful tools. The following is an attempt at proving a proposal I made up.
Proposal.  Let $n$ be a positive integer greater than $1$. Prove
$$\int_{0}^{2\pi}\left|\sin{(n-1)x}\right|dx = 4.$$
Proof. Let $f(x) = \sin{(n-1)x}$ and $I$ equal the given integral. The roots of $f(x)$ are obtained by
$$\sin{((n-1)x)} = 0 \implies (n-1)x = \pi k \implies x = \frac{\pi k}{n-1},$$
where $k$ is in some subset of $\mathbb{Z}$. To find that set, we can bound $k$ since $x \in \left[0,2\pi\right]$ like this:
$$0 \leq \frac{\pi k}{n-1} \leq 2\pi \iff 0 \leq k \leq 2n-2.$$
The set of roots of $f(x)$ is $\left\{\frac{\pi k}{n-1} \in \mathbb{R} : n \in \mathbb{N}\setminus\left\{1\right\} \text{ and } k \in \left\{0,1,2,\ldots,2n-2\right\}\right\}$. We will partition $I$ such that the lower and upper bounds are elements of the aforementioned set. We will make $I$ equal to two summations adding each other where the first one represents the sum of positive areas and the second one represents the sum of the other areas (that would have been negative if the absolute values weren't involved). To elaborate,
$$I = \sum_{i=0}^{n-2}\int_{\frac{2\pi i}{n-1}}^{\frac{\left(2i+1\right)\pi}{n-1}}f\left(x\right)dx\ +\ \sum_{i=0}^{n-2}\int_{\frac{\left(2i+1\right)\pi}{n-1}}^{\frac{2\pi i}{n-1}}-f\left(x\right)dx\ =\ 2\sum_{i=0}^{n-2}\int_{\frac{2\pi i}{n-1}}^{\frac{\left(2i+1\right)\pi}{n-1}}f\left(x\right)dx.$$
To further prove where this equation comes from, we will prove via induction that
$$\int_{0}^{2\pi}\left|\sin\left(\left(n-1\right)x\right)\right|dx\ =\ \ 2\sum_{i=0}^{n-2}\int_{\frac{2\pi i}{n-1}}^{\frac{\left(2i+1\right)\pi}{n-1}}\sin\left(\left(n-1\right)x\right)dx.$$
Base Step. If $n = 2$, then the left side becomes
$$\int_{0}^{2\pi}\left|\sin\left(\left(n-1\right)x\right)\right|dx = \int_{0}^{2\pi}\left|\sin\left(\left(2-1\right)x\right)\right|dx = 4.$$
The right side becomes
$$2\sum_{i=0}^{n-2}\int_{\frac{2\pi i}{n-1}}^{\frac{\left(2i+1\right)\pi}{n-1}}\sin\left(\left(n-1\right)x\right)dx = 2\sum_{i=0}^{2-2}\int_{\frac{2\pi i}{2-1}}^{\frac{\left(2i+1\right)\pi}{2-1}}\sin\left(\left(2-1\right)x\right)dx = 4.$$
Inductive Step. Fix $n = k$ and suppose
$$\int_{0}^{2\pi}\left|\sin\left(\left(k-1\right)x\right)\right|dx\ =\ \ 2\sum_{i=0}^{k-2}\int_{\frac{2\pi i}{k-1}}^{\frac{\left(2i+1\right)\pi}{k-1}}\sin\left(\left(k-1\right)x\right)dx.$$
We want to show
$$\int_{0}^{2\pi}\left|\sin\left(kx\right)\right|dx\ =\ \ 2\sum_{i=0}^{k-1}\int_{\frac{2\pi i}{k}}^{\frac{\left(2i+1\right)\pi}{k}}\sin\left(kx\right)dx.$$
We will manipulate the right side of that equation above like this:
$$\eqalign{
2\sum_{i=0}^{k-1}\int_{\frac{2\pi i}{k}}^{\frac{\left(2i+1\right)\pi}{k}}\sin\left(kx\right)dx &= 2\left(\sum_{i=0}^{k-2}\int_{\frac{2\pi i}{k}}^{\frac{\left(2i+1\right)\pi}{k}}\sin\left(kx\right)dx\ +\ \int_{\frac{2\pi\left(k-1\right)}{k}}^{\frac{\left(2k-1\right)\pi}{k}}\sin\left(kx\right)dx\right) \cr
&= \frac{2\left(k-1\right)}{k}\sum_{i=0}^{k-2}\int_{\frac{2\pi i}{k-1}}^{\frac{\left(2i+1\right)\pi}{k-1}}\sin\left(\left(k-1\right)u\right)du+\frac{4}{k}
\text{ (after letting $kx = (k-1)u$)} \cr
&= \frac{k-1}{k}\int_{0}^{2\pi}\left|\sin\left(\left(k-1\right)x\right)\right|dx+\frac{4}{k} \text{ (by inductive hypothesis)} \cr
&= \frac{k-1}{k}\int_{0}^{\frac{2\pi\left(k-1\right)}{k}}\left|\sin\left(kv\right)\right|\left(\frac{k}{k-1}\right)dv+\frac{4}{k} \text{ (after letting $(k-1)x = kv$)} \cr
&= \int_{0}^{2\pi-\frac{2\pi}{k}}\left|\sin\left(kv\right)\right|dv+\frac{4}{k} \cr
&= \int_{0}^{2\pi}\left|\sin\left(kv\right)\right|dv\ -\ \int_{2\pi-\frac{2\pi}{k}}^{2\pi}\left|\sin\left(kv\right)\right|dv\ +\ \frac{4}{k} \cr
&= \int_{0}^{2\pi}\left|\sin\left(kv\right)\right|dv+\int_{0}^{-\frac{2\pi}{k}}\left|\sin\left(kv\right)\right|dv+\frac{4}{k} \cr
&= \int_{0}^{2\pi}\left|\sin\left(kv\right)\right|dv+\frac{1}{k}\int_{0}^{-2\pi}\left|\sin\left(w\right)\right|dw+\frac{4}{k} \text{ (after letting w = kv)} \cr
&= \int_{0}^{2\pi}\left|\sin\left(kx\right)\right|dx.
}$$
Therefore by Principal of Mathematical Induction, the induction proof is done.
Going back to the solution, we see
$$\eqalign{
I &= 2\sum_{i=0}^{n-2}\int_{\frac{2\pi i}{n-1}}^{\frac{\left(2i+1\right)\pi}{n-1}}\sin\left(\left(n-1\right)x\right)dx \cr
&= 2\sum_{i=0}^{n-2}\frac{1}{n-1}\left(\cos\left(2\pi i\right)-\cos\left(\left(2i+1\right)\pi\right)\right) \cr
&= 2\sum_{i=0}^{n-2}\frac{1}{n-1}\left(1+1\right) \cr
&= \frac{4}{n-1}\sum_{i=0}^{n-2}1 \cr
&= \frac{4}{n-1}\left(n-2+1\right) \cr
&= 4.
}$$
Q.E.D.
Is there a nicer way to prove that proposal? I know it's a lot of work but if anyone can find any optimizations/errors then please let me know. Or if you have any other ideas/solutions you want to add, I would greatly appreciate it!

A: A more general result: let $m$ and $n$ be positive integers. If $f$ is any periodic function of period $T$, by changing variable $t=nx$ we find
\begin{align}
\int_{0}^{mT} f(nx) dx&=\frac{1}{n}\int_{0}^{mnT} f(t)dt=
\frac{1}{n}\sum_{k=1}^{mn}\int_{(k-1)T}^{kT} f(t)dt\\
&=\frac{1}{n}\sum_{k=1}^{mn}\int_{0}^{T} f(t)dt=\frac{mn}{n}\int_{0}^{T} f(t) dt=m\int_{0}^{T} f(t) dt
\end{align}
where we apply:  Show that $\int_a^{a+T}f(t)dt=\int_0^Tf(t)dt$ for all $a$ when $f$ is $T-$periodic.
Notice that the final result does not depend on $n$.
When $f(x)=|\sin(x)|$ then $T=\pi$ and
$$\int_{0}^{T} f(t) dt=\int_{0}^{\pi} |\sin(t)| dt=\int_{0}^{\pi} \sin(t) dt=[-\cos(t)]_0^\pi=2.$$
Therefore
$$\int_{0}^{m\pi} |\sin(nx)| dx=2m.$$


text:
Q: "I hope all's well, and absolutely. " Meaning I have been stalking a bit one of my colleagues so that she would answer 4 of my e-mails that were asking her how our ongoing project was going forward.
Two weeks after, she sends me an e-mail update where I believe she was a bit pissed off... She started by writing the following :

Hi "MopMop",
I hope all's well, and absolutely. We have an [...] project ongoing and budget to plan.

I wanted to know what she meant by the "and absolutely". I really have issues communicating with that women see other post here and I would like to know if she told me that because she is annoyed of my behavior or it is just an expression that I oviously don't get..

A: I would put her failure to communicate down to carelessness and lack of time. Emails are not formal writing, more like conversation in text. In conversation, we use a practice known as "conversational deletion"—reducing syntax to the bare minimum to convey meaning.
Since you say you were requesting a meeting to get more information, her "absolutely" probably means that she "absolutely" agrees to the meeting.
Imagine you were speaking to her in person. The conversation would probably go something like this:

YOU: How are you doing?
SHE: Pretty good. I hope all is well with you.
YOU: Hey, can we have a meeting so I can get more information about the project's advancement.
SHE: Absolutely.

In that exchange the pleasantries are exchanged first and then the business at hand is discussed. In the email version, however, that would require multiple emails, so she is compressing those things together in one line.

1 I hope all's well, 2 and absolutely. 3 We have an [...] project ongoing and budget to plan.

[1] is just a pleasantry because she doesn't want to be too abrupt.
[2] is the meat of the business response, acceding to your request.
[3] This is further information. It's not clear whether this is germane to the discussion or not, but she apparently wants you to be aware of it in either case.
The important thing to remember is that you should parse email responses more as conversation than expository writing. That may help you to interpret them better.


text:
Q: Delete PDF file made in R I have created a couple of pdf's using the pdf() device and I can't seem to delete them from my computer. I received the following error when I ran my code.
> pdf(file="Appendix_B_1.pdf")
> plot(1:10)
> dev.off
function (which = dev.cur())
{
    if (which == 1)
        stop("cannot shut down device 1 (the null device)")
    .External(C_devoff, as.integer(which))
    dev.cur()
}
<bytecode: 0x0000000008c7ecd0>
<environment: namespace:grDevices>

Above is my attempt to trick the computer into thinking it is a new file.  It changed the file and I am able to open it. I just can't delete it.
I don't know what this means and all I want to do is delete the files.  Is there some workaround for either turning off the device or deleting the files from my hard drive?

A: dev.off is the name of a function.  When you type the name of a function, the source code for that function is printed.  If you want to run the function, add parenthesis: dev.off()


text:
Q: How to create a new column in the table that receives the value of a condition using postgreSQL? I have the following table in the postgres database (the table name is table_example):
       id          data_sensor_analog        data_sensor_dig         qtd
      1452               255                       0                   1
      2114               255                       1                   2
      2548               144                       0                   3
      8745               144                       1                   4
      7548               144                       0                   5
      8785               144                       1                   6

I need to create a new column in this table.
This column should receive 'LOW' if the 'qty' column is between [1, 2]. You should receive 'MEAN' if the column 'qty' is between [3, 4] and in other cases you should receive 'HIGH'.
I thought about creating a new column in the table as follows:
       ALTER TABLE table_example
       ADD Class_Output  Varchar(10)

This command creates the new column as desired. However, I don't know how I can do to assign the desired values to the new column.
      -- The desired output is:

       id          data_sensor_analog        data_sensor_dig         qtd           Class_Output
      1452               255                       0                   1              LOW
      2114               255                       1                   2              LOW
      2548               144                       0                   3              MEAN
      8745               144                       1                   4              MEAN
      7548               144                       0                   5              HIGH
      8785               144                       1                   6              HIGH

I thought about building something like the code below, but I don't know how I can combine it with the rest.
       IF (qtd >= 1 AND qtd <= 2) THEN
       -- Insert 'LOW'
       class_output = 'LOW';

       [ELSIF (qtd >= 3 AND qtd <= 4) THEN
       -- Insert 'MEAN'
       class_output = 'MEAN';]

       [ELSE
       -- Insert 'HIGH'
       class_output = 'HIGH';]
      END IF;

A: you can use case :
select  * , case when (qtd >= 1 AND qtd <= 2) THEN 'LOW'
                 when (qtd >= 3 AND qtd <= 4) THEN 'MEAN'
            else 'HIGH'
       end as class_output
from table_example

to update :
update table_example
set class_output= case when (qtd >= 1 AND qtd <= 2) THEN 'LOW'
                       when (qtd >= 3 AND qtd <= 4) THEN 'MEAN'
            else 'HIGH'
       end

but generally this is not something you want to add to your table permanently ,since you can always calculate it whenever is needed.

A: I would recommend writing the case expression as:
update table_example
    set class_output = (case when qtd <= 2 THEN 'LOW'
                             when qtd <= 4 THEN 'MEAN'
                             else 'HIGH'
                        end);

In other words, you don't need ranges.  The first matching condition is used.
However, my advice is to include this as a generated column:
alter table table_example add class_output text
    generated always as
        (case when qtd <= 2 then 'LOW'
              when qtd <= 4 then 'MEAN'
              else 'HIGH'
         end) stored;

Then you don't have to worry about the column ever being out-of-synch with the qtd column.


text:
Q: Symfony Form with Sub Form and OneToMany Relationship A Topic Entity exists which can have many Comment Entities, One To Many.
When creating the Form TopicType the Form CommentType is embedded:
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('title')
        ->add('comments', CommentType::class)
    ;
}

Symfony renders this form correctly with an input box for title and the input boxes for Comment (e.g. message).
When the form is submitted an error occurs:
Neither the property "messages" nor one of the methods
"addMessag()"/"removeMessag()", "addMessage()"/"removeMessage()",
"setMessages()", "messages()", "__set()" or "__call()" exist and have
public access in class "Foo\BarBundle\Entity\Topic".

What is the correct way to embed the Comment Form in the Topic Form?  The user will only ever be able to add one Comment when creating a Topic.
Should CollectionType be used?  This results in a 0 being render as a form label before the Comment is displayed. (0 being the first index of new Comment() attached to Thread).
 ->add('messages', CollectionType::class)

A: You do need a CollectionType::class, and then you will need a little javascript to be able to add multiple comment from the same form. The doc explains how to do it.
http://symfony.com/doc/current/cookbook/form/form_collections.html


text:
Q: How to continue to the end of duration for indefinite animation on mouse out I want to create an SVG that has the animation attributes that can continue the animation on mouse over.
On mouse out, I want the animation to continue to its end of duration before ending.
I am unable to achieve this as my animation always ends abruptly.

<svg viewBox="0 0 300 100" xmlns="http://www.w3.org/2000/svg">
  <!-- Simple color fill -->
  <circle cx="50" cy="50" r="40" fill="teal" >
<animate attributeName="fill" values="teal;cyan;teal;" dur="1s" calcMode="paced" repeatCount="indefinite" begin="mouseover" end="mouseout" />
  </circle>
</svg>

Understand that we can achieve a slightly seamless feel by adding the fill="freeze" attribute.
However it brings back the issue of the colour not being the same as from where it left off.
Any idea how we can create a smooth animation on mouse over just by using svg attributes?
I hope to not use Javascript.


text:
Q: Entity Framework LINQ to SQL translation: how does it work? In my application the data in the database must never be deleted.
Entities have a property, Deleted, which can be set to true or false.
Entities which are virtually deleted can not go out from the database, they must not exist from the application perspective.
I am managing this by creating GetAll- methods (for example GetAllUsers) in my data access layer. The methods return only entities which are flaged as NOT deleted (!Deleted), and all other methods (for example GetUserById) retrieved data with these methods.
See the example below...
public IEnumerable<User> GetAllUsers()
{
    return _dataContext.Users.Where(element => !element.Deleted);
}

public User GetUserById(string userName)
{
    return GetAllUsers().FirstOrDefault(elt => elt.UserName.Equals(userName));
}

This architecture is very good from the perpsctive of reliability because I'm sure that I always extract NOT deleted entities, but I'm afraid that this is not efficient.
My question is very simple: is my application extracting all data from the User table (select * from User) each time a specific User is requested, or is Entity Framework smart enough to understand what I want and translates to a SQL query of something like: select * from User where userName = @userName?
If I'm extracting all data from the database each time I need a single user, then how can I change my code so that it creates the correct query? I would like to mantain the centralization, so that I don't have to specify !Deleted in each LINQ query.

A:
is my application extracting all data from the User table (select * from User) each time a specific User is requested, or Entity Framework is smart enough to understand what I want and the built SQL queries is something like: select * from User where userName = @userName ?

You are retrieving all users that are not deleted each time.  The reason is because GetAllUsers returns an IEnumerable<User> instead of an IQueryable<user>, so you have left the world of Linq-to-EF and are now working in Linq-to-objects, which does all filtering, sorting, etc. in memory and does not go back to the database.
The good news is you can easily refactor this without changing the return type to IQueryable and possibly breaking existing code:
// make the base query private
private IQueryable<User> GetAllUsersQuery()
{
    return _dataContext.Users.Where(element => !element.Deleted);
}

public IEnumerable<User> GetAllUsers()
{
    return GetAllUsersQuery().AsEnumerable();
}

public User GetUserById(string userName)
{
    return GetAllUsersQuery().FirstOrDefault(elt => elt.UserName.Equals(userName));
}

Now GetUserByID just appends a condition onto the original query, so the operations will then be pushed to the database rather than filtering in-memory.

A: Yes, Entity Framework creates a SQL statement for your query.
Regarding the deleted rows issue, you could create a SQL view and map your entities to this, rather than the actual table. That way you make it far less likely that you'd select deleted rows.
N.B. You can still insert new rows.
CREATE VIEW UsersActive
AS
SELECT *
FROM Users
WHERE Deleted != 1

And then on your entity:
[Table("UsersActive")]
public class User
{
    ...
}

A: Yes, for every user it will request it from the database,If you want to avoid interacting with the database then you can cache the user table and then you can get the users from that cached object based on username

A: I would change the GetUserById function to this, to ensure a proper SQL Query:
public User GetUserById(string userName)
{
    return _dataContext.FirstOrDefault(elt => elt.UserName.Equals(userName) && !elt.Deleted);
}

This should generate a query with a proper where clause.


text:
Q: How to query not available value in the column? I've a table as follows:

From this, I'm trying to get the user_id's where status IS NOT STATUS 4 AVAILABLE . In other word the results I'm expecting are:

User Ids: 17, 19 and 20.

I tried many queries but nothing didn't worked for me. For example I tried.
SELECT user_id WHERE status NOT IN (4)

The above above query still returns as follows:

User Ids: 1, 17, 18, 19 and 20.

I know the reason why it's returning but I'm not sure how to overcome the problem.
Any help would be appreciated.

A: You are going to need to do a subquery for this.  For example:
 Select user_id from table Where user_id not in
         (select user_id from table where status = 4 and user_id is not null);

This allows you to exclude all user_id's that are in a status of 4.

A: Try this:
SELECT user_id
FROM mytable
GROUP BY user_id
HAVING COUNT(CASE WHEN status = 4 THEN 1 END) = 0

or, alternatively:
SELECT user_id
FROM mytable AS t1
WHERE NOT EXISTS (SELECT 1
                  FROM mytable AS t2
                  WHERE t1.user_id = t2.user_id AND status = 4)


text:
Q: How do I install docker using cloud-init? I want to create instances in Openstack that will have Docker in them already installed prior to ssh to them. So naturally I got interested in Cloud-init technology because it allows us to install packages on virtual machines during first boot time. So now I'm trying to install Docker on my instances during boot time, here is my code that I'm passing to the user data;
#cloud-config

packages:
   - docker.io

This doesn't work obviously, so how can I make it work?

A: Ricardo's solution is great if you only need to add docker to the deployed instance. But, in cases where you still DO need a #cloud-config (to customize other stuff, like pre-installed packages), here is a simple solution inspired by his answer, just add this command:
#cloud-config
# ... more config here

runcmd:
  - curl -fsSL https://get.docker.com -o get-docker.sh; sh get-docker.sh

A: If you want to install from the Docker repositories on an Ubuntu instance, and you don't especially like the idea of downloading and executing an arbitrary shell script, all you need is this:
#cloud-config

apt:
  sources:
    docker.list:
      source: deb [arch=amd64] https://download.docker.com/linux/ubuntu $RELEASE stable
      keyid: 9DC858229FC7DD38854AE2D88D81803C0EBFCD88

packages:
  - docker-ce
  - docker-ce-cli

cloud-init already knows how to get a GPG key, how to add an APT source (even if it is HTTPS), how to update APT before installing packages, and how to do all the other stuff you'll find in various shell script heavy ways of doing this.
If Docker should ever change their repo signing key, you can satisfy yourself that the change is legitimate and then get the new fingerprint with something like:
$ curl -sL https://download.docker.com/linux/ubuntu/gpg | gpg
gpg: keybox '/home/ubuntu/.gnupg/pubring.kbx' created
gpg: WARNING: no command supplied.  Trying to guess what you mean ...
pub   rsa4096 2017-02-22 [SCEA]
      9DC858229FC7DD38854AE2D88D81803C0EBFCD88
uid           Docker Release (CE deb) <docker@docker.com>
sub   rsa4096 2017-02-22 [S]

A: CAUTION: You should not use the Docker Convenience script (get.docker.com), it carries a warning for production environments:

Using these scripts is not recommended for production environments

Here are three ways to install Docker on Ubuntu using cloud-init for all environments that don't use the Docker Convenience script.
Install via apt-source (recommended approach):
#cloud-config

apt:
  sources:
    docker.list:
      source: deb [arch=amd64] https://download.docker.com/linux/ubuntu $RELEASE stable
      keyid: 9DC858229FC7DD38854AE2D88D81803C0EBFCD88

packages:
  - apt-transport-https
  - ca-certificates
  - curl
  - gnupg-agent
  - software-properties-common
  - docker-ce
  - docker-ce-cli
  - containerd.io

# Enable ipv4 forwarding, required on CIS hardened machines
write_files:
  - path: /etc/sysctl.d/enabled_ipv4_forwarding.conf
    content: |
      net.ipv4.conf.all.forwarding=1

# create the docker group
groups:
  - docker

# Add default auto created user to docker group
system_info:
  default_user:
    groups: [docker]

Full install via cURL: (gist reference)
#cloud-config

packages:
  - apt-transport-https
  - ca-certificates
  - curl
  - gnupg-agent
  - software-properties-common

# Enable ipv4 forwarding, required on CIS hardened machines
write_files:
  - path: /etc/sysctl.d/enabled_ipv4_forwarding.conf
    content: |
      net.ipv4.conf.all.forwarding=1

# create the docker group
groups:
  - docker

# Install Docker, for production, consider pinning to stable versions
runcmd:
  - curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -
  - add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
  - apt-get update -y
  - apt-get install -y docker-ce docker-ce-cli containerd.io
  - systemctl start docker
  - systemctl enable docker

# Add default auto created user to docker group
system_info:
  default_user:
    groups: [docker]

Simplified install using the default package: (gist reference)
#cloud-config

packages:
  - docker.io

# create the docker group
groups:
  - docker

# Add default auto created user to docker group
system_info:
  default_user:
    groups: [docker]

A: There's a docker script which can be #include'd that's very handy for docker.
Instead of #cloud-config, use
#include https://get.docker.com

A: simple code
#cloud-config

groups:
  - docker

system_info:
  default_user:
    groups: [docker]

packages:
    - docker.io

A: Debian does not contain gpg by default so you have to do the following:
#cloud-config

write_files:
  - path: /usr/share/keyrings/docker.asc
    owner: root:root
    permissions: '0644'
    content: |
      -----BEGIN PGP PUBLIC KEY BLOCK-----
      paste content of https://download.docker.com/linux/debian/gpg (do not remove the blank line it fails if you do)
      -----END PGP PUBLIC KEY BLOCK-----

apt:
  sources:
    docker.list:
      source: deb [arch=amd64 signed-by=/usr/share/keyrings/docker.asc] https://download.docker.com/linux/debian $RELEASE stable

packages:
  - docker-ce
  - docker-ce-cli
  - containerd.io
  - docker-compose-plugin

Source: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=970796


text:
Q: Apply function on all but K columns in a dataframe (similarity of a vector to each member of the df, without id column)? I have the following df and vector:
df = pd.DataFrame(dict(id = [0,1,2], a=[4,5,6], b=[22,11.1,-5]))
vec = pd.DataFrame(dict(id = [90], a=[9], b=[6.4]))

I want to calculate a similarity of vec to all vectors in df, without the id column.
I know I can hold out the columns, calculate the similarity and glue it back.
df_id = df['id']
vec_id = vec['id']

df_wo_id = df.drop(['id'], axis=1)
vec_wo_id = vec.drop(['id'], axis=1)
df_wo_id['similarity'] = df_wo_id.apply(lambda row: 1 - cosine(row, vec_wo_id),axis=1)

df = pd.concat([df_id, df_wo_id], axis=1)

Is there another approach to apply some function like the one above simpler (maybe using some masks)?

A: you can specify a mask beforehand and use it in the apply method:
mask = ~df.columns.isin(['id'])
df['similiarity'] = df.apply(lambda row: 1 - cosine(row[mask], vec.loc[:,mask]),axis=1)


text:
Q: Functional composition with variadic templates My goal is to get composition of functions working with this exact syntax:
int main() {
    Function<std::string, int> f([](const std::string& s) {return s.length();});
    Function<int, double> g([](int x) {return x + 0.5;});
    Function<double, int> h([](double d) {return int(d+1);});
    std::cout << compose(g, f, "hello") << '\n';  // g(f("hello")) = 5.5
    std::cout << compose(h, g, f, "hello") << '\n';  // h(g(f("hello"))) = 6
}

By changing the syntax slightly so that the "hello" argument goes first, I have it working easily with the following code:
#include <iostream>
#include <functional>
#include <tuple>
#include <string>

template <typename D, typename R>
struct Function {
    using domain = const D&;
    using range = R;
    using function = std::function<range(domain)>;
    const function& f;
    Function (const function& f) : f(f) {}
    range operator()(domain x) const {return f(x);}
};

template <typename... Ts>
struct LastType {
    using Tuple = std::tuple<Ts...>;
    using type = typename std::tuple_element<std::tuple_size<Tuple>::value - 1, Tuple>::type;
};

template <typename F, typename G>
typename G::range compose (const typename F::domain& x, const G& g, const F& f) {
    return g(f(x));
}

template <typename F, typename... Rest>
auto compose (const typename LastType<Rest...>::type::domain& x, const F& f, const Rest&... rest) {
    return f(compose(x, rest...));
}

int main() {
    Function<std::string, int> f([](const std::string& s) {return s.length();});
    Function<int, double> g([](int x) {return x + 0.5;});
    Function<double, int> h([](double d) {return int(d+1);});
    std::cout << compose("hello", g, f) << '\n';  // g(f("hello")) = 5.5
    std::cout << compose("hello", h, g, f) << '\n';  // h(g(f("hello"))) = 6
}

Having done that, I thought it would be a trivial task to adapt the above code so that I get the exact syntax I want (i.e. with "hello" being at the end of the list), but it is turning more difficult than I thought.  I attempted the following, which does not compile:
#include <iostream>
#include <functional>
#include <tuple>
#include <string>

template <typename D, typename R>
struct Function {
    using domain = const D&;
    using range = R;
    using function = std::function<range(domain)>;
    const function& f;
    Function (const function& f) : f(f) {}
    range operator()(domain x) const {return f(x);}
};

template <typename F, typename G>
typename G::range compose (const G& g, const F& f, const typename F::domain& x) {
    return g(f(x));
}

template <typename F, typename... Rest>
auto compose (const F& f, const Rest&... rest) {
    return f(compose(rest...));
}

int main() {
    Function<std::string, int> f([](const std::string& s) {return s.length();});
    Function<int, double> g([](int x) {return x + 0.5;});
    Function<double, int> h([](double d) {return int(d+1);});
    std::cout << compose(g, f, "hello") << '\n';  // g(f("hello")) = 5.5
    std::cout << compose(h, g, f, "hello") << '\n';  // h(g(f("hello"))) = 6
}

And I don't know how to fix it. Can anybody help me fix this?
A new idea I've come up with is to define compose_, which will reorder the arguments of args... (by some std::tuple manipulation) so that the first element goes last and then passing that argument pack to compose.  This looks very messy though, and even if it works, there must be a more direct (and shorter) solution.

A: It looks like the following also works:
template <typename T>
const T& compose (const T& t) {
    return t;
}

template <typename F, typename... Rest>
typename F::range compose(const F& f, Rest... rest) {
    return f(compose(rest...));
}

A: what about in this way?
#include <iostream>
#include <functional>
#include <tuple>
#include <string>

template <typename D, typename R>
struct Function {
    using domain = const D&;
    using range = R;
    using function = std::function<range(domain)>;
    const function& f;
    Function (const function& f) : f(f) {}
    range operator()(domain x) const {return f(x);}
};

template <typename F, typename X = typename F::domain>
typename F::range compose (const F& f, const X & x) {
    return f(x);
}

template <typename F, typename... Rest>
typename F::range  compose (const F& f, const Rest&... rest) {
    return f(compose(rest...));
}

int main() {
    Function<std::string, int> f([](const std::string& s) {return    s.length();});
    Function<int, double> g([](int x) {return x + 0.5;});
    Function<double, int> h([](double d) {return int(d+1);});
    std::cout << compose(g, f, "hello") << '\n';  // g(f("hello")) = 5.5
    std::cout << compose(h, g, f, "hello") << '\n';  // h(g(f("hello"))) = 6
}

You can use auto for the returning type of compose() only in c++14 (if I'm not wrong).
Your version doesn't compile because your variadic version of compose() uses N variadic types and N arguments when the final (not varidic) uses 2 types and 3 arguments. In other words, the variadic version lost the final argument.
Your version doesn't compile because the final (not variadic version) is never used: the compiler chooses the variadic version. Adding typename X = typename F::domain (and changing const typename F::domain& with const X&) the final version is preferred and your code should compile (with c++14, at least) [corrected by  Piotr Skotnicki; thanks]
p.s.: sorry for my bad English.


text:
Q: Is there a design pattern other than producer consumer to describe this pattern? In my application in C++ I am using pthreads.  I have a main thread that parcels out work to another thread to read from disk and a third thread to write to disk.  This allows the main thread to perform in real-time and not get hiccups due to disk io by the read thread keeping ahead of the main threads consumption and the write thread keeping up with the main threads production. In other words, the read thread produces data for processing by the main thread and the write thread consumes data produced by the main thread.
In my application, I have shared resources between the main thread and the read thread and I have another set of shared resources between the main thread and the write thread.  During periods when no synchronization between threads is needed, the main thread freely accesses the the shared resources of the read and write threads.  Then, when it wishes to supply work to be read or written, it sets up the shared resources to indicate the required work and then releases a condition variable to notify the read or write thread (as appropriate) that it should gather the request from the shared area. It then blocks itself until the requested thread completes its gathering of the request and releases a separate condition variable upon which it waits.  In this way, the main thread in its normal state accesses the shared resource and then blocks itself by waiting on the condition during periods when its read or write thread needs access, whereas the read and write threads are opposite in that in their normal state they do not access the shared resource, but only do so during synchronization periods when the main thread has signaled and is waiting for them to complete their access.
Here is some very rough pseudo code (do not worry about exact flow here, this is just a rough idea of the functioning code):
MainThread:
  do {
    While (no pending requests) {
      manipulate shared resources;
    }
    if (need write && ready for read requests) {
      setup write request in shared resources;
      Release condition startWrite variable;
      Wait on condition endWrite variable;
    }
    if (need read && ready for read requests) {
      setup read request in shared resources;
      Release condition startRead variable;
      Wait on condition endRead variable;
    }
  }
ReadThread:
  do {
    Notify I am ready for read requests;
    Wait on condition startRead;
    copy request out of shared resources;
    update shared resources to account for reads completed;
    Release condition EndRead;
    Perform Read from disk;
  }
WriteThread:
  do {
    Notify I am ready for write requests;
    Wait on condition startWrite;
    copy request out of shared resources;
    update shared resources to account for writes completed;
    Release condition EndWrite;
    Perform write to disk;
  }

My question is whether this is considered just a normal producer consumer design pattern or whether there is a more specific commonly accepted design pattern that would describe what I have created?

A: You're getting some background activity to perform input and output, independently of the mainline processing. Reads can be scheduled ahead of time so the data is already there when needed, and writes can be farmed out to as a background activity so the mainline doesn't have to block on comitting data to storage.
This "design pattern" has a name, being known as "asynchronous IO".

A: Have you looked at the read/write lock pattern?  The scheduler pattern would be another idea though I'm not sure how well this would work in your given situation.

A: You could describe this as an instance of the "Master/Worker" pattern. The "master" thread hands out work (read or write requests) to the "worker" threads (the read thread and the write thread).


text:
Q: Error in installing Tensorflow in Python 3.9.2 with pip 21.0.1 I have installed Python 3.9.2. And mt pip version is 21.0.1.
While installing tensorflow I am getting below error
ERROR: Could not find a version that satisfies the requirement tensorflow
ERROR: No matching distribution found for tensorflow

A: Currently there is no version of Tensorflow that would work with python 3.9.


text:
Q: Who was inside the green armor with stag horns in the Battle of Blackwater? At the Battle of the Blackwater Rush,

 King's Landing is being assaulted by Baratheon forces under Stannis. Tywin Lannister shows up leading his host from Harrenhal and most of Renly's army as well. They attack and rout Stannis's army from the rear. During the battle, many soldiers report seeing "Renly's Ghost" riding alongside Tywin Lannister and Loras Tyrell. The knight is described as wearing green armor very similar to King Renly's with golden antlers coming form the head.

Who is the knight wearing this armor? Is it ever revealed? Did such a knight even fight in the battle or was it a mass hallucination / popular rumor started by a few?

A: It was Garlan Tyrell. Loras Tyrell confesses it to Jaime Lannister during their conversation in the White Room of the Kingsguard.
From A Storm of Swords, Jaime's POV, page 759:

"It's said you fought magnificiently in the battle... almost as well as Lord Renly's ghost beside you. A Sworn Brother has no secrets from his Lord Commander. Tell me, ser. Who was wearing Renly's armor?"
For a moment Loras Tyrell looked as though he might refuse, but in the end he remembered his vows. "My brother," he said sullenly. "Renly was taller than me, and broader in the chest. His armor was too loose on me, but it suited Garlan well."
"Was the masquerade your notion, or his?"
"Lord Littlefinger suggested it. He said it would frighten Stannis's ignorant men-at-arms."

It is also mentioned on the wiki, although it is not easy to find: http://awoiaf.westeros.org/index.php/Renly_Baratheon#A_Clash_of_Kings

A: The answer is contained within A Storm of Swords:

 "Tell me, ser. Who was wearing Renly's armor?"

 For a moment Loras Tyrell looked as though he might refuse, but (...) "My brother," he said sullenly. "Renly was taller than me, and broader in the chest. His armor was too loose on me, but it suited Garlan well."

 "Was the masquerade your notion, or his?"

 "Lord Littlefinger suggested it. He said it would frighten Stannis's ignorant men-at-arms."


text:
Q: Arduino trouble with Serial.readbytes() when reading from a Java program over USB I am using an Arduino Uno. I am experiencing weird behavior with Serial.readbytes(). The Arduino is powered and communicating via USB on COM4. I am running Eclipse on 64-bit Windows 7.
My current Arduino code looks like the following; the delays are so I can start and stop my Java service and look at the serial window in the Arduino IDE, inputBuffer is a character array.
char inputBuffer[10];   // For incoming serial data
void setup() {
    Serial.begin(9600); // Opens serial port, sets data rate to 9600 bit/s.
}

void GetTemp(){
    int temp = 123;
    Serial.print(temp);
}

void loop() {
    if (Serial.available() > 0) {
        Serial.readBytes(inputBuffer, Serial.available());
        delay(5000);
        Serial.print("I got this ->");
        Serial.print(inputBuffer);
        Serial.println("<-");
    }
    delay(5000);
    Serial.println("delay");
    Serial.println(inputBuffer[0], DEC);
}

Here is the code for my Java side. I modified it from Two way communcation with the serial port. This just sends one byte array upon start.
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.IOException;
import java.io.OutputStream;

public class TwoWaySerialComm
{
    public TwoWaySerialComm()
    {
        super();
    }

    void connect ( String portName ) throws Exception
    {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if ( portIdentifier.isCurrentlyOwned() )
        {
            System.out.println("Error: Port is currently in use");
        }
        else
        {
            CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);

            if ( commPort instanceof SerialPort )
            {
                SerialPort serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);

                OutputStream out = serialPort.getOutputStream();

                (new Thread(new SerialWriter(out))).start();
            }
            else
            {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }
    }

    public static class SerialWriter implements Runnable
    {
        OutputStream out1;

        public SerialWriter ( OutputStream out )
        {
            this.out1 = out;
        }

        public void run ()
        {
            try
            {
                byte[] test = ("H567").getBytes();//testing string to send
                this.out1.write(test);
            }
            catch ( IOException e )
            {
                e.printStackTrace();
            }
        }
    }

    public static void main ( String[] args )
    {
        try
        {
            (new TwoWaySerialComm()).connect("COM4");
        }
        catch ( Exception e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

When I run it, my Arduino just prints out a blank line. If I prepare the Arduino with "hiya" using the Serial window first, then when the java is executed, it will return back to a blank line.
Since the char array is just over-written each time I sent "H567\r\n" and then in the Serial window typed sent "hiya" where the extra newline was still being executed, so I know characters are being stored somehow.
Another test was to change the last Serial.prinln() to Serial.println(inputBuffer[0], DEC). Using the Serial Window, results are as expected, but from Java it just prints out "0". Serial communication works wonderful coming from the Arduino talking to the Java code, just not from Java code to the Arduino. How can I fix this problem?
Per suggestion, I tried reading Serial.available() instead of a fixed max of 10. No changes were experienced.

A: I found a solution, but I am unsure of the reason. When starting the Serial writing thread, I must call thread.sleep(2000) upon start for the Arduino to read characters correctly.

A: Try adding out1.flush() after out1.write().


text:
Q: Crashlytics - how can I delete builds/versions? I want to delete 2 of the builds/versions from the Crashlytics dashboard — they were uploaded with the wrong version number and it's creating havoc in the testing process.
I would prefer to completely and totally remove them from Crashlytics.

A: Alex from Fabric here. If you want to archive a version of your app, head to:
https://fabric.io/settings/apps
Then select your app, click on the Versions tab, and disable any versions you no longer need.
You can't technically delete an app, because maybe someone has downloaded it and you want to still receive its crash reports. Hence you can only restrict others from downloading it moving forward

A: To delete a specific app version/build/flavor from Crashlytics/Fabric:

*

*Go to https://fabric.io/settings/apps

*Select the app version/build/flavor you want to delete

*On the screen you will see the following options

Enable Privacy Prompt |
Enable Answers Enhanced Feature Set |
Disable IP Address Tracking |
Delete App
To delete, select the last option.  Please note you must be an admin

A: Go to Settings -> APPS -> select your app -> Click on versions tab -> disable accident version.


text:
Q: The resource from [...] was blocked due to MIME type ("text/html") mismatch (X-Content-Type-Options: nosniff) with pug and express i'm trying to charge a style.css in an pug and express project.
I tried lot of tricks found in the other topics but noting works.
here the app.js file:
const app = express();
const pug = require('pug');
const path = require('path')
const helmet = require('helmet')

app.set('view engine', 'pug');

app.use(helmet.contentSecurityPolicy({
    directives: {
        defaultSrc: ["'self'"],
        scriptSrc: ["'self'"],
        styleSrc: ["'self'"]
    }
}));

app.use(express.static(path.join(__dirname + '/views')));

console.log(app.use(express.static(path.join(__dirname + '/views'))))

app.get('/', (req, res, next) => {
    res.render('index');
})

app.listen(8080);

here the index.pug file:
    head
        meta(http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval' http://localhost:8080")
        link(rel="stylesheet" href="/views/css/style.css")
    body
        h1='hello world'

I already tried to delete the rel attribute of the link tag and others basics stuff.
thanks.

A: This is how it works for me:
router.use('/', express.static(path.join(__dirname, 'views')));

Get the resource with:
link(rel="stylesheet" href="/css/style.css")

If you want or need the word views in your url then this combination should work:
router.use('/views', express.static(path.join(__dirname, 'views')));

link(rel="stylesheet" href="/views/css/style.css")


text:
Q: Creating XML from the parent node information I have an xml file that has information of the roots as follows:
usequery attribute has a SQL query from which the XML element data is populated from.
<ARAXmlFormat>
    <root name="level1" index = "1" parentid ="0" haschildren="yes"/>
    <root name="level2" index = "2" parentid ="1" haschildren="yes" usequery="query2"/>
    <root name="level21" index = "3" parentid ="2" haschildren="no" usequery="query1"/>
    <root name="level22" index = "4" parentid ="2" haschildren="no" usequery="query3"/>
    <root name="level3" index = "5" parentid ="1" haschildren="yes"/>
    <root name="level31" index = "6" parentid ="5" haschildren="no" usequery="query4"/>
</ARAXmlFormat>

From this I need to generate an XML tree as follows. As of now I already have individual XElements for leve2, level21, level22, level31. But how do I create XML but adding these elements in the XML format as below from the parentid information  above?
<level1>
  <level2>
      <level21 attrib1 ="val1" attrib2="val2"/>
      <level22 attrib1 ="val1" attrib2="val2"/>
  </level2>
  <level3>
       <level31 attrib1 ="val1" attrib2="val2"/>
  </level3>
</level1>

A: I don't know where the value of attrib1 and attrib2 attributes come from. But as far as the hierarchical structure of the output XML tree is concerned, you could construct it recursively, using something like this:
var doc = XDocument.Load("roots.xml"); // read input xml file

Func<int, IEnumerable<XElement>> selectChildNodes = null; // declare delegate

selectChildNodes = parentId => doc.Elements("ARAXmlFormat").Elements().Where(
                        p => p.Attribute("parentid").Value == parentId.ToString()
                ).Select(
                   x => new XElement(
                                        x.Attribute("name").Value,
                                        selectChildNodes(Convert.ToInt32(x.Attribute("index").Value))
                                     )
                );

IEnumerable<XElement> levels = selectChildNodes(0);

This solution works independent of order of <root> elements in the input file. selectChildNodes is a delegate that accepts the index of parent node as the input parameter and returns all child nodes of that element recursively. The output would be like this, without attributes:
<level1>
  <level2>
    <level21 />
    <level22 />
  </level2>
  <level3>
    <level31 />
  </level3>
</level1>

The value of node attributes could be included when constructing each node with new XElement.

A: You can do it like this:
var source = XDocument.Parse(xml); // or whatever
var sourceElems = source.Root.Elements("root");

var result = new XDocument(new XElement("result"));
var resultElems = new Dictionary<int, XElement>();
resultElems.Add(0, result.Root);

foreach (var sourceElem in sourceElems)
{
    var resultElem = new XElement((string)sourceElem.Attribute("name"));

    int parentId = (int)sourceElem.Attribute("parentid");
    resultElems[parentId].Add(resultElem);

    resultElems.Add((int)sourceElem.Attribute("index"), resultElem);
}

Basically, walk through the elements, and for each find the parent in a dictionary, add it as a child to that parent and finally add it to the dictionary, so that it can be parent itself. This assumes that parent is always declared before all its children.
With your source data, it creates the following result:
<result>
  <level1>
    <level2>
      <level21 />
      <level22 />
    </level2>
    <level3>
      <level31 />
    </level3>
  </level1>
</result>


text:
Q: how to make the modes change, that is, looks, plays, listens. I only play for some reason discord.js const activities_list = ['Watching', 'Playing']; // creates an arraylist containing phrases you want your bot to switch through.

bot.on('ready', () => {
 setInterval(() => {
  const index = Math.floor(Math.random() * (activities_list.length - 1) + 1); // generates a random number between 1 and the length of the activities array list (in this case 5).
  bot.user.setActivity(activities_list[index]); // sets bot's activities to one of the phrases in the arraylist.
 }, 10000); // Runs this every 10 seconds.
});

A: If I have understood your question correctly, I am assuming that you are trying to change your Client's activity type (PLAYING, STREAMING, LISTENING, WATCHING, CUSTOM_STATUS) every 10 seconds.
I've written a code explaining how to do that.

// We are creating an Array containing the Activity type and message.
const activities_list = [
 {
  type: 'LISTENING',
  message: 'some music.',
 },
 {
  type: 'WATCHING',
  message: 'a movie.',
 },
 {
  type: 'PLAYING',
  message: 'a game.',
 },
];

client.on('ready', () => {
 console.log(`${client.user.tag} is ready.`);

 // Once the Client is ready, we are creating a setInterval that repeats every 10 seconds.
 // The setInterval will run 10 seconds after the Client is ready, not immediately.
 setInterval(() => {
  // Picking a random activity from the activities_list Array.
  const Activity =
   activities_list[Math.floor(Math.random() * activities_list.length)];

  // client.user.setActivity accepts two parameters, the name and the Object of options. We're going to set the name in the options Object.
  client.user
   .setActivity({
    name: Activity.message,
    type: Activity.type,
   })
   .catch((error) => console.error(`Couldn't set activity status. | ${error}`));
 }, 10 * 1000);

 // 10000ms is the same as 10 * 1000ms, but this way it's more readable.
});

A: For me i use this
const activities_list = [
  "Hey",
  "What's up?",
  "do !help",
  "contact the developer to report any bug"
  ]; // creates an arraylist containing phrases you want your bot to switch through.

client.on('ready', () => {
  setInterval(() => {
      const index = Math.floor(Math.random() * (activities_list.length - 1) + 1); // generates a random number between 1 and the length of the activities array list (in this case 5).
      client.user.setActivity(activities_list[index]); // sets bot's activities to one of the phrases in the arraylist.
  }, 10000); // Runs this every 10 seconds.
});


text: Q: Put Image on Parent Form Background I am using MDI parent form and I've put Background image on that. Now I am Adding two Dock Panel on the Parent Form. I've Changed Background of both the panel to Transparent. but when I run Background is not visible.


text:
Q: Swift 3 iOS -Google GMSAutoComplete malfunctioning since upgrade Error caption:

I'm using Google GMSAutocompleteViewController.
I have my API key in AppDelegate, the most recent pod for Swift 3 Xcode 8, the import GoogleMaps and import GooglePlacesAPI are at the top of the vc and in appDelegate, and my internet connection is fine.
When I was using Swift 2.2 whenever I typed in an address everything worked fine. Now that I upgraded to Swift 3 every now and then I'll make a mistake on an address, then the "Can't load search results" cloud caption appears. When I dismiss the vc and try again I keep getting the same caption. I tried shutting the app off and restarting the simulator but it won't let me access autocomplete services. I'm way under the 2500 free daily limit search because it's literally only me testing the app.
I also notice the Google AutoComplete docs says to use GMSPlacesClient.provideAPIKey("...") but the the GMSPlacesClient method provideAPIKey isn't available so I only use GMSServices.provideAPIKey(".."). I wonder is this part of the issue.
Does anyone know the fix for this issue?
AppDelegate:
import UIKit
import GoogleMaps
import GooglePlacesAPI
import SystemConfiguration

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    override init() {
        super.init()

        //Google Maps API Key
        GMSServices.provideAPIKey("WORKS")

        GMSPlacesClient.provideAPIKey("DOES NOT WORK")
    }

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

my code from googlePlaces:
import UIKit
import GooglePlaces
import GoogleMaps

class ViewController: UIViewController {

  @IBAction func onLaunchClicked(sender: UIButton) {
    let acController = GMSAutocompleteViewController()
    acController.delegate = self
    present(acController, animated: true, completion: nil)
  }
}

extension ViewController: GMSAutocompleteViewControllerDelegate {

  func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
    print("Place name: \(place.name)")
    print("Place address: \(place.formattedAddress)")
    print("Place attributions: \(place.attributions)")
    dismiss(animated: true, completion: nil)
  }

  func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
    print(".....\(error)")
    dismiss(animated: true, completion: nil)
  }

  func wasCancelled(_ viewController: GMSAutocompleteViewController) {
    dismiss(animated: true, completion: nil)
  }
}

A: You should put GooglePlaces, GooglePlacePicker and GoogleMaps into your Podfile:
pod 'GooglePlaces'
pod 'GooglePlacePicker'
pod 'GoogleMaps'

And provide your API_KEY:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    GMSPlacesClient.provideAPIKey("API_KEY_HERE")

    return true
}

For more information, follow this guide: https://developers.google.com/places/ios-api/start