Is there a simple way to time a function call in elisp?

[Originally Posted By]: http://stackoverflow.com/questions/21246688/is-there-a-simple-way-to-time-a-function-call-in-elisp

I found exactly what I was looking for at http://nullprogram.com/blog/2009/05/28/

(defmacro measure-time 
    (&rest 
     body)
  "Measure and return the running time of the code block."
  (declare (indent defun)) 
  (let ((start (make-symbol "start"))) 
    `(let ((,start (float-time))) ,@body (- (float-time) ,start))))
Advertisements

fix to get smooth scrolling in emacs?

[Originally Posted By]: http://stackoverflow.com/questions/3631220/fix-to-get-smooth-scrolling-in-emacs

I find myself wanting to use Emacs, mostly because of org-mode, but I’m having a lot of trouble getting used to the jerky scrolling behavior. I know this is a well-known problem/eccentricity of Emacs and that there are various ways to minimize jerkiness when scrolling. But nothing I’ve tried so far works very well at all.

The main suggestions I’ve seen are (setq scroll-conservatively 10000) or to use the more comprehensive fix available in smooth-scrolling.el . I think both of these might work okay for me, but both fail miserably when I hold down the up-arrow and down-arrow key to get repeated scrolling up or down. When I do this the screen freezes and I see the scroll-indicator-bar in the scroll margin move up or down. The screen does not refresh until I stop holding down the up-arrow or down-arrow key.

If I repeatedly press up-arrow or down-arrow then I do get behavior close to what I want, i.e., the screen scrolls smoothly and cursor key does not get reset to middle of screen. But this is undesirable because (1) it requires repeated keypresses and (2) I assume the scrolling is at a slower rate than what I should be able to get in better solution.

The problem with holding the cursor keys down seems to me to be that the repeat rate of up-arrow or down-arrow is so fast that it triggers emacs to stop the screen refresh until key is released. I wonder whether a possible fix for me would be to add some lag into the key-repeat rate or the rate at which the next/previous line function is called in emacs.

I haven’t seen this reported as a problem by others and I wonder whether other people have experienced same behavior. What’s best way to fix things so I can hold the up/down arrow keys down and have repeat rate that’s slow enough so that the screen doesn’t freeze?

UPDATE: The above behavior is what I get when I run emacs on Win7/64. On same machine when I run emacs inside a VirtualBox VM running Ubuntu 10.04 it’s no problem to get scrolling that works fine even when cursor keys are held down.

shareimprove this question

I had the same problem! Tried all the scroll-* settings, didn’t help when holding down arrow. But found this on gnu.emacs.help which finally worked (for me at least):

(setq redisplay-dont-pause t)

This is what I have in .emacs for now:

(setq redisplay-dont-pause t
  scroll-margin 1
  scroll-step 1
  scroll-conservatively 10000
  scroll-preserve-screen-position 1)
shareimprove this answer

Try this:

;; scroll one line at a time (less "jumpy" than defaults)
(setq mouse-wheel-scroll-amount '(1 ((shift) . 1))) ; one line at a time
(setq mouse-wheel-progressive-speed nil)            ; don't accelerate scrolling
(setq-default smooth-scroll-margin 0)
(setq scroll-step 1
      scroll-margin 1
      scroll-conservatively 100000)

And use pager.el.

;; Pager
(require 'pager-default-keybindings)

That’s what I want 🙂 Enjoy!

shareimprove this answer

How to get IpAddress and UserAgent in ASP.NET Web API get methods

[Originally Posted By]: http://stackoverflow.com/questions/17364801/how-to-get-ipaddress-and-useragent-in-asp-net-web-api-get-methods

I am using ASP.NET Web Api to expose a few GET methods.

But before I return the data I need to log a couple of details to the db, of which few of them are as listed below :

  • Caller’s Ip
  • Caller’s User Agent
  • Caller’s Used Url

Now in the controller when I used to do this I used to use the following code,

var ipAddress = Request.ServerVariables["REMOTE_ADDR"];
var userAgent = Request.UserAgent;

But here in Web API I am unable to use this.

Can anyone please help me out with this.

shareedit

I figured it out,

public static LogModel GetApiLogDetails()
{
    var logModel = new LogModel();
    logModel.TimeStamp   = DateTime.Now;
    logModel.CallerIp    = HttpContext.Current.Request.UserHostAddress;
    logModel.CallerAgent = HttpContext.Current.Request.UserAgent;
    logModel.CalledUrl   = HttpContext.Current.Request.Url.OriginalString;
    return logModel;
}

with a little help from

Get Web Api consumer IP Address and HostName in ASP.net C# &

Get the IP address of the remote host

shareedit

You should use HttpRequestMessage class, that conteins all data you need.

Read more:

shareedit

MACRO COUNTERS

[Originally Posted By]: http://pragmaticemacs.com/emacs/macro-counters/

I’ve posted about using keyboard macros to record and play back repetitive tasks. Macros include acounter which lets you insert numerical values that increment each time the macro is called.

For example, go to a new line and start a macro with C-x ( and then hit C-a to move to the start of the line, C-x C-k C-i to insert the macro counter (initially zero) and then RET to go to a new line andC-x ) to stop the recording. Run the macro a few times with C-x e and then just e to repeat the macro and you’ll get something like this:

0
1
2
3
4

The counter starts at zero every time you define a new macro. To set it to another value, use C-x C-k C-c before defining or invoking a macro.

DATA AT THE ROOT LEVEL IS INVALID. LINE 1, POSITION 1.

[Originally Posted By]: http://www.ipreferjim.com/2014/09/data-at-the-root-level-is-invalid-line-1-position-1/

Recently, I encountered a really weird problem with an XML document. I was trying to load a document from a string:

var doc = XDocument.parse(someString);

I received this unhelpful exception message:

Data at the root level is invalid. Line 1, position 1.

I verified the XML document and retried two or three times with and without the XML declaration (both of which should work with XDocument). Nothing helped, so I googled for an answer. I found the following answer on StackOverflow by James Brankin:

I eventually figured out there was a byte mark exception and removed it using this code:

string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if (xml.StartsWith(_byteOrderMarkUtf8))
{
    xml = xml.Remove(0, _byteOrderMarkUtf8.Length);
}

This solution worked. I was happy. I discussed it with a coworker and he had never heard of a BOM character before, so I thought “I should blog about this”.

Byte-Order Mark

The BOM is the character returned by Encoding.UTF8.GetPreamble(). Microsoft’s documentation explains:

The Unicode byte order mark (BOM) is serialized as follows (in hexadecimal):

  • UTF-8: EF BB BF
  • UTF-16 big endian byte order: FE FF
  • UTF-16 little endian byte order: FF FE
  • UTF-32 big endian byte order: 00 00 FE FF
  • UTF-32 little endian byte order: FF FE 00 00

Converting these bytes to a string (Encoding.UTF8.GetString) allows us to check if the xml string starts with the BOM or not. The code then removes that BOM from the xml string.

A BOM is a bunch of characters, so what? What does it do?

From Wikipedia:

The byte order mark (BOM) is a Unicode character used to signal the endianness (byte order) of a text file or stream. It is encoded at U+FEFF byte order mark (BOM). BOM use is optional, and, if used, should appear at the start of the text stream. Beyond its specific use as a byte-order indicator, the BOM character may also indicate which of the several Unicode representations the text is encoded in.

This explanation is better than the explanation from Microsoft. The BOM is (1) an indicator that a stream of bytes is Unicode and (2) a reference to the endianess of the encoding. UTF8 is agnostic of endianness (reference), so the fact that the BOM is there and causing problems in C# code is annoying. I didn’t research why the UTF8 BOM wasn’t stripped from the string (XML is coming directly from SQL Server).

What is ‘endianness’?

Text is a string of bytes, where one or more bytes represents a single character. When text is transferred from one medium to another (from a flash drive to a hard drive, across the internet, between web services, etc.), it is transferred as stream of bytes. Not all machines understand bytes in the same way, though. Some machines are ‘little-endian’ and some are ‘big-endian’.

Wikipedia explains the etymology of ‘endianness’:

In 1726, Jonathan Swift described in his satirical novel Gulliver’s Travels tensions in Lilliput and Blefuscu: whereas royal edict in Lilliput requires cracking open one’s soft-boiled egg at the small end, inhabitants of the rival kingdom of Blefuscu crack theirs at the big end (giving them the moniker Big-endians).

For text encoding, ‘endianness’ simply means ‘which end goes first into memory’. Think of this as a direction for a set of bytes. The word ‘Example’ can be represented by the following bytes (example taken from StackOverflow):

45 78 61 6d 70 6c 65

‘Big Endian’ means the first bytes go first into memory:

45 78 61 6d 70 6c 65
<-------------------

‘Little Endian’ means the text goes into memory with the small-end first:

45 78 61 6d 70 6c 65
------------------->

So, when ‘Example’ is transferred as ‘Big-Endian’, it looks exactly as the bytes in the above examples:

45 78 61 6d 70 6c 65

But, when it’s transferred in ‘Little Endian’, it looks like this:

65 6c 70 6d 61 78 45

Users of digital technologies don’t need to care about this, as long as they see ‘Example’ where they should see ‘Example’. Many engineers don’t need to worry about endianness because it is abstracted away by many frameworks to the point of only needing to know which type of encoding (UTF8 vs UTF16, for example). If you’re into network communications or dabbling in device programming, you’ll almost definitely need to be aware of endianness.

In fact, the endianness of text isn’t constrained by the system interacting with the text. You can work on a Big Endian operating system and install VoIP software that transmits Little Endian data. Understanding endianness also makes you cool.

Summary

I don’t have any code to accompany this post, but I hope the discussion of BOM and endianness made for a great read!

How to Deserialize XMLDocument to object in C#?

[Originally Posted By]: http://stackoverflow.com/questions/2694860/how-to-deserialize-xmldocument-to-object-in-c

I have a .Net webserivce that accepts XML in string format. XML String sent into the webserivce can represent any Object in the system. I need to check the first node to figure out what object to deserialize the XML string. For this I will have to load the XML into an XMLDocument (Don’t want to use RegEx or string compare). I am wondering if there is a way to Deserialize the XMLDocument/XMLNoderather that deserializing the string to save some performance? Is there going to be any performance benefit serializing the XMLNode rather that the string?

Method to Load XMLDocument

public void LoadFromString(String s)
{
    m_XmlDoc = new XmlDocument();
    m_XmlDoc.LoadXml(s);        
}

Thanks

shareedit

If you have an XmlDocument, you can use XmlNodeReader as an XmlReader to pass to XmlSerializer, but I wonder if it would be better to do it the other way; use an XmlReader to get the outermost element name, and give that to XmlSerializer

[XmlRoot("foo")]
public class Foo
{
    [XmlAttribute("id")]
    public int Id { get; set; }
}
static class Program
{
    static void Main()
    {
        string xml = "&lt;foo id='123'/&gt;";
        object obj;
        using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
        {
            reader.MoveToContent();
            switch (reader.Name)
            {
                case "foo":
                    obj = new XmlSerializer(typeof(Foo)).Deserialize(reader);
                    break;
                default:
                    throw new NotSupportedException("Unexpected: " + reader.Name);
            }
        }            
    }
}
shareedit

Don’t forget a powerfull contender, LINQ to XML!

XElement root = XElement.Load(myfile);

var foos = root.Descendants("Foo").Where(e =&gt; e.Attribute("bar") != null);

XML Serialization and Deserialization in C#

[Originally Posted By]: https://blog.udemy.com/csharp-serialize-to-xml/

Serialization is a mechanism for converting an object (such as an instance of a class, or a collection of objects) into a stream of bytes or characters that you can save to a file or database, or even send across the Internet to other systems. When needed, you can deserialize the data – converting it back to a usable object in memory. The .NET framework contains many classes to help with this process, and offers in-built support for XML serialization (serializing an object to an XML data file) through the XmlSerializer class and the System.Xml.Serialization library.

This article provides a brief overview of XML serialization and deserialization in the C# programming language. It assumes that readers have a reasonable knowledge of C# and Microsoft Visual Studio, and so complete beginners would benefit from exploring the fundamentals of C# programming first. Readers who are unfamiliar with XML should learn the basics of XML programming before continuing. This is especially important if intending to use serialization to exchange data with other systems.

Serializing XML in C#

Many .NET framework objects and classes can be serialized without adding any special directives or attributes to the code. By default, all public properties of a class are already serializable.

The example below defines a simple class in a Visual C# Console Application, and then serializes the contents to the console window.

/*
 * 
 * Udemy.com
 * XML Serialization and Deserialization in C#
 * 
*/

using System;
using System.Xml.Serialization;

namespace XMLTest1
{
    public class Test
    {
        public String value1;
        public String value2;
    }

    class Program
    {
        static void Main(string[] args)
        {
            Test myTest = new Test() { value1 = "Value 1", value2 = "Value 2" };
            XmlSerializer x = new XmlSerializer(myTest.GetType());
            x.Serialize(Console.Out, myTest);
            Console.ReadKey();
        }
    }
}

The actual serialization is done by an instance of the class XmlSerializer, from the System.Xml.Serialization namespace. The serializer’s constructor requires a reference to the type of object it should work with – which can be obtained by using the GetType() method of an instanced object, or a call to the function typeof()and specifying the class name as the only argument.

The Serialize() method takes an object of the defined type, translates that object into XML, and then writes the information to a defined stream (in this case, the TextWriter object of the console’s output stream). The XML output of the sample code is shown below:

<?xml version="1.0" encoding="ibm850"?>
<Test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <value1>Value 1</value1>
 <value2>Value 2</value2>
</Test>

The names of elements and attributes in the XML output are set by the names of the properties and fields from the object.

You can direct the output of the serialization to a wide variety of .NET streams, including MemoryStream (with XmlWriter and StringWriter), FileStream, and NetworkStream classes. It is also possible to serialize an object into an XmlDocument with the help of an instance of XPathNavigator, as shown in the following example:

/*
 * 
 * Udemy.com
 * XML Serialization and Deserialization in C#
 * 
*/

using System;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Serialization;

namespace XMLTest1
{
    public class Test
    {
        public String value1;
        public String value2;
    }

    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument myXml = new XmlDocument();
            XPathNavigator xNav = myXml.CreateNavigator();
            Test myTest = new Test() { value1 = "Value 1", value2 = "Value 2" };
            XmlSerializer x = new XmlSerializer(myTest.GetType());
            using (var xs = xNav.AppendChild())
            {
                x.Serialize(xs, myTest);
            }
            Console.WriteLine(myXml.OuterXml);
            Console.ReadKey();
        }
    }
}

Deserializing XML Data

Deserialization is the process of taking XML-formatted data and converting it to a .NET framework object: the reverse of the process shown above. Providing that the XML is well-formed and accurately matches the structure of the target type, deserialization is a relatively straightforward task.

In the example below, the XML output of the preceding examples is hard-coded into a string, but it could be fetched from a network stream or external file. The XmlSerializer class is used to deserialize the string to an instance of the Test class, and the example then prints the fields to the console. To obtain a suitable stream that can be passed into the XmlSerializer’s constructor, a StringReader (from the System.IO namespace) is declared.

/*
 * 
 * Udemy.com
 * XML Serialization and Deserialization in C#
 * 
 */

using System;
using System.IO;
using System.Xml.Serialization;

namespace XMLTest1
{
    public class Test
    {
        public String value1;
        public String value2;
    }

    class Program
    {
        static void Main(string[] args)
        {
            String xData = "<?xml version=\"1.0\" encoding=\"ibm850\"?><Test xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><value1>Value 1</value1><value2>Value 2</value2></Test>";            
            XmlSerializer x = new XmlSerializer(typeof(Test));
            Test myTest = (Test)x.Deserialize(new StringReader(xData));
            Console.WriteLine("V1: " + myTest.value1);
            Console.WriteLine("V2: " + myTest.value2);
            Console.ReadKey();
        }
    }
}

Serializing Lists and Collections

You can serialize arrays, generic lists, and other collection objects to XML, provided that their class implements ICollection or IEnumerable.

Simple arrays and generic lists generally work unmodified, and may appear identical in the final output. For example, whether objects are declared as an array of Test objects or as a generic list of Test objects, the XmlSerializer will write both using the same XML code:

<?xml version="1.0" encoding="ibm850"?>
<ArrayOfTest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <Test>
    <value1>A1</value1>
    <value2>B1</value2>
 </Test>
 <Test>
    <value1>B1</value1>
    <value2>B2</value2>
 </Test>
</ArrayOfTest>

As a result, XML data in this format can be deserialized to either a generic list ofTest objects, or an array of Test objects. It is up to the programmer to specify which type of object should be used for deserialization.

Controlling the Serialization Using Attributes

When serializing data for exchange with other applications, or when working to a predefined XML schema, it is useful to be able to change the element and attribute names used during the process. By default, elements in the XML output are named after the properties or fields that they are based on. You can rename the root node using the XmlRoot attribute, and change the name of child nodes by using the XmlElement attribute and setting its ElementName.

Multiple properties can be specified for an attribute by separating them with commas within the parenthesis. This usually takes the form[attributename(property1=value1, property2=value2…)]

[XmlRoot("XTest")]
public class Test
{
    [XmlElement(ElementName="V1")]
    public String value1;

    [XmlElement(“V2")]
    public String value2;        
}

Note that when you are only specifying the element name, the property name can be omitted.

Adding the XmlElement attribute, as shown above, not only sets the name to be used, but it also tells the XmlSerializer to use an XML element for that field. You can change value1 to be an attribute of the XTest element by declaring the field with XmlAttribute instead.

Two different attributes are used for arrays and collections. XmlArray controls the root node of the list, and XmlArrayItem controls each element in that array.

[XmlRoot("XTest")]
public class Test
{
    [XmlElement(ElementName="V1")]
    public String value1;

    [XmlElement(ElementName="V2")]
    public String value2;

    [XmlArray("OtherValues")]
    [XmlArrayItem("OValue")]
    public List others = new List();
}

The example above is serialized to XML in a format similar to the following:

<?xml version="1.0" encoding="ibm850"?>
<XTest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <V1>A1</V1>
 <V2>B1</V2>
 <OtherValues>
    <OValue>Test</OValue>
 </OtherValues>
</XTest>

In certain situations, you may want to exclude a public property or field from the output. This can be done by adding the attribute XmlIgnore to the property in the class’s declarations:

[XmlIgnore]
public String value2;
…

Finally, when working to a defined schema, it is often necessary to remove the standard namespace definitions that are added by the XmlSerializer. This is usually best handled when calling the Serialize() method of the XmlSerializer instance. An optional parameter for this method specifies the namespaces to be used, an XmlSerializerNamespaces collection, and can contain blank values.

XmlSerializer x = new XmlSerializer(myTest.GetType());
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
x.Serialize(Console.Out, myTest, ns);

Of course, namespaces can also be added using the same XmlSerializerNamespaces collection. However, it is often clearer to use theNamespace property of the XmlRoot attribute in combination with the code above.

By keeping in mind, or pre-planning, the serialization needs of the structures used in your application as you write the classes, it is possible to add object persistence and loading of external data files to the application with a very minimal amount of programming effort.

Overriding the Serialization of a Class

As mentioned earlier, all public properties and fields of a class are automatically serializable, and can usually be converted to XML without using any directives or attributes. Private properties and fields are not serialized by default. To include these, and for more precise control over how an object is serialized to XML, you can override the entire serialization process.

You do this by implementing IXmlSerializable in your classes, and including three methods that are required for the XML serialization to work: GetSchema(), WriteXml(), and ReadXml().

A thorough explanation of working with the XmlWriter and XmlReader classes used by these methods is beyond the scope of this article. Working with the data at such a level may draw on many different aspects of C# programming and a variety of technologies from the .NET framework. For more advanced C# information, C# 2012 Fundamentals at Udemy.com forms a complete course from beginner-level projects to advanced concepts, and contains more examples of serialization in Part III.