How to Decrypt and Play CENC protected contents in DASH?

Question: I have a MPD clip which supports CENC,how to decrypt and play without using any specific DRM engine??Is there any decryption algorithm available to decrypt AES CTR 128 bit?If so will it be used to decrypt MPEG-DASH content?There are some third party libraries available in net like NACL,Openssl,crypto++,which can do AES ctr 128 decryption.Can i use one of them to decrypt DASH Content(CENC supported) ??
Answer: MPEG-CENC is simply AES-128 CTR encryption on an ISO BMFF (mp4) file. The specification for how this is applied to CENC is here: https://www.w3.org/TR/2014/WD-encrypted-media-20140828/cenc-format.html
and
https://www.iso.org/obp/ui/#iso:std:iso-iec:23001:-7:ed-1:v1
And a good explanation of AES-128 CTR
https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_.28CTR.29
To decrypt you will need the key and also the Initialization Vector (IV) that was used to encrypt the content. This is available from the senc and tenc boxes in the mp4 file. Once you will have those you will simply need to go through the samples or fragments of the file and decrypt and reassemble the mp4 (assuming you want to play it).
As mentioned by Bento tools mp4decrypt gives an example on how to do this: https://github.com/axiomatic-systems/Bento4/blob/master/Source/C%2B%2B/Apps/Mp4Decrypt/Mp4Decrypt.cpp
Comment: @Alastair I have a MPEG-CENC encrypted file and its key but not the iv. Any idea how to get the iv from the video ? It was encrypted using ffmpeg command that just takes key param.
Answer: DASH videos protected using CENC can be played back using many different DRM technologies. The primary factors you need to care for are:

The player used must support the chosen DRM technology. Of the popular browsers, Internet Explorer 11 supports PlayReady and Chrome supports Widevine. For non-browser platforms, various 3rd party players are available.
The video must contain metadata that allows the DRM technology to recognize the actions needed in order to decrypt the video (most importantly, the ID of the encryption key and the URL to acquire it from).
There must be a service running that will provide the decryption key to the player on demand, after validating that the user is authorized to view the video. Generally, the key is embedded in a data structure called a license which can provide additional data to the player regarding content protection requirements (e.g. "HDCP must be turned on to play this video").

Note that in order to reach a wide spectrum of players, you will need to support multiple DRM technologies simultaneously.
You will find some references to the DRM technologies at the DASH-IF content protection references page.
Note that some browsers may also support the "clearKey" DRM technology, which is a fake implementation that simply takes the decryption key and uses it directly. If you have the decryption key and a video, you can use the clearKey mechanism to play your video.
Edit: If you have the cryptographic key then you can use the mp4decrypt tool from the Bento4 suite to decrypt the fragment files.
Comment: I have seen some third party libraries like Openssl,NACL,crypto++ which can do the decryption of AES ctr 128.Can i use this for decryption??
Answer: ClearKey via MPEG-CENC and the HTML5 Encrypted Media Extentions is supported by some browsers, e.g. Google Chrome. Other browsers may have to use a fallback to do the decryption e.g. using Flash.
MPEG-CENC using Clearkey in HTML5 as well as Flash is shown on this demo website http://www.dash-player.com/demo/drm-and-protection/


JSON.NET and nHibernate Lazy Loading of Collections

Question: Is anybody using JSON.NET with nHibernate?  I notice that I am getting errors when I try to load a class with child collections.
Comment: May you please post details about the errors you're seeing?
Comment: I was getting 'The method or operation is not implemented.' and Liedman's fix worked for me.
Answer: I was facing the same problem so I tried to use @Liedman's code but the GetSerializableMembers() was never get called for the proxied reference.
I found another method to override:
  public class NHibernateContractResolver : DefaultContractResolver
  {
      protected override JsonContract CreateContract(Type objectType)
      {
          if (typeof(NHibernate.Proxy.INHibernateProxy).IsAssignableFrom(objectType))
              return base.CreateContract(objectType.BaseType);
          else
              return base.CreateContract(objectType);
      }
  }

Comment: +1 - This seems to be the only working version right now with NH 3.3 and JSON.NET 4.5.7.
Comment: It does work if I do this however, return JsonConvert.SerializeObject(obj, new JsonSerializerSettings
   {
    ContractResolver = new NHibernateContractResolver()
   });
Answer: We had this exact problem, which was solved with inspiration from Handcraftsman's response here.
The problem arises from JSON.NET being confused about how to serialize NHibernate's proxy classes. Solution: serialize the proxy instances like their base class.
A simplified version of Handcraftsman's code goes like this:
public class NHibernateContractResolver : DefaultContractResolver {
    protected override List<MemberInfo> GetSerializableMembers(Type objectType) {
        if (typeof(INHibernateProxy).IsAssignableFrom(objectType)) {
            return base.GetSerializableMembers(objectType.BaseType);
        } else {
            return base.GetSerializableMembers(objectType);
        }
    }
}

IMHO, this code has the advantage of still relying on JSON.NET's default behaviour regarding custom attributes, etc. (and the code is a lot shorter!).
It is used like this
        var serializer = new JsonSerializer{
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            ContractResolver = new NHibernateContractResolver()
        };
        StringWriter stringWriter = new StringWriter();
        JsonWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(stringWriter);
        serializer.Serialize(jsonWriter, objectToSerialize);
        string serializedObject = stringWriter.ToString();

Note: This code was written for and used with NHibernate 2.1. As some commenters have pointed out, it doesn't work out of the box with later versions of NHibernate, you will have to make some adjustments. I will try to update the code if I ever have to do it with later versions of NHibernate.
Comment: Liedman's solution doesn't work anymore since the type passed in is Interface so objectType.BaseType returns null and crashes
Comment: In using this solution for NHibernate 18.104.22.16800 and Json.NET 4.0.4, I found it necessary to combine this with sos00's solution. Also, I am encountering proxy objects that do NOT implement NHibernate.Proxy.INHibernateProxy, but DO implement NHibernate.Proxy.DynamicProxy.IProxy.  I have modified the code to check for both. I have not found it necessary to use ReferenceLoopHandling.Ignore. Hope this helps somebody else--I know I spent too much time on this!
Comment: @ChrisNielsen: Thanks, I updated the answer with a note regarding compatibility with later versions of NHibernate.
Comment: Made this as an extension method... Works like a charm :)
Answer: I use NHibernate with Json.NET and noticed that I was getting inexplicable "__interceptors" properties in my serialized objects. A google search turned up this excellent solution by Lee Henson which I adapted to work with Json.NET 3.5 Release 5 as follows.
public class NHibernateContractResolver : DefaultContractResolver
{
  private static readonly MemberInfo[] NHibernateProxyInterfaceMembers = typeof(INHibernateProxy).GetMembers();

  protected override List<MemberInfo> GetSerializableMembers(Type objectType)
  {
    var members = base.GetSerializableMembers(objectType);

    members.RemoveAll(memberInfo =>
                      (IsMemberPartOfNHibernateProxyInterface(memberInfo)) ||
                      (IsMemberDynamicProxyMixin(memberInfo)) ||
                      (IsMemberMarkedWithIgnoreAttribute(memberInfo, objectType)) ||
                      (IsMemberInheritedFromProxySuperclass(memberInfo, objectType)));

    var actualMemberInfos = new List<MemberInfo>();

    foreach (var memberInfo in members)
    {
      var infos = memberInfo.DeclaringType.BaseType.GetMember(memberInfo.Name);
      actualMemberInfos.Add(infos.Length == 0 ? memberInfo : infos[0]);
    }

    return actualMemberInfos;
  }

  private static bool IsMemberDynamicProxyMixin(MemberInfo memberInfo)
  {
    return memberInfo.Name == "__interceptors";
  }

  private static bool IsMemberInheritedFromProxySuperclass(MemberInfo memberInfo, Type objectType)
  {
    return memberInfo.DeclaringType.Assembly == typeof(INHibernateProxy).Assembly;
  }

  private static bool IsMemberMarkedWithIgnoreAttribute(MemberInfo memberInfo, Type objectType)
  {
    var infos = typeof(INHibernateProxy).IsAssignableFrom(objectType)
                  ? objectType.BaseType.GetMember(memberInfo.Name)
                  : objectType.GetMember(memberInfo.Name);

    return infos[0].GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Length > 0;
  }

  private static bool IsMemberPartOfNHibernateProxyInterface(MemberInfo memberInfo)
  {
    return Array.Exists(NHibernateProxyInterfaceMembers, mi => memberInfo.Name == mi.Name);
  }
}

To use it just put an instance in the ContractResolver property of your JsonSerializer. The circular dependency problem noted by jishi can be resolved by setting the ReferenceLoopHandling property to ReferenceLoopHandling.Ignore .  Here's an extension method that can be used to serialize objects using Json.Net
  public static void SerializeToJsonFile<T>(this T itemToSerialize, string filePath)
  {
    using (StreamWriter streamWriter = new StreamWriter(filePath))
    {
      using (JsonWriter jsonWriter = new JsonTextWriter(streamWriter))
      {
        jsonWriter.Formatting = Formatting.Indented;
        JsonSerializer serializer = new JsonSerializer
          {
            NullValueHandling = NullValueHandling.Ignore,
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            ContractResolver = new NHibernateContractResolver(),
          };
        serializer.Serialize(jsonWriter, itemToSerialize);
      }
    }
  }

Comment: Thanks for this code, it works great! And saved me from using a StatelessSession.
Comment: This stopped working in JSON.NET 3.5 release 7, but still works fine in 3.5 release 5.
Comment: they seem to have updated the AssemblyVersion as of release 6, meaning that if you previously included this file in your solution, the version would mismatch, and throw some sort of securityexception. Could that be the case?
Answer: Are you getting a circular dependancy-error? How do you ignore objects from serialization?
Since lazy loading generates a proxy-objects, any attributes your class-members have will be lost. I ran into the same issue with Newtonsoft JSON-serializer, since the proxy-object didn't have the [JsonIgnore] attributes anymore.
Comment: Kind of retarded to down vote an answer that was written 1,5 years before yours?
Comment: See mine and Handcraftsman's replies, they contain a solution for exactly this problem.
Comment: Yes that's exactly the issue I was running into. I hadn't been ignoring any objects from serialization when I was getting the errors though. I think I need to go back and read the docs properly!
Comment: It's not retarded, if the answer were now unhelpful or obsolete. You may want to update it, or at least provide specific context  (i.e. JS/NH version numbers you refer to?) so people finding it not-helpful with later versions won't be compelled to downvote. As a side note, I almost marked your answer as not-an-answer because I read it uncarefully and at first I thought it to be a follow-up question. You could make it a bit more obvious for lazy readers like me :) Maybe, just maybe, the downvoter also would need to re-read it, but did not.
Answer: You will probably want to eager load most of the object so that it can be serialized:
        ICriteria ic = _session.CreateCriteria(typeof(Person));

        ic.Add(Restrictions.Eq("Id", id));

        if (fetchEager)
        {
            ic.SetFetchMode("Person", FetchMode.Eager);
        }

A nice way to do this is to add a bool to the constructor (bool isFetchEager) of your data provider method.
Answer: I'd say this is a design problem in my opinion. Because NH makes connections to the database underneath all and has proxies in the middle, it is not good for the transparency of your application to serialize them directly (and as you can see Json.NET does not like them at all).
You should not serialize the entities themselves, but you should convert them into "view" objects or POCO or DTO objects (whatever you want to call them) and then serialize these.
The difference is that while NH entity may have proxies, lazy attributes, etc. View objects are simple objects with only primitives which are serializable by default.
How to manage FKs?
My personal rule is:
Entity level: Person class and with a Gender class associated
View level: Person view with GenderId and GenderName properties.
This means that you need to expand your properties into primitives when converting to view objects. This way also your json objects are simpler and easier to handle.
When you need to push the changes to the DB, in my case I use AutoMapper and do a ValueResolver class which can convert your new Guid to the Gender object.
UPDATE: Check http://blog.andrewawhitaker.com/blog/2014/06/19/queryover-series-part-4-transforming/ for a way to get the view directly (AliasToBean) from NH. This would be a boost in the DB side.
Answer: The problem can happen when NHibernate wraps the nested collection properties in a PersistentGenericBag<> type.
The GetSerializableMembers and CreateContract overrides cannot detect that these nested collection properties are "proxied". One way to resolve this is to override the CreateProperty method. The trick is to get the value from the property using reflection and test whether the type is of PersistentGenericBag. This method also has the ability to filter any properties that generated exceptions.
    public class NHibernateContractResolver : DefaultContractResolver
    {
        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            JsonProperty property = base.CreateProperty(member, memberSerialization);

            property.ShouldSerialize = instance =>
            {
                try
                {
                    PropertyInfo prop = (PropertyInfo)member;
                    if (prop.CanRead)
                    {
                        var value = prop.GetValue(instance, null);
                        if (value != null && typeof(NHibernate.Collection.Generic.PersistentGenericBag<>).IsSubclassOfRawGeneric(value.GetType()))
                            return false;

                        return true;
                    }
                }
                catch
                { }
                return false;
            };

            return property;
        }
    }

The IsSubclassOfRawGeneric extension used above:
public static class TypeExtensions
{
    public static bool IsSubclassOfRawGeneric(this Type generic, Type? toCheck)
    {
        while (toCheck != null && toCheck != typeof(object))
        {
            var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
            if (generic == cur)
            {
                return true;
            }
            toCheck = toCheck?.BaseType;
        }
        return false;
    }
}

Answer: If you serialize objects that contain NHibernate proxy classes you might end up downloading the whole database, because once the property is accessed NHibernate would trigger a request to the database.
I've just implemented a Unit of Work for NHibernate: NHUnit that fixes two of the most annoying issues from NHibernate: proxy classes and cartesian product when using fetch.
How would you use this?
var customer = await _dbContext.Customers.Get(customerId) //returns a wrapper to configure the query
           .Include(c => c.Addresses.Single().Country, //include Addresses and Country
                    c => c.PhoneNumbers.Single().PhoneNumberType) //include all PhoneNumbers with PhoneNumberType
           .Unproxy() //instructs the framework to strip all the proxy classes when the Value is returned
           .Deferred() //instructs the framework to delay execution (future)
           .ValueAsync(token); //this is where all deferred queries get executed

The above code is basically configuring a query: return a customer by id with multiple child objects which should be executed with other queries (futures) and the returned result should be stripped of NHibernate proxies. The query gets executed when ValueAsync is called.
NHUnit determines if it should do join with the main query, create new future queries or make use of batch fetch.
There is a simple example project on Github to show you how to use NHUnit package. If others are interested in this project I will invest more time to make it better.
Answer: This is what I use:

Have a marker interface and inherit it on your entities, e.g. in my case empty IEntity.

We will use the marker interface to detect NHibernate entity types in the contract resolver.
   public class CustomerEntity : IEntity {    ...   }

Create a custom contract resolver for JSON.NET
    public class NHibernateProxyJsonValueProvider : IValueProvider {

     private readonly IValueProvider _valueProvider;

     public NHibernateProxyJsonValueProvider(IValueProvider valueProvider)
     {
         _valueProvider = valueProvider;
     }

     public void SetValue(object target, object value)
     {
         _valueProvider.SetValue(target, value);
     }

     private static (bool isProxy, bool isInitialized) GetProxy(object proxy)
     {
         // this is pretty much what NHibernateUtil.IsInitialized() does.
         switch (proxy)
         {
             case INHibernateProxy hibernateProxy:
                 return (true, !hibernateProxy.HibernateLazyInitializer.IsUninitialized);
             case ILazyInitializedCollection initializedCollection:
                 return (true, initializedCollection.WasInitialized);
             case IPersistentCollection persistentCollection:
                 return (true, persistentCollection.WasInitialized);
             default:
                 return (false, false);
         }
     }

     public object GetValue(object target)
     {
         object value = _valueProvider.GetValue(target);
         (bool isProxy, bool isInitialized) = GetProxy(value);
         if (isProxy)
         {
             if (isInitialized)
             {
                 return value;
             }

             if (value is IEnumerable)
             {
                 return Enumerable.Empty<object>();
             }

             return null;
         }

         return value;
     }
}

public class NHibernateContractResolver : CamelCasePropertyNamesContractResolver {

     protected override JsonContract CreateContract(Type objectType)
     {
         if (objectType.IsAssignableTo(typeof(IEntity)))
         {
             return base.CreateObjectContract(objectType);
         }

         return base.CreateContract(objectType);
     }

     protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
     {
         JsonProperty property = base.CreateProperty(member, memberSerialization);

         property.ValueProvider = new NHibernateProxyJsonValueProvider(property.ValueProvider);

         return property;
     }
 }

Normal uninitialized lazy loaded properties will result in null in the json output.
Collection uninitialized lazy loaded properties will result in an [] empty array in json.

So for a lazy loaded property to appear in the json output you need to eagerly load it in the query or in code before serialization.
Usage:
JsonConvert.SerializeObject(entityToSerialize, new JsonSerializerSettings() {
  ContractResolver = new NHibernateContractResolver()
});

Or globally in in ASP.NET Core Startup class
   services.AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver = new NHibernateContractResolver();
            });

Using:

NET 5.0
NHibernate 5.3.8
JSON.NET latest via ASP.NET Core


Network wireless USB dongle

Question: Here in Panama City, Panama they have a telephone company which sells wireless USB adapters for laptops and desktops.  Can other computers use the same connection with a wireless router and a USB dongle to share the internet wireless USB adapter?
Answer: Depends on the wireless router, but you don't need it.  You don't mention which Operating System you're using, but since the odds are good that you're running Windows, look into "Internet Connection Sharing".
You set that up on the computer with the dongle, share it over that computer's wifi in "ad-hoc" mode and other computers can connect and use it.

Network wireless USB dongle


Forecasting volatility using GARCH

Question: How do I forecast volatility using GARCH in STATA after estimating the conditional volatility?
Comment: Don't yell STATA, just say Stata. This is not an acronym, unlike SPSS or SAS.
Answer: ARCH postestimation help file explains it all. You will most likely need
<code>     predict hat_volatility, variance
</code>
or
<code>     predict hat_volatility_factor, het
</code>
depending on what exactly you mean by ``volatility''. The former is the full prediction, the latter is the multiplier that goes in front of the $\hat\sigma^2$.
Answer: I can't speak to whether stata has a built-in function for forecasting specific GARCH models. I imagine they do, but you can dig through the help manuals to find it.
More generally, assume a Garch(1,1) model has been fit to $X$, a variable with a constant mean of zero. This model is of the form:$$\sigma_{t}^{2}=\beta_{0}+\beta_{1}\sigma_{t-1}^{2}+\beta_{2}\varepsilon_{t-1}^{2}$$
The next step is to scale the variable $X$ by the conditional standard deviation $\sigma_{t}$ to obtain $\varepsilon_{t}$, the scaled residuals. You would then simulate $\varepsilon_{t}$ under the relevant assumption (so for instance, if you estimate the Garch model with t errors, then you would simulate from that distribution). The future value of volatility would then be: $$\sigma_{t+1}^{2}=\beta_{0}+\beta_{1}\sigma_{t}^{2}+\beta_{2}\varepsilon_{t}^{2}$$
The values in $t+1$ are known, but thereafter you would use the simulated values. If you just want to get a single value for future volatility, rather than a large panel of simulated values, you can simply set $\varepsilon$ to be a vector of zeros.

Forecasting volatility using GARCH


Development of なんか?

Question: Is there anymore to the usage of なんか that isn't saying "something", but rather something like, or along the lines of? I know the two are very similar, but using なんか at the end of a sentence seems to be very clear syntactically, while using it to modify a noun seems weird, especially given the か at the end- further kanji isn't generally used, I don't think. So is there more to it? Is there a more formal way of saying it that would make sense syntactically?
Comment: Compare など and なんて.
Comment: The comparison just makes me more confused, where do those come from?
Comment: Could you give an example or two so we can make sure which なんか you're talking about?
Comment: I forget what exactly my friend said- it was なんか followed by a noun. She was trying to say "Something like a-".
There is more than one なんか?
Comment: Are you sure it was なんか followed by a noun and not preceded by a noun?
Comment: I think that's how she used it, she could have been wrong.
Answer: My answer will be based on the assumption that OP is talking about when 「なんか」 is indeed followed, not preceded, by a noun as s/he so states in the comments (but not in the question).
In informal conversation, there actually exists such a structure.

"なんか + Noun + みたいな(のような) + Noun"

For instance, I have little appetite when I have a fever.  Since I do not want to eat a regular meal, I would say to someone:

「なんかゼリーかヨーグルトみたいなもの、いくつか[買]{か}ってきてくれる?」
"Could you go get some jello or yogurt type of things for me?"

In this sentence, your TL "along the lines of" is spot-on. Note that in this case, 「なんか」 can be replaced by 「なにか」.
EDIT:
Just in case, I will briefly talk about when 「なんか」 is preceded by a noun.  There are two main usages of this structure.
1) Citing an instance.

A: どこか[暖]{あたた}かいところに行きたいなあ。"I'd love to go someplace warm."
B: 暖かいところ?サイパンなんかどう? "Someplace warm?  How about Saipan?"

2) Making light of something.

「[愛]{あい}なんかいらない![金]{かね}が[欲]{ほ}しい!」 "I don't want love!  I want money!"

Note that when 「なんか」 is preceded by a noun, it cannot be replaced by 「なにか」.
Comment: l'électeurさん, Is なんか in 2) used only with negative constructions? If affirmative is possible, could you provide an example?
Answer: It can be used in front of adjectives to convey the sense of "somewhat" (e.g. なんか強い = "somewhat strong").  Is that close to what you're getting at?
Comment: I know the use- I just don't know where it come from. I suppose the syntax label might have been misleading...

Development of なんか？


What is Fourier transform in terms of area under the curve?

Question: We know that integration gives area under the curve.  And that FT is also an integration.  How do we interpret FT in terms of the area under the curve especially because e^(jwt) is a complex term?  In general, while dealing with complex terms in integration can we relate to some area?
Comment: Its best to interpret it as an infinite sum, rather than an area.
Comment: Since the function is continuous it is actually similar to area under the curve rather than a sum.
Answer: Since
$$X(\omega)=\int_{-\infty}^{\infty}x(t)e^{-j\omega t}dt$$
you get for the real part of $X(\omega)$ (assuming that $x(t)$ is real)
$$X_R(\omega)=\int_{-\infty}^{\infty}x(t)\cos(\omega t)dt\tag{1}$$
and for the imaginary part
$$X_I(\omega)=-\int_{-\infty}^{\infty}x(t)\sin(\omega t)dt\tag{2}$$
So if you like, from (1) and (2) you can interpret the real part of the Fourier transform as the area under the curve $x(t)\cos(\omega t)$, and the imaginary part would then be the area under the curve $-x(t)\sin(\omega t)$.
Note that interpreting an integral as the area under a curve does not always help intuition. In the case of the Fourier transform it is more natural to interpret the integrals (1) and (2) as inner products.
Comment: @seethaRama I agree with Matt L. in the sense that the Fourier transform's most natural interpretation is as an inner product. If you want to think in terms of "area under the curve" I advice you to think about the inner product of two function rather than the Fourier transform. You could think about why there is a sum in the inner product of two vectors and how it is used to measure dissimilarity, extend these tought to the continuous case then to the fourier case
Answer: Actually the Fourier transform (and similar transforms like Laplace, and so on ) is not an area calculation, but a change of basis.
This is more intuitive if you see a (continous or discrete) signal $x$ as a vector expressed in some basis (the time-domain basis). i.e
$$x = \sum a^i x_i$$
Then by linear algebra a change of basis is :
$$y = \sum b^i y_i$$
where $a$ and $b$ basis coefficients are related through a linear transformation. Now go to the continous limit (so sums become integrals) and use the roots of unity (i.e $e^{2\pi\omega t}$) as basis components and you have the Fourier transform.
You see it is not related to an area under the signal curve, but it is a linear change a of basis to another (the frequency) domain. This domain encodes the signal in such a way that further information can be extracted more easily (change of signal representation)


How did the T-850 still function after it removed its second battery?

Question: In T-3, the T-850 removes its backup battery and shoves it in the T-X's mouth. It then says "You're terminated" while still holding on to the T-X's wires. How did the 850 keep functioning for so long after its second battery is removed?  Do terminators have a third battery?
Comment: All Schwarzenegger-shaped terminators are built with enough emergency power to get off at least one final cheesy one-liner.
Comment: This isn't an answer, but it's possible to design electronics to have a very small amount of power to be available (without a power supply) for a very short amount of time after running for a bit -- storing energy in a capacitor from a connected power source is the key. Perhaps used in the case of an emergency shutdown to save important information or to share a few last words. Real world example https://electronics.stackexchange.com/questions/153306/using-a-capacitor-to-keep-circuit-powered-for-1s-after-battery-disconnected
Comment: I was thinking the Terminator might have had some kind of emergency back-up battery, like when he started running again after being shut down in the second movie.
Comment: It would be surprising to see the T-850 immediately shut down when the battery removed. Almost all critical systems have an emergency temporary power system, and most high power equipment takes time to shut down - they have large capacitors storing energy. Unplug your laptop power supply and watch how long it takes the power light on the supply to go out. That is the capacitors discharging.
Comment: Ow darn you! You've [ruined the film](https://youtu.be/cfUUGrSMmxI?t=77).
Comment: @VogonPoet - that's only if the laptop was already off. If it was on, the capacitors will be drained instantly.
Comment: @Agreed - well *faster*, not instantly. But it's a real-world demonstration showing how not everything with electricity is like a light bulb. You can do stuff on residual charges, most often in high-powered systems. That's the point.
Answer: This appears to be a filming error. In the original script (on which the film's official novelisation is based), the fuel cell seems to be still wired to the Terminator right up to the point that it exploded. Even in its damaged state it would, presumably, give out sufficient power to allow one last quip.

Without hesitation he yanked the cell out of his chest, trailing wires and mechanical parts, sparks and fluids flying in all directions.
  With his free hand he grabbed the T-X by a piece of tubing protruding from her hip and dragged her back.
  She turned and fixed him with a baleful gaze.
  "You are terminated," he told her.
  Terminator crushed the fuel cell to rupture it, and thrust it into the T-X's mouth, driving it deep into her throat.
  "Eat me," Terminator said, and the fuel cell erupted with a tremendous explosion.
Comment: I can see the "eat me" part being cut off because it might appear as sexual innuendo. I.E. Terminator is shoving in a female character's mouth a part of himself that is longer in one dimension even though it has a square cross-section. And is located in his abdomen.
Comment: @Mindwin - As innuendos go, this one is pretty damn overt
Comment: I don't think that "he yanked the cell out of his chest, trailing wires and mechanical parts, sparks and fluids flying in all directions" at all implies that the battery is still wired and can still provide power.   Also, the fact that he "ruptures it" and can still shoving it in her mouth suggests he's not getting power from the fuel cell.
Answer: Endoskeleton components have emergency power sources
In Terminator: The Sarah Connor Chronicles, the head of the Cromartie T-888 retained power(1) when detached from its body and separated from the body's fuel cells:

Judging by how its eyes glowed and darkened, the head apparently had to ration its remaining energy while the body was en route to recover the head.  The head's backup power supply seems to be limited.
The T-888 series is a more recent design than the T-850 from Terminator 3, but they have similar frames, and so it's reasonable to suppose that they have similar capabilities such as emergency power for their components.  Even if only the head has an emergency power source, we know from the closing battle of Terminator 2 that a terminator can re-route its power supply to bypass internal damage:

It seems that a terminator's head can deliver enough power for a triumphant final taunt.

(1) And the body still had visual sensors and a robust wireless link to the CPU in the head, but I think we're supposed to forget that ever happened.
Answer: From a design perspective I wouldn't build sophisticated electronic/mechanical equipment like a murder-cyborg with just fuel cells.
For example, anything with flash RAM would want a battery for when it powers down or gets unplugged.  Or the mechanical system might want something like super capacitors for very high load tasks like benching a car that the fuel cells either can't instantaneously deliver or would suffer huge loses to efficiency from the high current draw that the task requires.
Comment: This strikes me as a useful answer, quite similar in spirit to Gaultheria's -- supercapacitors could well have powered it for just long enough, and that would be more sensible than a third battery for the reasons indicated.


Is Rack::Session::Cookie secure when used with a session_secret?

Question: How secure is the strategy used in which the cookie consists of base64 encoded array content followed by (I believe) a SHA1 hash of that content salted with a long session_secret known only to the server?  The hash is, as I understand it, a signature to prevent the client from tampering with the cookie contents.  Is this system secure?  In particular, could an attacker figure out how to forge the signature without having access to the session_secret?  Are there any other vulnerabilities?
Answer: SHA1 has known vulnerabilities, so if that's what it uses, I wouldn't recommend it. In theory, this can be exploited to forge the signature.
Comment: Oleksi, wouldn't an attack take months on years if the session_secret was sufficiently long and random?  I guess this is the heart of my question.  Also if there is some other types of attacks which stem from the fact that the attacker could create multiple samples of the form SHA1(+) = .


What 2.5 in. adapter for mSata SSD?

Question: I bought an SSD for my laptop, not knowing there are different form factors and what I got is mSata. It's a tiny thing. Deciding to get an adapter, I want to be sure I get the correct one, and I don't want reduced performance. The Amazon title is "Crucial MX200 250GB mSATA Internal Solid State Drive - CT250MX200SSD3" seen at  http://www.amazon.com/gp/product/B00RQA6LFA . Please give recommendations.
Comment: I looked at the stack exchange meta site for what forum to post my question. In three different places it said superuser is the correct forum. This is because there is no hardware forum as such. My question is not off-topic.
Answer: I was very curious about this post and I started to do some research. I didn't know there were such things as mSATA drives. I found an adapter SY-ADA40050 which boast "No Sacrifice on the mSATA SSD Performance". Shop around you might find a good price for it.
Comment: I saw a similar item. I think an adapter can be found that does not reduce performance. Most likely, none will reduce performance. I'm hoping someone with experience will post. My main concern is for the mSata SSD to fit the adapter, There seems to be different physical sizes. I found http://www.amazon.com/gp/product/B00J1EQH5I , but am waiting to buy it until I see more posts here. An issue is said to be heat dissipation and metal is said to be better.

What 2.5 in. adapter for mSata SSD?


Why do mag mounts not achieve proper grounding seeing as the coax outer connects to ground?

Question: Diamond instructions for my CR8900 antenna state that proper grounding is required for the antenna to work. The battery negative is already grounded and has continuity to the coax outer so isn't the antenna thus already grounded without the need for a short grounding wire?
Answer: A DC ground connection is not the same as an AC ground, especially at RF frequencies and in EM fields, and not the same as the ground plane or counterpoise that a quarter wave vertical antenna requires for decent efficiency and radiation pattern.
So mere DC continuity is not enough.
Answer: The instructions could be worded better.  The point that the instructions are trying to get across is that a proper ground plane is needed for the antenna to work as it was designed.  The manufacturer doesn't want to be blamed for poor performance if someone tries to mount the antenna on the (non-metallic) roof of a house, or a fiberglass pickup truck topper, etc.  On most bands that antenna is a quarter-wave vertical, and as such it needs to be mounted on a conductive surface perpendicular to the antenna (that's the definition of a ground plane), such the roof of a car.  The larger the ground plane, and the closer the antenna is mounted to the center of the plane, the better the antenna will perform.
A grounding wire between the antenna and the ground plane is completely unnecessary, and might prevent the antenna from working as designed.
This is off-topic, but I'd like to discourage you from using a mag mount.  I understand that you might not want to make any permanent alterations to the vehicle, but mag mounts are dangerous, because they can easily detach in a crash and turn your antenna and its mount into a dangerous missile.  Alan K0BG says it better than I could on his web site, which is loaded with information about mobile operating.
Comment: Funny enough, for this antenna, CR8900, Diamond say it must NOT be mounted in the centre of the roof but on the edge of the trunk. I queried this as my 4x4 doesn't have a trunk but Diamond didn't respond. It's a quad band antenna and I suspect Diamond have designed some witch craft to make it work, hence the need to be on the edge. I am wondering if this antenna isn't a serious compromise that's loosing me range.
Comment: Sure enough, the [manual](https://www.diamondantenna.net/pdfdocs/CR8900.pdf) says "Optimized for Trunk Lid Mounting" and "not recommended for magnet mounts or mounting in center of roof" (the latter is in upper case in the manual).  I wonder why that is?  The gain specifications they quote for 10m/6m/2m, 2.15 dBi, is suspiciously exactly the same as the theoretical gain of a dipole.  Anyway their specified gain, 2.15 dBi or 5.5 dBi, is respectable, and VHF/UHF are line-of-sight, so if you actually get gain that is anything like that, then you should have no trouble communicating.
Comment: "Excessive VSWR may occur with the following antennas if used on a magnet mount: ..., CR8900A, ..." Their matching network does not want a ground plane. I bet the mounting bracket holds it up and over, and the first tuning coil is out of range if you add a large ground plane directly underneath. As you say, this is line of sight so it'll probably be ok, but it would be interesting to see how far from 1:5 it goes on the roof. You could probably mount it a little higher on the roof with a custom bracket to hold it away from the rest of the vehicle a little.
Comment: What you say makes sense @jdv.  I'd think that the antenna still depends upon the vehicle being a ground plane, because any λ/4 vertical loses tens of decibels without one. But the designers could have designed the bracket to hold the antenna far away from the vehicle in an effort to trade efficiency for more consistent impedance, which would be easier to match.
Comment: As they say, any antenna wants to be a dipole, and if you don't give it a counterpoise, it'll find one anyway. I guess they didn't want this one to couple so closely with the vehicle I guess.


Chess task - King,Rook Vs King

Question: I want to do a C program to find the minimum no. of moves needed to check mate in a king and rook Vs king,I am supposed to use mini max algorithm.A lot of search haven't led me to any thing fruitful.It would be of great help if some one give some steps how to do it.
Answer: Every min-max algorithm takes as granted you have the tree of all possible made positions.
So for start you have to claculate this tree.
King has limited moves (8) considering all the other pieces, hoewever the tree will grow big enough.
The function you shouldd use  for evaluation is one that values up boards where opposite King tends to be placed towards the ending line of the board (because thats the mate positions if you know how mate is achieved in the scenario you are interested in).
So in every position of the tree where king is closer to the end line of the board this function will have bigger value.
For my chess experience take in consideration that the max number of moves to mate in the scenario you are interested are 25 for every given board...
Simple example of function values for each position on the board:
<code>  100 90 90 90 90 90 90 100
  90  80 80 80 80 80 80 90
  90  80 70 70 70 70 80 90
  90  80 70 60 60 70 80 90
  90  80 70 60 60 70 80 90
  90  80 70 70 70 70 80 90
  90  80 80 80 80 80 80 90
  100 90 90 90 90 90 90 100
</code>
Comment: This doesn't exactly work. With just this evaluation the engine isn't guaranteed to find an optimal mate.
Answer: I'd recommend defining all terminal positions (checkmate and stalemate) and work backwards, creating a hash table of positions and "distance to mate" for each position.  Or download a Nalimov tablebase, since this task has already been done!

Chess task - King,Rook Vs King


How to draw equipotential surfaces for a dipole or system of two like charges?

Question: How can we draw the equipotential surfaces (i.e the surface which has constant potential on all its points) for an electric dipole and a system of two like charges? I read it in some book that they are distorted spheres but why??
Comment: This Wolfram demonstration shows both the electric field lines and the equipotentials.  Do not worry when you move a slider and see a very strange pattern, calculations are being done to produce the final diagram.  http://demonstrations.wolfram.com/LinesOfForceForTwoPointCharges/  Very near each of the charges you would expect something which is nearly a circle as in that region one charge dominates.  Far way from two charges of the same sign again near circular because they look like one charge.
Answer: Let's consider two charges $q_1 = q_2$ charged by $q$ placed respectively at (x,y) = (-1,0) and (1,0) in a plane.
Books tells us that the electrical potential $V(M)$ at point $M = (x_m,y_m)$ is given by :
$$
V(M) = Kq\left(\frac{1}{\sqrt{(x_m+1)^2+y_m^2}}+\frac{1}{\sqrt{(x_m-1)^2+y_m^2}}\right)
$$
Which is simply the sum of the potential created by $q_1$ and the potential created by $q_2$, according to the superposition principle.
To extract an equation of an equipotential surface (which in a 2D plane is a line), we have to find for which $(x_m,y_m)$'s the quantity $V(M)$ remains the same. Let's set a constant $C$ for example, then, the equipotential line equation for $C$ is given by :
$$
Kq\left(\frac{1}{\sqrt{(x_m+1)^2+y_m^2}}+\frac{1}{\sqrt{(x_m-1)^2+y_m^2}}\right) = C
$$
Here is an example plot with $C = \frac{1}{Kq}$ :

and another with $C = \frac{2}{Kq}$ :
Answer: Pretty easy! So let the charges be $-q_1$ and $-q_2$, then we can write potential at any point $P$ as:
$$ V = \frac{-kq_1}{r_1} - \frac{kq_2}{r_2}$$
Where $r_1$ is the distance of the vector which connects $q_1$ to the point of consideration and $r_2$ is the vector which connects $q_2$ to that point. Now, took find equipotential surface, simply fix $V$ like so:
$$ C=  - \frac{kq_1}{r_1} - \frac{kq_2}{r_2}$$
By dividing both sides by $-k$, and saying that $ C' =  - \frac{C}{k}$ then:
$$ C' = \frac{q_1}{r_1} + \frac{q_2}{r_2} \tag{1}$$
I have made a plot of this by assuming $q_1$ is at origin and $q_2$ is at point (a,b), view my graph here
Examples:
If the negative charges are close and equal in magnitude:

If they are very different in magnitude:

If they are far apart and of different magnitude:

If it's a dipole, simply switch signs of one of the charges:


Historical volatility calculation to price options with the Black-Scholes formula

Question: I'm looking for a reference algorithm for calculating historical volatility to price options. I know there are several volatility calculation models that use the time series of the underlying's returns. Is there a reference method for determining the number of days to consider for the calculation?
Comment: Use a time period having the same order of magnitude as your option's tenor.  Please do *not* try and trade around the price you find.  It will be fairly different from what sophisticated market participants work with (i.e. in trading with them you would lose money).
Comment: There is no agreement as to how many days to use to compute historical volatitliy. Some years ago S. Figlewski suggested that you should use as many days of history as the maturity of the option you consider. For example for a 3 month option you should use 3 months of daily data. This is just a heuristic which he suggested based on some empirical tests.
Answer: To answer strictly: no there's no reference method for determining the number of days.
Delving a bit deeper
Always remember the profit from option trading does not come from the price at which you trade but from the mismatch between implied volatility and realised volatility.
Moreover, you can reap that profit only setting up the replicating portfolio, that is constantly delta-hedging the position.
Whatever the way you use to estimate the volatility "generated" by the movements of the underlying between the inception of the contract and the expiry of the option, you should hedge using that estimate when computing the delta-hedge amount of underlying.
Delving way deeper
Check on the market and see an option (either call or put) with maturity $T$ and (irrelevant) strike $K$ trading at some (irrelevant) price $O(T,K)$. You invert the Black-Formula and obtain the so called implied volatility $\sigma_{Blk}(K,T)=25\%$.
Say you have a very good model for the instantaneous volatility of the underlying process $\sigma_{mdl}(t)$. It can be stochastic, state-dependent, whatever. Given your model, compute the following quantity (also called root-mean-squared-volatility)
$$\hat{\sigma}(T) = \sqrt{\frac{1}{T}\int_0^T\sigma^2(u)du}$$
Turns out $\hat{\sigma}(T)=50\%$ from your model. Now you should:

Buy the option on the market
Delta-hedge the option using $\hat{\sigma}(T)$
Continue rebalancing your hedge portfolio after each $dt$ computing the Delta always using $\hat{\sigma}(T-dt)$
If your model is correct, you would end up in profit irregardless if the option expires in the money or not.

What does it mean "the model is correct"? It means that the underlying had a realised volatility of $50\%$ instead of $25\%$.
How much profit? The difference
$$Profit = O(T,K,\sigma_{Blk}=50\%) - O(T,K,\sigma_{Blk}=25\%)$$
How much is $dt$? Theory says "infinitesimal amount of time".
What happens if $dt$ longer than "infinitesimal amount of time"? Your $Profit$ in formula up there is no more going to be a single number, but it turns out to have a distribution (centered on the original value). This distribution is going to be wider and wider the higher $dt$ is, therefore making your profit more and more random (and possibly negative).
Comment: For a dt larger than an infinitesimal amount of time, your portfolio will not be constantly delta neutral and therefore the adjustments will be made potentially after the market moves a bit. As a consequence the final result will depend on how the market moved in relation to your hedging strategy. That's why the profit will be a distribution around the single number of the constantly delta neutral strategy.
Comment: nice answer. Could you pls elaborate a little bit on the last paragraph about the length of $dt$ turning the profit into distribution rather than a single number?
Comment: Totally agree with @DavidDuarte comment (thanks David). To add a little bit: in the theoretical setting "there is no lucky path" (as long as you have continuous paths) that's why the theoretical value of the option is correct no matter what happens during the life of the option. You can picture it easily: hedge the option just once! you see that your profit at expiry will depend on when you hedged and what happened after. I can point you to chapter 4 of Volatility and Correlation by Riccardo Rebonato, where this entire story is explained perfectly (IMHO).
Answer: You should review the difference between implied volatility and realised volatility. Historical volatility is the realised volatility that happen in the past but an option price will have to be determined by the view of the market about volatility in the future for a given period. Normally you do the inverse, ie the option price is given by the market but you can work out the implied volatility from that price.


Battery saver mode does not work

Question: My battery saver mode on Pokemon go does not work. When I turn my phone upside down, it does not dim the screen. How can I make it work?
Comment: The battery saver mode works for me when I turn the phone upside down. It will still have the app running, count walks and notify you when a pokemon shows up, but the screen will be dimmed with a faint PoGo logo.
Comment: What phone are you using?
Comment: @David "PoGo" - love it
Comment: It's not activating for me either. Not just you. Using a Samsung Galaxy Grand Prime
Answer: The problem is with your phones gyroscope, look up your model and see if it even has one, my moto x play does not and therefore cannot use ar or battery saver
Answer: Battery saver mode works by detecting if your phone is in an "idle position" and making the screen black. Make sure the setting is ON, then restart your game. Try placing your phone on a table and seeing if the screen turns black.
If it doesn't, it could be a hardware problem with your phone's internal gyroscopes
Comment: Don't place it on a table, it won't activate for a lot of people like that, just hold it down by your side. The battery saver mode is supposed to let you rest your arm while walking, or having the phone in your pocket, it's supposed to be activated if you turn your phone 180 degrees, not holding it flat upside down.
Answer: On Android I wouldn't recommend using the battery save mode at all. Three of my friends and myself have had issues with the game disconnecting from the game servers and being unable to reconnect afterwards, should the game go to power saving mode. Phones are One+ 1, One+ 2 and a couple of Samsungs. The issue is consistent too: Every time PoGo activates the battery save mode the connection is lost until the game is restarted.
This is an issue with the version 0.29.0, it might be resolved in the very near future.
Comment: I'm using 0.29.2 on an Android - and not a particularly good one either - and I haven't had any issue with connection. So either that did fix it or the signal in your region may be weaker.

Battery saver mode does not work


Cannot Find Vertices Counter in Plugin QGIS 3

Question: I have recently installed the new version of QGIS and can't seem to find the vertices counter in the plugin menu to install. Does anyone know where I can find it?
Comment: Welcome to GIS:SE @user115775! I don't think that plugin has been ported over to QGIS 3 (in fact the [last update](https://plugins.qgis.org/plugins/Vertices_Counter/) was in 2014) :)
Comment: Thanks for getting back to me :D  Do you know if there is any other way I can count the vertices in my shapefile using QGIS?
Comment: You could use the **Field Calculator** to create a new integer field with the expression `num_points( $geometry )`. This will give the number of vertices for each feature. You could then use `Vector > Analysis Tools > Basic statistics for fields` on the new field you created to get the sum of the vertices.
Answer: Since QGIS is using QT 5 and Python 3, many plugins, if not all, need to be updated. You can refer to this article about the changes in PyQGIS API:
QGIS 3 is underway – what does it mean for your plugins and scripts?
The existing plugins will not work properly in QGIS 3.0 due to the changes in the QGIS 3.x API compared with the QGIS 2.x API.
Comment: Thanks for getting back to me! Do you know if there is any other way I can count the vertices in my shapefile using QGIS
Comment: You can use Extract Node tool to convert the vertices to points. You can search for extract node tool in the processing tool bar. Then open the attribute table and you will see the number of points which is actually the vertices. However, if the shapefile is polygon, the output of extract node will contain duplicate vertices as there will be an extra point to close the polygon. Make sure to remove that point.


Why can you remove the gravitational constant from a computer game simulation?

Question: I've seen in a few gravity simulation games (ie. bouncing balls) the equation:
force = G * m1 * m2 / distance^2

shortened to this by removing the gravitational constant:
force = m1 * m2 / distance^2

I accept that it works fine and saves some calculations, but I'm wondering why it still works? Is the value just too small to matter? What's the physics behind this?
Comment: In simple words: force and distance in games are usually measured in chickens and ducks.
Comment: Gravity is not "removed" there in the sense that attraction is still there.
Answer: $G$ is just a constant of proportionality to get the units right (so that when $m_1$ and $m_2$ are in kilograms and $r$ is in meters you get a force in Newtons rather than wingdingalings or something really weird). Indeed cosmologists like to work in a system of units where $G = c = 1 \text{ (dimensionless)}$, and particle physicists like to work in units where $c = \hbar = 1 \text{ (dimensionless)}$, you can even set all three of these numbers to 1 if you like.
In your game implementation you have broad freedom to choose the scale of the masses and the time intervals over which to evaluate stuff, so obviously you can ditch the constant if you want to. Now, if you want to model the solar system and to use the masses you find in a table for the planets and the sun, you'll have to include the constant.
This has nothing to do with the size of the constant however, because it is a multiplicative coefficient.
Comment: Yes. It's just there because meters, kilograms and seconds have their own historical reasons for being as large they are.If you write a game, you don't have to care about such things. You obviously need to think about how strong gravity should be in your game, but you can tweak the masses to do that. If you want the strength of gravity to change dynamically in the game (say, become stronger over time) you could keep it as a variable, but there's no need for it as a constant.
Comment: A very similar situation occurs in electrostatics: in SI units, Coulomb's law is $F = (1/4\pi\epsilon_0)(q_1q_2/r^2)$; the funky constant is there because the unit charge (coulomb) is defined in a roundabout way using magnetic force in current-carrying wires. But in Gaussian units, it is $F = q_1q_2/r^2$, with no constant, because the unit charge (esu) is defined in terms of Coulomb's law instead. Look up "geometrized units" on wikipedia for an extreme version of this.
Comment: Thanks. Would you say that G is used to normalize the equation to fit a particular implementation (cosmology, particle physics, etc.)? And since I'm working in my own game implementation, it's just 1, so I can leave it out? Sorry I'm speaking as like a programmer, it's my only frame of reference.


A question on star-congruence.

Question: We consider $n\times n$ complex matrices. Let $i_+(A), i_-(A), i_0(A)$ be the number of eigenvalues of $A$ with positive real part, negative real part and pure imaginary. It is well known if two Hermitian matrices $A$ and $B$ are $*-$congruent, then
 $$(i_+(A), i_-(A), i_0(A))=(i_+(B), i_-(B), i_0(B)).\qquad{(1)}$$
If two general matrices $A$ and $B$ are $*-$congruent, (1) may not hold (can you provide an example?).
Moreover, whether a matrix and its transpose are always $*-$congruent?
Comment: A and B are $*$-congruent if there is an invertible matrix C such that $B=CAC^*$.
Comment: What do you mean by "But I have come up a counterexample for this"? Counter-example for what? Also, what do you mean by *-congruent?
Comment: Really sorry. I mean I'd like to see a counterexample such that (1) does not hold when $A$ and $B$ are not Hermitian matrices.
Answer: An answer to the second question: Yes, a square complex matrix is always $*$-congruent to its transpose, according to a more general result proved by Horn and Sergeichuk in "Congruences of a square matrix and its transpose".   They prove the result for all fields with involution in characteristic other than 2.
Added:
Here's a counterexample for your first question:
$\left( \begin{matrix} 1 & 0 \\ 1 & 1 \end{matrix} \right) \left( \begin{matrix} 0 & 1 \\ 0 & 0 \end{matrix} \right) \left( \begin{matrix} 1 & 1 \\ 0 & 1 \end{matrix} \right) = \left( \begin{matrix} 0 & 1 \\ 0 & 1 \end{matrix} \right)$.

A question on star-congruence.


What is the original ancient Egyptian names for the "Book of Two Ways"?

Question: After much research, I am asking for help with this matter. I can find no reverse translation for the "Book of Two Ways." Is it like the "Book of the Dead," a modern convenience name for this set of texts, when its original name wasn't discovered until more recently (rw nw prt m hrw 'Utterances of Coming Forth in the Day') ? Or is there no known name for it? I have read that it is also called the "Guide to the Ways of Rostau". If anyone knows the original Egyptian name for either of these two naming conceits and could share them, I would be grateful.
Answer: Hi,
Most likely, you would probably need an interlinear bilingual translation with phonetization of the hieroglyphs. As far as I'm concerned, no such edition exists.
Perhaps the late Theban version "Pert em hru" will serve the purpose? I know it's Budge, and a lot of research was carried out since then, but why not? I guess it should be called "The book of life for the dead to have a safe journey", very much like Orphic Golden Tablets.
Budge E. A. Wallis. 198AD. The Book of the Dead : The Papyrus of Ani in the British Museum : The Egyptian Text with Interlinear Transliteration and Translation a Running Translation Introduction Etc Dover ed. Gloucester MA: Peter Smith. , p. XXX, accessible here:
Internet Archives


Is this headlice or bed bug

Question:
This is very small. About the size of a grain of rice. I Felt it crawling in my hair.  When I brushed my hair off this fell out in the sink. I was wondering if it's lice. I'm in Mojave county Az
Comment: Please add your location and the approximate size of the specimen. Both are needed for an accurate ID. I also advise that you upload any additional pictures you may have of the specimen. Currently, your post is lacking adequate detail and will be closed and unanswered. Please [edit] accordingly. thanks.
Answer: That is a Thrips, order Thysanoptera. Not harmful. Not a bedbug or a louse. You can read about them here.
https://en.wikipedia.org/wiki/Thrips
(by the way the singular form of "Thrips" is "Thrips": there is no such thing as a "Thrip")

Is this headlice or bed bug


Creating shapefile with auto increment primary key in QGIS

Question: Is there a way to create an auto increment primary key column when creating a new Shapefile in QGIS?
Answer: As far as I know, Shapefiles have no concept of primary key or auto increment data types.
What you can do is use Field Calculator to populate a column with row number.
Comment: The only issue is that they seem to change when I edit the data and recalculate; I think the best option is to switch to Spatialite.
Answer: I get this question a lot on the pyshp mailing list and underdark is correct. The shapefile format provides no unique identifiers for geometry or attribute records.
The object id, feature id, or other GUID is a trapping of the software you use and is just a row number assigned as the records are read in.  The only options are to assign a new attribute using scripting or spreadsheet software, or load the data into a spatial database.
Answer: A Shapefile has a OBJECTID field; which serves as its key and primary index which should suit your purposes.
Comment: But the OBJECTID can change as you delete rows; but that is the primary index.
Comment: I believe this is the same as the row number, and is what ArcGIS uses, but I'm not sure.
Answer: I used maximum(id)+1 in the default value field and checked 'Apply default value on update'. It worked fine with me.


What would an astronaut on the moon experience if a 1 meter diameter meteorite struck the surface one km away?

Question: Would the impact result in sufficient gas expelled from the vaporization of the meteorite to carry sound waves a distance of a kilometre from the impact? Would the blast wave be sufficient to injure an unprotected astronaut?
Answer: It depends largely on the speed at impact, which could vary widely. If it's in a similar orbit to the Earth/moon system around the sun, catching up with the Earth/moon around the sun and the moon around the Earth, that would be pretty bad a kilometer away. The ejecta could certainly turn an astronaut into an astronaught.
On the other hand, if the meteorite were coming in from a different direction, say it was orbiting the sun in a similar orbit to the Earth/moon but in the opposite direction, the speed at impact could be as high as 135,000 miles per hour, or 37.5 miles per second. It would be a spectacular show, launching fragments of the moon into orbit around the Earth and likely beyond. Not a lot, but some. Your astronaut 1 kilometer away could never survive.
Comment: I'm not sure you'd call a blast wave composed of vaporized rock a "sound wave", first, because it isn't a pressure wave traveling through a gas so much as a super-heated gas traveling through a vacuum, and second, because the scale of the event would be so much greater than anything we would traditionally call "sound".
Comment: Methinks the composition of the meteor may be relevant too ...
Comment: lol, I completely underestimated the effect of an impactor of that size. So would there be an audible sound a kilometre or two away by the vaporized blast fragments carrying the sound waves?
Comment: Need calculations, and extra assumptions: density, regolith properties, angle of incidence, concrete velocity. -1 for the time being, please revise.
Comment: A useful source is: Melosh, H.J., 1989. Impact Cratering. Oxford University Press, Oxford, UK. By the same author: 2011, Planetary Surface Processes.


A dream in which I remember "real" events

Question: I wonder if there is a word to describe a dream in which my conscience bridges reality and I remember real events in my dream world.  I recently had a dream like this. It was not a lucid dream, because I didn't realize I was dreaming until I woke up afterwards. In the dream I remembered events from a previous dream a week ago but also remembered real events from a day or two before and was somewhat confused by the inconsistency of the facts encountered. So my question is: is there a name for such a dream? Either a single word or a short phrase?
Answer: Vivid dream could be used (Collins).

conveying to the mind striking realism, freshness, or trueness
to life; graphic
(of a recollection, memory, etc) remaining distinct in the mind (of
the imagination, etc) prolific in the formation of lifelike images


What if the thief refuses to admit?

Question: An employer found out that his worker has been stealing money from his business for some time. Though he has not caught him red handed, the overwhelming circumstantial evidences leaves no doubt at all about the thefts. However the worker stubbornly refused to admit his wrongdoing. What is the Islam ruling if the employer straightaway cut the wages of the worker to cover his loss due to the theft as it would not be worth the trouble to bring the case to the court?
Comment: "البينة على من ادعى واليمين على من أنكر" is a relevant ruling. It states that "Whoever accuses a person with a crime must bring an evidence, and if the person wants to deny the accusation, he must make a holy swear that he didn't do."
Comment: If its allot of money and he thinks he did, then he should act on it because if he don't it could continue and he lose the company by him/her. What @Tamer said is true, but if it all traces to him  and you are sure it is him you should act if you are not sure do not do anything and bring some more evidence. Make him swear to Allah that he did not steal anything, If he does you should just assume he didn't do it even when you still think he did it. An other option is to fire him, if he refuses to go tell him you will go to the police he may tell the truth if not, escalate it to the police.
Answer: In Islam, if a husband walks in on his wife having intercourse with another man he can not do anything unless he has 4 other witnesses or swears upon Allah that she did it -at which she can swear she didn't and she is free to go as Allah mentions in the Quran:

واللاتي يأتين الفاحشة من نسائكم فاستشهدوا عليهن أربعة منكم

The same thing is true with all crimes in Islam, the person must be caught in the act of stealing and not just from one person, unless the person confesses his crimes.
Lawfully speaking, if you take a person to court or the police with circumstantial evidence (even if they are overwhelming), it is all that is,  circumstantial and will be thrown out of the court.
Sources:
 - http://library.islamweb.net/newlibrary/display_book.php?idfrom=6280&idto=6299&bk_no=15&ID=6171

What if the thief refuses to admit?


Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value on an mp4 file I've added to project

Question: I'm unable to figure out why I'm getting this "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value" error when the file is clearly in the project and is an mp4 file. I've imported the proper AVKit, etc. and still cannot figure this out

 @State var player = AVPlayer(url:  Bundle.main.url(forResource: "bump", withExtension: "mp4")!)

    var body: some View {
        VStack {
            VideoPlayer(player: player)
                .allowsHitTesting(false)
        }
        .padding()
    }

I've even replaced the player with the following code and have gotten the same result
AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: "bump", ofType: "mp4")!))

Answer: Double-check to make sure bump.mp4 was added into bundle resources.

Project -> Target -> Build Phases -> Copy Bundle Resources -> Tap (+)
Comment: face palming myself because this was the problem, thank you!
Comment: No worries, take it easy.


Could not load the preview image. Please reload the page and try again - error on image upload

Question: i am getting this error "Could not load the preview image. Please reload the page and  try again" whenever i upload any image on my Blog Site blog.knorish. I can see the thumbnail and image is loaded in Image folder and database with multiple sizes but on viewing it shows error, Divi Extra theme is being used to create this blog site.  I am sending you the screen shot of the error page.
Comment: On the page you are having the error, use the Inspect the element on your browser and then click on console and then post here what is the error is showing on the browser console
Comment: I had the same problem... In one of my php files I had opening my opening php tags on LINE 2 and not LINE 1. Looked right over it so many times.. good luck
Answer: In my particular case functions.php of my theme was involved.
Just remove empty space after end of "<?php /*code or comment*/ ?> "
There should be NO empty space between "<?php ?>" tags.
You can find more info: https://wordpress.org/support/topic/basic-image-editor-not-working/
Good luck!


OpenStreetMap - Determining number of nodes, ways, and relations in a PBF file?

Question: I'm currently importing a subsection of North America into PostGIS to render my own basemap tiles using osm2pgsql. Is there any way to get an accurate count of the number of nodes, ways, and relations contained within my PBF file that I am generating to determine how long this will take to process on my computer?
Comment: osm2pgsql generates the nodes and ways, so you can definitely count those... I can't remember how to count the relations, though, so will add the pgRouting tag to this question just in case someone can answer...
Answer: You can run osm2pgsql with null output, no RAM cache, and no slim cache. For a 2.5GB PBF extract of Canada, it took me about 37 seconds to count the nodes, on an NVMe SSD.
$ osm2pgsql --output null --cache 0 canada-latest.osm.pbf
osm2pgsql version 0.96.0 (64 bit id space)

WARNING: ram cache is disabled. This will likely slow down processing a lot.

Using projection SRS 3857 (Spherical Mercator)
Allocating memory for dense node cache
Allocating dense node cache in one big chunk
Allocating memory for sparse node cache
Sharing dense sparse
Node-cache: cache=0MB, maxblocks=0*65536, allocation method=3

Reading in file: canada-latest.osm.pbf
Using PBF parser.
Processing: Node(327502k 32750.3k/s) Way(18801k 895.29k/s) Relation(0 0.00/s)  parse time: 31s
Node stats: total(327502800), max(6338602157) in 10s
Way stats: total(19016827), max(676910855) in 21s
Relation stats: total(321360), max(9397389) in 0s

Going over pending ways...
        0 ways are pending

Using 12 helper-processes
Finished processing 0 ways in 0 s

Going over pending relations...
        0 relations are pending

Using 12 helper-processes
Finished processing 0 relations in 0 s

node cache: stored: 0(0.00%), storage efficiency: nan% (dense blocks: 0, sparse nodes: 0), hit rate: nan%

Osm2pgsql took 37s overall

Note that there are two numbers, the total for this file, and the max for the OSM database.
The node count can then be multiplied by 8 bytes to get a good estimate for the cache size when you import into PostgreSQL. In this case, 327502800 * 8 bytes = 2.44 GB. The osm2pgsql manual recommends adding 10 to 30% overhead on top of that cache value.
Answer: You can use PyOsmium Python package. -Documentation-
It can be time consuming, because it scans all the data to count all elements.
import osmium

class Counter(osmium.SimpleHandler):
    def __init__(self):
        osmium.SimpleHandler.__init__(self)
        self.num_nodes = 0
        self.num_ways = 0
        self.num_relations = 0

    # this method runs for each node
    def node(self, n):
        self.num_nodes += 1

    # this method runs for each way
    def way(self, w):
        self.num_ways += 1

    # this method runs for each relation
    def relation(self, r):
        self.num_relations += 1

counter = Counter()
counter.apply_file("path/to/pbf/file.pbf")

print("Number of nodes : %d"    % counter.num_nodes)
print("Number of ways : %d"     % counter.num_ways)
print("Number of relations: %d" % counter.num_relations)


Simultaneous diagonalization

Question: Given two symmetric matrices $A,B\in\Bbb R^n$ how can we find if they are simultaneously diagonalizable? If they have such property how can we find $U$ such that $UAU'$ and $UBU'$ are simultaneously diagonalized efficiently?
Answer: It suffices to use the fact that any two commuting matrices are simultaneously upper-triangularizable. In particular, because $A$ and $B$ commute, there exists a unitary matrix $U$ such that both $UAU'$ and $UBU'$ are upper-trinagular.
Note, however, that $(UAU')' = UAU'$, and $(UBU')' = UBU'$. So, these matrices are upper triangular and symmetric.  We may therefore conclude that they are both diagonal.  Thus, $U$ is a unitary matrix that simultaneously diagonalizes $A$ and $B$.
This can be done if and only if $A$ and $B$ commute.

One method of finding this $U$ is given in Horn and Johnson, which I don't have on hand for reference.  The key is to do this recursively, noting first that any two commuting matrices have a common eigenvector.
In particular: if $A u = Bu$, with $\|u\| = 1$, then take $u$ to be the first column of the unitary matrix $U_1$.  We then have
$$
U_1AU_1' = \pmatrix{\lambda & *\\0&\tilde A} \quad
U_1BU_1' = \pmatrix{\lambda & *\\0&\tilde B}
$$
Now, suppose that $\tilde V \tilde A \tilde V'$ and $\tilde V \tilde B \tilde V'$ is upper triangular for some unitary $\tilde V$. Then, define
$$
V = \pmatrix{1&0\\0&\tilde V}
$$
verify that both $(VU_1) A(VU_1)'$ and $(VU_1)B(VU_1)'$ will be upper-triangular.
Comment: Given that the two matrices are symmetric, it may very well be faster to *separately* diagonalize them first, then adjust the diagonlizing unitary matrices so that they match.
Answer: Two diagonalizable matrices $A$ and $B$ are simultaneously diagonalizable if and only they commute, that is, $AB=BA$. For details see this answer. Note that we do not need to assume they are symmetric, only that they are diagonalizable.
I don't know of a good answer to the question of finding a unitary operator $U$ that diagonalizes some given commuting symmetric matrices. Of course, one can just brute force find a common eigenbasis (see Theorem 5.1 in the notes referenced in the linked answer), but this seems inefficient, and I don't know of any better algorithms for when $A,B$ are large.
Comment: diagonalize $AB$ perhaps?

Simultaneous diagonalization


Proper reflexive verbs (echte reflexive Verben)

Question: I have a question concerning the reflexive use of verbs. While I do understand that there's no such thing as "reflexive verbs", only verbs that may or may not be used reflexively depending on context, I can't help but wonder whether there exists a comprehensive list of German verbs that are exclusively used reflexively. I was told that verbs of grooming are of mandatory reflexive type but I've seen use-cases which suggest otherwise. Thanks in advance.
Comment: I shall be surprised if there is a single verb concerning grooming which can be used *only* reflexively. Anything I can do upon myself I could also do to you - even if that may be strange or uncommon and / or unwelcome. There sure are verbs which can only be used reflexively like 'sich bedanken', but that's not of the mentioned category
Comment: @Dr.Doom To keep it short: Yes, there are true reflexive verbs.
Comment: I'm pretty sure the OP is referring to [this Herr Antrim video](https://www.youtube.com/watch?v=rw5Pd9OQ3fA) with the title "German Reflexive Verbs Don't Exist". I can see his point, and perhaps for teaching purposes the label "reflexive verb" is less than helpful, but his terminology isn't really accepted by most people.
Comment: @planetmaker: Sei bedankt für diesen Kommentar! Or, if you prefer it classically: "Nun sei bedankt, mein lieber Schwan!" (Lohengrin, Act 1, scene 3). It is disputable, if the participle here is still a form of a verb or rather acts like an adjective, but it is non-reflexive. I haven't checked but I suppose "bedanken" could be used non-reflexively historically and when that form went out of use only the participles retained that option.
Answer: Unlike in English, there are proper reflexive verbs in German, i.e. verbs that MUST be used together with a reflexive pronoun under all circumstances. In addition, there are transitive verbs that can also be used reflexively, but these types of verbs also exist in English. An example of a transitive verb that can be used reflexively is waschen (to wash):

transitive usage:

Ich wasche das Auto.
I wash the car.

reflexive usage:

Ich wasche mich.
I wash myself.

However, proper reflexive verbs are verbs that can never be used without a reflexive pronoun. In German, there are two kinds of them. One kind needs the reflexive pronoun in the accusative, the other in the dative case. And because the reflexive pronouns differ only in the first and second person singular (ich, du) in these cases, I give all the examples in second person singular. And because some of these verbs are separable, I will use the future tense so they are not separated:
Proper reflexive verbs with accusative reflexive pronoun

Du wirst dich aufregen.
You will be upset.
Du wirst dich auskennen.
You'll know your way around. You'll know your stuff.
Du wirst dich ausruhen.
You will rest.
Du wirst dich bedanken.
You will say thank you.
Du wirst dich beeilen.
You will hurry.
Du wirst dich (über etwas) beschweren.
You will complain (about something).
Du wirst dich bewerben.
You will apply.
Du wirst dich bücken.
You will bend over.
Du wirst dich (für etwas) entscheiden.
You will decide (for something).
Du wirst dich entschließen (etwas zu tun).
You will decide (to do something).
Du wirst dich (für etwas) entschuldigen.
You will apologize (for something).
Du wirst dich erholen.
You will recover.
Du wirst dich erkälten.
You will catch a cold.
Du wirst dich (nach etwas) erkundigen.
You will inquire (about something).
Du wirst dich freuen.
You will be happy.
Du wirst dich (vor etwas) fürchten.
You will be afraid (of something).
Du wirst dich (für etwas) interessieren.
You will be interested (in something).
Du wirst dich irren.
You will be wrong.
Du wirst dich (auf etwas) konzentrieren.
You will focus (on something).
Du wirst dich (um etwas) kümmern.
You will take care (of something).
Du wirst dich schämen.
You will be ashamed.
Du wirst dich (nach etwas) sehnen.
You will long/yearn (for something).
Du wirst dich umsehen.
You will look around.
Du wirst dich verbeugen.
You will bow down. You will take a bow.
Du wirst dich verirren.
You will get lost.
Du wirst dich weigern.
You will refuse.
Du wirst dich wundern.
You'll be surprised.

There is also a fixed phrase that works like a proper reflexive verb:

Du wirst dich auf den Weg machen.
You will be on your way. You're going to hit the road.

Proper reflexive verbs with dative reflexive pronoun

Du wirst dir etwas denken.
You will think of something.
Du wirst dir etwas merken.
You'll remember something.
Du wirst dir etwas vorstellen.
You will imagine something.

Fixed phrase that works like a proper reflexive verb:

Du wirst dir Mühe geben.
You will make an effort.
Du wirst dir Sorgen machen.
You will worry.

Note, that some of these verbs also can used in other meanings (and then in other constructions) where they are no longer proper reflexive verbs. Here is an example:

proper reflexive verb:

Du wirst dich (für etwas) interessieren.
You will be interested (in something).

transitive verb:

Du wirst ihn interessieren.
He will be interested in you.

Although Du is the subject in both sentences, the person who has interest is du only in sentence 1, while in sentence 2 it's ihn who has interest, and du is the object of his interest. So, the verb has another meaning, and therefore it's technically a different verb. (The two verbs are homonyms.) And only one of them is a proper reflexive verb, while in this example, the other is a transitive verb.
Another example:

Du wirst dich fürchten. = You will be afraid. (Proper reflexive)
Du wirst ihn fürchten. = You will fear him. (Transitive)

The meanings are similar, but not identical, and this becomes clearer whan you add something:

Du wirst dich vor der Schlange fürchten. = You will be afraid of the snake. (Proper reflexive)
Du wirst ihn vor der Schlange fürchten. = You will fear him of the snake. (Transitive)

The later sentence makes no sense in German and also no sense in Englisch.
Also this example:

Du wirst dich auf die Arbeit konzentrieren. = You'll focus on the work. (Proper reflexive)
Du wirst den Saft konzentrieren. = You will concentrate the juice. (transitive)

In German it looks like the same verb (konzentrieren), but in English the two homonyms even become two different verbs.
And there is a similar case in the dative group:

Du wirst dir jetzt sicherlich den Herrn Müller vorstellen. = You will surely imagine Mr. Müller now. (Proper reflexive)
Du wirst mir jetzt sicherlich den Herrn Müller vorstellen. = You will certainly introduce Mr. Müller to me now. (transitive)

I think this list is quite comprehensive, as requested by you. But I cannot guarantee that this list is complete. Maybe there is one or another rare verb that should also be on this list.
Comment: I haven't looked through the entire list, but "aufregen" definitely isn't exclusively reflexive. Etwas kann jemanden aufregen.
Comment: One nitpick, there are actually two verbs in English that are only used reflexively, at least in ordinary language. They are "perjure" and "pride". I guess that's nothing compared to a lot of languages, including German.
Comment: bewerben also can be used non-reflexively (etwas bewerben). Similarily konzentrieren. Darf ich Dir eine nicht-reflexive Form dieses Verbs vorstellen und Dich dafür interessieren? Sie machen mir echt Sorgen.


Do magnetic field lines physically exist?

Question: I always thought that the field lines drawn in magnetic fields in diagrams were simply visual aids showing the direction of particles at arbitrary points people chose to place a field line. However, when viewing images of iron filings being acted upon by magnetic dipoles, they group together and follow distinct lines. Does this mean that the field lines aren't just visual aids but real physical phenomena?
Comment: If you place some pieces of iron along the north-south direction will this mean that the meridian lines are real?
Comment: Physics is about physical things and something physically forced those iron fillings to form those lines. They are really there so they physically exist.
Comment: See https://physics.stackexchange.com/q/566712/74763 for an explanation of why the iron filings "self organize" to form visible lines.
Answer: I think the linked answers don't satisfactorily justify the phenomenology of the iron filings, so here's an attempt to answer that part of the question only.
The apparent lines are a thing ferromagnetic things (like iron filings) do in a continuous magnetic field, not characteristics of the magnetic field.
Iron particles align in a way resembling field lines because the high magnetic permeability of iron makes the iron particles function like tiny bar magnets whose poles are lined up in the same direction as the magnetic field. The magnetic field itself is continuous.
Just like bar magnets, they are most stable when they line up pole to opposite pole.
Furthermore, the strength of the field at the end of the line of iron filings is much stronger than it is elsewhere. This is again because of the iron's high magnetic permeability. The magnetic field of the magnet diverges much less when it is passing$^1$ through iron than when it is passing through air, effectively focusing the field strength to the end of the cluster of filings farthest from the magnet. This is analogous to how a fiberoptic cable focuses light from a source to the end of the cable, although the mechanism is different.
So: the lines emerge as a consequence of the attractive and repulsive forces between opposite and like poles of magnets respectively, combined with the fact that the iron particles are magnetized in the direction of the magnetic field wherever they randomly happen to start out, and the magnetic field being stronger near the outer end of a cluster of iron filings than elsewhere nearby.

$1:$ despite the word choice, no actual movement of the field is going on
Comment: Small correction: iron filings are ferromagnetic, not paramagnetic
Comment: Edited, thanks for the correction.


Connect cakephp 2.4 with redis on centos 6.4 and nginx

Question: Well first of all I'm sorry for my bad english, and I hopefully to be answered to my questions.
Good I'll do my question and maybe it's quite complicated, but I'am novice in that topic.
I have an application working on cakephp version 2.4 working on centos 6.4 64 bits with nginx server and working nice.
Now I need to integrate a part of my application with node.js and there is a problem, it's because I need to know the session (File cache) of my cakephp, and I was reading/trying over all the day about to configure each other application and I tried first reading the session files directly only to make a test but I knew it that it wasn't correct because is very insecure and also it's difficult to parse the data and the last reason was it's node.js can't match that user connected to my cakephp application is the same of node.js.
Then reading more about it I saw it's possible to match each application if I use memcached or redis cache and I tried to install memcached and after redis on centos, everything was ok during install but when I tried to put on my cakephp application with this:
Core.php
$engine = 'Redis';
bootstrap.php
Cache::config('default', array('engine' => 'Redis'));
Always cakephp give me the next error:
16:58:57 Error: [CacheException] Cache engine default is not properly configured.
Stack Trace:
0 /var/www/public_html/project/lib/Cake/Cache/Cache.php(151): Cache::_buildEngine('default')
1 /var/www/public_html/project/app/Config/bootstrap.php(28): Cache::config('default', Array)
2 /var/www/public_html/project/lib/Cake/Core/Configure.php(92): include('/var/www/public...')
3 /var/www/public_html/project/lib/Cake/bootstrap.php(177): Configure::bootstrap(true)
4 /var/www/public_html/project/app/webroot/index.php(92): include('/var/www/public...')
5 {main}

And I'm not sure if on nginx I need to configure something about Redis ( About it memcached it was happen the same on cakephp).
On nginx I had the next config:
user              nginx;
worker_processes  2;
error_log         /var/log/nginx/error.log;
pid               /var/run/nginx.pid;
events {
worker_connections  4000;
# essential for linux, optmized to serve many clients with each thread
use epoll;

# Accept as many connections as possible, after nginx gets notification about
    #a new connection.
# May flood worker_connections, if that option is set too low.
multi_accept on;

}
http {
include       /etc/nginx/mime.types;
default_type  application/octet-stream;
sendfile        on;

# Caches information about open FDs, freqently accessed files.
# Changing this setting, in my environment, brought performance up from 560k req/sec, to 904k req/sec.
# I recommend using some varient of these options, though not the specific values listed below.
open_file_cache max=200000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;

#tcp_nopush     on;

#keepalive_timeout  0;
keepalive_timeout  65;

#gzip  on;

server {
    listen       80;
    server_name  dev.project;

    client_max_body_size 2m;
    access_log  /var/log/nginx/cakeapp.access.log;
    error_log   /var/log/nginx/cakeapp.error.log;
    rewrite_log on;
    root    /var/www/public_html/project/app/webroot;
    index   index.php;

    # Not found this on disk?
    # Feed to CakePHP for further processing!
    if (!-e $request_filename) {
            rewrite ^/(.+)$ /index.php?url=$1 last;
            break;
    }

    # Pass the PHP scripts to FastCGI server
    # listening on 127.0.0.1:9000
    location ~ \.php$ {
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_intercept_errors on; # to support 404s for PHP files no$
            fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
    }

    # Deny access to .htaccess files,
    # git & svn repositories, etc
    location ~ /(\.ht|\.git|\.svn) {
            deny  all;
    }
}

# Compression. Reduces the amount of data that needs to be transferred over
    # the network
gzip on;
gzip_min_length 10240;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml;
gzip_disable "MSIE [1-7]\.";

}
Please any tip what I need to do to connect session of cakephp with Redis?
One more thing I tried redis with cli and was working well making a test with set and get and was working ok.
Thanks in advanced.
PD. All of that project is working on a virtual box machine
Answer: I just ran into this. There is one of two things going on. I am not sure that you can configure the cache for Redis with It looks like your configuration is incomplete. I think you need the server parameter. Try copying the Cache config for memcached and updating it for Redis. The other problem could be that Redis isn't running. This was the final issue for me. Start Redis and test again.


Is it possible to install Gnome3 in Kubuntu 11.04

Question: Just wondering if it is possible to install Gnome3 under Kubuntu 11.04?
Comment: Yes, you can install any DE you like
Comment: Yes it is possible.
Answer: Yes.
sudo apt-get install gnome3-session

If you want to know if a package is available, search Synaptic (or whatever package manager you want). For the definitive answer, search Apt.
$ apt-cache search --names-only gnome3
gnome3-session - The GNOME Session Manager - GNOME 3 session

Answer: When you say Gnome 3, you probably mean Gnome Shell, right? Because those are different things. Gnome 3 includes Evolution, Nautilus, Epiphany, etc. Gnome Shell is just that.
But yes, you can install anything in any Ubuntu; you can install a desktop environment on Ubuntu Server, you can install all services on all desktop variants, and you can install all desktop environments in other desktop environments. Or you can just install parts of them. I sometimes use Xfce4 Panel in my Unity session, to add a bottom panel, for instance.
Just install http://apt.ubuntu.com/p/gnome-shell and then you can choose it when you log in.
Answer: sudo apt-get install gnome-shell

I'm not sure what dependencies gnome-shell installs, since I haven't tried this. Maybe
sudo apt-get install --no-recommends gnome-shell


Convert solana wallet to custom program owned wallet

Question: Is it possible to convert a system program owned account which has sol and other spl tokens in it to a custom program owned account and still retain all the items the account previously had?
Answer: It's possible, but you may see some unexpected behavior. Let's say you have an account A, which is currently owned by the system program, and also is marked as the owner of a few SPL token accounts.
If you assign account A to some other program, then that program will be able to change its data and move its SOL, per the normal Solana ownership model: https://docs.solana.com/developing/programming-model/accounts#ownership-and-assignment-to-programs
However, the private key for A will still be able to authorize transfers of the SPL tokens that it owns, and not the program it is assigned to. This is because the SPL token program just looks for a signature from the owner, and it's still possible to generate valid signatures for A.
To properly solve this problem, you should move everything to be owned by program-derived addresses: https://docs.solana.com/developing/programming-model/calling-between-programs#program-derived-addresses -- this way, only the program can "sign" for the assets.
Comment: I have a discord based wallet system which stores wallet pk's nd ties them to users which is not really web3 thing to do. Now I want to create a custom program and assign accounts to users under that program. But the problem is being in discord, people can't sign tx's with their wallet which will require them to go to external link and I really don't want that.

What would be the best way to provide users an account under the custom program to use and still keep it secure from being accessed anyone other than that person? And without storing anything sensitive in local db?
Comment: If you want to validate user actions, you have two main options: they sign transactions themselves, which requires them to store the private key on their side, or you need to have an external authentication service for them to access. In the second case, you'd be managing their funds, which might cause regulatory issues depending on your jurisdiction. If you can find a way to go with the first way, through self-custody, then you can provide a more web3-style experience. All that to say: it's a hard problem!


Filtering Gmail on From field

Question: When I create a Gmail filter using the FROM field, do I want to enter the entire sender address or can I just use the name Google puts in the Inbox's from column?  And, if I want to trap a string of words, how do I enter the string? With " or '?
Answer: Gmail filters don't reach out to your contacts, so you want to use a fully-qualified email address.
As for strings in your filter, unless you're looking to exact match on multiple words, you shouldn't need any quotes. If you do, either should suffice.

Filtering Gmail on From field


Negative istekhara

Question: A.O.A
I met a guy before 7 months and i really like him he also likes me so we want to marry each other. So for that purpose we asked a moulvi to do istekhara for us n he told us that your istakara came negative. But we want to do nikkah and we are very serious for each other plz trll me is there anyway so that Allah will also agree with our marriage and the result will be positive. And what if i ignore the negative sign of istekhara and pray again of our marriage in front of Allah? Plz help me i m really confused and tensed and i dont want to leave him and we are not doing anything wrong we just want to do nikkah and to spend life with eachother.
Comment: Salam and welcome to IslamSE the Q&A site about Islam. Why didn't you both do istikhara? Leaving a third person do istikhara is a rather discussed topic among scholars. Please click on the tag istikhara you may find posts answering your inquiry.
Answer: You can do istikhara as many times you want.
Also you can go opposite to results of istikhara, it is not like going against Allah, you both can get married.
Also remember dua is a very powerful gift from Allah which can change things.
Lastly just an advise, while going for marriage two factors are very important; other person's religious attachments. More a person is God fearing the better. And second is Ikhlaq, compassion is the key to happy marriage life.

Negative istekhara


Can I come to Canada 6 months before my college starts and get work here?

Question: My flights got cancelled due to Covid-19 and I am thinking to defer classes to September intake.
I want to fly as soon as flights open before it gets banned again.
Comment: Can you clarify but editing in your nationality and what you mean by work, do you mean employment with a Canadian employer? This may be more suitable for our Expatriates site.
Answer: If you are not a Canadian citizen or permanent resident, and do not otherwise have a valid work permit, it is not possible for you to work.
As a full-time student you may be eligible to work on- or off-campus under conditions. But in any case, you may not work in Canada until you start your studies (i.e. after the semester starts).


triggering outside actions from tezos

Question: assuming I am running a tezos node, is there any way to create a smart contract in tezos that is capable of triggering outside actions? For example, sending an email to an address, or turning lights on or off in my home? This will I guess involve having a listener process running on the same processor as my node, that listens to all the new transactions and takes action when a transaction corresponding to the firing of the smart contract occurs. The crude idea for an on/off type command is that I can generate in advance hardcoded "flag" hashes for each particular command, and check if the hash appears anywhere in a new block and if it does, the command fires (whether a human put it there or a smart contract generated it doesn't matter). So that the sleeping value in a contract does not fire the trigger, I can simply store the hash minus one, and until the contract adds 1 to it it doesn't show up. Since the data in Tezos is public, I'm sure this can be done, but I'm wondering whether it can be done in a more simple and efficient way than the above hack, or if it's been done already. Thank you
Answer: If you want to monitor one smart contract in particular you can use DIP {DUP} or Que Pasa.

triggering outside actions from tezos