Q:

Reason of phase difference!

Why is there a phase difference between resistor and capacitor? I am looking for the conceptual reason behind this.
What does a phase difference of \$\pi/2\$ show conceptually? According to me, the one with positive phase difference would reach to its peak value earlier than the another, but how do we come to know the time difference between the two quantities to reach at its peak? What's the reason that there is a difference in reaching at its peak value?
Please illustrate in as much detail as possible.

A:

Q = CV in a capacitor and \$\dfrac{dQ}{dt}\$ = current therefore: -
I = \$C\dfrac{dV}{dt}\$
This means that current is proportional to the derivative of voltage.
If that voltage is a sine wave then the derivative is a cosine wave hence a phase difference of pi/2 (90 degrees).
In a resistor, V = IR i.e. the relationship between voltage and current is that they are in-phase.

A:

One simplified answer would be:
A capacitor is a simple device that when a greater voltage than what its current voltage is will charge and result in its own voltage increasing. If you put a load ( or aply a smaller voltage) on the capacitor then it will discharge. This is all fine. But if we start using an AC waveform to rapidly charge and discharge the capacitor we get this interesting phase shift. What happens is in a sinus wave the voltage does not change at a constant rate. And the faster you try to charge or discharge a capacitor , the more current you would need. It just so happens that the place in a sine wave where the current changes the fastest is \$90^\circ\$ (\$0.5 \times \pi\$ or \$0.25 \times \tau\$) offset from where the peak is.
So a capacitors current is offset by \$90^\circ\$ because that's when the voltage changes the fastest.


Q:

Spacelike, timelike and null geodesics

I have a question about an exercise in Misner, Thorne, and Wheeler's Gravitation. On page 321, exercise 13.5 says

Show that a geodesic of spacetime which is timelike at one event is
  everywhere timelike. Similarly, show that a geodesic initially
  spacelike is everywhere spacelike, and a geodesic initially null is
  everywhere null. [Hint: This is the easiest exercise in the book!]

Ok so the idea is that timelike means that the timelike geodesic have a negative-length 4-velocity, a spacelike would have a positive-length 4-velocity and a null would have a 0-length 4-velocity. So my idea was to use the definition of the geodesic to show that the sign of the length of the 4-velocity doesn't change. The definition of the geodesic translates to a curve that parallel transport conserves the tangent vector to the curve.
My idea was to say that the tangent vector of a spacelike is always in the space parts of spacetime. But it doesn't seem true at all. Finally the Hint doesn't help me much.
I assume there are two kinds of solutions for this problem: one purely abstract with words and one with a more mathematical approach of the concept of geodesics and tangent vectors.

A:

Just use the geodesic equation to evaluate the derivative along the curve of the "length" of the tangent to the curve.  You'll find that it is zero, so the "length" does not change along the curve.  In particular, the sign of the "length" does not change.
The geodesic equation is
\begin{align}
  T^a \nabla_a T^b = 0,
\end{align}
where $T^a$ is the tangent to the curve, in whatever affine parameterization you want.  The norm of the tangent (which determines whether it's timelike, spacelike, or null) is given by $T^b T^c g_{bc}$.  The quantity $T^a \nabla_a$ is just the derivative along the curve, so the derivative along the curve of the norm of the tangent is
\begin{align}
  T^a \nabla_a \left( T^b T^c g_{bc} \right) = 0.
\end{align}
Since the covariant derivative of the metric is zero, we can pull it out of the derivative, and expand this as
\begin{align}
  T^a \nabla_a \left( T^b T^c g_{bc} \right)
  &=
  g_{bc} T^a \nabla_a \left( T^b T^c \right) \\
  &=
  g_{bc} \left[ \left( T^a \nabla_a T^b \right) T^c + T^b \left( T^a \nabla_a T^c \right) \right] \\
  &=
  0
\end{align}
To get to zero, we just apply the geodesic equation twice in that second-to-last line.  Again, since this derivative along the curve is zero, the norm does not change — so the sign of the norm does not change.

A:

A geodesic is a curve of auto-parallel transport, then the tangent vectors are transported parallely.
In GR one usually uses Levi-Civita connection, so the scalar product of transported vectors is conserved.
So the scalar product of the tangent vector with himself (its norm) is conserved, so if it is less than zero in one point it is less than zero everywhere on the geodesic.

A:

Let $u^\mu = \frac{d x^\mu}{d\tau}$ be the 4-velocity of a geodesic where $\tau$ is the affine parameter along a geodesic. It satisfies the geodesic equation
$$
\frac{du^\lambda}{d\tau} + \Gamma^\lambda_{\mu\nu} u^\mu u^\nu = 0 .
$$
Then,
\begin{align}
\frac{ d }{d\tau} ( g_{\mu\nu} u^\mu u^\nu ) &= u^\mu \left( u^\nu \frac{ d }{d\tau}  g_{\mu\nu}    +  2 g_{\mu\nu}  \frac{ d }{d\tau}  u^\nu  \right)= u^\mu \left( u^\nu u^\rho \partial_\rho g_{\mu\nu}    +  2 g_{\mu\nu}  \frac{ d }{d\tau}  u^\nu  \right)
\end{align}
Now, recall the definition
$$
\Gamma^\lambda_{\mu\nu} = \frac{1}{2} g^{\lambda \rho} \left( \partial_\mu g_{\nu\rho} + \partial_\nu g_{\mu\rho} - \partial_\rho g_{\mu\nu} \right)
$$
Then,
$$
2 g_{\lambda \rho} \Gamma^\lambda_{\mu\nu} =  \partial_\mu g_{\nu\rho} + \partial_\nu g_{\mu\rho} - \partial_\rho g_{\mu\nu}
$$
Interchanging $\mu$ and $\rho$, we find
$$
2 g_{\lambda \mu} \Gamma^\lambda_{\rho\nu} =  \partial_\rho g_{\mu\nu} + \partial_\nu g_{\mu\rho} - \partial_\mu g_{\nu\rho}
$$
Adding the two equations above and then rearranging the indices, we find
$$
\partial_\rho g_{\mu\nu} = 2 g_{\lambda(\mu}\Gamma^\lambda_{\nu)\rho}
$$
Substituting this into the equation, we find
\begin{align}
\frac{ d }{d\tau} ( g_{\mu\nu} u^\mu u^\nu ) &=  2 g_{\mu\lambda} u^\mu   \left(  u^\nu u^\rho \Gamma^\lambda_{\nu\rho}  + \frac{ d  u^\lambda }{d\tau}  \right)  = 0.
\end{align}
Thus, $u^2$ is a constant along the geodesic. An immediately corollary of this result is the statement in the question.


Q:

Can't convert memory address to value

thanks for visiting my question! Currently, when I run this code (an implementation of the Set data structure in c++), the memory address of each element in the set is printed instead of the values in the set. To help with debugging, here's my code:
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <cassert>

#define PB push_back
typedef std::vector<int> vint;

class SetBase
{
public:
  SetBase() {}
  ~SetBase() {}

  void insert(int x)
  {
    if (!this->isInSet(x))
    {
      this->set.PB(x);
    }
  }

  int size()
  {
    return this->set.size();
  }

  bool empty()
  {
    return this->size() == 0;
  }

  int operator[](int index)
  {
    if (index >= 0 && index < this->size())
    {
      return this->set[index];
    }
    else
    {
      return -1;
    }
  }

  bool find(int target)
  {
    sort(this->set.begin(), this->set.end());

    int low = 0, high = this->size();

    while (low <= high)
    {
      long long mid = low + (high - low) / 2;
      long long guess = this->set[mid];

      if (guess == target)
        return true;
      else if (guess < target)
        low = mid + 1;
      else
        high = mid - 1;
    }

    return false;
  }

  int count(int target)
  {
    int counter = 0;

    for (int i = 0; i < this->set.size(); i++)
    {
      if (this->set[i] == target)
        counter++;
    }

    return counter;
  }

  bool operator=(SetBase &other)
  {
    if (other.size() != this->size())
      return false;

    for (int i = 0; i < other.size(); i++)
    {
      if (other[i] != this->set[i])
        return false;
    }

    return true;
  }

private:
  vint set;

  bool isInSet(int target)
  {
    for (int i = 0; i < this->size(); i++)
    {
      if (set[i] == target)
      {
        return true;
      }
    }

    return false;
  }
};

class Set : public SetBase
{
public:
  void set_union(Set *set1, Set *set2, Set &back_insertor)
  {
    for (int i = 0; i < set1->size(); i++)
    {
      if (this->isInSet(back_insertor, i))
      {
        back_insertor.insert(i);
      }
    }
  }

  void set_difference(Set set1, Set set2, Set &back_insertor)
  {
    // set_difference = set1 - set2
  }

  void set_intersection(Set set1, Set set2, Set &back_insertor)
  {
    // set_difference = set1 U set2
    for (int i = 0; i < set1.size(); i++)
    {
      for (int j = 0; j < set2.size(); j++)
      {
        if (set1[i] == set2[j])
        {
          back_insertor.insert(set1[i]);
        }
      }
    }
  }

  void printSet(Set *in)
  {
    for (int i = 0; i < in->size(); i++)
    {
      std::cout << &in[i] << "\n";
    }
  }

private:
  bool isInSet(SetBase set1, int target)
  {
    for (int i = 0; i < set1.size(); i++)
    {
      if (target == set1[i])
      {
        return true;
      }
    }

    return false;
  }
};

int main()
{
  Set *set_1 = new Set();
  Set *set_2 = new Set();
  Set *back = new Set();

  for (int i = 1; i <= 10; i++)
    set_1->insert(i);

  for (int i = 1; i <= 10; i++)
    set_2->insert(i);

  set_2->insert(11);

  set_1->set_union(set_1, set_2, *back);
  set_1->printSet(set_1);

  delete set_1;
  delete set_2;
  delete back;
}

When running the set_1->printSet(set_1); line, here's what I get:
0x7fb498c05a20
0x7fb498c05a38
0x7fb498c05a50
0x7fb498c05a68
0x7fb498c05a80
0x7fb498c05a98
0x7fb498c05ab0
0x7fb498c05ac8
0x7fb498c05ae0
0x7fb498c05af8

Even though this works, I would like to print out the values (integer) instead. Any help would be appreciated! Thanks! :)

A:

Inside printSet(), you use &in[i] to print each element.
The & operator returns the address of the object you are referencing. So, instead of getting the value, you are getting its address.  You should remove it, eg:
void printSet(Set *in)
{
    for (int i = 0; i < in->size(); i++)
    {
        std::cout << (*in)[i] << "\n";
    }
}


Q:

Proc SQL running total

I am building a process in SAS EG and came to a sticking point when I needed a running total.  This would be very easy to do in Excel but my table is 22M records long.  I have VBA experience but not Proc SQL.  Can someone show me how to do a running total of dollars by item?  The data is sorted by Market/Segment/Item/Month.
Thanks
Jeff
MyData

A:

You hierarchy is Market / Segment / Item, and maybe from the question one can presume an Item is unique across all Markets and Segments.
A running total is easiest in a DATA Step.  You will want to use first. automatic variables that are prepared when the step has a BY statement.
data want;
  set have;
  by Market Segment Item Month; * add month to make sure incoming data is ordered timewise, if not an error will appear in the log;

  if first.Item then RunningDollars = 0;
  RunningDollars + Dollars;  * The + syntax here is a `SUM` statement that causes the RunningDollars variable to be automatically retaine, meaning the value is available for the next record.
run;


Q:

Modified EXIF data doesn't save properly

After countless attempts and sieving through every SO answer + google result, it baffles me that working with EXIF on iOS is so frustrating.
Below is working code with its results.
[[self stillImageOutput] captureStillImageAsynchronouslyFromConnection:videoConnection
    completionHandler:^(CMSampleBufferRef imageSampleBuffer, NSError *error)
    {
        NSData *imageNSData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];

        CGImageSourceRef imgSource = CGImageSourceCreateWithData((__bridge_retained CFDataRef)imageNSData, NULL);

        //get all the metadata in the image
        NSDictionary *metadata = (__bridge NSDictionary *)CGImageSourceCopyPropertiesAtIndex(imgSource, 0, NULL);

        NSLog(@"original metadata Info: %@",metadata);

        //make the metadata dictionary mutable so we can add properties to it
        NSMutableDictionary *metadataAsMutable = [metadata mutableCopy];

        NSMutableDictionary *EXIFDictionary = [[metadataAsMutable objectForKey:(NSString *)kCGImagePropertyExifDictionary]mutableCopy];
        NSMutableDictionary *GPSDictionary = [[metadataAsMutable objectForKey:(NSString *)kCGImagePropertyGPSDictionary]mutableCopy];
        NSMutableDictionary *RAWDictionary = [[metadataAsMutable objectForKey:(NSString *)kCGImagePropertyRawDictionary]mutableCopy];

        if(!EXIFDictionary)
            EXIFDictionary = [[NSMutableDictionary dictionary] init];

        if(!GPSDictionary)
            GPSDictionary = [[NSMutableDictionary dictionary] init];

        if(!RAWDictionary)
            RAWDictionary = [[NSMutableDictionary dictionary] init];

        [GPSDictionary setObject:@"camera coord Latitude"
                         forKey:(NSString*)kCGImagePropertyGPSLatitude];
        [GPSDictionary setObject:@"camera coord Longitude"
                         forKey:(NSString*)kCGImagePropertyGPSLongitude];
        [GPSDictionary setObject:@"camera GPS Date Stamp"
                         forKey:(NSString*)kCGImagePropertyGPSDateStamp];
        [GPSDictionary setObject:@"camera direction (heading) in degrees"
                         forKey:(NSString*)kCGImagePropertyGPSImgDirection];

        [GPSDictionary setObject:@"subject coord Latitude"
                         forKey:(NSString*)kCGImagePropertyGPSDestLatitude];
        [GPSDictionary setObject:@"subject coord Longitude"
                         forKey:(NSString*)kCGImagePropertyGPSDestLongitude];

        [EXIFDictionary setObject:@"[S.D.] kCGImagePropertyExifUserComment"
                           forKey:(NSString *)kCGImagePropertyExifUserComment];

        [EXIFDictionary setValue:@"69 m" forKey:(NSString *)kCGImagePropertyExifSubjectDistance];

        //Add the modified Data back into the image’s metadata
        [metadataAsMutable setObject:EXIFDictionary forKey:(NSString *)kCGImagePropertyExifDictionary];
        [metadataAsMutable setObject:GPSDictionary forKey:(NSString *)kCGImagePropertyGPSDictionary];
        [metadataAsMutable setObject:RAWDictionary forKey:(NSString *)kCGImagePropertyRawDictionary];

        NSLog(@"metadataAsMutable Info: %@",metadataAsMutable);

        CFStringRef UTI = CGImageSourceGetType(imgSource); //this is the type of image (e.g., public.jpeg)

        //this will be the data CGImageDestinationRef will write into
        NSMutableData *newImageData = [NSMutableData data];

        CGImageDestinationRef destination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)newImageData, UTI, 1, NULL);

        if(!destination)
            NSLog(@"***Could not create image destination ***");

        //add the image contained in the image source to the destination, overidding the old metadata with our modified metadata
        CGImageDestinationAddImageFromSource(destination, imgSource, 0, (__bridge CFDictionaryRef) metadataAsMutable);

        //tell the destination to write the image data and metadata into our data object.
        //It will return false if something goes wrong
        BOOL success = NO;
        success = CGImageDestinationFinalize(destination);

        if(!success)
            NSLog(@"***Could not create data from image destination ***");

        CIImage *testImage = [CIImage imageWithData:newImageData];
        NSDictionary *propDict = [testImage properties];
        NSLog(@"Properties %@", propDict);

    }];

Which outputs this:
2012-10-12 23:17:45.415 Waypointer[3120:907] original metadata Info: {
ColorModel = RGB;
DPIHeight = 72;
DPIWidth = 72;
Depth = 8;
Orientation = 1;
PixelHeight = 2448;
PixelWidth = 3264;
"{Exif}" =     {
    ApertureValue = "2.526069";
    BrightnessValue = "-4.410617";
    ColorSpace = 1;
    ComponentsConfiguration =         (
        1,
        2,
        3,
        0
    );
    ExifVersion =         (
        2,
        2,
        1
    );
    ExposureMode = 0;
    ExposureProgram = 2;
    ExposureTime = "0.06666667";
    FNumber = "2.4";
    Flash = 16;
    FlashPixVersion =         (
        1,
        0
    );
    FocalLenIn35mmFilm = 35;
    FocalLength = "4.28";
    ISOSpeedRatings =         (
        800
    );
    MeteringMode = 5;
    PixelXDimension = 3264;
    PixelYDimension = 2448;
    SceneCaptureType = 0;
    SensingMethod = 2;
    ShutterSpeedValue = "3.906905";
    SubjectArea =         (
        1631,
        1223,
        881,
        881
    );
    WhiteBalance = 0;
};
"{TIFF}" =     {
    Orientation = 1;
    ResolutionUnit = 2;
    XResolution = 72;
    YResolution = 72;
    "_YCbCrPositioning" = 1;
};
}

And this:
2012-10-12 23:17:45.421 Waypointer[3120:907] metadataAsMutable Info: {
ColorModel = RGB;
DPIHeight = 72;
DPIWidth = 72;
Depth = 8;
Orientation = 1;
PixelHeight = 2448;
PixelWidth = 3264;
"{Exif}" =     {
    ApertureValue = "2.526069";
    BrightnessValue = "-4.410617";
    ColorSpace = 1;
    ComponentsConfiguration =         (
        1,
        2,
        3,
        0
    );
    ExifVersion =         (
        2,
        2,
        1
    );
    ExposureMode = 0;
    ExposureProgram = 2;
    ExposureTime = "0.06666667";
    FNumber = "2.4";
    Flash = 16;
    FlashPixVersion =         (
        1,
        0
    );
    FocalLenIn35mmFilm = 35;
    FocalLength = "4.28";
    ISOSpeedRatings =         (
        800
    );
    MeteringMode = 5;
    PixelXDimension = 3264;
    PixelYDimension = 2448;
    SceneCaptureType = 0;
    SensingMethod = 2;
    ShutterSpeedValue = "3.906905";
    SubjectArea =         (
        1631,
        1223,
        881,
        881
    );
    SubjectDistance = "69 m";
    UserComment = "[S.D.] kCGImagePropertyExifUserComment";
    WhiteBalance = 0;
};
"{GPS}" =     {
    DateStamp = "camera GPS Date Stamp";
    DestLatitude = "subject coord Latitude";
    DestLongitude = "subject coord Longitude";
    ImgDirection = "camera direction (heading) in degrees";
    Latitude = "camera coord Latitude";
    Longitude = "camera coord Longitude";
};
"{Raw}" =     {
};
"{TIFF}" =     {
    Orientation = 1;
    ResolutionUnit = 2;
    XResolution = 72;
    YResolution = 72;
    "_YCbCrPositioning" = 1;
};
}

And, after it's all done, this:
2012-10-12 23:17:47.131 Waypointer[3120:907] Properties {
ColorModel = RGB;
DPIHeight = 72;
DPIWidth = 72;
Depth = 8;
Orientation = 1;
PixelHeight = 2448;
PixelWidth = 3264;
"{Exif}" =     {
    ApertureValue = "2.526069";
    BrightnessValue = "-4.410617";
    ColorSpace = 1;
    ComponentsConfiguration =         (
        0,
        0,
        0,
        1
    );
    ExifVersion =         (
        2,
        2,
        1
    );
    ExposureMode = 0;
    ExposureProgram = 2;
    ExposureTime = "0.06666667";
    FNumber = "2.4";
    Flash = 16;
    FlashPixVersion =         (
        1,
        0
    );
    FocalLenIn35mmFilm = 35;
    FocalLength = "4.28";
    ISOSpeedRatings =         (
        800
    );
    MeteringMode = 5;
    PixelXDimension = 3264;
    PixelYDimension = 2448;
    SceneCaptureType = 0;
    SensingMethod = 2;
    ShutterSpeedValue = "3.906905";
    SubjectArea =         (
        1631,
        1223,
        881,
        881
    );
    UserComment = "[S.D.] kCGImagePropertyExifUserComment";
    WhiteBalance = 0;
};
"{JFIF}" =     {
    DensityUnit = 1;
    JFIFVersion =         (
        1,
        1
    );
    XDensity = 72;
    YDensity = 72;
};
"{TIFF}" =     {
    Orientation = 1;
    ResolutionUnit = 2;
    XResolution = 72;
    YResolution = 72;
    "_YCbCrPositioning" = 1;
};
}

As the example illustrates, you can see the image's original metaData, its modification, and then its final output.
The final output is what bothers me because no matter what I do, I cannot get my modified values to stick!
Is there some very specific format I'm missing?
Why is iOS stripping my modifications?
What do I need to do to add these extra values?  They are listed in the .header and figured it should be easily accepted.

A:

Scott, a developer at Apple, returned with my incident report and fixed the issue:

The previous code above is writing string values for the GPS
  values - this won't work, they must be NS/CFNumbers (we extract
  a float value for EXIF).

I'll be filing a bug report to Apple against their documentation.
Although it took a week to get this response, I really do appreciate the support Apple provides to their developers.  (thanks Scott!)  ;-)
Below is the improved code and its correct output:
[[self stillImageOutput] captureStillImageAsynchronouslyFromConnection:videoConnection
    completionHandler:^(CMSampleBufferRef imageSampleBuffer, NSError *error)
    {
        NSData *imageNSData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];

        CGImageSourceRef imgSource = CGImageSourceCreateWithData((__bridge_retained CFDataRef)imageNSData, NULL);

        //get all the metadata in the image
        NSDictionary *metadata = (__bridge NSDictionary *)CGImageSourceCopyPropertiesAtIndex(imgSource, 0, NULL);

        //make the metadata dictionary mutable so we can add properties to it
        NSMutableDictionary *metadataAsMutable = [metadata mutableCopy];

        NSMutableDictionary *EXIFDictionary = [[metadataAsMutable objectForKey:(NSString *)kCGImagePropertyExifDictionary]mutableCopy];
        NSMutableDictionary *GPSDictionary = [[metadataAsMutable objectForKey:(NSString *)kCGImagePropertyGPSDictionary]mutableCopy];
        NSMutableDictionary *RAWDictionary = [[metadataAsMutable objectForKey:(NSString *)kCGImagePropertyRawDictionary]mutableCopy];

        if(!EXIFDictionary)
            EXIFDictionary = [[NSMutableDictionary dictionary] init];

        if(!GPSDictionary)
            GPSDictionary = [[NSMutableDictionary dictionary] init];

        if(!RAWDictionary)
            RAWDictionary = [[NSMutableDictionary dictionary] init];

        [GPSDictionary setObject:[NSNumber numberWithFloat:37.795]
                          forKey:(NSString*)kCGImagePropertyGPSLatitude];

        [GPSDictionary setObject:@"N" forKey:(NSString*)kCGImagePropertyGPSLatitudeRef];

        [GPSDictionary setObject:[NSNumber numberWithFloat:122.410]
                          forKey:(NSString*)kCGImagePropertyGPSLongitude];

        [GPSDictionary setObject:@"W" forKey:(NSString*)kCGImagePropertyGPSLongitudeRef];

        [GPSDictionary setObject:@"2012:10:18"
                          forKey:(NSString*)kCGImagePropertyGPSDateStamp];

        [GPSDictionary setObject:[NSNumber numberWithFloat:300]
                          forKey:(NSString*)kCGImagePropertyGPSImgDirection];

        [GPSDictionary setObject:[NSNumber numberWithFloat:37.795]
                          forKey:(NSString*)kCGImagePropertyGPSDestLatitude];

        [GPSDictionary setObject:@"N" forKey:(NSString*)kCGImagePropertyGPSDestLatitudeRef];

        [GPSDictionary setObject:[NSNumber numberWithFloat:122.410]
                          forKey:(NSString*)kCGImagePropertyGPSDestLongitude];

        [GPSDictionary setObject:@"W" forKey:(NSString*)kCGImagePropertyGPSDestLongitudeRef];

        [EXIFDictionary setObject:@"[S.D.] kCGImagePropertyExifUserComment"
                           forKey:(NSString *)kCGImagePropertyExifUserComment];

        [EXIFDictionary setObject:[NSNumber numberWithFloat:69.999]
                           forKey:(NSString*)kCGImagePropertyExifSubjectDistance];

        //Add the modified Data back into the image’s metadata
        [metadataAsMutable setObject:EXIFDictionary forKey:(NSString *)kCGImagePropertyExifDictionary];
        [metadataAsMutable setObject:GPSDictionary forKey:(NSString *)kCGImagePropertyGPSDictionary];
        [metadataAsMutable setObject:RAWDictionary forKey:(NSString *)kCGImagePropertyRawDictionary];

        CFStringRef UTI = CGImageSourceGetType(imgSource); //this is the type of image (e.g., public.jpeg)

        //this will be the data CGImageDestinationRef will write into
        NSMutableData *newImageData = [NSMutableData data];

        CGImageDestinationRef destination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)newImageData, UTI, 1, NULL);

        if(!destination)
            NSLog(@"***Could not create image destination ***");

        //add the image contained in the image source to the destination, overidding the old metadata with our modified metadata
        CGImageDestinationAddImageFromSource(destination, imgSource, 0, (__bridge CFDictionaryRef) metadataAsMutable);

        //tell the destination to write the image data and metadata into our data object.
        //It will return false if something goes wrong
        BOOL success = NO;
        success = CGImageDestinationFinalize(destination);

        if(!success)
            NSLog(@"***Could not create data from image destination ***");

        CIImage *testImage = [CIImage imageWithData:newImageData];
        NSDictionary *propDict = [testImage properties];
        NSLog(@"Final properties %@", propDict);

    }];

Which outputs this:
Final properties info {
    ColorModel = RGB;
    DPIHeight = 72;
    DPIWidth = 72;
    Depth = 8;
    Orientation = 6;
    PixelHeight = 2448;
    PixelWidth = 3264;
    "{Exif}" =     {
        ApertureValue = "2.526069";
        BrightnessValue = "0.547474";
        ColorSpace = 1;
        ComponentsConfiguration =         (
            0,
            0,
            0,
            1
        );
        ExifVersion =         (
            2,
            2,
            1
        );
        ExposureMode = 0;
        ExposureProgram = 2;
        ExposureTime = "0.05";
        FNumber = "2.4";
        Flash = 16;
        FlashPixVersion =         (
            1,
            0
        );
        FocalLenIn35mmFilm = 35;
        FocalLength = "4.28";
        ISOSpeedRatings =         (
            320
        );
        MeteringMode = 5;
        PixelXDimension = 3264;
        PixelYDimension = 2448;
        SceneCaptureType = 0;
        SensingMethod = 2;
        ShutterSpeedValue = "4.321929";
        SubjectArea =         (
            1631,
            1223,
            881,
            881
        );
        SubjectDistance = "69.999";
        UserComment = "[S.D.] kCGImagePropertyExifUserComment";
        WhiteBalance = 0;
    };
    "{GPS}" =     {
        DateStamp = "2012:10:18";
        DestLatitude = "37.795";
        DestLatitudeRef = N;
        DestLongitude = "122.41";
        DestLongitudeRef = W;
        ImgDirection = 300;
        Latitude = "37.795";
        LatitudeRef = N;
        Longitude = "122.41";
        LongitudeRef = W;
    };
    "{JFIF}" =     {
        DensityUnit = 1;
        JFIFVersion =         (
            1,
            1
        );
        XDensity = 72;
        YDensity = 72;
    };
    "{TIFF}" =     {
        Orientation = 6;
        ResolutionUnit = 2;
        XResolution = 72;
        YResolution = 72;
        "_YCbCrPositioning" = 1;
    };
}

As you can see, all values are now properly embedded into the EXIF header and I've tested that this is correctly written with the JPG to the camera roll.
Enjoy!  :)


Q:

Given a table with a varchar column, return the entries that do not have any suffix in a different row

Example: A query on a table containing the following strings -
----------
| abcd    |
----------
| abc     |
----------
| bcda    |
----------
| bcdag   |
----------
| bc      |
----------

Would output
--------
| abcd |
--------
| bcdag|
--------

A:

You could use the not exists operator:
SELECT col
FROM   mytbale a
WHERE  NOT EXISTS (SELECT *
                   FROM   mytable b
                   WHERE  a.col <> b.col AND
                          a.col LIKE CONCAT(b.col, '%'))


Q:

Fancy container - Fancy box

Please, I would like to know how can I produce this type of fancy container in latex. Do I have to use fancy box or something like that?
Thanks in advance for any help

A:

Use the bclogo package and its bclogo environment, changing the default logo with logo=\bccrayon.
\documentclass{article}

\usepackage{blindtext}
\usepackage[tikz]{bclogo}

\begin{document}

\begin{bclogo}[logo={\bccrayon},arrondi=0.1]{Code}
\blindtext
\end{bclogo}

\end{document}


Q:

How to use the "Grid for Indexing" in the print composer QGIS 2.14.2?

I created a grid with plugin Create Grid for Indexing. Until now all fine.
But how can I use the grid (Create Grid for Indexing) in the print composer?
The task:
I have a map and a overview. I want to have information about the location of the map, for example, "The map is in M1" or "The map is in G5", etc.
How to make that in the print composer and using Create Grid for Indexing?

A:

I tried it to create an atlas with output from the plugin and had problems, but got it to work, eventually! (disclosure - I'm the plugin author)
The plugin creates a memory layer. It seems that you can't use memory layers as coverage in Atlas. But you can get around that by saving the layer as a shapefile or other format (I suggest you do this anyway, as the memory layer will be lost when you close QGIS).
To get around this,

set the CRS in the memory layer if required (the plugin doesn't do that at the moment)
save the memory layer to a new shapefile layer
use the new shapefile layer as coverage in the atlas
add a piece of text, and use the following expression  This is map [% "name" %]

Name is the field which contains the cell reference (A1,A2,B15 etc)
You should now be able to produce one map per grid square, like this...

.. or with an overview


Q:

Haskell: Desugaring State do notation

I have a contrived function to help calculate the Fibonacci sequence using State.
fbs :: Int -> State (Int,Int) Int
fbs = \_ -> do
  (a,b) <- get
  put (b,a+b)
  (a,_) <- get
  pure a

It compiles when I write it with do notation, but I can't desugar it:
fbs' :: Int -> State (Int, Int) Int
fbs' = \_ -> get >>= (\(a,b) ->
  put (b,a+b) *>
    get (\(a,_) ->
      pure a ))

 * Ambiguous type variable `f0' arising from a use of `pure'

What am I doing wrong?

A:

Roughly put, each do line corresponds to >>= (or some of its simpler forms like >>).
In your case, you get:
fbs = \_ ->
  get >>= ( \ (a,b) ->
     put (b,a+b) >>
        get >>= ( \ (a,_) ->
           pure a ))

I added some redundant parentheses and indentation for clarity.
Your original code lacks a >>= after the second get.


Q:

Creating components from templates (Template or XTemplate)

I'd like to be able to generate a component from within a template. The use case for it is that when I generate a row in a DataView I'd like to be able to incorporate buttons and/or other components (maybe even a nested grid) to the rendered items.
So far everywhere I look all I see is a template calling another template. Is there a way to do what I'd like (generate component instead of just plain html) from an XTemplate?

A:

Since an XTemplate is just used for generating markup to be inserted into the DOM, it alone is not enough to create components -- Components do have an underlying DOM element (through component.el.dom), but also exist as JavaScript objects in browser memory with other methods and properties.
It is possible to accomplish what you are asking through several different ways... you can use the XTemplate to generate the markup, and use the Component.applyTo config option to create a Component object in memory that is linked to the DOM element from your template.  Of course, you will have to wait until the template is applied and then create a component with applyTo set to the correct DOM element.
You could also extend the XTemplate class to do the same thing just mentioned, but wrapped up in the applyTemplate stuff.  I am pretty sure that Ext does not have a built-in way for the templates to create components -- so far they just create HTML.


Q:

c++ count in for statement

I use atom when writing code in C++. When I auto complete a for statement it looks like:
for (size_t i = 0; i < count; i++) {
    /* code */
}

What does "count" mean (if anything)?

A:

Count is a descriptive term identifying the number of iterations (of the loop).  Replace 'count' with a number or a symbol from which the iteration count can be computed.

A:

count is a variable, that should be defined 'before the loop', or like this:
int count = 10;
for (size_t i = 0; i < count; i++) { /* ... */ }

or just substitute count with a number i.e.
for (size_t i = 0; i < 10; i++) { /* ... */ }


Q:

Cumulative amount by Date

We have a table holding the values of a cumulative amount by date, for instance:
|       date.      |          |

| 2015-03-01 | 1.23 |

| 2015-03-04 | 1.98 |

| 2015-03-06 | 2.23 |

And we have a table with all dates we need, for instance:

|       date.      |

| 2015-03-01 |

| 2015-03-02 |

| 2015-03-03 |

| 2015-03-04 |

| 2015-03-05 |

| 2015-03-06 |

We would like to get:

|       date.      |          |

| 2015-03-01 | 1.23 |

| 2015-03-02 | 1.23 |

| 2015-03-03 | 1.23 |

| 2015-03-04 | 1.98 |

| 2015-03-05 | 1.98 |

| 2015-03-06 | 2.23 |

Is that possible just using SQL itself?
I'm having a bad time trying to figure how to do that.
I have tried some cross joins operations, without success.
Thanks

A:

SELECT
  [date],
  amount
FROM (
  SELECT
    [date],
    amount,
    ROW_NUMBER() OVER(PARTITION BY [date] ORDER BY delta) AS win
  FROM (
    SELECT
      dates_table.date AS [date],
      DATEDIFF(TIMESTAMP(dates_table.date), TIMESTAMP(amounts_table.date)) AS delta,
      amount
    FROM amounts_table CROSS JOIN dates_table
    WHERE DATEDIFF(TIMESTAMP(dates_table.date), TIMESTAMP(amounts_table.date)) >= 0
  )
)
WHERE win = 1
ORDER BY 1

A:

I realized - it should be even simplier (much simplier) in this particular case.
Try below
SELECT
  dates_table.date,
  MAX(amounts.amount) OVER(ORDER BY dates_table.date) AS amount
FROM dates_table LEFT JOIN amounts_table
ON dates_table.date  = amounts_table.date

As some of you have problem adopting this answer and thinking it
  doesnt work  - I just added below example to "prove" above is working
  :o)

SELECT
  dates.date,
  MAX(amounts.amount) OVER(ORDER BY dates.date) AS amount
FROM (
  SELECT * FROM
    (SELECT '2015-03-01' AS [date]),
    (SELECT '2015-03-02' AS [date]),
    (SELECT '2015-03-03' AS [date]),
    (SELECT '2015-03-04' AS [date]),
    (SELECT '2015-03-05' AS [date]),
    (SELECT '2015-03-06' AS [date])
) AS dates
LEFT JOIN (
  SELECT * FROM
    (SELECT '2015-03-01' AS [date],  1.23 AS amount),
    (SELECT '2015-03-04' AS [date], 1.98 AS amount),
    (SELECT '2015-03-06' AS [date], 2.23 AS amount)
) AS amounts
ON dates.date  = amounts.date

Result is:
Row dates_date  amount
1   2015-03-01  1.23
2   2015-03-02  1.23
3   2015-03-03  1.23
4   2015-03-04  1.98
5   2015-03-05  1.98
6   2015-03-06  2.23


Q:

Date range issue in pandas python

I tried this:
pd.date_range(2000, periods = 365, freq = 'D',format = '%d-%m-%Y')

why I am getting this result:
DatetimeIndex(['1970-01-01 00:00:00.000002', '1970-01-02 00:00:00.000002',
               '1970-01-03 00:00:00.000002', '1970-01-04 00:00:00.000002',
               '1970-01-05 00:00:00.000002', '1970-01-06 00:00:00.000002',
               '1970-01-07 00:00:00.000002', '1970-01-08 00:00:00.000002',

Any help?

A:

You need add '' to 2000 only:
print (pd.date_range('2000', periods = 365, freq = 'D'))

DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04',
               '2000-01-05', '2000-01-06', '2000-01-07', '2000-01-08',
               '2000-01-09', '2000-01-10',
               ...
               '2000-12-21', '2000-12-22', '2000-12-23', '2000-12-24',
               '2000-12-25', '2000-12-26', '2000-12-27', '2000-12-28',
               '2000-12-29', '2000-12-30'],
              dtype='datetime64[ns]', length=365, freq='D')

If use int, cast it to str:
print (pd.date_range(str(2000), periods = 365, freq = 'D'))


Q:

Getting "An action can only be invoked as a 'POST' request" when I am trying to call outlook restful api

Currently working with the outlook api, even tough I usually work with the outlook library acquired via Nuget; I have reached a limitation where I am not able to accept event invitations.  So I proceeded in making a a restful call out to the the outlook api.  However, when I am making the call I am getting the following message {"error":{"code":"InvalidMethod","message":"An action can only be invoked as a 'POST' request."}} when executing the call.
Bad Code
 class Program
    {
        static void Main(string[] args)
        {
                var testAccept = ExecuteClientCall.AcceptEvent().Result;
        }

 public static async Task<bool> AcceptEvent()
        {
            AuthenticationContext authenticationContext = new AuthenticationContext(CrmPrototype.Helpers.AuthHelper.devTenant);
            try
            {
                var token = await GetTokenHelperAsync(authenticationContext, CrmPrototype.Helpers.AuthHelper.OutlookAuthenticationEndpoint);
                string requestUrl = "https://outlook.office.com/api/v2.0/Users/***@nowwhere.com/events('AAQkAGZiNDQxZTVkLWQzZjEtNDdjNy04OTc4LTM4NmNjM2JiOTRjNAAQAFpV0CnWR0FIpWFYRtszPHU=')/accept";

                HttpClient hc = new HttpClient();
                hc.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);

                var method = new HttpMethod("POST");

                var request = new HttpRequestMessage(method, requestUrl)
                {
                    Content = new StringContent("{SendResponse: true}", Encoding.UTF8, "application/json")
                };

                HttpResponseMessage hrm = await hc.GetAsync(requestUrl);

                if (hrm.IsSuccessStatusCode)
                {
                    string jsonresult = await hrm.Content.ReadAsStringAsync();
                    var stophere = 0;

                }
                else
                {
                    return false;
                }
                return true;
            }

            catch (Exception ex)
            {
                throw;
            }
        }

    }

A:

Maybe the reason is that you called
hc.GetAsync(requestUrl);

The doc said that this method:
Sends a GET request to the specified Uri as an asynchronous operation.

Try:
PostAsync(Uri, HttpContent)

https://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.118).aspx
Hope this help you.


Q:

Subsequent from clause vs query continuation

What's the difference between using a subsequent from clause and a query continuation?
By subsequent from clause, I mean using the ...from...in...from...in...select pattern of building a query.
About query continuations and into, this MSDN article says:

It is often useful to treat the results of one query as a generator in a subsequent query.

So, the into keyword helps us with chaining together queries, so to speak. It seems, though, that we don't need the into keyword for this. Instead, we can just use a subsequent from clause. But, the article elaborates:

...use the into keyword to splice a new query expression after a select or group clause.

So, the into permits using a select or group before splicing in the new query. Is that the only reason to use a query continuation instead of the simpler subsequent from clause?
For instance, the following two queries do the same thing.
https://dotnetfiddle.net/pwKcQU
using System;
using System.Collections;
using System.Linq;

public static class Program
{
    public static void Main()
    {
        var array = new [] { "ab", "cd" };

        var subsquentFromClause =
            from first in array
            from second in first
            select second;

        subsquentFromClause.Dump("Subsequent");

        var queryContinuation =
            from first in array select first into x
            from second in x select second;

        queryContinuation.Dump("Continuation");

    }

    public static void Dump(this IEnumerable query, string title)
    {
        Console.WriteLine("\n" + title);
        foreach(var r in query)
        {
            Console.WriteLine(r);
        }
    }
}

A:

The best way to find out what actually happens is to use a tool like ILSpy to disassemble the code and look at it.
Query expressions are basically syntactic sugar. They are there for your convenience and then are converted to actual function calls. The compiler mechanically translates them into a series of calls to IEnumerable<T> extension methods. For example, the two from clauses are translated into the SelectMany extension method with required arguments for that expression.
In this specific query-continuation case:

you would have an extra projection to do before the SelectMany, and
your SelectMany would have access to the projection x, but
the variable first will no longer be in scope.

The actual extension method chain call generated is kind of hard to do manually. The easiest way is to look at it in ILSpy.
I don't even think there are any optimizations done in the conversion as it is completely mechanical. If the conversion was smarter it could optimize the projection out in your example.
Take a look at here to see some instance of ILSpy decompilation.
For instance, here is the IL for your queries:
//Subsequent
System.String[]
   .SelectMany (
      first => first,
      (first, second) => second
   )

//Continuation
System.String[]
   .Select (first => first)
   .SelectMany (
      x => x,
      (x, second) => second
   )


Q:

Writing a file in PHP with a cron

I am trying to write a file to a sub folder of the directory my cron script is in using file_ put_ contents. However, I keep getting a warning "failed to open stream: No such file or directory."
I have this directory structure:

httpdocs/scripts/fileDirectory

The cron script lives in the scripts folder. I call it with the cron command:
php httpdocs/scripts/cron_writeFile.php

In the cron_writeFile file, I first tried:
file_put_contents('fileDirectory/', $fileName, $fileContents);

which works when I load the page in a browser, but not when the cron executes.
When I require_once a file in a cron, I have to put the 'absolute' path to it:
require_once('httpdocs/scripts/requiredFile.php');

So, I tried that:
file_put_contents('httpdocs/scripts/fileDirectory/', $fileName, $fileContents);

No luck. I'm pretty sure it's getting to the right folder because the warning is:

"Warning: file_ put_ contents(httpdocs/scripts/fileDirectory/4.txt):
  failed to open stream: No such file or directory in
  /var/www/vhosts/myDomain.com/httpdocs/scripts/cron_writeFile.php
  on line 93"

The both directories have write permissions.
I am using a VPS running (I know it sucks and I need to upgrade, but I don't have the authority)
Parallels Plesk Panel version   9.2.1
with PHP 5.0.4
The file does not exist and I need a new file each time the script runs.
I am not sure if there is a certain way to define the file path or some other thing I am missing.
Thanks for your help!

A:

What if you use dirname(__FILE__) (see) to get an absolute path to your "fileDirectory" directory ?
Something like this in your script, I guess, if your fileDirectory is a child of the directory where your file resides :
file_put_contents(dirname(__FILE__) . '/fileDirectory/' . $fileName, $fileContents);

That way, you don't depend on relative path, which can be wrong if your script is not launched from the "right" directory.


Q:

Calculate integrals $\int_{{\pi \over 4}}^{\arctan {1 \over 2}} {{{\sqrt {{\mathop{\rm cos}\nolimits u} } } \over {\sqrt {\sin u} }}du} $

This is my homework. And it's really a challenge for me. Can anyone solve this.

$$\large\int\limits_{{\pi  \over 4}}^{\arctan {1 \over 2}} {{\sqrt{\cos u}   \over {\sqrt {\sin u} }}du} $$

A:

You can simplify the integral as follows:
$$
\int \sqrt{\cot u}~ du
$$
Let's set $$I_1=\int (\sqrt{\tan u}+\sqrt{\cot u})~du$$
By taking $u=\arctan t^2$ so $du= \frac{2t}{1+t^4}dt$ and then:
 $$I_1=2\int \frac{t(t+\frac{1}{t})}{1+t^4}dt=2\int \frac{1+\frac{1}{t^2}}{(t-\frac{1}{t})^2+2}dt$$
Now, setting $t-\frac{1}{t}=z$, we get $(1+\frac{1}{t^2})dt=dz$ and $I_1$ would be changed to:
$$I_1=2\int \frac{1}{z^2+2}dz =\sqrt{2}\tan^{-1}\left(\frac{z}{\sqrt{2}}\right)+c=\sqrt{2}\tan^{-1}\left(\frac{\sqrt{\tan u}-\sqrt{\cot u}}{\sqrt{2}}\right)+C$$
By the similar way, if we take $$I_2=\int (\sqrt{\tan u}-\sqrt{\cot u})du$$
then, in denominator make term $(t+1/t)^2-1$ and substitute $t+1/t=z$ next. This gives us $I_2$. Now we have:
$$I_3=\int \sqrt{\cot u}du=\frac{I_1-I_2}{2}$$
I let you put the bounds and calculate the value!


Q:

I want print alert message when login failed

I am trying to print alert message when login failed.when user failed login then i get this URL. what I am trying print alert message when I getting this url. clearly I want print alert message behalf of URL Value.
Any help .
http://example.com/?login=failed&redirect_to=%2Fstarstruckmedia%2F

A:

if(window.location.href.indexOf("login=failed") > -1) {
   alert("login failed");
}


Q:

Tune FFmpeg H.264 Decoder

I'm using the FFmpeg avcodec to decode live video - the avcodec_decode_video2 function from libx264 to be exact. How can I decrease the decoding time for each frame? At the moment it takes 20 ms for each frame (frame size about 1.5 KB).

A:

Ok, may be it will be helpful for someone. By the way, for decoding we use function avcodec_video_decode2 from FFMPEG. And we can make delay lesser by two ways. The first: turn on AVCodecContext *ctx->thread_count=NBut in this case we get a stream with a delay however it is not good for real time video. The second way is use coder which will be code image in slice based mode e.g. libx264. In this case the delay is absent by definition. But it makes some limitation e.g. a count of threads is a count of slice.


Q:

OpenCL conditional statement issue

I've attempted to parallelize a set of conditional statements, but the output does not match existing implementation after the first loop which contains the kernel executes (mapI is an int array of 135, and on the 60th index of the second loop it fails, totaling 195 calls to mapI). I've checked that all arrays are passing to and from the kernel correctly by comparing them to the existing implementation and am baffled as to why this computation does not return the correct result, as it does for the first loop of the code. All OpenCL overhead functions return CL_SUCCESS.
cl_mem Q1cl, Q3cl;
Q1cl = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(double)*um->Npts*um->Nel, Q1, &err);
Q3cl = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, sizeof(double)*um->Npts*um->Nel, Q3, &err);
nxcl = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, sizeof(double)*um->Nel*um->Nfaces*um->Nfq, nx, &err);
nycl = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, sizeof(double)*um->Nel*um->Nfaces*um->Nfq, ny, &err);
mapIcl = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(int)*(um->Nfq+um->Ninflow), mapI, &err);
mapFcl = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(int)*(um->Nfq+um->Nfar), mapF, &err);
fluxQ1cl = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_USE_HOST_PTR, sizeof(double)*um->Nel*um->Nfaces*um->Nfq, *fluxQ1check, &err);

err = clSetKernelArg(kernel[7], 0, sizeof(cl_mem), (void*)&mapIcl);
err = clSetKernelArg(kernel[7], 1, sizeof(cl_mem), (void*)&nxcl);
err = clSetKernelArg(kernel[7], 2, sizeof(cl_mem), (void*)&nycl);
err = clSetKernelArg(kernel[7], 3, sizeof(cl_mem), (void*)&mapFcl);
err = clSetKernelArg(kernel[7], 4, sizeof(cl_mem), (void*)&Q1cl);
err = clSetKernelArg(kernel[7], 5, sizeof(cl_mem), (void*)&Q3cl);
err = clSetKernelArg(kernel[7], 6, sizeof(cl_mem), (void*)&fluxQ1cl);

globalWorkSize[0] = Ninflow; //Old implementation, now NEL
globalWorkSize[1] = Nfar;    //Old implementation, now NFACES*NFQ

err = clEnqueueNDRangeKernel(queue[0], kernel[7], 2, NULL, globalWorkSize, NULL, 0, NULL, NULL);
err = clEnqueueReadBuffer(queue[0], fluxQ1cl, CL_TRUE, 0, sizeof(double)*um->Nel*um->Nfaces*um->Nfq, *fluxQ1check, 0, NULL, NULL);

Kernel Code:
__kernel void umBC(__global int* mapI,
               __global double* nx,
               __global double* ny,
               __global int* mapF,
               __global double* Q1,
               __global double* Q3,
               __global double* fluxQ1)
{

int id, idF;
double e[9][2] = { {0, 0},  {1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, 1}, {-1, 1}, {-1, -1}, {1, -1}};
double t_1 = 1. / 9.;
double uf = 0.;
double vf = 0.;

int globalx = get_global_id(0);
int globaly = get_global_id(1);
id = mapI[globalx];
fluxQ1[id] = ((e[1][0]*nx[id] + e[1][1]*ny[id]) < 0)*((Q1[id]-Q3[id] -2.*t_1*1.*(e[1][0]*uf+e[1][0]*vf)*3.) * (e[1][0]*nx[id] + e[1][1]*ny[id])) + 0.;

uf = 0.01;
vf = 0.;
idF = mapF[globaly];
fluxQ1[idF] = ((e[1][0]*nx[idF] + e[1][1]*ny[idF]) < 0)*((Q1[idF]-Q3[idF] -2.*t_1*1.*(e[1][0]*uf+e[1][0]*vf)*3.) * (e[1][0]*nx[idF] + e[1][1]*ny[idF])) + 0.;

}

Edit: Below is the working implementation, thank you again doqtor and Lee for your help. To implementthis I needed to change the way mapI and mapF worked to match the sizing of fluxQ.
__kernel void umBC(__global int* mapI,
               __global double* nx,
               __global double* ny,
               __global int* mapF,
               __global double* Q1,
               __global double* Q3,
               __global double* fluxQ1)
{

double e[9][2] = { {0, 0},  {1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, 1}, {-1, 1}, {-1, -1}, {1, -1}};
double t_1 = 1. / 9.;
double uf = 0.;
double vf = 0.;

int globalx = get_global_id(0); //NEL
int globaly = get_global_id(1); //NFACES*NFQ

if(mapI[globalx*NFACES*NFQ+globaly] != NEL*NFACES*NFQ+1000){
    fluxQ1[globalx*NFACES*NFQ+globaly] = 0.0;
    if ((e[1][0]*nx[globalx*NFACES*NFQ+globaly] + e[1][1]*ny[globalx*NFACES*NFQ+globaly]) < 0){
        fluxQ1[globalx*NFACES*NFQ+globaly] = (Q1[globalx*NFACES*NFQ+globaly]-Q3[globalx*NFACES*NFQ+globaly] -2.*t_1*1.*(e[1][0]*uf+e[1][0]*vf)*3.) * (e[1][0]*nx[globalx*NFACES*NFQ+globaly] + e[1][1]*ny[globalx*NFACES*NFQ+globaly]);
    }
}
uf = 0.01;
vf = 0.;
if(mapF[globalx*NFACES*NFQ+globaly] != NEL*NFACES*NFQ+1000){
    fluxQ1[globalx*NFACES*NFQ+globaly] = 0.0;
    if ((e[1][0]*nx[globalx*NFACES*NFQ+globaly] + e[1][1]*ny[globalx*NFACES*NFQ+globaly]) < 0){
        fluxQ1[globalx*NFACES*NFQ+globaly] = (Q1[globalx*NFACES*NFQ+globaly]-Q3[globalx*NFACES*NFQ+globaly] -2.*t_1*1.*(e[1][0]*uf+e[1][0]*vf)*3.) * (e[1][0]*nx[globalx*NFACES*NFQ+globaly] + e[1][1]*ny[globalx*NFACES*NFQ+globaly]);
    }
}
}

A:

You get wrong results because your kernel is not implemented correctly. @Lee already said that, I will try to further explain why.
Let's say for simplicity we consider executing kernel using 2x2 global range.
Now, the (globalx, globaly) for each work item will be:
(0, 0)
(0, 1)
(1, 0)
(1, 1)

so:
work item (0, 0) writes to fluxQ1[mapI[0]] and fluxQ1[mapF[0]]
work item (0, 1) writes to fluxQ1[mapI[0]] and fluxQ1[mapF[1]]
work item (1, 0) writes to fluxQ1[mapI[1]] and fluxQ1[mapF[0]]
work item (1, 1) writes to fluxQ1[mapI[1]] and fluxQ1[mapF[1]]

Assuming that mapI[0], mapI[1], mapF[0] and mapF[1] return unique ids then 2 work items write to the same location in parallel which obviously can't give you correct results. This will get worse if mapI and mapF can return same ids.
Some of the results you get correct by luck.
Changing number of global or local work items won't help, using select or not won't help either. You need to ensure work items don't write to the same location at the same time!


Q:

Jquery - I have got multiple forms on page. How to update each form without reloading the page

I am a beginner with jQuery and I am trying to create a page with multiple forms and each form is having 3 common fields in them, they are: 1. Hidden field with uniqueID, 2. textbox and 3. submit button.
My concern is how do I get the value of a hidden field and text box for each form record on click of a submit button but not refreshing the page. I have used the below jQuery, AJAX but this doesn't pass the values for that form on submit.
Anyone can help me with this please.
Javascript I am using is below:
$(document).ready(function() {
    $(".submit").click(function(){
        alert($(this).serialize());
        $.ajax({
        url:"ajax.php",
        type:"POST",
        //data:form.serialize(),
        data:$(this).serialize(),
        success:function(response){
          console.log(response);
            //Do stuff here
      }

   });
        return false;
    });
});

A:

Try and see what
alert($(this).parent().serialize());

is returning. this is relative to the selector which in your example is the element with class="submit"


Q:

append array of json logstash elasticsearch

how can i append an array on elasticsearch with json object using logstash from csv
exemple of csv
a csv containt lines
id,key1,key2
1,toto1,toto2
1,titi1,titi2
2,tata1,tata2

the result should be 2 documents
{
    "id": 1,
    [{
        "key1": "toto1",
        "key2": "toto2"
    }, {
        "key1": "titi1 ",
        "key2": "titi2"
    }]
}
,{
    "id": 2,
    [{
        "key1": "tata1",
        "key2": "tata2"
    }]
}

cordially

A:

First, create your ES mapping, if necessarry, declaring you inner objects as nested objects.
{
 "mappings": {
    "key_container": {
      "properties": {
        "id": {
          "type": "keyword",
          "index": true
        },
        "keys": {
          "type": "nested",
          "properties": {
            "key1": {
              "type": "keyword",
              "index": true
            },
            "key2": {
              "type": "text",
              "index": true
            }
          }
        }
      }
    }
  }
 }

The keys property will contain the array of nested objects.
Than you can load the csv in two hops with logstash:

Index (Create) the base object containing only the id property
update the base object with the keys property containing the array of nested objects

The first logstash configuration (only the relevant part):
filter {
    csv {
        columns => ["id","key1","key1"]
        separator => ","
        # Remove the keys because the will be loaded in the next hop with update
        remove_field => [ "key1", "key2"]
    }
    # Remove the row containing the column names
    if [id] == "id" {
        drop { }
    }
}
output {
    elasticsearch {
        action => "index"
        document_id => "%{id}"
        hosts => [ "localhost:9200" ]
        index => "key_container"
    }
}

The second steps logstash configuration (you have to enable scripting in elasticsearch):
filter {
    csv {
        columns => ["id","key1","key2"]
        separator => ","
    }
    # Convert the attributes into an object called 'key' that is passed to the script below (via the 'event' object)
    mutate{
        rename => {
            "key1" => "[key][key1]"
            "key2" => "[key][key2]"
        }
    }
}
output {
    elasticsearch {
        action => "update"
        document_id => "%{id}"
        doc_as_upsert => "true"
        hosts => [ "localhost:9200" ]
        index => "key_container"
        script_lang => "groovy"
        # key_container.keys is an array of key objects
        # arrays can be built only with scripts and defined as an array when we put the first element into it
        script => "if (ctx._source.containsKey('keys')) {ctx._source.keys += event.key} else {ctx._source.keys = [event.key]}"
    }
}

Summary, you need this two hop loading because of array creation that requires scripting which is available only with update.


Q:

MessageSecurityException, UsernamePasswordValidator, and HttpWebRequest Problem

is there a better way to return back the standard "Invalid username/password" message to clients that connect to a WCF service requiring credentials? I have the following code, which causes an exception when I connect to my WCF service with invalid usernames/passwords.
Ideally I'd like back just a simple string, but to get the UsernamePasswordValidator to signal bad usernames requires throwing either a FaultException or SecurityTokenException, which causes an exception on the client-side at the HttpWebRequest's GetResponse method.
FileInfo file = new FileInfo("Request.xml");
string payload = file.OpenText().ReadToEnd();

HttpWebRequest request = HttpWebRequest.Create(URL) as HttpWebRequest;
request.ContentType = "text/xml";
request.ContentLength = payload.Length;
request.MediaType = "utf-8";
request.Method = "POST";
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(payload);
writer.Flush();
writer.Close();

Console.WriteLine("Awaiting Response...");
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
StreamReader reader = new StreamReader(response.GetResponseStream());
Console.WriteLine(reader.ReadToEnd());
Console.ReadKey(true);

The reason I want to do that is the service will be hit by clients not using .NET.

A:

Put it in a try - catch statement and catch the exception, then pass your own message in the catch block


Q:

How to edit the font options in CKEditor?

I am using CKEditor 4.6 with the official font size and family plugin. Is it possible to change the font family option?
I am using fonts from Google Fonts and so I have the extra font files needed.

A:

Use the font_names configuration option.

The list of fonts names to be displayed in the Font combo in the
  toolbar. Entries are separated by semi-colons (';'), while it's
  possible to have more than one font for each entry, in the HTML way
  (separated by comma).
A display name may be optionally defined by prefixing the entries with
  the name and the slash character. For example, 'Arial/Arial,
  Helvetica, sans-serif' will be displayed as 'Arial' in the list, but
  will be outputted as 'Arial, Helvetica, sans-serif'.

config.font_names =
    'Arial/Arial, Helvetica, sans-serif;' +
    'Times New Roman/Times New Roman, Times, serif;' +
    'Verdana';

config.font_names = 'Arial;Times New Roman;Verdana';


Q:

100k "thank yous" or 100k "thank you's"?

I wanted to thank people for their visits to a profile but Google wasn't quite sure either. Is there another way to express the same meaning?

A:

the expresion comes from a verbal form, so the noun has to be hyphenated.
So, it is one "thank-you" or several "thank-you's" (because of the compound form).
but, in everyday use, "thank yous" is also correct. and please note that hyphens are also omitted in everyday use so it might become "thank you's".
you can also say " I thank you all for ..." or " I express my gratitude to all..." or " I am thankful..."


Q:

mvc - show/hide stuff based on what view it is for a user control

Im using asp.net mvc. I have a create and edit form which are very similar so im using a user control for the form.
and placing that in each view.
the form is very slightly different on the edit form eg it has some extra text and a link.
how can i show/hide that based on the view im in?

A:

I would either put it in the model (i.e. an "IsEditMode" or "IsAddMode" parameter) or, better yet, pass it in via the ViewData:
<%
ViewData["IsEditMode"] = true;
Html.RenderPartial("FormView", Model);
%>

Then just check for the IsEditMode value in the ViewData


Q:

with Ansible and apt, how do I update bash to for the remotely exploitable security vulnerability CVE-2014-6271?

Given bash's remote code execution vulnerability announced on Sept 24 2014, how can I update my apt-based systems using Ansible?

A:

Here's my preferred solution in a fairly homogenous environment. The advantage of this is the update won't take a lot of time in the future, unlike the version=latest pattern others are using.
- name: update apt cache if not done today
  apt: update_cache=yes cache_valid_time=86400

# http://seclists.org/oss-sec/2014/q3/650
- name: ensure secure ansible, ubuntu 1204 edition
  apt: pkg=bash=4.2-2ubuntu2.5 state=present
  when: ansible_distribution=='Ubuntu' and ansible_distribution_version=='12.04'

- name: ensure secure ansible, ubuntu 1404 edition
  apt: pkg=bash=4.3-7ubuntu1.3 state=present
  when: ansible_distribution=='Ubuntu' and ansible_distribution_version=='14.04'

# based on the following gist and comments below. there have been several exploits, this covers them well.
# https://gist.github.com/kacy/2b9408af04c71fab686e
- name: ensure bash is not vulnerable to 201409 problem
  shell: "foo='() { echo not patched; }' bash -c foo"
  register: command_result
  ignore_errors: yes
  failed_when: "'command not found' not in command_result.stderr"

Explanation: updating the apt-cache is expensive if done many times per day. The cache time can be adjusted. The code actually tests to make sure the vulnerability is fixed- tests are good. This will highlight any hosts that aren't covered by the distributions/versions coded.
SO user @jarv posted a great solution too. Instead of always updating apt, it only does so if the problem hasn't been fixed. This is the fastest solution possible (in this answer, at least). jarv has also added a distribution test in the linked repo, useful for heterogeneous environments.
- name: Check if we are vulnerable
  shell: executable=/bin/bash env x='() { :;}; echo vulnerable'  bash -c "echo this is a test"
  register: test_vuln

- name: Apply bash security update if we are vulnerable
  apt: name=bash state=latest update_cache=true
  when: "'vulnerable' in test_vuln.stdout"

- name: Check again and fail if we are still vulnerable
  shell: executable=/bin/bash env x='() { :;}; echo vulnerable'  bash -c "echo this is a test"
  when: "'vulnerable' in test_vuln.stdout"
  register: test_vuln
  failed_when: "'vulnerable' in test_vuln.stdout"

There are other ways. Michael DeHaan, creator of Ansible, and the official @ansible account tweeted a few solutions:
Here's a one-liner:
ansible all -m apt -a 'update_cache=yes name=bash state=latest'

Here's a update-and-check solution:
- name: update apt
  command: apt-get update

- name: update bash
  command: apt-get --only-upgrade install bash

- name: check bash fix
  command: env x='() { :;}; echo vulnerable' bash -c "echo this is a test"
  register: command_result
  failed_when: "'error' not in command_result.stderr"


Q:

Values of array not calculating in subclass when called

Just doing some of the Gold challenges in the BNR iOS book and Chapter 2's challenge has got me stumped.
This is my BNRContainer.m class file that is a subclass of BNRItem. The object of the challenge is to override the object's description and print out some of it's attributes. The one that isn't calculating correctly is the BNRContainer's containerValue.
#import "BNRContainer.h"

...

-(int)containerValue{

    int total = 0;

    for (BNRItem *item in self.subItems) {
        total += item.valueInDollars;
    }

    return total;
}

-(NSString *)description{

    NSString *descriptionstr = [NSString stringWithFormat:@"I'm a container named %@! My total value is %d and my items are %@",self.itemName, containerValue, self.subItems];
    return descriptionstr;
}

Here's the Main.m:
#import <Foundation/Foundation.h>
#import "BNRItem.h"
#import "BNRContainer.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        NSMutableArray *items = [[NSMutableArray alloc] init];

        BNRItem *item = [[BNRItem alloc] initWithItemName:@"Red Sofa" valueInDollars:100 serialNumber:@"A1B2C"];
        BNRItem *itemWithName = [[BNRItem alloc] initWithItemName:@"Blue Sofa" valueInDollars:45 serialNumber:NULL];
        BNRItem *itemWithNoName = [[BNRItem alloc]init];

        [items addObject:item];
        [items addObject:itemWithName];
        [items addObject:itemWithNoName];

        BNRContainer *container = [[BNRContainer alloc]init];

        container.itemName = @"TheMainContainer";
        container.subItems = items;

        NSLog(@"%@",container);

        items = nil;

    }
    return 0;
}

my results:
2014-04-08 23:38:58.395 RandomItems[83205:303] I'm a container named TheMainContainer! My total value is 0 and my items are (
    "Red Sofa (A1B2C): Worth 100, Recorded on 2014-04-09 03:38:58 +0000",
    "Blue Sofa ((null)): Worth 45, Recorded on 2014-04-09 03:38:58 +0000",
    "Item (): Worth 0, Recorded on 2014-04-09 03:38:58 +0000"

A:

well there it is... good old exclusion of self
NSString *descriptionstr = [NSString
                            stringWithFormat:@"I'm a container named %@! My total value is %d and my items are %@",
                            self.itemName,
                            self.containerValue, //self was missing
                            self.subItems];


Q:

Can pip (python2) and pip3 (python3) coexist?

I always thought that pip was for Python 2 and pip3 was for Python 3.  To install the different versions of pip I have done the following:
sudo apt-get install python-pip
sudo apt-get install python3-pip

then I get the following as one would expect:
$ pip --version
pip 8.1.1 from /usr/lib/python2.7/dist-packages (python 2.7)
$ pip3 --version
pip 8.1.1 from /usr/lib/python3/dist-packages (python 3.5)

Those are old versions, though, so I do the following:
$ sudo pip install pip --upgrade

and I get this:
$ pip --version
pip 19.0.3 from /usr/local/lib/python2.7/dist-packages/pip (python 2.7)
$ pip3 --version
pip 8.1.1 from /usr/lib/python3/dist-packages (python 3.5)

and when I do a pip3 install for some package, I get the following message:
You are using pip version 8.1.1, however version 19.0.3 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

Well, I already ran that, so I try this:
$ sudo pip3 install pip --upgrade
Installing collected packages: pip
  Found existing installation: pip 8.1.1
    Not uninstalling pip at /usr/lib/python3/dist-packages, outside environment /usr
Successfully installed pip-19.0.3

But now I get this:
$ pip --version
pip 19.0.3 from /usr/local/lib/python3.5/dist-packages/pip (python 3.5)
$ pip3 --version
pip 19.0.3 from /usr/local/lib/python3.5/dist-packages/pip (python 3.5)

Is that correct?  Does this matter?  Does a pip version from Python 3.5 work for installing Python 2 packages?
UPDATE
Based on the answer provided by @furas, these are all the commands I run to get updated versions of pip and pip3 installed correctly:
sudo apt-get install python-pip --yes
sudo apt-get install python3-pip --yes
sudo python3 -m pip install pip --upgrade
sudo python -m pip install pip --upgrade --force # this line fixes the pip install to point to the python2 version instead of the python3 version

and that yields the following:
$ pip --version
pip 19.0.3 from /usr/local/lib/python2.7/dist-packages/pip (python 2.7)
$ pip3 --version
pip 19.0.3 from /usr/local/lib/python3.5/dist-packages/pip (python 3.5)

A:

Every Python should have own pip because every Python may use different version of the same module and every Python installs modules in different folder.
You can use Python2 to install pip for Python2 and it should create correct file pip
python -m pip install -U --force pip

You should also have pip, pip2, pip2.7, pip3, pip3.5. You can even have pip3.6, pip3.7 at the same time.
Write in console pip and press tab and it should shows you all programs which starts with pip
You can find full path for pip with
which pip

and see it is python's script.
Different pip has different first line #!/usr/bin/python or #!/usr/bin/python3.5. Rest code should be the same for all versions.


Q:

How can I create a List with predefined Id in SharePoint Apps?

I'm working on the Apps development for SharePoint 2013. I need a List for my app, so I can do it using visual studio. But I can't find any option to set up an Id for my List. Is it possible?
P.S. I can get my List by title, but I want to get it by Id.

A:

It isn't possible if the list is in the app package because the ID is
  generated during publishing.

So, the only way is to first get the list by title and then get the ID of this list.
Otherwise, I don't think you can get the ID without first getting the list by title because the ID is generated when your app containing the list is published.


Q:

View css styles originating from user agent style sheet in IE9

Is there a way in IE9 to see styles that are originating from the user agent?
Similar to firebug's show user agent css feature.

A:

Today I thumbled accros a nice site. Internet Explorer User Agent Style Sheets
You can find there all user agent styles of the last IE Versions listed in a nice table. Of course you can open developer tools on any major browser by hitting F12

Within IE11 you'll see a picture as shown below. Navigate to DOM Explorer open Calculated Style at the right hand and disable options marked with red.

Right now I can't find a working IE9 installation on one of my computers. So I hope this may still be of any use for you.


Q:

Coolant spillover tank boiling but engine not overheating

After driving some time, is it normal that the plastic spillover coolant tank, usually attached to the fan housing, that takes boiling overflow, get so hot that you get bubbles boiling out of it even though the engine itself, according to the temperature gauge on the dashboard, does not get overheated? Is it an indicator that the engine borderlines overheating? Or is it a normal occurrence to have it boil?
I just recently had some overheating issues on my 4wd Tacoma and, after replacing the thermostat, water pump and radiator cap, the truck drives fine WITH JUST TAP WATER IN THE COOLANT SYSTEM (which I will replace with real coolant after I'm done testing) but, when I check the coolant spillover tank right after driving, I see it mildly boiling and I'm curious if that's a sign of potentially more overheating or is normal. So maybe I thought it was getting to a simmering point because it's just water and not 50/50 mix.

A:

What you are describing is usually caused by a weak radiator cap. Weak meaning it is no longer holding the pressure which is needed inside the system. Since you said you just replaced the cap, having just water in the system will lower the boiling point and may cause over pressure in the system. You'll also want to ensure you have the entire system burped of all air, which also causes hot spots inside the engine. Easiest way to do this is to fill it from the radiator with the front of the truck pointing uphill.
When you do get this fixed, you'll need to ensure you drain the entire system to get the tap water out. Then you'll want to refill with 50/50 mix which utilizes distilled water instead of tap water, which will introduce minerals and contaminants into the system which degrades it over time.


Q:

Spring Data Mongo - Dynamically change repository template

I have this scenario: same database structure (same collections) replicated in multiple mongo databases. This mean that I have one mongo repository for each collection (Document).
Now I need to manage these databases through the same Control Panel App, connecting to each one of them dynamically, and using the same repository classes (the databases are identical).
I know that I can specify known templates for repositories as described in this post, but this implies that I have to know the database's connection properties at startup. How can I implement a dynamic behaviour of that, instead?

A:

The core interface you might want to look at is MongoDBFactory. You can provide a custom one by overriding mongoDbFactory() in AbstractMongoConfiguration or just an ordinary bean definition in XML.
To transparently switch between different databases, simply keep track of the one selected in the implementation and return a DB instance according to that.


Q:

Pass by value faster than pass by reference

I made a simple program in c++ to compare performance between two approaches - pass by value and pass by reference. Actually pass by value performed better than pass by reference.
The conclusion should be that passing by value require fewer clock-cycles (instructions)
I would be really glad if someone could explain in detail why pass by value require fewer clock-cycles.
#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

void function(int *ptr);
void function2(int val);

int main() {

   int nmbr = 5;

   clock_t start, stop;
   start = clock();
   for (long i = 0; i < 1000000000; i++) {
       function(&nmbr);
       //function2(nmbr);
   }
   stop = clock();

   cout << "time: " << stop - start;

   return 0;
}

/**
* pass by reference
*/
void function(int *ptr) {
    *ptr *= 5;
}

/**
* pass by value
*/
void function2(int val) {
   val *= 5;
}

A:

A good way to find out why there are any differences is to check the disassembly. Here are the results I got on my machine with Visual Studio 2012.
With optimization flags, both functions generate the same code:
009D1270 57                   push        edi
009D1271 FF 15 D4 30 9D 00    call        dword ptr ds:[9D30D4h]
009D1277 8B F8                mov         edi,eax
009D1279 FF 15 D4 30 9D 00    call        dword ptr ds:[9D30D4h]
009D127F 8B 0D 48 30 9D 00    mov         ecx,dword ptr ds:[9D3048h]
009D1285 2B C7                sub         eax,edi
009D1287 50                   push        eax
009D1288 E8 A3 04 00 00       call        std::operator<<<std::char_traits<char> > (09D1730h)
009D128D 8B C8                mov         ecx,eax
009D128F FF 15 2C 30 9D 00    call        dword ptr ds:[9D302Ch]
009D1295 33 C0                xor         eax,eax
009D1297 5F                   pop         edi
009D1298 C3                   ret

This is basically equivalent to:
int main ()
{
    clock_t start, stop ;
    start = clock () ;
    stop = clock () ;
    cout << "time: " << stop - start ;
    return 0 ;
}

Without optimization flags, you will probably get different results.
function (no optimizations):
00114890 55                   push        ebp
00114891 8B EC                mov         ebp,esp
00114893 81 EC C0 00 00 00    sub         esp,0C0h
00114899 53                   push        ebx
0011489A 56                   push        esi
0011489B 57                   push        edi
0011489C 8D BD 40 FF FF FF    lea         edi,[ebp-0C0h]
001148A2 B9 30 00 00 00       mov         ecx,30h
001148A7 B8 CC CC CC CC       mov         eax,0CCCCCCCCh
001148AC F3 AB                rep stos    dword ptr es:[edi]
001148AE 8B 45 08             mov         eax,dword ptr [ptr]
001148B1 8B 08                mov         ecx,dword ptr [eax]
001148B3 6B C9 05             imul        ecx,ecx,5
001148B6 8B 55 08             mov         edx,dword ptr [ptr]
001148B9 89 0A                mov         dword ptr [edx],ecx
001148BB 5F                   pop         edi
001148BC 5E                   pop         esi
001148BD 5B                   pop         ebx
001148BE 8B E5                mov         esp,ebp
001148C0 5D                   pop         ebp
001148C1 C3                   ret

function2 (no optimizations)
00FF4850 55                   push        ebp
00FF4851 8B EC                mov         ebp,esp
00FF4853 81 EC C0 00 00 00    sub         esp,0C0h
00FF4859 53                   push        ebx
00FF485A 56                   push        esi
00FF485B 57                   push        edi
00FF485C 8D BD 40 FF FF FF    lea         edi,[ebp-0C0h]
00FF4862 B9 30 00 00 00       mov         ecx,30h
00FF4867 B8 CC CC CC CC       mov         eax,0CCCCCCCCh
00FF486C F3 AB                rep stos    dword ptr es:[edi]
00FF486E 8B 45 08             mov         eax,dword ptr [val]
00FF4871 6B C0 05             imul        eax,eax,5
00FF4874 89 45 08             mov         dword ptr [val],eax
00FF4877 5F                   pop         edi
00FF4878 5E                   pop         esi
00FF4879 5B                   pop         ebx
00FF487A 8B E5                mov         esp,ebp
00FF487C 5D                   pop         ebp
00FF487D C3                   ret

Why is pass by value faster (in the no optimization case)?
Well, function() has two extra mov operations. Let's take a look at the first extra mov operation:
001148AE 8B 45 08             mov         eax,dword ptr [ptr]
001148B1 8B 08                mov         ecx,dword ptr [eax]
001148B3 6B C9 05             imul        ecx,ecx,5

Here we are dereferencing the pointer. In function2 (), we already have the value, so we avoid this step. We first move the address of the pointer into register eax. Then we move the value of the pointer into register ecx. Finally, we multiply the value by five.
Let's look at the second extra mov operation:
001148B3 6B C9 05             imul        ecx,ecx,5
001148B6 8B 55 08             mov         edx,dword ptr [ptr]
001148B9 89 0A                mov         dword ptr [edx],ecx

Now we are moving backwards. We have just finished multiplying the value by 5, and we need to place the value back into the memory address.
Because function2 () does not have to deal with referencing and dereferencing a pointer, it gets to skip these two extra mov operations.

A:

Overhead with passing by reference:

each access needs a dereference, i.e., there is one more memory read

Overhead with passing by value:

the value needs to be copied on stack or into registers

For small objects, such as an integer, passing by value will be faster. For bigger objects (for example a large structure), the copying would create too much overhead so passing by reference will be faster.

A:

Imagine you walk into a function and you're supposed to come in with an int value. The code in the function wants to do stuff with that int value.
Pass by value is like walking into the function and when someone asks for the int foo value, you just give it to them.
Pass by reference is walking into the function with the address of the int foo value. Now whenever someone needs the value of foo they have to go and look it up. Everyone's gonna complain about having to dereference foo all the freaking time. I've been in this function for 2 milliseconds now and I must have looked up foo a thousand times! Why didn't you just give me the value in the first place? Why didn't you pass by value?
This analogy helped me see why passing by value is often the fastest choice.


Q:

php object property NULL in required page

Why does this work:
echo $session->name;
require_once('test.php');
//echos the name then loads the required page

But
var_dump($session->name);

in the code of test.php returns NULL.
I thought require_once pretty much plops all the code from the required page into the spot I told it to.
EDIT
$session instance is created before the require, outside of test.php. If I create a new instance of $session inside test.php it works. Glad it works but this still doesnt make sense to me, can anyone explain?

A:

$session is not in the scope. include that script where you have initialized $session. or declare it as global in all scripts that will save the include just for $session. why not use $_SESSION though?


Q:

c - Linking a PGI OpenACC-enabled library with gcc

Briefly speaking, my question relies in between compiling/building files (using libraries) with two different compilers while exploiting OpenACC constructs in source files.
I have a C source file that has an OpenACC construct. It has only a simple function that computes total sum of an array:
#include <stdio.h>
#include <stdlib.h>
#include <openacc.h>

double calculate_sum(int n, double *a) {
    double sum = 0;
    int i;

    printf("Num devices: %d\n", acc_get_num_devices(acc_device_nvidia));

    #pragma acc parallel copyin(a[0:n])
    #pragma acc loop
    for(i=0;i<n;i++) {
        sum += a[i];
    }

    return sum;
}

I can easily compile it using following line:
pgcc -acc -ta=nvidia -c libmyacc.c
Then, create a static library by following line:
ar -cvq libmyacc.a libmyacc.o
To use my library, I wrote a piece of code as following:
#include <stdio.h>
#include <stdlib.h>

#define N 1000

extern double calculate_sum(int n, double *a);

int main() {
    printf("Hello --- Start of the main.\n");
    double *a = (double*) malloc(sizeof(double) * N);
    int i;
    for(i=0;i<N;i++) {
        a[i] = (i+1) * 1.0;
    }

    double sum = 0.0;
    for(i=0;i<N;i++) {
        sum += a[i];
    }
    printf("Sum: %.3f\n", sum);

    double sum2 = -1;
    sum2 = calculate_sum(N, a);
    printf("Sum2: %.3f\n", sum2);

    return 0;
}

Now, I can use this static library with PGI compiler itself to compile above source (f1.c):
pgcc -acc -ta=nvidia f1.c libmyacc.a
And it will execute flawlessly. However, it differs for gcc. My question relies in here. How can I built it properly with gcc?
Thanks to Jeff's comment on this question:
linking pgi compiled library with gcc linker, now I can build my source file (f1.c) without errors, but the executable file emits some fatal errors.
This is what I use to compile my source file with gcc (f1.c):
gcc f1.c -L/opt/pgi/linux86-64/16.5/lib -L/usr/lib64 -L/usr/lib/gcc/x86_64-redhat-linux/4.8.5 -L. -laccapi -laccg -laccn -laccg2 -ldl -lcudadevice -lpgmp -lnuma -lpthread -lnspgc -lpgc -lm -lgcc -lc -lgcc -lmyacc
This is the error:
Num devices: 2
Accelerator Fatal Error: No CUDA device code available

Thanks to -v option when compiling f1.c with PGI compiler, I see that the compiler invokes so many other tools from PGI and NVidia (like pgacclnk and nvlink).

My questions:

Am I on the wrong path? Can I call functions in PGI compiled libraries from GCC and use OpenACC within those functions?
If answer to above is positive, can I use still link without steps (calling pgacclnk and nvlink) that PGI takes?
If answer to above is positive too, what should I do?

A:

Add "-ta=tesla:nordc" to your pgcc compilation.  By default PGI uses runtime dynamic compilation (RDC) for the GPU code.  However RDC requires an extra link step (with nvlink) that gcc does not support.  The "nordc" sub-option disables RDC so you'll be able to use OpenACC code in a library.  However by disabling RDC you can no longer call external device routines from a compute region.
% pgcc -acc -ta=tesla:nordc -c libmyacc.c
% ar -cvq libmyacc.a libmyacc.o
a - libmyacc.o
% gcc f1.c -L/proj/pgi/linux86-64/16.5/lib -L/usr/lib64 -L/usr/lib/gcc/x86_64-redhat-linux/4.8.5 -L. -laccapi -laccg -laccn -laccg2 -ldl -lcudadevice -lpgmp -lnuma -lpthread -lnspgc -lpgc -lm -lgcc -lc -lgcc -lmyacc
% a.out
Hello --- Start of the main.
Sum: 500500.000
Num devices: 8
Sum2: 500500.000

Hope this helps,
Mat


Q:

how can i print this data? (object data)

Var_dump result:
object(stdClass)#2 (1) {
 [0]=>
  array(5) {
    ["title"]=>
    string(71) "Tarihte Bugün Neler Olmuş? Bugünün önemli olayları! | Ttbugun.com"
    ["keywords"]=>
    string(47) "tarih,tarih dersi,tarihte bugün,günün sözü"
    ["description"]=>
    string(69) "Tarihte bugün olan olaylar ve diğer tarihi olayların hepsi burada."
    ["author"]=>
    string(17) "Yusuf Ali Bozkır"
    ["id"]=>
    string(1) "1"
  }
}

using var_dump:
var_dump($header->headers);

How can i print title,description and others?

A:

try this
echo $header->headers{0}['title'];
echo $header->headers{0}['keyword'];
echo $header->headers{0}['description'];
echo $header->headers{0}['author'];
echo $header->headers{0}['id'];


Q:

Book recommendation/reference request on regular (abstract) polytopes

My actual goal is understanding highly symmetric polytopes. For example, regular polytopes, archimedean solids, complex regular polytopes, regular abstract polytopes, etc.
I apologize that I don't know the general term including all of these concepts hence I use the term regular abstract polytopes.
I choose H.S.M. Coxeter, Regular Polytopes and Peter McMullen, Egon Schulte, Abstract Regular Polytopes to refer.
Are there any suggestions?

A:

The two books you mention, Coxeter and McMullen & Schulte, are the standard texts on the subject. You can also add Coxeter's Regular Complex Polytopes.
However polytopes and high symmetries are distinct areas of study which do not overlap as cleanly as one might expect. For example a regular complex polytope has no bounding surface in the topological sense but is better understood as a configuration. An abstract polytope is a class of incidence complex having a "diamond condition" ensuring for example that faces meet in pairs along edges and so on, but each cell (subface of 3 or more dimensions) does not need to be a topological ball. These both fly in the face of the simplicial decomposition of a manifold in order to determine its homology class, which is derived from Euler's original polyhedron formula V − E + F = 2 and leads to the understanding of a polytope as a class of topological CW complex.
A simple and well-illustrated introduction to the symmetry aspect is provided by Conway, Burgiel and Goodman-Strauss in The Symmetries of Things, while a good account of the topological origins is given by David S. Richeson in Euler's Gem: The Polyhedron Formula and the Birth of Topology.
You can find my own embryonic attempt at resolving some of these inconsistencies at http://www.steelpillow.com/polyhedra/morphic/morphic.html


Q:

Can/should JPA be used to return values rather than entities?

I'm using JPA for a project and in most cases, want to get entities, but there are a few cases (reporting being one of them, but there are others) where I do not want or need to get entities, but rather want a selection of values. Does JPA support this? If so, does it make sense to use it or does it make sense to use straight JDBC in these cases?

A:

Q1:
Yes, it does.
It's so called scalar queries, e.g.:
select u.name from User u

as opposed to
select u from User u

Q2:
When it comes to sense of using it:
Such queries have sense - you just simply need a single property not the whole object. But if you plan to make all your queries only fetching separate values, then the question 'why?' seems valid. The whole idea of O/R mappers is to allow you operate on objects, not (related) tables and ids. So fetching ids using JPA usually doesn't make sense. Once you have objects mapped to database, it should be easier for you to operate on the data.


Q:

What does mean VarType(aVariant) = 273 (or $111)?

What does mean VarType(aVariant) = 273 (or $111)? It's undocumented variant type. VarTypeAsText(aVariant) returns Expression illegal in evaluator error.

A:

From the source code of the system unit:
const
{ Variant type codes (wtypes.h) }

  varEmpty    = $0000; { vt_empty        0 }
  varNull     = $0001; { vt_null         1 }
  varSmallint = $0002; { vt_i2           2 }
  varInteger  = $0003; { vt_i4           3 }
  varSingle   = $0004; { vt_r4           4 }
  varDouble   = $0005; { vt_r8           5 }
  varCurrency = $0006; { vt_cy           6 }
  varDate     = $0007; { vt_date         7 }
  varOleStr   = $0008; { vt_bstr         8 }
  varDispatch = $0009; { vt_dispatch     9 }
  varError    = $000A; { vt_error       10 }
  varBoolean  = $000B; { vt_bool        11 }
  varVariant  = $000C; { vt_variant     12 }
  varUnknown  = $000D; { vt_unknown     13 }
//varDecimal  = $000E; { vt_decimal     14 } {UNSUPPORTED as of v6.x code base}
//varUndef0F  = $000F; { undefined      15 } {UNSUPPORTED per Microsoft}
  varShortInt = $0010; { vt_i1          16 }
  varByte     = $0011; { vt_ui1         17 }
  varWord     = $0012; { vt_ui2         18 }
  varLongWord = $0013; { vt_ui4         19 }
  varInt64    = $0014; { vt_i8          20 }
  varUInt64   = $0015; { vt_ui8         21 }
  varRecord   = $0024; { VT_RECORD      36 }
{  if adding new items, update Variants' varLast, BaseTypeMap and OpTypeMap }

  varStrArg   = $0048; { vt_clsid        72 }
  varObject   = $0049; {                 73 }
  varUStrArg  = $004A; {                 74 }
  varString   = $0100; { Pascal string  256 } {not OLE compatible }
  varAny      = $0101; { Corba any      257 } {not OLE compatible }
  varUString  = $0102; { Unicode string 258 } {not OLE compatible }
  // custom types range from $110 (272) to $7FF (2047)

See the comment at the very bottom of the list. In other words, $111 is a custom variant type. Exactly what it is depends on the code that defined that type. Code that is not in the RTL and is presumably in your program.


Q:

Handling multiple forms in React

I'm trying to make two simple forms with a Save button to work in React, but it appears that the Save button component is unable to see the two forms.

My Form component is as follows:
import React from "react";
import { Field, reduxForm } from "redux-form";

const validate = values => {
  const errors = {};
  if (!values.name) {
    errors.name = "Required";
  }

  if (!values.age) {
    errors.age = "Required";
  }

  return errors;
};

const renderField = ({
  input,
  label,
  type,
  value,
  meta: { touched, error, warning }
}) => (

    {label}

      <input {...input} placeholder={label} type={type} />
      {touched && (error && {error})}

);

const Form1 = props => {
  const { handleSubmit } = props;
  return (

      <form onSubmit={handleSubmit}>
        <Field name="name" component={renderField} type="text" label="Name" />
        <Field name="age" component={renderField} type="text" label="Age" />
        <button type="submit">Submit</button>
      </form>

  );
};

export default reduxForm({
  form: "step1", // a unique identifier for this form
  validate
})(Form1);

And my SaveButton is as follows:
import React, { Component } from "react";

export default class SaveButton extends Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.submit = this.submit.bind(this);
  }

  submit() {
    console.log(this.props);
    const { dispatch, forms } = this.props;

    forms.forEach(({ formName, isValid, values, errors }) => {
      if (isValid) {
        console.log(values);
      } else {
        //        dispatch(touch(formName, ...Object.keys(errors)));
      }
    });
  }

  render() {
    return (
      <button type="button" onClick={this.submit}>
        Save
      </button>
    );
  }
}

Sandbox example

Clicking Save gives Cannot read property 'forEach' of undefined because forms is undefined and this.props is empty. Anyone know why the forms can't be seen from SaveButton?

A:

This is because your Save button is not the part of the form element. So to get the value you have to do it manually. Here is how I do it,
I will pass a handleSave function as a prop from App.js like,
import React, { Component } from "react";
import "./App.css";
import Form1 from "./components/form1/Form";
import Form2 from "./components/form2/Form";
import SaveButton from "./components/SaveButton";
import { connect } from "react-redux";
import {
  submit,
  isValid,
  getFormNames,
  getFormValues,
  getFormSyncErrors,
  touch
} from "redux-form";

class App extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (

Welcome to React

          Form 1:
          <Form1 onSubmit={this.step1} />

          Form : 2
          <Form2 onSubmit={this.step2} />

          <SaveButton handleSave={this.handleSave} />

    );
  }

  step1(values) {
    console.log(values);
  }

  step2(values) {
    console.log(values);
  }
  handleSave = () => {
    const { dispatch, forms } = this.props;
    console.log(forms);

     forms.forEach(({ formName, isValid, values, errors }) => {
       if (isValid) {
         console.log(values);
       } else {
         //        dispatch(touch(formName, ...Object.keys(errors)));
       }
     });
  }
}

const mapStateToProps = state => {
  return {
    forms: getFormNames()(state).map(formName => ({
      formName,
      isValid: isValid(formName)(state),
      values: getFormValues(formName)(state),
      errors: getFormSyncErrors(formName)(state)
    }))
  };
};

export default connect(mapStateToProps)(App);`

and in SaveButton.js, I will simply call that function,
import React, { Component } from "react";

export default class SaveButton extends Component {
  constructor(props) {
    super(props);
    this.props = props;
  }

  submit = () => {
    this.props.handleSave();
  };

  render() {
    return (
      <button type="button" onClick={this.submit}>
        Save
      </button>
    );
  }
}


Q:

What is the best way to store slide-out sidebar menu data

I have a sidebar menu in my application (like facebook's one) and currently I have hard coded the categories of my sidebar. My question is the following : what is the best place to store the data of that menu?

Hardcoded like I have done actually?
SQLite database?
plist file?

I am asking that because I would like to keep in memory in which menu I am, and I wonder if database would not be the better way to do that?
Thanx in advance

A:

If you just mean the categories of the menu itself, then hardcoding is fine depending on how likely they are to change. But if it's like facebook and they don't change, then it's fine.
In terms of the content that is displayed when you tap a menu item, that's different. There I'd recommend either a SQLite database, or better yet use CoreData to manage it for you.
If you have a view controller manage the state of that menu, you can keep in there which menu item you have selected, keep a list of items to display etc and that's fine, no need for a database there really. What I would suggest though is something flexible so that you could easily add new items.
For example one app I worked on, I created an array of NSDictionary objects that each had a title, image, and selector. When it came to rendering the list, I simply looped through the list, created a new item with the title and icon, and when the user tapped in called the selector. This way, if we needed new menu items, I could just add a new item to the array and that was it.
I had this array hard coded in the controllers initialiser, but you could if you wanted serialise this into a plist file, but that's just a preference thing


Q:

Azure POST login.microsoftonline.com/oauty2/token fails on AADSTS900144

I need to automate connecting to logs analytics on Azure.  Before I can do that, I need to get an access token.
With different docs and https://www.youtube.com/watch?v=ujzrq8Fg9Gc, I am trying to set that up.

TRY1
My first try was using SoapUI to send a POST request to:
https://login.microsoftonline.com/MY TENANT ID/oauth2/token
?grant_type=client_credentials
&client_id=MY CLIENT ID
&redirect_uri=MY URL
&resource=https%3A%2F%2Fwestus2.api.loganalytics.io
&client_secret=MY CLIENT SECRET

With header:
Content-Type: application/x-www-form-urlencoded

I always get this response:
HTTP/1.1 400 Bad Request
Cache-Control: no-cache, no-store
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
x-ms-request-id: SOMETHING
P3P: CP="DSP CUR OTPi IND OTRi ONL FIN"
Set-Cookie: fpc=SOMETHING; expires=Mon, 05-Aug-2019 13:14:50 GMT; path=/; secure; HttpOnly
Set-Cookie: x-ms-gateway-slice=prod; path=/; secure; HttpOnly
Set-Cookie: stsservicecookie=ests; path=/; secure; HttpOnly
Date: Sat, 06 Jul 2019 13:14:49 GMT
Content-Length: 437

{
    "error":"invalid_request",
    "error_description":"AADSTS900144: The request body must contain
                         the following parameter: 'grant_type'.\r\n
                         Trace ID: SOMETHING\r\n
                         Correlation ID: SOMETHING\r\n
                         Timestamp: 2019-07-06 13:14:50Z",
    "error_codes":[900144],
    "timestamp":"2019-07-06 13:14:50Z",
    "trace_id":"SOMETHING",
    "correlation_id":"SOMETHING"
}

TRY 2
I wrote it in Python using import requests, like so:
import os,sys
import requests

Azure_client_id     = 'MY CLIENT ID'
Azure_redirect_uri  = 'MY URL'
Azure_client_secret = 'CLIENT SECRET'
Azure_tenant_id     = 'TENANT ID'
Azure_resource      = 'https://westus2.api.loganalytics.io'

###############################################################################
token_url = 'https://login.microsoftonline.com/' + Azure_tenant_id + '/oauth2/token'
token_headers = {
    'Content-type': 'application/x-www-form-urlencoded',
}
token_params = {
    'grant_type': 'client_credentials',
    'client_id': Azure_client_id,
    'redirect_uri': Azure_redirect_uri,
    'resource': Azure_resource,
    'client_secret': Azure_client_secret,
}

token_response = requests.post(token_url, headers=token_headers, params=token_params)
# This is to see what was sent
print(token_response.url + "\n\n")

# get the response and print it
token_result = ''
for chunk in token_response.iter_content(chunk_size=128):
    token_result = token_result + str(chunk)

print(token_result.replace("\\n","\n"))

The URL that was sent is this (formatted for readability):
https://login.microsoftonline.com/MY TENANT ID/oauth2/token
    ?grant_type=client_credentials
    &client_id=MY CLIENT ID
    &redirect_uri=https%3A%2F%2FMY URL
    &resource=https%3A%2F%2Fwestus2.api.loganalytics.io
    &client_secret=MY SECRET URL ENCODED

The response I get is this (reformatted for readability):
b'{"error":"invalid_request",
    "error_description":"AADSTS900144: The request body must contain
                         the following parameter: \'grant_type'b"'.\\r\
                         Trace ID: SOMETHING\\r\
                         Correlation ID: SOMETHING\\r\
                         Timestamp: 2019-"b'07-06 13:49:59Z",
   "error_codes":[900144],
   "timestamp":"2019-07-06 13:49:59Z",
   "trace_id":"SOMETHING",
   "co'b'rrelation_id":"SOMETHING"}''

At least I get the same error (!).  Since my requests clearly include a "grant_type" parameter, my guess is that there is either something wrong with the encoding (which is done by SoapUI and Python's requests), something wrong with my URL, or I am not using the proper IDs.
Is there a way in Azure to validate that my client secret is valid?  Once created, it cannot be read anymore.  And someone else created this key so I cannot assume what he gave me is ok.
Any comment, hints, pointing out blatant mistakes on my part are appreciated.

A:

Change
token_response = requests.post(token_url, headers=token_headers, params=token_params)

to
token_response = requests.post(token_url, data=token_params)

You don't need to specify the Content-type header, it's inferred from your payload (dictionary, so x-www-form-urlencoded), also data is what you want (payload), not params (URL parameters).
Your request should look like this on the wire -
POST /TENANT_ID/oauth2/token HTTP/1.1
Host: localhost:9000
User-Agent: python-requests/2.22.0
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
Content-Length: 151
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials
&client_id=MY+CLIENT+ID
&redirect_uri=MY+URL
&resource=https%3A%2F%2Fwestus2.api.loganalytics.io
&client_secret=CLIENT+SECRET

Everything is in the body where it should be for x-www-form-urlencoded.
More on x-www-form-urlencoded here -
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST#Example