问:
How can I read the content of the User-Parameters attribute of an Active Directory Object?
I need to extract some information from an Active Directory object, such as the profile path or if the user is locked out or not.

I can see these information are saved inside the User-Parameters attribute of the Active Directory object, but the value of this attribute is a mangled string of incomprehensible characters:

I can see that another user had the same problem, but there's not clear solution on how to parse that attribute.

How can I extract the data I need while maintaining my sanity?

答:
The User-Parameters attribute value is quite… particular.

While the attribute definition says that the value is a Unicode string, the reality is a little more complex: the value is a binary payload of mixed text and binary data encoded using a couple of "algorithms" and then casted to a Unicode string — that's why you see junk characters, these character are actually pure binary data displayed as a string.

There are many articles on the internet on how to decode this value, but most of them are either wrong or manage to decode the value using a wrong procedure (which, while yielding correct data in their examples, could break at any time).

Examples of such articles are:

Reading and writing the Terminal Server userParameters binary blob in Active Directory — the decoding algorithm is wrong, see below on how it works;

Microsoft Active Directory: UserParameters Header — uses the same wrong decoding algorithm as the previous one and is needlessly complicated;

and VB.NET Decode AD UserParameters Attribute Values — this seems to get it right, but I'm not skilled enough in VB to validate the code.

How the data is encoded is defined in the Terminal Services Terminal Server Runtime Interface Protocol documentation.

In particular you're looking for:

the userParameters document, which describes the overall structure of the binary payload;

the TSProperty document, which describes the structure of the properties contained in the payload;

and the Encoding PropValue Field in TSProperty Structure document, which explains how the value of the properties contained in the payload is encoded.

Optionally you can have a look to the Encoding/Decoding Example for a (really) terse example on how to decode the properties values.

If you're still with me, didn't lose your sanity, summoned Cthulhu or set on fire whoever inside Microsoft ever thought that doing something like this was a good idea, let's proceed to write the code to parse and extract the data.

Per me si va ne la città dolente,

  per me si va ne l'etterno dolore,

  per me si va tra la perduta gente.

  […]

  Lasciate ogni speranza, voi ch'entrate.

— Dante Alighieri, Divina Commedia, Inferno, Canto III

(There's a Minimal, Complete, and Verifiable example linked at the end of the answer for those who are too impatient to read everything.)

Step 1 — Getting the attribute value

You can get the value through either the System.DirectoryServices (usually calles "S.DS") or System.DirectoryServices.Protocols (usually called "S.DS.P") libraries. If you need some help on how these libraries work you can read the Using System.DirectoryServices to Search the Active Directory and Introduction to System.DirectoryServices.Protocols articles.

If you are a .NET Framework user, these are your usual GAC assemblies so you'll have to add them as you always do.

If you are a .NET Core user, rejoice! Both libraries have been released on NuGet — albeit as a pre-release — on 2017-11-15, so you too can query Active Directory now! Go fetch them: System.DirectoryServices, System.DirectoryServices.Protocols.

Nota bene: The code in this answer has been written for a .NET Core 2.0 target, if you're not using .NET Core you probably have to adjust the code slightly; these changes however should be small and easy as the Core and non-Core version of the libraries are very similar.

Here we're reading the attribute using System.DirectoryServices.Protocols:

```<code>var ldapDirectoryIdentifier = new LdapDirectoryIdentifier(
  "domain-controller.example.com",
  389,
  true,
  false);

var networkCredential = new NetworkCredential(
  "alice@example.com",
  "p@sSw0rd",
  "example.com");

var ldapConnection = new LdapConnection(
  ldapDirectoryIdentifier,
  networkCredential,
  AuthType.Kerberos);

var searchRequest = new SearchRequest(
  "DC=example,DC=com",
  "(objectClass=user)",
  SearchScope.Subtree,
  "userParameters");

// WARNING
// If the parameters of either LdapDirectoryIdentifier or NetworkCredential are wrong
// (e.g. invalid credentials) you'll get an exception here.
var searchResponse = (SearchResponse) ldapConnection.SendRequest(searchRequest);

foreach (SearchResultEntry searchResultEntry in searchResponse.Entries)
{
  // WARNING
  // This WILL throw an exception when used on an object where the attribute is missing.
  // You should really check that the attribute exists and has exactly one value.
  // I skipped that for brevity, you should not.
  var directoryAttribute = searchResultEntry.Attributes["userParameters"];
  var attributeValue = (string) directoryAttribute[0];
}
</code>```

Step 2 — Define what the attribute contains

Now that we have the value of the attribute, we need something to hold the values it contains.

First of all, we need some enums.

The first one is the CtxCfgFlags1 enum:

```<code>[Flags]
public enum CtxCfgFlags1 : uint
{
  Undefined1 = 0x00000000,
  Undefined2 = 0x00000001,
  Undefined3 = 0x00000002,
  DisableCam = 0x00000004,
  WallpaperDisabled = 0x00000008,
  DisableExe = 0x00000010,
  DisableClip = 0x00000020,
  DisableLpt = 0x00000040,
  DisableCcm = 0x00000080,
  DisableCdm = 0x00000100,
  DisableCpm = 0x00000200,
  UseDefaultGina = 0x00000400,
  HomeDirectoryMapRoot = 0x00000800,
  DisableEncryption = 0x00001000,
  ForceClientLptDef = 0x00002000,
  AutoClientLpts = 0x00004000,
  AutoClientDrives = 0x00008000,
  LogonDisabled = 0x00010000,
  ReconnectSame = 0x00020000,
  ResetBroken = 0x00040000,
  PromptForPassword = 0x00080000,
  InheritSecurity = 0x00100000,
  InheritAutoClient = 0x00200000,
  InheritMaxIdleTime = 0x00400000,
  InheritMaxdisconnectionTime = 0x00800000,
  InheritMaxsessionTime = 0x01000000,
  InheritShadow = 0x02000000,
  InheritCallbackNumber = 0x04000000,
  InheritCallback = 0x08000000,
  Undefined4 = 0x10000000,
  Undefined5 = 0x20000000,
  Undefined6 = 0x40000000,
  Undefined7 = 0x80000000
}
</code>```

Nota bene: The values defined in TSProperty are missing a couple of entries, the ones named Undefined*; these values are not listed in the definition but have been observed in the wild, if you don't define them your flag enum will break and won't be displayed nicely when you look at it through the debugger or .ToString().

The second one is the CtxShadow enum:

```<code>public enum CtxShadow : uint
{
  Disable = 0x00000000,
  EnableInputNotify = 0x00000001,
  EnableInputNoNotify = 0x00000002,
  EnableNoInputNotify = 0x00000003,
  EnableNoInputNoNotify = 0x00000004
}
</code>```

Now we can define the class to hold the properties:

```<code>public class UserParameters
{
  public uint? CtxCfgPresent { get; set; }
  public CtxCfgFlags1? CtxCfgFlags1 { get; set; }
  public uint? CtxCallBack { get; set; }
  public uint? CtxKeyboardLayout { get; set; }
  public byte? CtxMinEncryptionLevel { get; set; }
  public uint? CtxNwLogonServer { get; set; }
  public string CtxWfHomeDir { get; set; }
  public string CtxWfHomeDirDrive { get; set; }
  public string CtxInitialProgram { get; set; }
  public uint? CtxMaxConnectionTime { get; set; }
  public uint? CtxMaxDisconnectionTime { get; set; }
  public uint? CtxMaxIdleTime { get; set; }
  public string CtxWfProfilePath { get; set; }
  public CtxShadow? CtxShadow { get; set; }
  public string CtxWorkDirectory { get; set; }
  public string CtxCallbackNumber { get; set; }
}
</code>```

Nothing fancy here, these are simply the properties defined in the TSProperty document.

Step 3 — Parse the payload

Now it's time to decode the payload contained inside the value of the attribute.

The userParameters and TSProperty documents define the structure of the payload.

The payload is divided in two main sections: a "header" section and a "data" section.

The "header" section contains

an undocumented 96 bytes byte array "ReservedData" subsection which will be treated as a black-box;

a 2 bytes Unicode string "Signature" which should be used as a "control value";

and a 2 bytes unsigned integer "TSPropertyCount" holding how many properties the payload contains.

The "data" section is an unseparated contiguous list of properties, each property contains

a 2 bytes unsigned integer "NameLength" holding the length in bytes of the name of the property;

a 2 bytes unsigned integer "ValueLength" holding the length bytes of the value of the property;

a 2 bytes unsigned integer "Type" holding the type of the property;

a variable-length Unicode string "PropName" holding the name of the property;

a variable-length double-ASCII-encoded byte array "PropValue" holding the value of the property;

The length of the "PropName" and "PropValue" fields must be obtained from the "NameLength" and "ValueLength" fields respectively.

Wait. "double-ASCII-encoded"? What's that?

Each property can have as a value either a byte, a uint, or an ASCII string. When saved the value of the property is converted to its binary representation, then the byte-array of the binary representation is converted to it hexadecimal string representation, then each character of the hexadecimal string representation is converted to its binary representation and then stored.

For posterity, this is how the encoding algorithm is explained by Microsoft:

To create the encoded binary BLOB for the PropValue field, for each byte of the input create its ASCII-encoded hexadecimal representation and place this representation in 2 consecutive bytes of the output buffer, the most significant hexadecimal digit first followed by the least significant hexadecimal digit.

For example, if the input byte contains the ASCII representation of character 'A', the resulting output will be a sequence of two ASCII characters: character '4' followed by character '1' because the hexadecimal representation of a byte that contains the ASCII character 'A' is 41.

Hence, the output buffer corresponding to the input buffer byte containing character 'A' will be a sequence of 2 bytes whose hexadecimal representations are 34 and 31.

As another example, the input buffer containing the ASCII string "ABCDE\0" would be encoded into the ASCII string "414243444500" (without the terminating 0), which is the same as a sequence of 12 bytes whose hexadecimal representations are 34, 31, 34, 32, 34, 33, 34, 34, 34, 35, 30, and 30.

Simple, yes?

Let's break down the process step-by-step.

First of all, we need to prepare a container for the properties and the convert the data to a more manageable form:

```<code>var userParameters = new UserParameters();
var bytes = Encoding.Unicode.GetBytes(attributeValue);
var memoryStream = new MemoryStream(bytes);
var binaryReader = new BinaryReader(memoryStream, Encoding.Unicode, true);
</code>```

Why are we using MemoryStream and BinaryReader? Because it's really, really easier to use: instead of having to keep track of the offset where we should start to read from as we gradually proceed, we can simply call .ReadBytes(int) which is consuming and be on our way.

Then we parse the "header" section of the payload:

```<code>byte[] reservedData = binaryReader.ReadBytes(96);
byte[] signature = binaryReader.ReadBytes(2);
byte[] tsPropertyCount = binaryReader.ReadBytes(2);

string signatureValue = Encoding.Unicode.GetString(signature);
ushort tsPropertyCountValue = BitConverter.ToUInt16(tsPropertyCount, 0);
</code>```

We don't care about reservedData so we can safely ignore it.

We however should care about signature: when converted to a Unicode string it should always be equal to the string "P", if it's not there's something wrong with the data. I really encourage you to throw a nice InvalidDataException if signatureValue is not equal to "P".

tsPropertyCount tells us how many properties we have to read, so we convert it to a ushort.

Then we need to read as many property as tsPropertyCountValue tells us:

```<code>for (var i = 0; i < tsPropertyCountValue; i++)
</code>```

We don't really care for i, we only need to execute the content of the loop as many times as required.

```<code>byte[] nameLength = binaryReader.ReadBytes(2);
byte[] valueLength = binaryReader.ReadBytes(2);
byte[] type = binaryReader.ReadBytes(2);

ushort nameLengthValue = BitConverter.ToUInt16(nameLength, 0);
ushort valueLengthValue = BitConverter.ToUInt16(valueLength, 0);
ushort typeValue = BitConverter.ToUInt16(type, 0);

byte[] propName = binaryReader.ReadBytes(nameLengthValue);
byte[] propValue = binaryReader.ReadBytes(valueLengthValue);

string propNameValue = Encoding.Unicode.GetString(propName);
byte[] propValueValue = GetPropValueValue(propValue);
</code>```

As previously stated we need to obtain nameLengthValue and valueLengthValue to know the length of the name of the property and the length of the value of the property.

typeValue, similarly to signature, should always be equal to 0x01, even if the documentation is not really clear about it. Personally I'd throw an InvalidDataException if it's not equal to 0x01.

We convert the value of propName back to a Unicode string to get the name of the property, and then the magic happens.

byte[] propValueValue = GetPropValueValue(propValue); is where the magic happens: GetPropValueValue decodes the doubly-ASCII-encoded value back to its native form:

```<code>private static byte[] GetPropValueValue(byte[] propValue)
{
  // Since the encoding algorithm doubles the space used, we halve it.
  var propValueValue = new byte[propValue.Length / 2];

  // Parse the encoded bytes two-by-two, since the encoding algorithm transforms
  // one bytes in two bytes we need to read two of them to obtain the original one.
  for (var j = 0; j < propValue.Length; j = j + 2)
  {
    // Compute the two halves (nibbles) of the original byte from the values of the
    // two encoded bytes. Each encoded bytes is actually an hexadecimal character,
    // so each encoded byte can only have a value between 48 and 57 ('0' to '9')
    // or between 97 and 102 ('a' to 'f'). Yes, it's an utter waste of space.
    var highNibble = HexToInt(propValue[j]);
    var lowNibble = HexToInt(propValue[j + 1]);

    // Recreate the original byte from the two nibbles.
    propValueValue[j / 2] = (byte) (highNibble << 4 | lowNibble);
  }

  return propValueValue;
}
</code>```

To convert the hexadecimal byte back to its value there's a simple helper function:

```<code>private static int HexToInt(byte value)
{
  if ('0' <= value && value <= '9')
  {
    return value - '0';
  }

  if ('a' <= value && value <= 'f')
  {
    return value - 'a' + 10;
  }

  if ('A' <= value && value <= 'F')
  {
    return value - 'A' + 10;
  }

  throw new Exception("Invalid character.");
}
</code>```

Why are we using int instead of byte when rebuilding the original byte?

Because the output of the subtraction performed inside HexToInt produces an int, and the bitshift and bitmask operations output is an int, so converting the two nibbles to byte is a waste of resources, they would be converted back to int in the next instruction.

Thanks to CodesInChaos for his hex-to-byte conversion and black magic.

Now we only have to convert the value to the correct type and assign it to the correct property of our class, we can do that with a simple if-else chain:

```<code>[Flags]
public enum CtxCfgFlags1 : uint
{
  Undefined1 = 0x00000000,
  Undefined2 = 0x00000001,
  Undefined3 = 0x00000002,
  DisableCam = 0x00000004,
  WallpaperDisabled = 0x00000008,
  DisableExe = 0x00000010,
  DisableClip = 0x00000020,
  DisableLpt = 0x00000040,
  DisableCcm = 0x00000080,
  DisableCdm = 0x00000100,
  DisableCpm = 0x00000200,
  UseDefaultGina = 0x00000400,
  HomeDirectoryMapRoot = 0x00000800,
  DisableEncryption = 0x00001000,
  ForceClientLptDef = 0x00002000,
  AutoClientLpts = 0x00004000,
  AutoClientDrives = 0x00008000,
  LogonDisabled = 0x00010000,
  ReconnectSame = 0x00020000,
  ResetBroken = 0x00040000,
  PromptForPassword = 0x00080000,
  InheritSecurity = 0x00100000,
  InheritAutoClient = 0x00200000,
  InheritMaxIdleTime = 0x00400000,
  InheritMaxdisconnectionTime = 0x00800000,
  InheritMaxsessionTime = 0x01000000,
  InheritShadow = 0x02000000,
  InheritCallbackNumber = 0x04000000,
  InheritCallback = 0x08000000,
  Undefined4 = 0x10000000,
  Undefined5 = 0x20000000,
  Undefined6 = 0x40000000,
  Undefined7 = 0x80000000
}
</code>```0

And we're done!

Nota bene: The CtxCfgPresent property is special, it should always be present and its value should always be equal to 0xB00B1E55 (yes, I know, very funny). If it's missing or its value is not equal to 0xB00B1E55 then the value of the attribute is corrupted and should not be used, personally I suggest throwing our friendly InvalidDataException in such cases.

For those who managed to stay with me until the end, I've published a Minimal, Complete, and Verifiable example on GitHub (I can't include the full code here due to character count limitations).

Body:
The User-Parameters attribute value is quite… particular.

While the attribute definition says that the value is a Unicode string, the reality is a little more complex: the value is a binary payload of mixed text and binary data encoded using a couple of "algorithms" and then casted to a Unicode string — that's why you see junk characters, these character are actually pure binary data displayed as a string.

There are many articles on the internet on how to decode this value, but most of them are either wrong or manage to decode the value using a wrong procedure (which, while yielding correct data in their examples, could break at any time).

Examples of such articles are:

Reading and writing the Terminal Server userParameters binary blob in Active Directory — the decoding algorithm is wrong, see below on how it works;

Microsoft Active Directory: UserParameters Header — uses the same wrong decoding algorithm as the previous one and is needlessly complicated;

and VB.NET Decode AD UserParameters Attribute Values — this seems to get it right, but I'm not skilled enough in VB to validate the code.

How the data is encoded is defined in the Terminal Services Terminal Server Runtime Interface Protocol documentation.

In particular you're looking for:

the userParameters document, which describes the overall structure of the binary payload;

the TSProperty document, which describes the structure of the properties contained in the payload;

and the Encoding PropValue Field in TSProperty Structure document, which explains how the value of the properties contained in the payload is encoded.

Optionally you can have a look to the Encoding/Decoding Example for a (really) terse example on how to decode the properties values.

If you're still with me, didn't lose your sanity, summoned Cthulhu or set on fire whoever inside Microsoft ever thought that doing something like this was a good idea, let's proceed to write the code to parse and extract the data.

Per me si va ne la città dolente,

  per me si va ne l'etterno dolore,

  per me si va tra la perduta gente.

  […]

  Lasciate ogni speranza, voi ch'entrate.

— Dante Alighieri, Divina Commedia, Inferno, Canto III

(There's a Minimal, Complete, and Verifiable example linked at the end of the answer for those who are too impatient to read everything.)

Step 1 — Getting the attribute value

You can get the value through either the System.DirectoryServices (usually calles "S.DS") or System.DirectoryServices.Protocols (usually called "S.DS.P") libraries. If you need some help on how these libraries work you can read the Using System.DirectoryServices to Search the Active Directory and Introduction to System.DirectoryServices.Protocols articles.

If you are a .NET Framework user, these are your usual GAC assemblies so you'll have to add them as you always do.

If you are a .NET Core user, rejoice! Both libraries have been released on NuGet — albeit as a pre-release — on 2017-11-15, so you too can query Active Directory now! Go fetch them: System.DirectoryServices, System.DirectoryServices.Protocols.

Nota bene: The code in this answer has been written for a .NET Core 2.0 target, if you're not using .NET Core you probably have to adjust the code slightly; these changes however should be small and easy as the Core and non-Core version of the libraries are very similar.

Here we're reading the attribute using System.DirectoryServices.Protocols:

var ldapDirectoryIdentifier = new LdapDirectoryIdentifier(
  "domain-controller.example.com",
  389,
  true,
  false);

var networkCredential = new NetworkCredential(
  "alice@example.com",
  "p@sSw0rd",
  "example.com");

var ldapConnection = new LdapConnection(
  ldapDirectoryIdentifier,
  networkCredential,
  AuthType.Kerberos);

var searchRequest = new SearchRequest(
  "DC=example,DC=com",
  "(objectClass=user)",
  SearchScope.Subtree,
  "userParameters");

// WARNING
// If the parameters of either LdapDirectoryIdentifier or NetworkCredential are wrong
// (e.g. invalid credentials) you'll get an exception here.
var searchResponse = (SearchResponse) ldapConnection.SendRequest(searchRequest);

foreach (SearchResultEntry searchResultEntry in searchResponse.Entries)
{
  // WARNING
  // This WILL throw an exception when used on an object where the attribute is missing.
  // You should really check that the attribute exists and has exactly one value.
  // I skipped that for brevity, you should not.
  var directoryAttribute = searchResultEntry.Attributes["userParameters"];
  var attributeValue = (string) directoryAttribute[0];
}

Step 2 — Define what the attribute contains

Now that we have the value of the attribute, we need something to hold the values it contains.

First of all, we need some enums.

The first one is the CtxCfgFlags1 enum:

[Flags]
public enum CtxCfgFlags1 : uint
{
  Undefined1 = 0x00000000,
  Undefined2 = 0x00000001,
  Undefined3 = 0x00000002,
  DisableCam = 0x00000004,
  WallpaperDisabled = 0x00000008,
  DisableExe = 0x00000010,
  DisableClip = 0x00000020,
  DisableLpt = 0x00000040,
  DisableCcm = 0x00000080,
  DisableCdm = 0x00000100,
  DisableCpm = 0x00000200,
  UseDefaultGina = 0x00000400,
  HomeDirectoryMapRoot = 0x00000800,
  DisableEncryption = 0x00001000,
  ForceClientLptDef = 0x00002000,
  AutoClientLpts = 0x00004000,
  AutoClientDrives = 0x00008000,
  LogonDisabled = 0x00010000,
  ReconnectSame = 0x00020000,
  ResetBroken = 0x00040000,
  PromptForPassword = 0x00080000,
  InheritSecurity = 0x00100000,
  InheritAutoClient = 0x00200000,
  InheritMaxIdleTime = 0x00400000,
  InheritMaxdisconnectionTime = 0x00800000,
  InheritMaxsessionTime = 0x01000000,
  InheritShadow = 0x02000000,
  InheritCallbackNumber = 0x04000000,
  InheritCallback = 0x08000000,
  Undefined4 = 0x10000000,
  Undefined5 = 0x20000000,
  Undefined6 = 0x40000000,
  Undefined7 = 0x80000000
}

Nota bene: The values defined in TSProperty are missing a couple of entries, the ones named Undefined*; these values are not listed in the definition but have been observed in the wild, if you don't define them your flag enum will break and won't be displayed nicely when you look at it through the debugger or .ToString().

The second one is the CtxShadow enum:

public enum CtxShadow : uint
{
  Disable = 0x00000000,
  EnableInputNotify = 0x00000001,
  EnableInputNoNotify = 0x00000002,
  EnableNoInputNotify = 0x00000003,
  EnableNoInputNoNotify = 0x00000004
}

Now we can define the class to hold the properties:

public class UserParameters
{
  public uint? CtxCfgPresent { get; set; }
  public CtxCfgFlags1? CtxCfgFlags1 { get; set; }
  public uint? CtxCallBack { get; set; }
  public uint? CtxKeyboardLayout { get; set; }
  public byte? CtxMinEncryptionLevel { get; set; }
  public uint? CtxNwLogonServer { get; set; }
  public string CtxWfHomeDir { get; set; }
  public string CtxWfHomeDirDrive { get; set; }
  public string CtxInitialProgram { get; set; }
  public uint? CtxMaxConnectionTime { get; set; }
  public uint? CtxMaxDisconnectionTime { get; set; }
  public uint? CtxMaxIdleTime { get; set; }
  public string CtxWfProfilePath { get; set; }
  public CtxShadow? CtxShadow { get; set; }
  public string CtxWorkDirectory { get; set; }
  public string CtxCallbackNumber { get; set; }
}

Nothing fancy here, these are simply the properties defined in the TSProperty document.

Step 3 — Parse the payload

Now it's time to decode the payload contained inside the value of the attribute.

The userParameters and TSProperty documents define the structure of the payload.

The payload is divided in two main sections: a "header" section and a "data" section.

The "header" section contains

an undocumented 96 bytes byte array "ReservedData" subsection which will be treated as a black-box;

a 2 bytes Unicode string "Signature" which should be used as a "control value";

and a 2 bytes unsigned integer "TSPropertyCount" holding how many properties the payload contains.

The "data" section is an unseparated contiguous list of properties, each property contains

a 2 bytes unsigned integer "NameLength" holding the length in bytes of the name of the property;

a 2 bytes unsigned integer "ValueLength" holding the length bytes of the value of the property;

a 2 bytes unsigned integer "Type" holding the type of the property;

a variable-length Unicode string "PropName" holding the name of the property;

a variable-length double-ASCII-encoded byte array "PropValue" holding the value of the property;

The length of the "PropName" and "PropValue" fields must be obtained from the "NameLength" and "ValueLength" fields respectively.

Wait. "double-ASCII-encoded"? What's that?

Each property can have as a value either a byte, a uint, or an ASCII string. When saved the value of the property is converted to its binary representation, then the byte-array of the binary representation is converted to it hexadecimal string representation, then each character of the hexadecimal string representation is converted to its binary representation and then stored.

For posterity, this is how the encoding algorithm is explained by Microsoft:

To create the encoded binary BLOB for the PropValue field, for each byte of the input create its ASCII-encoded hexadecimal representation and place this representation in 2 consecutive bytes of the output buffer, the most significant hexadecimal digit first followed by the least significant hexadecimal digit.

For example, if the input byte contains the ASCII representation of character 'A', the resulting output will be a sequence of two ASCII characters: character '4' followed by character '1' because the hexadecimal representation of a byte that contains the ASCII character 'A' is 41.

Hence, the output buffer corresponding to the input buffer byte containing character 'A' will be a sequence of 2 bytes whose hexadecimal representations are 34 and 31.

As another example, the input buffer containing the ASCII string "ABCDE\0" would be encoded into the ASCII string "414243444500" (without the terminating 0), which is the same as a sequence of 12 bytes whose hexadecimal representations are 34, 31, 34, 32, 34, 33, 34, 34, 34, 35, 30, and 30.

Simple, yes?

Let's break down the process step-by-step.

First of all, we need to prepare a container for the properties and the convert the data to a more manageable form:

var userParameters = new UserParameters();
var bytes = Encoding.Unicode.GetBytes(attributeValue);
var memoryStream = new MemoryStream(bytes);
var binaryReader = new BinaryReader(memoryStream, Encoding.Unicode, true);

Why are we using MemoryStream and BinaryReader? Because it's really, really easier to use: instead of having to keep track of the offset where we should start to read from as we gradually proceed, we can simply call .ReadBytes(int) which is consuming and be on our way.

Then we parse the "header" section of the payload:

byte[] reservedData = binaryReader.ReadBytes(96);
byte[] signature = binaryReader.ReadBytes(2);
byte[] tsPropertyCount = binaryReader.ReadBytes(2);

string signatureValue = Encoding.Unicode.GetString(signature);
ushort tsPropertyCountValue = BitConverter.ToUInt16(tsPropertyCount, 0);

We don't care about reservedData so we can safely ignore it.

We however should care about signature: when converted to a Unicode string it should always be equal to the string "P", if it's not there's something wrong with the data. I really encourage you to throw a nice InvalidDataException if signatureValue is not equal to "P".

tsPropertyCount tells us how many properties we have to read, so we convert it to a ushort.

Then we need to read as many property as tsPropertyCountValue tells us:

for (var i = 0; i < tsPropertyCountValue; i++)

We don't really care for i, we only need to execute the content of the loop as many times as required.

byte[] nameLength = binaryReader.ReadBytes(2);
byte[] valueLength = binaryReader.ReadBytes(2);
byte[] type = binaryReader.ReadBytes(2);

ushort nameLengthValue = BitConverter.ToUInt16(nameLength, 0);
ushort valueLengthValue = BitConverter.ToUInt16(valueLength, 0);
ushort typeValue = BitConverter.ToUInt16(type, 0);

byte[] propName = binaryReader.ReadBytes(nameLengthValue);
byte[] propValue = binaryReader.ReadBytes(valueLengthValue);

string propNameValue = Encoding.Unicode.GetString(propName);
byte[] propValueValue = GetPropValueValue(propValue);

As previously stated we need to obtain nameLengthValue and valueLengthValue to know the length of the name of the property and the length of the value of the property.

typeValue, similarly to signature, should always be equal to 0x01, even if the documentation is not really clear about it. Personally I'd throw an InvalidDataException if it's not equal to 0x01.

We convert the value of propName back to a Unicode string to get the name of the property, and then the magic happens.

byte[] propValueValue = GetPropValueValue(propValue); is where the magic happens: GetPropValueValue decodes the doubly-ASCII-encoded value back to its native form:

private static byte[] GetPropValueValue(byte[] propValue)
{
  // Since the encoding algorithm doubles the space used, we halve it.
  var propValueValue = new byte[propValue.Length / 2];

  // Parse the encoded bytes two-by-two, since the encoding algorithm transforms
  // one bytes in two bytes we need to read two of them to obtain the original one.
  for (var j = 0; j < propValue.Length; j = j + 2)
  {
    // Compute the two halves (nibbles) of the original byte from the values of the
    // two encoded bytes. Each encoded bytes is actually an hexadecimal character,
    // so each encoded byte can only have a value between 48 and 57 ('0' to '9')
    // or between 97 and 102 ('a' to 'f'). Yes, it's an utter waste of space.
    var highNibble = HexToInt(propValue[j]);
    var lowNibble = HexToInt(propValue[j + 1]);

    // Recreate the original byte from the two nibbles.
    propValueValue[j / 2] = (byte) (highNibble << 4 | lowNibble);
  }

  return propValueValue;
}

To convert the hexadecimal byte back to its value there's a simple helper function:

private static int HexToInt(byte value)
{
  if ('0' <= value && value <= '9')
  {
    return value - '0';
  }

  if ('a' <= value && value <= 'f')
  {
    return value - 'a' + 10;
  }

  if ('A' <= value && value <= 'F')
  {
    return value - 'A' + 10;
  }

  throw new Exception("Invalid character.");
}

Why are we using int instead of byte when rebuilding the original byte?

Because the output of the subtraction performed inside HexToInt produces an int, and the bitshift and bitmask operations output is an int, so converting the two nibbles to byte is a waste of resources, they would be converted back to int in the next instruction.

Thanks to CodesInChaos for his hex-to-byte conversion and black magic.

Now we only have to convert the value to the correct type and assign it to the correct property of our class, we can do that with a simple if-else chain:

if (string.Equals(propNameValue, nameof(UserParameters.CtxCfgPresent), StringComparison.OrdinalIgnoreCase))
{
  userParameters.CtxCfgPresent = BitConverter.ToUInt32(propValueValue, 0);
}
else if (string.Equals(propNameValue, nameof(UserParameters.CtxCfgFlags1), StringComparison.OrdinalIgnoreCase))
{
  userParameters.CtxCfgFlags1 = (CtxCfgFlags1) BitConverter.ToUInt32(propValueValue, 0);
}
else if (string.Equals(propNameValue, nameof(UserParameters.CtxCallBack), StringComparison.OrdinalIgnoreCase))
{
  userParameters.CtxCallBack = BitConverter.ToUInt32(propValueValue, 0);
}
else if (string.Equals(propNameValue, nameof(UserParameters.CtxKeyboardLayout), StringComparison.OrdinalIgnoreCase))
{
  userParameters.CtxKeyboardLayout = BitConverter.ToUInt32(propValueValue, 0);
}
else if (string.Equals(propNameValue, nameof(UserParameters.CtxNwLogonServer), StringComparison.OrdinalIgnoreCase))
{
  userParameters.CtxNwLogonServer = BitConverter.ToUInt32(propValueValue, 0);
}
else if (string.Equals(propNameValue, nameof(UserParameters.CtxMaxConnectionTime), StringComparison.OrdinalIgnoreCase))
{
  userParameters.CtxMaxConnectionTime = BitConverter.ToUInt32(propValueValue, 0);
}
else if (string.Equals(propNameValue, nameof(UserParameters.CtxMaxDisconnectionTime), StringComparison.OrdinalIgnoreCase))
{
  userParameters.CtxMaxDisconnectionTime = BitConverter.ToUInt32(propValueValue, 0);
}
else if (string.Equals(propNameValue, nameof(UserParameters.CtxMaxIdleTime), StringComparison.OrdinalIgnoreCase))
{
  userParameters.CtxMaxIdleTime = BitConverter.ToUInt32(propValueValue, 0);
}
else if (string.Equals(propNameValue, nameof(UserParameters.CtxShadow), StringComparison.OrdinalIgnoreCase))
{
  userParameters.CtxShadow = (CtxShadow) BitConverter.ToUInt32(propValueValue, 0);
}
else if (string.Equals(propNameValue, nameof(UserParameters.CtxMinEncryptionLevel), StringComparison.OrdinalIgnoreCase))
{
  userParameters.CtxMinEncryptionLevel = propValueValue[0];
}
else if (string.Equals(propNameValue, nameof(UserParameters.CtxWfHomeDir), StringComparison.OrdinalIgnoreCase))
{
  userParameters.CtxWfHomeDir = Encoding.ASCII.GetString(propValueValue, 0, propValueValue.Length - 1);
}
else if (string.Equals(propNameValue, nameof(UserParameters.CtxWfHomeDirDrive), StringComparison.OrdinalIgnoreCase))
{
  userParameters.CtxWfHomeDirDrive = Encoding.ASCII.GetString(propValueValue, 0, propValueValue.Length - 1);
}
else if (string.Equals(propNameValue, nameof(UserParameters.CtxInitialProgram), StringComparison.OrdinalIgnoreCase))
{
  userParameters.CtxInitialProgram = Encoding.ASCII.GetString(propValueValue, 0, propValueValue.Length - 1);
}
else if (string.Equals(propNameValue, nameof(UserParameters.CtxWfProfilePath), StringComparison.OrdinalIgnoreCase))
{
  userParameters.CtxWfProfilePath = Encoding.ASCII.GetString(propValueValue, 0, propValueValue.Length - 1);
}
else if (string.Equals(propNameValue, nameof(UserParameters.CtxWorkDirectory), StringComparison.OrdinalIgnoreCase))
{
  userParameters.CtxWorkDirectory = Encoding.ASCII.GetString(propValueValue, 0, propValueValue.Length - 1);
}
else if (string.Equals(propNameValue, nameof(UserParameters.CtxCallbackNumber), StringComparison.OrdinalIgnoreCase))
{
  userParameters.CtxCallbackNumber = Encoding.ASCII.GetString(propValueValue, 0, propValueValue.Length - 1);
}
else
{
  throw new Exception("Unsupported property.");
}

And we're done!

Nota bene: The CtxCfgPresent property is special, it should always be present and its value should always be equal to 0xB00B1E55 (yes, I know, very funny). If it's missing or its value is not equal to 0xB00B1E55 then the value of the attribute is corrupted and should not be used, personally I suggest throwing our friendly InvalidDataException in such cases.

For those who managed to stay with me until the end, I've published a Minimal, Complete, and Verifiable example on GitHub (I can't include the full code here due to character count limitations).


来源: stackexchange

问:
how to get cookie php/wordpress
Users come to my site thorough a referral link.

I can successfully set the cookie using either of the following code snippets:
(I know it is successful because I can see the cookie file saved on my computer)

```<code>function set_my_cookie() {
if (empty($_COOKIE['OREF2']))
{
wp_set_auth_cookie('OREF2', $_SERVER['QUERY_STRING'], time()+5200, "/", ".website.com");
}
}
add_action( 'init', 'set_my_cookie');
</code>```

or

```<code>function set_newuser_cookie() {
    if (!isset($_COOKIE['OREF2'])) {
        setcookie('OREF2', $_SERVER['QUERY_STRING'], time()+5200, "/", ".website.com");
}
}
add_action( 'init', 'set_newuser_cookie');
</code>```

Now the user clicks to a different page in my site. They click a form which should pass the cookie info when they click submit.

I am using the following code snippets:

```<code>function get_my_cookie() {
//$_COOKIE['OREF2'];
//var_dump($_COOKIE);
echo $_COOKIE['OREF2'];
}
add_shortcode('cookies', 'get_my_cookie');
</code>```

This first bit of code has commented lines where I have attempted different ways to get my cookie. None of the 3 ways worked. I then moved on to trying to read if my cookie is set with the following code:

```<code>function get_my_cookie() {
if(!isset($_COOKIE['OREF2'])) {
    echo "Cookie named '" . OREF2 . "' is not set!";
} else {
    echo "Cookie '" . OREF2 . "' is set!<br>";
    echo "Value is: " . $_COOKIE['OREF2'];
}}
add_shortcode('cookies', 'get_my_cookie');
</code>```

When using this code I am ALWAYS met with "cookie is NOT set" Even though I can clearly see the cookie file on my computer. If the cookie is not set my shortcode can't be used to display anything...

All I want is a shortcode to display my cookie. What am I doing wrong?
Any help would be greatly appreciated!

答:
If you're using the following code:

```<code>setcookie('OREF2', $_SERVER['QUERY_STRING'], time()+5200, "/", ".website.com");
</code>```

This may not setup the cookie properly. One test would be to clear the cookie and test with :

```<code>setcookie('OREF2', $_SERVER['QUERY_STRING'], time()+5200);
</code>```

These parameters, Path and Domain, are optional. If they are not set correctly, even slightly, you (actually the browser) will not be able to read the Cookie properly as the HTTP URL may not match properly.

As suggested in the comments, you may want to examine this more: http://php.net/manual/en/function.setcookie.php

Something that wasn't made clear to me here and totally confused me for a while was that domain names must contain at least two dots (.), hence 'localhost' is invalid and the browser will refuse to set the cookie! instead for localhost you should use false.

To make your code work on both localhost and a proper domain, you can do this:

<?php

$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;

setcookie('cookiename', 'data', time()+60*60*24*365, '/', $domain, false);

?>

You may want to consider using this code going forward:

```<code>function set_newuser_cookie() {
  if (!isset($_COOKIE['OREF2'])) {
    $domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;
    setcookie('OREF2', $_SERVER['QUERY_STRING'], time()+5200, "/", $domain);
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: how to get cookie php/wordpress

Body:
Users come to my site thorough a referral link.

I can successfully set the cookie using either of the following code snippets:
(I know it is successful because I can see the cookie file saved on my computer)

function set_my_cookie() {
if (empty($_COOKIE['OREF2']))
{
wp_set_auth_cookie('OREF2', $_SERVER['QUERY_STRING'], time()+5200, "/", ".website.com");
}
}
add_action( 'init', 'set_my_cookie');

or

function set_newuser_cookie() {
    if (!isset($_COOKIE['OREF2'])) {
        setcookie('OREF2', $_SERVER['QUERY_STRING'], time()+5200, "/", ".website.com");
}
}
add_action( 'init', 'set_newuser_cookie');

Now the user clicks to a different page in my site. They click a form which should pass the cookie info when they click submit.

I am using the following code snippets:

function get_my_cookie() {
//$_COOKIE['OREF2'];
//var_dump($_COOKIE);
echo $_COOKIE['OREF2'];
}
add_shortcode('cookies', 'get_my_cookie');

This first bit of code has commented lines where I have attempted different ways to get my cookie. None of the 3 ways worked. I then moved on to trying to read if my cookie is set with the following code:

function get_my_cookie() {
if(!isset($_COOKIE['OREF2'])) {
    echo "Cookie named '" . OREF2 . "' is not set!";
} else {
    echo "Cookie '" . OREF2 . "' is set!
";
    echo "Value is: " . $_COOKIE['OREF2'];
}}
add_shortcode('cookies', 'get_my_cookie');

When using this code I am ALWAYS met with "cookie is NOT set" Even though I can clearly see the cookie file on my computer. If the cookie is not set my shortcode can't be used to display anything...

All I want is a shortcode to display my cookie. What am I doing wrong?
Any help would be greatly appreciated!

Body:
If you're using the following code:

setcookie('OREF2', $_SERVER['QUERY_STRING'], time()+5200, "/", ".website.com");

This may not setup the cookie properly. One test would be to clear the cookie and test with :

setcookie('OREF2', $_SERVER['QUERY_STRING'], time()+5200);

These parameters, Path and Domain, are optional. If they are not set correctly, even slightly, you (actually the browser) will not be able to read the Cookie properly as the HTTP URL may not match properly.

As suggested in the comments, you may want to examine this more: http://php.net/manual/en/function.setcookie.php

Something that wasn't made clear to me here and totally confused me for a while was that domain names must contain at least two dots (.), hence 'localhost' is invalid and the browser will refuse to set the cookie! instead for localhost you should use false.

To make your code work on both localhost and a proper domain, you can do this:

<?php

$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;

setcookie('cookiename', 'data', time()+60*60*24*365, '/', $domain, false);

?>

You may want to consider using this code going forward:

function set_newuser_cookie() {
  if (!isset($_COOKIE['OREF2'])) {
    $domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;
    setcookie('OREF2', $_SERVER['QUERY_STRING'], time()+5200, "/", $domain);
  }
}


问:
How do I rollback a SQL CLR stored procedure when a user cancels the query?
I'm trying to create a SQL CLR stored procedure that will create a table, pass the table name onto a service which will bulk insert some data into it, display the results of the table, then clean up the table.

What I've tried so far:

Use SqlTransaction. Cancelling the transaction works, but it puts my query window into a state where I couldn't continue working on it.

The transaction active in this session has been committed or aborted by another session

Use TransactionScope. Same issue as 1.

Manually clean up the table in a finally clause by issuing a DROP TABLE SqlCommand. This doesn't seem to get run, though my SqlContext.Pipe.Send() prior to issuing the command does. It doesn't seem like it's related to any time constraints since if I issue a Thread.Sleep(2000) before printing another line, it still prints the second line whereas the command.ExecuteNonQuery() would stop before printing the second line.

Placing the manual cleanup code into a CER or SafeHandle. This doesn't work as having a CER requires some guarantees, including not allocating additional memory or calling methods that are not decorated with a ReliabilityContract.

Am I missing something obvious here?  How do I handle the user cancelling their query?

Edit: There were multiple iterations of the code for each scenario, but the general actions taken are along the lines of the following:

```<code>    [SqlProcedure]
    public static void GetData(SqlString code)
    {
        Guid guid = Guid.NewGuid();
        using (var connection = new SqlConnection("context connection=true"))
        {
            connection.Open();

            try
            {
                SqlContext.Pipe?.Send("Constrain");

                SqlCommand command1 = new SqlCommand($"CREATE TABLE qb.{code}_{guid:N} (Id INT)", connection);
                command1.ExecuteNonQuery();
                SqlContext.Pipe?.Send($"Create: qb.{code}_{guid:N}");

                //emulate service call
                Thread.Sleep(TimeSpan.FromSeconds(10));

                SqlContext.Pipe?.Send($"Done: qb.{code}_{guid:N}");
            }
            finally
            {
                SqlContext.Pipe?.Send("1");
                //drop table here instead of sleep
                Thread.Sleep(2000);
                SqlContext.Pipe?.Send("2");
            }
        }
    }
</code>```

答:
Stepping back there are probably much better ways to pass the data out of your CLR procedure.

1) you can simply use the SqlContext Pipe to return a resultset without creating a table.

2) you can create a temp table (#) in the calling code and access it from inside the CLR procedure.  You might want to introduce a TSQL wrapper procedure to make this convenient.

Anyway using BEGIN TRAN/COMMIT | ROLLBACK worked for me:

```<code>using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Threading;

static class SqlConnectionExtensions
{
    public static DataTable ExecuteDataTable(this SqlConnection con, string sql, params SqlParameter[] parameters)
    {
        var cmd = new SqlCommand(sql, con);
        foreach (var p in parameters)
        {
            cmd.Parameters.Add(p);
        }
        using (var dr = cmd.ExecuteReader())
        {
            var dt = new DataTable();
            dt.Load(dr);
            return dt;
        }
    }

    public static int ExecuteNonQuery(this SqlConnection con, string sql, params SqlParameter[] parameters)
    {
        var cmd = new SqlCommand(sql, con);
        foreach (var p in parameters)
        {
            cmd.Parameters.Add(p);
        }
        return cmd.ExecuteNonQuery();
    }

}

public partial class StoredProcedures
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void GetData(SqlString code)
    {
        Guid guid = Guid.NewGuid();
        using (var connection = new SqlConnection("context connection=true"))
        {
            connection.Open();

            try
            {
                connection.ExecuteNonQuery("begin transaction;");
                SqlContext.Pipe?.Send("Constrain");

                connection.ExecuteNonQuery($"CREATE TABLE qb.{code}_{guid:N} (Id INT)");

                SqlContext.Pipe?.Send($"Create: qb.{code}_{guid:N}");

                //emulate service call
                Thread.Sleep(TimeSpan.FromSeconds(10));

                SqlContext.Pipe?.Send($"Done: qb.{code}_{guid:N}");
                connection.ExecuteNonQuery("commit transaction");

            }
            catch (Exception ex)
            {
                connection.ExecuteNonQuery("rollback;");
                throw;
            }

        }

    }
}
</code>```

Body:
I'm trying to create a SQL CLR stored procedure that will create a table, pass the table name onto a service which will bulk insert some data into it, display the results of the table, then clean up the table.

What I've tried so far:

Use SqlTransaction. Cancelling the transaction works, but it puts my query window into a state where I couldn't continue working on it.

The transaction active in this session has been committed or aborted by another session

Use TransactionScope. Same issue as 1.

Manually clean up the table in a finally clause by issuing a DROP TABLE SqlCommand. This doesn't seem to get run, though my SqlContext.Pipe.Send() prior to issuing the command does. It doesn't seem like it's related to any time constraints since if I issue a Thread.Sleep(2000) before printing another line, it still prints the second line whereas the command.ExecuteNonQuery() would stop before printing the second line.

Placing the manual cleanup code into a CER or SafeHandle. This doesn't work as having a CER requires some guarantees, including not allocating additional memory or calling methods that are not decorated with a ReliabilityContract.

Am I missing something obvious here?  How do I handle the user cancelling their query?

Edit: There were multiple iterations of the code for each scenario, but the general actions taken are along the lines of the following:

    [SqlProcedure]
    public static void GetData(SqlString code)
    {
        Guid guid = Guid.NewGuid();
        using (var connection = new SqlConnection("context connection=true"))
        {
            connection.Open();

            try
            {
                SqlContext.Pipe?.Send("Constrain");

                SqlCommand command1 = new SqlCommand($"CREATE TABLE qb.{code}_{guid:N} (Id INT)", connection);
                command1.ExecuteNonQuery();
                SqlContext.Pipe?.Send($"Create: qb.{code}_{guid:N}");

                //emulate service call
                Thread.Sleep(TimeSpan.FromSeconds(10));

                SqlContext.Pipe?.Send($"Done: qb.{code}_{guid:N}");
            }
            finally
            {
                SqlContext.Pipe?.Send("1");
                //drop table here instead of sleep
                Thread.Sleep(2000);
                SqlContext.Pipe?.Send("2");
            }
        }
    }

Body:
Stepping back there are probably much better ways to pass the data out of your CLR procedure.

1) you can simply use the SqlContext Pipe to return a resultset without creating a table.

2) you can create a temp table (#) in the calling code and access it from inside the CLR procedure.  You might want to introduce a TSQL wrapper procedure to make this convenient.

Anyway using BEGIN TRAN/COMMIT | ROLLBACK worked for me:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Threading;

static class SqlConnectionExtensions
{
    public static DataTable ExecuteDataTable(this SqlConnection con, string sql, params SqlParameter[] parameters)
    {
        var cmd = new SqlCommand(sql, con);
        foreach (var p in parameters)
        {
            cmd.Parameters.Add(p);
        }
        using (var dr = cmd.ExecuteReader())
        {
            var dt = new DataTable();
            dt.Load(dr);
            return dt;
        }
    }

    public static int ExecuteNonQuery(this SqlConnection con, string sql, params SqlParameter[] parameters)
    {
        var cmd = new SqlCommand(sql, con);
        foreach (var p in parameters)
        {
            cmd.Parameters.Add(p);
        }
        return cmd.ExecuteNonQuery();
    }

}

public partial class StoredProcedures
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void GetData(SqlString code)
    {
        Guid guid = Guid.NewGuid();
        using (var connection = new SqlConnection("context connection=true"))
        {
            connection.Open();

            try
            {
                connection.ExecuteNonQuery("begin transaction;");
                SqlContext.Pipe?.Send("Constrain");

                connection.ExecuteNonQuery($"CREATE TABLE qb.{code}_{guid:N} (Id INT)");

                SqlContext.Pipe?.Send($"Create: qb.{code}_{guid:N}");

                //emulate service call
                Thread.Sleep(TimeSpan.FromSeconds(10));

                SqlContext.Pipe?.Send($"Done: qb.{code}_{guid:N}");
                connection.ExecuteNonQuery("commit transaction");

            }
            catch (Exception ex)
            {
                connection.ExecuteNonQuery("rollback;");
                throw;
            }

        }

    }
}


问:
Query and regex find data

Hello guys! I try to accomplish the following.
I have a string which is a query string like:

```<code>let query = "?course_subject=Robotica&course_type=%20C&course_location=%20VIV7&course_teacher=%20Pozna_C_R&course_start_hour=14:00%20&course_end_hour=%2015:50"
</code>```

Which I get with:window.location.search

What I try to get back is all the pairs name - value in an array like:

```<code>output_array = [["course_subject","Robotia"],["course_type","C"]]
</code>```

And so on.
But I can not figure out how to write the code using regex.
Can someone help me with the code?
I mention that I do not know the query string which it will come, so I can not search using a name,like:course_subject or course_type

答:
No need to use regex.

First you need to decode uri (https://www.w3schools.com/jsref/jsref_decodeuri.asp)

```<code>let loc = decodeURI(window.location.search);
</code>```

Then you have to remove first character and split string with '&'

```<code>loc = loc.substring(1).split('&');
</code>```

This will give you something like this:

```<code>["course_subject=Robotica", "course_type= C", "course_location= VIV7", "course_teacher= Pozna_C_R", "course_start_hour=14:00 ", "course_end_hour= 15:50"]
</code>```

As you can see we only need to split each key with '='. You can do this by looping through each value with for loop but there is Array.map method.

```<code>let output_array = loc.map(function(value) {
  return value.split('=');
});
</code>```

And the result is:

```<code>[["course_subject", "Robotica"], ["course_type", " C"], ["course_location", " VIV7"], ["course_teacher", " Pozna_C_R"], ["course_start_hour", "14:00 "], ["course_end_hour", " 15:50"]]
</code>```

Title: Query and regex find data

Body:
Hello guys! I try to accomplish the following.
I have a string which is a query string like:

let query = "?course_subject=Robotica&course_type=%20C&course_location=%20VIV7&course_teacher=%20Pozna_C_R&course_start_hour=14:00%20&course_end_hour=%2015:50"

Which I get with:window.location.search

What I try to get back is all the pairs name - value in an array like:

output_array = [["course_subject","Robotia"],["course_type","C"]]

And so on.
But I can not figure out how to write the code using regex.
Can someone help me with the code?
I mention that I do not know the query string which it will come, so I can not search using a name,like:course_subject or course_type

Body:
No need to use regex.

First you need to decode uri (https://www.w3schools.com/jsref/jsref_decodeuri.asp)

let loc = decodeURI(window.location.search);

Then you have to remove first character and split string with '&'

loc = loc.substring(1).split('&');

This will give you something like this:

["course_subject=Robotica", "course_type= C", "course_location= VIV7", "course_teacher= Pozna_C_R", "course_start_hour=14:00 ", "course_end_hour= 15:50"]

As you can see we only need to split each key with '='. You can do this by looping through each value with for loop but there is Array.map method.

let output_array = loc.map(function(value) {
  return value.split('=');
});

And the result is:

[["course_subject", "Robotica"], ["course_type", " C"], ["course_location", " VIV7"], ["course_teacher", " Pozna_C_R"], ["course_start_hour", "14:00 "], ["course_end_hour", " 15:50"]]


问:
Rails Devise only redirects to a fixed path. Need to redirect back where the user came from when authentication was triggered
Working on a Ruby on Rails app with Devise.

Devise only redirects to a fixed path, root app path by default.
There are protected urls, and if the user click some links (e.g. "Ask Question" here), he is sent to the /sign_in page. On successful logon, the user is not sent back to the "Ask Question", but rather to "/".
Any idea how to fix that?

答:
You have to save the url on your session hash for it to work.

```<code>session[:return_to] ||= request.referer
</code>```

Then redirect to it in your update action, after a successful save:

```<code>redirect_to session[:return_to]
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You have to save the url on your session hash for it to work.

session[:return_to] ||= request.referer

Then redirect to it in your update action, after a successful save:

redirect_to session[:return_to]


问:
C LuaJit Profiling
I have following execution stack:

C++

C Lua API

LuaJIT

C functions - my own functions,  injected to Lua via C-Lua-API which called from lua script

I want to profiling this code. And I want to know percentage time spent in luajit phase.

I see come problems here. If I will compile luajit with flags something like -pg -fprofile-generate -fprofile-use it will be not the same that  luajit compiled for production build.

Is there any way to figure out what's going on in LUAJit phase?

Good example of this executions stack - openresty

答:
It's good idea use perf utility and flamegraph.
And there is no reason to recompile with gcc flags like -fomit-frame-pointer,  -fprofile-generate, -fprofile-use.

perf doesn't need this flags for collect information. Only -pg flag.

Title: C LuaJit Profiling


问:
Cursor doesn't gaze on my UI Slider when deployed in the Hololens
Based on this repo https://github.com/qian256/ur5_unity. I am trying to get this working with some modifications, as I need. You can also see the issue in this repo.

I am unable to get the sliders move when I deploy it in the Hololens. I have a cursor that can gaze over the robot body but doesn't gaze on the slider bar or handle. I have tried most of the suggestions online including setting canvas to world-space.

I have already tried this out: HoloLens - UI/Slider and Cursor do not intersect during gaze

答:
Don't have 50 rep otherwise I would have commented but, I answered a very similar question here dealing with if your cursor goes through your UI element.

In the canvas I loose the cursor

However, if the problem is just that you can't move the cursor then, you need to make sure you have subscribed to the scroll/manipulation events for your cursor. You can test this to see if this is the case by just clicking on the slider in a different spot and the slider should jump to the spot you clicked.


问:
Default selection and reroute on changing selection for <select> in React-Redux
So I am having a few problems with this, but first let me outline what I am trying to do.

When the user first logs in , it takes them to /home which has a list of projects. Clicking on one of the projects will take them to /project/84 if 84 is the number of that project. When they are routed to that URL there is a <select> with a list of projects (that were also listed on /home).

This is what should happen:

1) The <select> should have a value equal to the name of the project selected. For example, if project 84 is called Project 84, it should already be displayed in the <select> even if there are 20 other other projects before and after it.

2) When the user selects a new <option> in <select>, it should automatically send a GET to the server to retrieve the information of the project they selected.

So here is what I have so far:

```<code>import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';

class SelectProject extends Component {

    getProject() {
        // console.log('Working');
        this.setState({
            value: event.target.value
        });
    }

    renderCurrentProjectName() {
        const { project_list } = this.props;

        if (!Project_list) {
            return <div>Loading...</div>;
        }

        return _(this.props.Project_list)
            .filter(c => c.project_id == this.props.Project_id)
            .map('project')
            .value();
    }

    renderProjectSelect() {
        return _.map(this.props.project_list, s => {
            return (
                <option key={s.project_id}>{s.project}</option>
            );
        });
    }

    render() {

        return (
            <div className='panel panel-default'>
                <div className='panel-heading'>
                    <h4><strong>{this.renderCurrentProjectName()}</strong></h4>
                </div>

                <div className='panel-body'>
                    <select className='form-control' onChange={this.getProject()} value={this.renderCurrentProjectName()}>
                        {this.renderProjectSelect()}
                    </select>
                </div>
            </div>
        );
    }
}

function mapStateToProps(state) {
    return {
        project_id: state.documents.project_id,
        project_list: state.documents.project_list
    }
}

export default connect(mapStateToProps, null)(SelectProject);
</code>```

This just generates 1000 errors saying: Cannot update during an existing state transition (such as within 'render' or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to 'componentWillMount'.

This is caused by the this.setState({ value: even.target.value }) so when I remove it I just get: Warning: Failed form propType: You provided a 'value' prop to a form field without an 'onChange' handler. This will render a read-only field. If the field should be mutable use 'defaultValue'. Otherwise, set either 'onChange' or 'readOnly'. Check the render method of 'SelectProduct'.

This does accomplish 1) though by selecting the name of the project in the <select>; however, you can't select anything else (haven't even gotten as sending the GET).

defaultValue doesn't seem to do anything, at least it doesn't select the correct <option>.

Also have done the following which resulted in the same errors and behavior (i.e. it selects the correct <option>, but won't let you select anything else):

```<code>...
class SelectProject extends Component {

    constructor(props) {
        super(props);

        this.state = {
            value: this.renderCurrentProductName()
        };
    }

    getProject() {
        // console.log('Working');
        this.setState({
            value: event.target.value
        });
    }

                ...
                    <select className='form-control' onChange={this.getProject()} value={this.state.value}>
                        {this.renderProjectSelect()}
                    </select>
                ...
</code>```

These are some of the SO questions I have been referencing.

OnChange event using React JS for drop down

ReactJS: Select with default value from props without onChange event?

答:
```<code>    const getProject = (event)=> {
    this.setState({
        value: event.target.value
    });
}
</code>```

so try passing the event onChange, you are not passing the event as an argument so there is nothing to call target.value

Body:
So I am having a few problems with this, but first let me outline what I am trying to do.

When the user first logs in , it takes them to /home which has a list of projects. Clicking on one of the projects will take them to /project/84 if 84 is the number of that project. When they are routed to that URL there is a <select> with a list of projects (that were also listed on /home).

This is what should happen:

1) The <select> should have a value equal to the name of the project selected. For example, if project 84 is called Project 84, it should already be displayed in the <select> even if there are 20 other other projects before and after it.

2) When the user selects a new <option> in <select>, it should automatically send a GET to the server to retrieve the information of the project they selected.

So here is what I have so far:

import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';

class SelectProject extends Component {

    getProject() {
        // console.log('Working');
        this.setState({
            value: event.target.value
        });
    }

    renderCurrentProjectName() {
        const { project_list } = this.props;

        if (!Project_list) {
            return
Loading...
;
        }

        return _(this.props.Project_list)
            .filter(c => c.project_id == this.props.Project_id)
            .map('project')
            .value();
    }

    renderProjectSelect() {
        return _.map(this.props.project_list, s => {
            return (
                <option key={s.project_id}>{s.project}</option>
            );
        });
    }

    render() {

        return (

{this.renderCurrentProjectName()}

                    <select className='form-control' onChange={this.getProject()} value={this.renderCurrentProjectName()}>
                        {this.renderProjectSelect()}
                    </select>

        );
    }
}

function mapStateToProps(state) {
    return {
        project_id: state.documents.project_id,
        project_list: state.documents.project_list
    }
}

export default connect(mapStateToProps, null)(SelectProject);

This just generates 1000 errors saying: Cannot update during an existing state transition (such as within 'render' or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to 'componentWillMount'.

This is caused by the this.setState({ value: even.target.value }) so when I remove it I just get: Warning: Failed form propType: You provided a 'value' prop to a form field without an 'onChange' handler. This will render a read-only field. If the field should be mutable use 'defaultValue'. Otherwise, set either 'onChange' or 'readOnly'. Check the render method of 'SelectProduct'.

This does accomplish 1) though by selecting the name of the project in the <select>; however, you can't select anything else (haven't even gotten as sending the GET).

defaultValue doesn't seem to do anything, at least it doesn't select the correct <option>.

Also have done the following which resulted in the same errors and behavior (i.e. it selects the correct <option>, but won't let you select anything else):

...
class SelectProject extends Component {

    constructor(props) {
        super(props);

        this.state = {
            value: this.renderCurrentProductName()
        };
    }

    getProject() {
        // console.log('Working');
        this.setState({
            value: event.target.value
        });
    }

                ...
                    <select className='form-control' onChange={this.getProject()} value={this.state.value}>
                        {this.renderProjectSelect()}
                    </select>
                ...

These are some of the SO questions I have been referencing.

OnChange event using React JS for drop down

ReactJS: Select with default value from props without onChange event?

Body:
    const getProject = (event)=> {
    this.setState({
        value: event.target.value
    });
}

so try passing the event onChange, you are not passing the event as an argument so there is nothing to call target.value


问:
Start new numbered list using jQuery
```<code><ul>
    <li>test</li>
    <li>test</li>
    <li>test</li>
    <li>test</li>
    <li>test</li>
    <li>test</li>
    <li>test</li>
</ul>

<script>
$(document).ready(function(){
    var increment=3;
    var start=8;
    $("ul").children().each(function(i) {
        $(this).prepend('<tag>'+(start+i*increment).toString()+'.</tag>');
    });
});
</script>
</code>```

Is there a way to start a new count for another ul list?
With the code above this is what i get!

```<code><ul>
<li> test
<li> test
<li> test
<ul/>
</code>```

Output

```<code>1. test
2. test
3. test
</code>```

second ul list

```<code><ul>
<li> test
<li> test
<li> test
<ul/>
</code>```

Output

```<code>4. test
5. test
6. test
</code>```

Instead of starting the second ul tag with 1. 2. 3. it continues to count using the first ul 5. 6. 7.

So is it possible to reset the count and star it all over again for another ul tag?
If it is possible how?

答:
```<code>var increment = 1;
$('ul').each(function() {
    var ul = $(this),
        li = ul.find('> li'),
        ol = $('<ol />').attr('start', increment);
    ul.after(ol);
    ol.append(li);
    ul.remove();
    increment += li.length;
});
</code>```

Example: http://jsbin.com/opuyi/3

This will crap out with nested lists, as they'd (probably) look something like this:

```1. One
2. Two
    4. Three
3. Four```

Title: Start new numbered list using jQuery

Body:
test

test

test

test

test

test

test

Is there a way to start a new count for another ul list?
With the code above this is what i get!

 test

 test

 test

Output

1. test
2. test
3. test

second ul list

 test

 test

 test

Output

4. test
5. test
6. test

Instead of starting the second ul tag with 1. 2. 3. it continues to count using the first ul 5. 6. 7.

So is it possible to reset the count and star it all over again for another ul tag?
If it is possible how?

Body:
var increment = 1;
$('ul').each(function() {
    var ul = $(this),
        li = ul.find('> li'),
        ol = $('<ol />').attr('start', increment);
    ul.after(ol);
    ol.append(li);
    ul.remove();
    increment += li.length;
});

Example: http://jsbin.com/opuyi/3

This will crap out with nested lists, as they'd (probably) look something like this:

1. One
2. Two
    4. Three
3. Four


问:
Azure API Management - require approval of new developer signup
As we all know, the Azure API Management provides a developer portal.  You can change the way that users login to the portal with AAD, Facebook, ...  I understand how to configure those options.

I don't want new developers to have automatic access to the portal.  I want to review the signup and approve them before they get access.  How do I implement this approval process for new users?

答: It's I remember correctly this can be done via the product, require subscription approval</p>


问:
UICollectionView not showing images after unhiding it
I have an UICollectionView that starts hidden in the viewDidLoad, then when an image is added with the UIImagePicker delegate the collection goes "unhidden" and then reloads, here is the code below

```<code>func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        self.imagesToSend.append(pickedImage)
    }

    self.imagenesCollectionView.isHidden = false
    self.imagenesCollectionView.reloadData()
    dismiss(animated: true, completion:nil)
}
</code>```

the problem is that when the collection shows it doesn't show any image, I have to add a second image so the image can show, I want the collection to show when there are images and to hide when there aren't images, until now the hiding functionality its working fine, but not the showing one.

答: Try to use the methods setNeedsLayout or setNeedsDisplay. They are related to the view update, and maybe you need to use them on the collectionView or on the imageView itself.

Body:
I have an UICollectionView that starts hidden in the viewDidLoad, then when an image is added with the UIImagePicker delegate the collection goes "unhidden" and then reloads, here is the code below

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        self.imagesToSend.append(pickedImage)
    }

    self.imagenesCollectionView.isHidden = false
    self.imagenesCollectionView.reloadData()
    dismiss(animated: true, completion:nil)
}

the problem is that when the collection shows it doesn't show any image, I have to add a second image so the image can show, I want the collection to show when there are images and to hide when there aren't images, until now the hiding functionality its working fine, but not the showing one.


问:
How does this function traverse Binary Tree?
I am working on a coding challenge. I found a solution, but I did not understand a part of the solution.

The prompt is

```<code>Given a binary tree, find the leftmost value in the last row of the tree.

Input:

        1
       / \
      2   3
     /   / \
    4   5   6
       /
      7

Output:
7
</code>```

Tree is defined:

```<code>/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
</code>```

This function works (I did not come up with it):

```<code>var findBottomLeftValue = function(root) {
    var result = root.val;
    var resultHeight = 0;
    (function recurse (node, height) {
        if (node === null) {
            return;
        }
        if (node.left !== null) {
            recurse(node.left, height + 1);
        }
        if (height > resultHeight) {
            result = node.val;
            resultHeight = height;
        }
        if (node.right !== null) {
            recurse(node.right, height + 1);
        }
    })(root, 1);
    return result;
};
</code>```

I understand most of the line, but frankly, this is my first time seeing IIFE inside another function, so maybe that threw me off a little.

What I don't understand is, let's say we start with root 1 (using example above), it starts off with node being 1. Since node.left !== null, node is now 2, since node.left !== null, it goes down to 4. node.left is now null, it goes to the next line, which updates height and resultHeight. Then next line, node.right is null, and function ends. In my understanding, it never went to check nodes 3, 5, etc. But the function clearly shows the right answer.

Where on the solution did it check for nodes 3, 5, 6, and 7?

答:
Your function descents to the left in the first call of recurse() (line 9).
If it is done with the left node, it'll go to the right in the second call to recurse() (line 16).

The sequence of the nodes will be 1 -> 2 -> 4 -> (2) -> (1) -> 3 -> 5 -> 7 -> (5) -> (3) -> 6 -> (3) -> (1).

The nodes in braces show where the call stack is reduced.

Body:
I am working on a coding challenge. I found a solution, but I did not understand a part of the solution.

The prompt is

Given a binary tree, find the leftmost value in the last row of the tree.

Input:

        1
       / \
      2   3
     /   / \
    4   5   6
       /
      7

Output:
7

Tree is defined:

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */

This function works (I did not come up with it):

var findBottomLeftValue = function(root) {
    var result = root.val;
    var resultHeight = 0;
    (function recurse (node, height) {
        if (node === null) {
            return;
        }
        if (node.left !== null) {
            recurse(node.left, height + 1);
        }
        if (height > resultHeight) {
            result = node.val;
            resultHeight = height;
        }
        if (node.right !== null) {
            recurse(node.right, height + 1);
        }
    })(root, 1);
    return result;
};

I understand most of the line, but frankly, this is my first time seeing IIFE inside another function, so maybe that threw me off a little.

What I don't understand is, let's say we start with root 1 (using example above), it starts off with node being 1. Since node.left !== null, node is now 2, since node.left !== null, it goes down to 4. node.left is now null, it goes to the next line, which updates height and resultHeight. Then next line, node.right is null, and function ends. In my understanding, it never went to check nodes 3, 5, etc. But the function clearly shows the right answer.

Where on the solution did it check for nodes 3, 5, 6, and 7?


问:
Calculate cardinal direction from GPS coordinates in Python
How can I calculate the cardinal direction of  a second point of geo coordinates in Python?
I need to know distance and direction of two different locations.

Example :
work : coord 41.4107628,2.1745004
home : coord 41.4126728,2.1704725

```<code>from geopy.distance import vincenty
work = geopy.Point(41.4107628,2.1745004)
home = geopy.Point(41.4126728,2.1704725)
print(vincenty(home, work))
0.398011015257 km
</code>```

I'd like to know in which directions the second point lies, ( ex.: North, North-West, etc) respect to the first one...

Many thanks in advance

答:
Edit for clarity: this is an approximation that will tell general direction. Use the link below for an easy online calculator. Otherwise follow other answers provided.

The first value in the coordinate system represents North/South direction, the second represents East/West. Simple subtraction will provide a general direction. For example subtracting B from A we get:

41.4126728 - 41.4107628 = 0.00191

2.1704725 - 2.1745004 = - 0.0040279

This indicates that to reach point B from point A, you would need to travel in a North (positive value) West (negative value) direction. <s>A precise angle can be found by using trigonometry (think of each value as a side of a right triangle).</s> As mentioned in the comments, trigonometry is insufficient for an accurate calculation.

You might find this website interesting: https://www.movable-type.co.uk/scripts/latlong.html

Body:
How can I calculate the cardinal direction of  a second point of geo coordinates in Python?
I need to know distance and direction of two different locations.

Example :
work : coord 41.4107628,2.1745004
home : coord 41.4126728,2.1704725

from geopy.distance import vincenty
work = geopy.Point(41.4107628,2.1745004)
home = geopy.Point(41.4126728,2.1704725)
print(vincenty(home, work))
0.398011015257 km

I'd like to know in which directions the second point lies, ( ex.: North, North-West, etc) respect to the first one...

Many thanks in advance

ContentLicense: CC BY-SA 4.0


问:
Typescript transpiled Javascript does not include properties
My transpiled Javascript for my client side models do not include the properties from the Typescript files.

These properties are never directly set as they are parsed and mapped from JSON so I thought perhaps the compiler was being clever and optimising the code to remove unused properties but I don't see any options to turn such behaviour off so perhaps something else.

One of my models as an example:

RfidData.ts

```<code>import { TimeModel } from "./Model";

export class RfidData extends TimeModel {
  DeviceId: string;
  Transponders: string[];
}
</code>```

RfidData.js (compiled output)

```<code>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Model_1 = require("./Model");
class RfidData extends Model_1.TimeModel {
}
exports.RfidData = RfidData;
//# sourceMappingURL=RfidData.js.map
</code>```

As you can see the two properties DeviceId and Transponders don't make it into the transpiled output.

.tsconfig (for reference)

```<code>{
  "compileOnSave": true,
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "moduleResolution": "node",
    "module": "commonjs",
    "target": "es6",
    "outDir": "Client/js/"
  },
  "exclude": [
    "node_modules",
    "wwwroot"
  ]
}
</code>```

Any help would be greatly appreciated.

UPDATE -- Further Discussion

After a good discussion there is another issue here which is that types are stripped after being transpiled, type erasure as jcalz points out. So mapping JSON through with an interface or setting the properties manually doesn't solve the issue if you have typed properties. For instance a Date is left as any in an underlying class so you cannot access any relevant properties, its left as a string on the JS.

Is there anyway to maintain types in ES6 transpiled from TypeScript? Otherwise this question was rather academic. :(

答:
TypeScript erases all type information when it transpiles to JavaScript.  In your case, the property declarations aren't setting any values, so they are erased too.  I'm not sure why you want to see them at runtime if you aren't setting their values, but you probably have your reasons.

If you really want to see properties in the JavaScript, then you can initialize them to values:

```<code>export class RfidData extends TimeModel {
  DeviceId: string = "";
  Transponders: string[] = [];
}
</code>```

transpiles to

```<code>class RfidData extends Model_1.TimeModel {
    constructor() {
        this.DeviceId = "";
        this.Transponders = [];
    }
}
</code>```

If you can't think of reasonable initial values, you can set them to undefined or void 0 (and if you have --strictNullChecks on you will have to use undefined! or the like).

Hope that helps; good luck!

Body:
My transpiled Javascript for my client side models do not include the properties from the Typescript files.

These properties are never directly set as they are parsed and mapped from JSON so I thought perhaps the compiler was being clever and optimising the code to remove unused properties but I don't see any options to turn such behaviour off so perhaps something else.

One of my models as an example:

RfidData.ts

import { TimeModel } from "./Model";

export class RfidData extends TimeModel {
  DeviceId: string;
  Transponders: string[];
}

RfidData.js (compiled output)

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Model_1 = require("./Model");
class RfidData extends Model_1.TimeModel {
}
exports.RfidData = RfidData;
//# sourceMappingURL=RfidData.js.map

As you can see the two properties DeviceId and Transponders don't make it into the transpiled output.

.tsconfig (for reference)

{
  "compileOnSave": true,
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "moduleResolution": "node",
    "module": "commonjs",
    "target": "es6",
    "outDir": "Client/js/"
  },
  "exclude": [
    "node_modules",
    "wwwroot"
  ]
}

Any help would be greatly appreciated.

UPDATE -- Further Discussion

After a good discussion there is another issue here which is that types are stripped after being transpiled, type erasure as jcalz points out. So mapping JSON through with an interface or setting the properties manually doesn't solve the issue if you have typed properties. For instance a Date is left as any in an underlying class so you cannot access any relevant properties, its left as a string on the JS.

Is there anyway to maintain types in ES6 transpiled from TypeScript? Otherwise this question was rather academic. :(

Body:
TypeScript erases all type information when it transpiles to JavaScript.  In your case, the property declarations aren't setting any values, so they are erased too.  I'm not sure why you want to see them at runtime if you aren't setting their values, but you probably have your reasons.

If you really want to see properties in the JavaScript, then you can initialize them to values:

export class RfidData extends TimeModel {
  DeviceId: string = "";
  Transponders: string[] = [];
}

transpiles to

class RfidData extends Model_1.TimeModel {
    constructor() {
        this.DeviceId = "";
        this.Transponders = [];
    }
}

If you can't think of reasonable initial values, you can set them to undefined or void 0 (and if you have --strictNullChecks on you will have to use undefined! or the like).

Hope that helps; good luck!


问:
How to print progress bar with negative values in Python 2.X?
I am doing some computation between two sensors and I would like to print "graphically" but in the stdout the % of asymetry between the two sensors.

Ex:
I have as a result -20% (meaning that the left sensor is 20% higher than the right one).

I would like to print this, dynamically, on the same line :

If I have -20%:
[___________________-20%########||_____________________________]

If I have 0%:
[_______________________________||_____________________________]

If I have 10%:
[_______________________________||###10%_______________________]

How could I proceed?
I tried with Progressbar API, but it does not allow to do this (only progressive bars, starting from the left).

I would prefer to not use a GUI because I run this in ssh without X11 forwarding.
But if someone have a similar solution with GUI I am also interested in.
Thank you very much!

答:
Printing a progress bar isn't difficult. The common method is to use the carriage return character (\r):

```<code>from __future__ import print_function

import sys

import fcntl
import struct
import termios

class ProgressBar(object):
    def __init__(self):
        pass

    def get_terminal_width(self):
        try:
            return struct.unpack('hh', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, '\x00' * 4))[1]
        except IOError:
            return 120

    def display(self, percentage):
        terminal_width = self.get_terminal_width()

        stars = '*' * int((percentage / 100.0) * terminal_width)

        print(stars, end='\r')  # Print out your progress and jump to the beginning of the line
        sys.stdout.flush()      # Flush stdout to make it show up immediately

if __name__ == '__main__':
    import time
    bar = ProgressBar()

    for i in range(100):
        bar.display(i)
        time.sleep(0.03)
</code>```

I'll leave it you to figure out the string manipulations you need to do to get the progress bar showing up in the middle.

Body:
Printing a progress bar isn't difficult. The common method is to use the carriage return character (\r):

from __future__ import print_function

import sys

import fcntl
import struct
import termios

class ProgressBar(object):
    def __init__(self):
        pass

    def get_terminal_width(self):
        try:
            return struct.unpack('hh', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, '\x00' * 4))[1]
        except IOError:
            return 120

    def display(self, percentage):
        terminal_width = self.get_terminal_width()

        stars = '*' * int((percentage / 100.0) * terminal_width)

        print(stars, end='\r')  # Print out your progress and jump to the beginning of the line
        sys.stdout.flush()      # Flush stdout to make it show up immediately

if __name__ == '__main__':
    import time
    bar = ProgressBar()

    for i in range(100):
        bar.display(i)
        time.sleep(0.03)

I'll leave it you to figure out the string manipulations you need to do to get the progress bar showing up in the middle.


问:
selenium webdriver - waiting until outerHTML attribute of last class in list contains "X"
Using c# and selenium webdriver, how can I wait until the last class in a list contains a specific attribute?

In my AUT, I have three classes on a page (they are all called paragraph).  I need to get the last paragraph specifically (I'm using a list but feel free to suggest better method) then wait until the last class on the page contains an outerHTML attribute of "X".

This is what I have so far:

I create a list to store all classes, get the last class and finally, get the outerHTML attribute for the last class.

```<code>IList<IwebElement> Element = driver.FindElements(By.ClassName("Paragraph"));
var GetLastElement = Element.Last();
var LastElementAttribute = GetLastElement.GetAttribute("outerHTML");
</code>```

Based on my code above, how can I add a wait condition that will check the last class in the list contains an outerHTML attribute of "X"?

答:
If I understood you right - lambda for X appearance in the last Paragraph outherHTML would look like this:</p>

```<code>Wait().Until(driver => driver
  .FindElements(By.ClassName("Paragraph"))
     .Last().GetAttribute("outerHTML")
       .Contains("X"));
</code>```

Body:
Using c# and selenium webdriver, how can I wait until the last class in a list contains a specific attribute?

In my AUT, I have three classes on a page (they are all called paragraph).  I need to get the last paragraph specifically (I'm using a list but feel free to suggest better method) then wait until the last class on the page contains an outerHTML attribute of "X".

This is what I have so far:

I create a list to store all classes, get the last class and finally, get the outerHTML attribute for the last class.

IList<IwebElement> Element = driver.FindElements(By.ClassName("Paragraph"));
var GetLastElement = Element.Last();
var LastElementAttribute = GetLastElement.GetAttribute("outerHTML");

Based on my code above, how can I add a wait condition that will check the last class in the list contains an outerHTML attribute of "X"?

Body:
If I understood you right - lambda for X appearance in the last Paragraph outherHTML would look like this:

Wait().Until(driver => driver
  .FindElements(By.ClassName("Paragraph"))
     .Last().GetAttribute("outerHTML")
       .Contains("X"));


问:
Include template as verbatim
I have a template which I'm inserting with include tag:

```<code>{% include 'template.html' %}
</code>```

Also in another place I want its contents to be displayed as raw. How can I achieve this?

答:
I ended up creating a template tag to do this:

```<code>from django import template
from django.template.loader import get_template
from django.utils.html import escape

register = template.Library()

@register.simple_tag()
def verbatim_include(name):
    """
    Example: {% verbatim_include "weblog/post.html" %}
    """
    template = get_template(name)
    return escape(template.render())
</code>```

I've no idea if it's the best or most efficient method, but it seems to work OK for me (Django 1.11).

In my main template I'll include another like this:

```<code>```{% verbatim_include 'my_template.html' %}```
</code>```

And if my_template.html is like this:

```<code><b>This is my template</b>
</code>```

Then in the browser I'll see:

```<code><b>This is my template</b>
</code>```

And not:

This is my template

Title: Include template as verbatim

Body:
I have a template which I'm inserting with include tag:

{% include 'template.html' %}

Also in another place I want its contents to be displayed as raw. How can I achieve this?

Body:
I ended up creating a template tag to do this:

from django import template
from django.template.loader import get_template
from django.utils.html import escape

register = template.Library()

@register.simple_tag()
def verbatim_include(name):
    """
    Example: {% verbatim_include "weblog/post.html" %}
    """
    template = get_template(name)
    return escape(template.render())

I've no idea if it's the best or most efficient method, but it seems to work OK for me (Django 1.11).

In my main template I'll include another like this:

<pre><code>{% verbatim_include 'my_template.html' %}</code></pre>

And if my_template.html is like this:

<b>This is my template</b>

Then in the browser I'll see:

<b>This is my template</b>

And not:

This is my template


问:
How to store a password without a database (PHP)?
I would like to have a page that requires a password to login, but without a dataabase.

I was thinking of having it hard coded in the page, ie:

```<code>$password = "something"
</code>```

Or encrypt it and store it in a text file?

Any advice is appreciated.

答:
You could use PHP's md5 encryption libraries to encrypt the password and then store it in the text file.  Since md5 isn't reversible, the password would be secure.

You definitely do not want to store in plain text.

You could also store the password in the PHP file, but using the encrypted hash.  The advantage of the file is that the data is separated from the business logic, which can make adding a database or the ability to use multiple users/passwords slightly easier.

UPDATE: If you store the password in plain text in the PHP script unencrypted, anyone who hacks your server or has access to the server can read the contents of your plain-text PHP files.

Body:
I would like to have a page that requires a password to login, but without a dataabase.

I was thinking of having it hard coded in the page, ie:

$password = "something"

Or encrypt it and store it in a text file?

Any advice is appreciated.


问:
Boolean equals method
Writing an abstract class project. Abstract class is the parent class and include a the equals method. Part of my project is to create a Boolean equals method that compares the client IDs (long) of 3 subclasses to make sure that their are not any duplicates IDs. Having an issue implementing the code. Below is what I have so far

```<code>public static boolean equals(Object A, Object B, Object C) {
    if(A.equals(B) || A.equals(C) || B.equals(C))
        return true;
    else
        return false;
}
</code>```

Need help dropping the 3 class values for client ID into the code and then incorporating the code into a toString() method.

答:
You can change your method to the following:

```<code>public static boolean equals(Object A, Object B, Object C) {
    return A != null && B != null && C != null && (A.equals(B) || A.equals(C) || B.equals(C));
}
</code>```

Few things:

Any place you have:

```<code>if (cond) {
    return true;
} else {
    return false;
}
</code>```

You can just return the cond: return cond;

Added non-null validation: A != null && B != null && C != null

You should override equals() method on each class(A, B and C) and include the field/s you want to use in equals (only id in your example)

Title: Boolean equals method

Body:
Writing an abstract class project. Abstract class is the parent class and include a the equals method. Part of my project is to create a Boolean equals method that compares the client IDs (long) of 3 subclasses to make sure that their are not any duplicates IDs. Having an issue implementing the code. Below is what I have so far

public static boolean equals(Object A, Object B, Object C) {
    if(A.equals(B) || A.equals(C) || B.equals(C))
        return true;
    else
        return false;
}

Need help dropping the 3 class values for client ID into the code and then incorporating the code into a toString() method.

Body:
You can change your method to the following:

public static boolean equals(Object A, Object B, Object C) {
    return A != null && B != null && C != null && (A.equals(B) || A.equals(C) || B.equals(C));
}

Few things:

Any place you have:

if (cond) {
    return true;
} else {
    return false;
}

You can just return the cond: return cond;

Added non-null validation: A != null && B != null && C != null

You should override equals() method on each class(A, B and C) and include the field/s you want to use in equals (only id in your example)


问:
Remove Headers from each page break using excel formulas
I am loading a text file to Excel 2016.Below is the example for your reference

When I load the data to excel I see Headers in every page break as shown in the below image.

I don't need these lines and I have to delete them, hence tried writing formula. I have written multiple conditions to get the data I want. However since there are headers in each page break the data is not matching.

The headers always start with ------ and ends with ------ (It is 10 rows in excel as shown below.I tried writing the below condition to get start and end of the line of the headers, but not successful.

=IFERROR(FIND("-----------",E10,1),"")

TE Connectivity

ZSD4R708
 PR2 (028)--TE220664 --21.11.2017(18:50:45)

How can I get rid of these 10 lines in the entire data set. All I need is 0 in one of columns as shown below (every time header repeats). Could we combine Rows and Find function, I am not sure.. Any help in this greatly appreciated.

0   ---------------------------
0   TE Connectivity
0

0      ZSD4R708
0    PR2 (028)--TE220664 --21.11.2017(18:50:45)
0

0   ----------------------------------------------------------------------------

Thanks,
Ganesh

答:
Assuming I understand your question properly, I got the below to work with crafty use of MATCH and OFFSET and ROW

```<code>=IF(ISNUMBER(MATCH("TE Connectivity",OFFSET(B1:B7,MAX(2-ROW(),-5),0),0)),0,"")
</code>```

Body:
Assuming I understand your question properly, I got the below to work with crafty use of MATCH and OFFSET and ROW

=IF(ISNUMBER(MATCH("TE Connectivity",OFFSET(B1:B7,MAX(2-ROW(),-5),0),0)),0,"")