text:
import resourceBase = require("./gen/tasks_base");
resourceBase.comment = "The _task_ is the basic object around which many operations in Asana are\ncentered. In the Asana application, multiple tasks populate the middle pane\naccording to some view parameters, and the set of selected tasks determines\nthe more detailed information presented in the details pane.\n";
resourceBase.properties = [
  {
    "name": "gid",
    "type": "Gid",
    "example_values": [
      "\"1234\""
    ],
    "comment": "Globally unique ID of the task.\n"
  },
  {
    "name": "resource_type",
    "type": "Enum",
    "comment": "The resource type of this resource. The value for this resource is always `task`.\n",
    "example_values": [
      "\"task\""
    ],
    "values": [
      {
        "name": "task",
        "comment": "A task resource type."
      }
    ]
  },
  {
    "name": "resource_subtype",
    "type": "Enum",
    "comment": "The type of task. Different subtypes of tasks retain many of the same fields and behavior, but may render differently in Asana or represent tasks with different semantic meaning.\n",
    "example_values": [
      "\"default_task\"",
      "\"milestone\"",
      "\"section\""
    ],
    "values": [
      {
        "name": "default_task",
        "comment": "A normal task."
      },
      {
        "name": "milestone",
        "comment": "A task that represents a milestone. A milestone marks a specific point in time and cannot have a start_date.\n"
      },
      {
        "name": "section",
        "comment": "\"**This value is under active migration—please see our [forum post](https://forum.asana.com/t/sections-are-dead-long-live-sections) for more information.**\"\n\nA task which represents a section in list projects - a task that ends in a colon and renders with a different style to visually group tasks together.\n"
      }
    ]
  },
  {
    "name": "assignee",
    "type": "User",
    "example_values": [
      "{ id: 12345, gid: \"12345\", resource_type: \"user\", name: 'Tim Bizarro' }",
      "null"
    ],
    "comment": "User to which this task is assigned, or `null` if the task is\nunassigned.\n"
  },
  {
    "name": "assignee_status",
    "type": "Enum",
    "example_values": [
      "\"inbox\"",
      "\"today\"",
      "\"upcoming\"",
      "\"later\""
    ],
    "values": [
      {
        "name": "inbox",
        "comment": "In the inbox."
      },
      {
        "name": "later",
        "comment": "Scheduled for _later_."
      },
      {
        "name": "upcoming",
        "comment": "Scheduled for _upcoming_."
      },
      {
        "name": "today",
        "comment": "Scheduled for _today_."
      }
    ],
    "comment": "Scheduling status of this task for the user it is assigned to. This field\ncan only be set if `assignee` is non-null. If the task has an assignee\nand `assignee_status` is null or not present, Asana will set\n`assignee_status` to `inbox`.\n"
  },
  {
    "name": "created_at",
    "type": "String",
    "example_values": [
      "'2012-02-22T02:06:58.147Z'"
    ],
    "comment": "The time at which this task was created.\n"
  },
  {
    "name": "completed",
    "type": "Boolean",
    "example_values": [
      "false"
    ],
    "comment": "True if the task is currently marked complete, false if not.\n"
  },
  {
    "name": "completed_at",
    "type": "String",
    "example_values": [
      "'2012-02-22T02:06:58.147Z'"
    ],
    "comment": "The time at which this task was completed, or null if the task is incomplete.\n"
  },
  {
    "name": "custom_fields",
    "type": "Array",
    "example_values": [
      "[ { id: 1646, gid: \"1646\", name: 'Priority', type: 'enum', enum_value: { id: 126, gid: \"126\", name: 'P1' } }, ...]"
    ],
    "comment": "Array of custom fields applied to the task. These custom fields represent\nthe values recorded on this task for a particular custom field. For\nexample, these fields will contain an `enum_value` property for custom\nfields of type `enum`, a `string_value` property for custom fields of\ntype `string`, and so on. Please note that the id returned on each custom\nfield value *is identical* to the id of the custom field, which allows\nreferencing the custom field metadata through the\n`/custom_fields/custom_field-id` endpoint.\n"
  },
  {
    "name": "dependencies",
    "type": "Resource",
    "example_values": [
      "[ { id: 1234, gid: \"1234\" }, ... ]"
    ],
    "comment": "[Opt In](/developers/documentation/getting-started/input-output-options). Array of resources referencing tasks that this task depends on. The objects contain only the ID of the dependency.\n"
  },
  {
    "name": "dependents",
    "type": "Resource",
    "example_values": [
      "[ { id: 1234, gid: \"1234\" }, ... ]"
    ],
    "comment": "[Opt In](/developers/documentation/getting-started/input-output-options).\nArray of resources referencing tasks that depend on this task. The objects\ncontain only the ID of the dependent.\n"
  },
  {
    "name": "due_on",
    "type": "String",
    "example_values": [
      "'2012-03-26'"
    ],
    "comment": "Date on which this task is due, or null if the task has no due date. This\ntakes a date with YYYY-MM-DD format and should not be used together with\n`due_at`.\n"
  },
  {
    "name": "due_at",
    "type": "String",
    "example_values": [
      "'2012-02-22T02:06:58.147Z'"
    ],
    "comment": "Date and time on which this task is due, or null if the task has no due\ntime. This takes a UTC timestamp and should not be used together with\n`due_on`.\n"
  },
  {
    "name": "external",
    "type": "Map",
    "example_values": [
      "{ id: 'my_id', data: 'A blob of information.' }"
    ],
    "comment": "*OAuth Required*. *Conditional*. This field is returned only if external values are set or included by using [Opt In] (#input-output-options). The external field allows you to store app-specific metadata on tasks, including a gid that can be used to retrieve tasks and a data blob that can store app-specific character strings. Note that you will need to authenticate with Oauth to access or modify this data. Once an external gid is set, you can use the notation `external:custom_gid` to reference your object anywhere in the API where you may use the original object gid. See the page on Custom External Data for more details."
  },
  {
    "name": "followers",
    "type": "Array",
    "example_values": [
      "[ { id: 1123, gid: \"1123\", resource_type: \"user\", name: 'Mittens' }, ... ]"
    ],
    "comment": "Array of users following this task.\n"
  },
  {
    "name": "is_rendered_as_separator",
    "type": "Boolean",
    "example_values": [
      "false"
    ],
    "comment": "[Opt In](/developers/documentation/getting-started/input-output-options). In some contexts tasks can be rendered as a visual separator; for instance, subtasks can appear similar to [sections](/developers/api-reference/sections) without being true `section` objects. If a `task` object is rendered this way in any context it will have the property `is_rendered_as_separator` set to `true`.

**Note:** Until the default behavior for our API changes integrations must [opt in to the `new_sections` change](https://forum.asana.com/t/sections-are-dead-long-live-sections/33951) to modify the `is_rendered_as_separator` property.\n"
  },
  {
    "name": "liked",
    "type": "Boolean",
    "example_values": [
      "false"
    ],
    "comment": "True if the task is liked by the authorized user, false if not.\n"
  },
  {
    "name": "likes",
    "type": "Array",
    "example_values": [
      "[ { id: 1123, gid: \"1123\", resource_type: \"user\", name: 'Mittens' }, ... ]"
    ],
    "comment": "Array of users who have liked this task.\n"
  },
  {
    "name": "memberships",
    "type": "Array",
    "example_values": [
      "[ { project: { id: 1331, gid: \"1331\", name: 'Bugs' }, section: { id: 1123, gid: \"1123\", name: 'P1:' } }, ... ]"
    ],
    "comment": "Array of projects this task is associated with and the section it is in.\nAt task creation time, this array can be used to add the task to specific\nsections. After task creation, these associations can be modified using\nthe `addProject` and `removeProject` endpoints. Note that over time, more\ntypes of memberships may be added to this property.\n"
  },
  {
    "name": "modified_at",
    "type": "String",
    "example_values": [
      "'2012-02-22T02:06:58.147Z'"
    ],
    "comment": "The time at which this task was last modified.\n",
  },
  {
    "name": "name",
    "type": "String",
    "example_values": [
      "'Buy catnip'"
    ],
    "comment": "Name of the task. This is generally a short sentence fragment that fits\non a line in the UI for maximum readability. However, it can be longer.\n"
  },
  {
    "name": "notes",
    "type": "String",
    "example_values": [
      "'Mittens really likes the stuff from Humboldt.'"
    ],
    "comment": "More detailed, free-form textual information associated with the task.\n"
  },
  {
    "name": "html_notes",
    "type": "String",
    "example_values": [
      "'<body>Mittens <em>really</em> likes the stuff from Humboldt.</body>'"
    ],
    "comment": "[Opt In](/developers/documentation/getting-started/input-output-options). The notes of the text with formatting as HTML.\n"
  },
  {
    "name": "num_likes",
    "type": "Integer",
    "example_values": [
      "5"
    ],
    "comment": "The number of users who have liked this task.\n"
  },
  {
    "name": "num_subtasks",
    "type": "Integer",
    "example_values": [
      "5"
    ],
    "comment": "[Opt In](/developers/documentation/getting-started/input-output-options). The number of subtasks on this task.\n"
  },
  {
    "name": "parent",
    "type": "Task",
    "example_values": [
      "{ id: 1234, gid: \"1234\", name: 'Bug task' }"
    ],
    "comment": "The parent of this task, or `null` if this is not a subtask. This property\ncannot be modified using a PUT request but you can change it with the\n`setParent` endpoint. You can create subtasks by using the subtasks endpoint.\n"
  },
  {
    "name": "projects",
    "type": "Array",
    "example_values": [
      "[ { id: 1331, gid: \"1331\", name: 'Stuff to Buy' }, ... ]"
    ],
    "comment": "Array of projects this task is associated with. At task creation time,\nthis array can be used to add the task to many projects at once. After\ntask creation, these associations can be modified using the `addProject`\nand `removeProject` endpoints.\n"
  },
  {
    "name": "start_on",
    "type": "String",
    "example_values": [
      "'2012-03-26'"
    ],
    "comment": "Date on which this task is due, or null if the task has no start date. This\nfield takes a date with YYYY-MM-DD format.

**Note:** `due_on` or\n`due_at` must be present in the request when setting or unsetting the\n`start_on` parameter.\n"
  },
  {
    "name": "workspace",
    "type": "Workspace",
    "example_values": [
      "{ id: 14916, gid: \"14916\", name: 'My Workspace' }"
    ],
    "comment": "The workspace this task is associated with. Once created, task cannot be\nmoved to a different workspace. This attribute can only be specified at\ncreation time.\n"
  },
  {
    "name": "tags",
    "type": "Array",
    "example_values": [
      "[ { id: 59746, gid:\"59746\", name: 'Grade A' }, ... ]"
    ],
    "comment": "Array of tags associated with this task. This property may be specified on\ncreation using just an array of tag IDs. In order to change tags on an\nexisting task use `addTag` and `removeTag`.\n"
  }
]

export = resourceBase;


text:
package org.emmalanguage.mitos.operators;

import org.apache.flink.api.java.tuple.Tuple2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

public class GroupByString0Count1 extends BagOperator<Tuple2<String, Integer>, Tuple2<String, Integer>> {

	private static final Logger LOG = LoggerFactory.getLogger(GroupByString0Count1.class);

	private HashMap<String, Integer> hm;

	@Override
	public void openOutBag() {
		super.openOutBag();
		hm = new HashMap<>();
	}

	@Override
	public void pushInElement(Tuple2<String, Integer> e, int logicalInputId) {
		super.pushInElement(e, logicalInputId);
		Integer cnt = hm.get(e.f0);
		if (cnt == null) {
			hm.put(e.f0, e.f1);
		} else {
			hm.replace(e.f0, e.f1 + cnt);
		}
	}

	@Override
	public void closeInBag(int inputId) {
		super.closeInBag(inputId);
		for (String k : hm.keySet()) {
			out.collectElement(Tuple2.of(k, hm.get(k)));
		}
		out.closeBag();
		hm = null;
	}
}

redpajama_set_name: RedPajamaGithub


text:
void _itTestForSanitize(id self, int lineNumber, const char *fileName, NSString *name,
                        NSDictionary* fields) {
    it(name, ^{
        NSDictionary* sanitized = CMASanitizeParameterDictionaryForJSON(fields);

        __block NSError* error = nil;
        __block NSData* result = nil;

        expect(^{ result = [NSJSONSerialization dataWithJSONObject:sanitized
                                                           options:0
                                                             error:&error]; }).toNot.raiseAny();

        expect(result).toNot.beNil();
        expect(error).to.beNil();
    });
}

SpecBegin(Utilities)

describe(@"CMAClientAllowsChangingServer", ^{
    it(@"uses the default server by default", ^{
        CMAClient* client = [[CMAClient alloc] initWithAccessToken:@"XYZ"];

        CDAClient* deliveryClient = [client valueForKey:@"client"];
        XCTAssertEqualObjects(deliveryClient.configuration.server, @"api.contentful.com");
    });

    it(@"uses the specified server if changed", ^{
        CDAConfiguration* config = [CDAConfiguration defaultConfiguration];
        config.server = @"api.yolo.com";
        CMAClient* client = [[CMAClient alloc] initWithAccessToken:@"XYZ" configuration:config];

        CDAClient* deliveryClient = [client valueForKey:@"client"];
        XCTAssertEqualObjects(deliveryClient.configuration.server, @"api.yolo.com");
    });
});

describe(@"CMASanitizeParameterDictionaryForJSON", ^{
    CLLocationCoordinate2D location = CLLocationCoordinate2DMake(40.0, 50.0);
    NSData* locationValue = [NSData dataWithBytes:&location length:sizeof(location)];

    CDAAsset* asset = (CDAAsset*)[CDAResource resourceObjectForDictionary:@{ @"sys": @{ @"type": @"Asset", @"id": @"XXX" } } client:[CDAClient new] localizationAvailable:NO];

    _itTestForSanitize(self, __LINE__, __FILE__, @"sanitizes arrays of values",
                       @{ @"en-US": @{ @"someAssetArray": @[asset] } });

    _itTestForSanitize(self, __LINE__, __FILE__, @"sanitizes asset values",
                       @{ @"en-US": @{ @"someAsset": asset } });

    _itTestForSanitize(self, __LINE__, __FILE__, @"sanitizes date values",
                       @{ @"en-US": @{ @"someDate": [NSDate new] } });

    _itTestForSanitize(self, __LINE__, __FILE__, @"sanitizes location values",
                       @{ @"en-US": @{ @"someLocation": locationValue } });
});

SpecEnd


text:
using System.Collections.Generic;
using Couchbase.Lite;
using Couchbase.Lite.Internal;
using Couchbase.Lite.Util;
using Sharpen;

namespace Couchbase.Lite
{
    /// A result row from a CouchbaseLite view query.
    /// <remarks>
    /// A result row from a CouchbaseLite view query.
    /// Full-text and geo queries return subclasses -- see CBLFullTextQueryRow and CBLGeoQueryRow.
    /// </remarks>
    public class QueryRow
    {
        /// The row's key: this is the first parameter passed to the emit() call that generated the row.
        ///
        /// <remarks>The row's key: this is the first parameter passed to the emit() call that generated the row.
        ///     </remarks>
        private object key;

        /// The row's value: this is the second parameter passed to the emit() call that generated the row.
        ///
        /// <remarks>The row's value: this is the second parameter passed to the emit() call that generated the row.
        ///     </remarks>
        private object value;

        /// The database sequence number of the associated doc/revision.
        /// <remarks>The database sequence number of the associated doc/revision.</remarks>
        private long sequence;

        /// The ID of the document that caused this view row to be emitted.
        /// <remarks>
        /// The ID of the document that caused this view row to be emitted.
        /// This is the value of the "id" property of the JSON view row.
        /// It will be the same as the .documentID property, unless the map function caused a
        /// related document to be linked by adding an "_id" key to the emitted value; in this
        /// case .documentID will refer to the linked document, while sourceDocumentID always
        /// refers to the original document.
        /// In a reduced or grouped query the value will be nil, since the rows don't correspond
        /// to individual documents.
        /// </remarks>
        private string sourceDocumentId;

        /// The properties of the document this row was mapped from.
        /// <remarks>
        /// The properties of the document this row was mapped from.
        /// To get this, you must have set the .prefetch property on the query; else this will be nil.
        /// (You can still get the document properties via the .document property, of course. But it
        /// takes a separate call to the database. So if you're doing it for every row, using
        /// .prefetch and .documentProperties is faster.)
        /// </remarks>
        private IDictionary<string, object> documentProperties;

        private Database database;

        ///
        /// Constructor
        /// The database property will be filled in when I'm added to a QueryEnumerator.
        ///
        /// <remarks>
        /// Constructor
        /// The database property will be filled in when I'm added to a QueryEnumerator.
        /// </remarks>
        [InterfaceAudience.Private]
        internal QueryRow(string documentId, long sequence, object key, object value, IDictionary
            <string, object> documentProperties)
        {
            this.sourceDocumentId = documentId;
            this.sequence = sequence;
            this.key = key;
            this.value = value;
            this.documentProperties = documentProperties;
        }

        /// Gets the Database that owns the Query's View.
        /// <remarks>Gets the Database that owns the Query's View.</remarks>
        [InterfaceAudience.Public]
        public virtual Database GetDatabase()
        {
            return database;
        }

        /// The document this row was mapped from.
        /// <remarks>
        /// The document this row was mapped from.  This will be nil if a grouping was enabled in
        /// the query, because then the result rows don't correspond to individual documents.
        /// </remarks>
        [InterfaceAudience.Public]
        public virtual Document GetDocument()
        {
            if (GetDocumentId() == null)
            {
                return null;
            }
            Document document = database.GetDocument(GetDocumentId());
            document.LoadCurrentRevisionFrom(this);
            return document;
        }

        /// The row's key: this is the first parameter passed to the emit() call that generated the row.
        ///
        /// <remarks>The row's key: this is the first parameter passed to the emit() call that generated the row.
        ///     </remarks>
        [InterfaceAudience.Public]
        public virtual object GetKey()
        {
            return key;
        }

        /// The row's value: this is the second parameter passed to the emit() call that generated the row.
        ///
        /// <remarks>The row's value: this is the second parameter passed to the emit() call that generated the row.
        ///     </remarks>
        [InterfaceAudience.Public]
        public virtual object GetValue()
        {
            return value;
        }

        /// The ID of the document described by this view row.
        /// <remarks>
        /// The ID of the document described by this view row.  This is not necessarily the same as the
        /// document that caused this row to be emitted; see the discussion of the .sourceDocumentID
        /// property for details.
        /// </remarks>
        [InterfaceAudience.Public]
        public virtual string GetDocumentId()
        {
            // _documentProperties may have been 'redirected' from a different document
            if (documentProperties != null && documentProperties.Get("_id") != null && documentProperties
                .Get("_id") is string)
            {
                return (string)documentProperties.Get("_id");
            }
            else
            {
                return sourceDocumentId;
            }
        }

        /// The ID of the document that caused this view row to be emitted.
        /// <remarks>
        /// The ID of the document that caused this view row to be emitted.  This is the value of
        /// the "id" property of the JSON view row. It will be the same as the .documentID property,
        /// unless the map function caused a related document to be linked by adding an "_id" key to
        /// the emitted value; in this case .documentID will refer to the linked document, while
        /// sourceDocumentID always refers to the original document.  In a reduced or grouped query
        /// the value will be nil, since the rows don't correspond to individual documents.
        /// </remarks>
        [InterfaceAudience.Public]
        public virtual string GetSourceDocumentId()
        {
            return sourceDocumentId;
        }

        /// The revision ID of the document this row was mapped from.
        /// <remarks>The revision ID of the document this row was mapped from.</remarks>
        [InterfaceAudience.Public]
        public virtual string GetDocumentRevisionId()
        {
            string rev = null;
            if (documentProperties != null && documentProperties.ContainsKey("_rev"))
            {
                rev = (string)documentProperties.Get("_rev");
            }
            if (rev == null)
            {
                if (value is IDictionary)
                {
                    IDictionary<string, object> mapValue = (IDictionary<string, object>)value;
                    rev = (string)mapValue.Get("_rev");
                    if (rev == null)
                    {
                        rev = (string)mapValue.Get("rev");
                    }
                }
            }
            return rev;
        }

        /// The properties of the document this row was mapped from.
        /// <remarks>
        /// The properties of the document this row was mapped from.
        /// To get this, you must have set the -prefetch property on the query; else this will be nil.
        /// The map returned is immutable (run through Collections.unmodifiableMap)
        /// </remarks>
        [InterfaceAudience.Public]
        public virtual IDictionary<string, object> GetDocumentProperties()
        {
            return documentProperties != null ? Sharpen.Collections.UnmodifiableMap(documentProperties
                ) : null;
        }

        /// The local sequence number of the associated doc/revision.
        /// <remarks>The local sequence number of the associated doc/revision.</remarks>
        [InterfaceAudience.Public]
        public virtual long GetSequenceNumber()
        {
            return sequence;
        }

        ///
        /// Returns all conflicting revisions of the document, or nil if the
        /// document is not in conflict.
        ///
        /// <remarks>
        /// Returns all conflicting revisions of the document, or nil if the
        /// document is not in conflict.
        /// The first object in the array will be the default "winning" revision that shadows the others.
        /// This is only valid in an allDocuments query whose allDocsMode is set to Query.AllDocsMode.SHOW_CONFLICTS
        /// or Query.AllDocsMode.ONLY_CONFLICTS; otherwise it returns an empty list.
        /// </remarks>
        [InterfaceAudience.Public]
        public virtual IList<SavedRevision> GetConflictingRevisions()
        {
            Document doc = database.GetDocument(sourceDocumentId);
            IDictionary<string, object> valueTmp = (IDictionary<string, object>)value;
            IList<string> conflicts = (IList<string>)valueTmp.Get("_conflicts");
            if (conflicts == null)
            {
                conflicts = new AList<string>();
            }
            IList<SavedRevision> conflictingRevisions = new AList<SavedRevision>();
            foreach (string conflictRevisionId in conflicts)
            {
                SavedRevision revision = doc.GetRevision(conflictRevisionId);
                conflictingRevisions.AddItem(revision);
            }
            return conflictingRevisions;
        }

        /// Compare this against the given QueryRow for equality.
        /// <remarks>
        /// Compare this against the given QueryRow for equality.
        /// Implentation Note: This is used implicitly by -[LiveQuery update] to decide whether
        /// the query result has changed enough to notify the client. So it's important that it
        /// not give false positives, else the app won't get notified of changes.
        /// </remarks>
        /// <param name="o">the QueryRow to compare this instance with.</param>
        /// <returns>true if equal, false otherwise.</returns>
        [InterfaceAudience.Public]
        public override bool Equals(object @object)
        {
            if (@object == this)
            {
                return true;
            }
            if (!(@object is Couchbase.Lite.QueryRow))
            {
                return false;
            }
            Couchbase.Lite.QueryRow other = (Couchbase.Lite.QueryRow)@object;
            bool documentPropertiesEqual = Utils.IsEqual(documentProperties, other.GetDocumentProperties
                ());
            if (database == other.database && Utils.IsEqual(key, other.GetKey()) && Utils.IsEqual
                (sourceDocumentId, other.GetSourceDocumentId()) && documentPropertiesEqual)
            {
                // If values were emitted, compare them. Otherwise we have nothing to go on so check
                // if _anything_ about the doc has changed (i.e. the sequences are different.)
                if (value != null || other.GetValue() != null)
                {
                    return value.Equals(other.GetValue());
                }
                else
                {
                    return sequence == other.sequence;
                }
            }
            return false;
        }

        /// Return a string representation of this QueryRow.
        /// <remarks>
        /// Return a string representation of this QueryRow.
        /// The string is returned in JSON format.
        /// </remarks>
        /// <returns>the JSON string representing this QueryRow</returns>
        [InterfaceAudience.Public]
        public override string ToString()
        {
            return AsJSONDictionary().ToString();
        }

        [InterfaceAudience.Private]
        internal virtual void SetDatabase(Database database)
        {
            this.database = database;
        }

        /// <exclude></exclude>
        [InterfaceAudience.Private]
        public virtual IDictionary<string, object> AsJSONDictionary()
        {
            IDictionary<string, object> result = new Dictionary<string, object>();
            if (value != null || sourceDocumentId != null)
            {
                result.Put("key", key);
                if (value != null)
                {
                    result.Put("value", value);
                }
                result.Put("id", sourceDocumentId);
                if (documentProperties != null)
                {
                    result.Put("doc", documentProperties);
                }
            }
            else
            {
                result.Put("key", key);
                result.Put("error", "not_found");
            }
            return result;
        }
    }
}


text:
package org.uberfire.backend.server;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.inject.Named;

import com.thoughtworks.xstream.XStream;
import org.jboss.errai.bus.server.annotations.Service;
import org.uberfire.commons.cluster.ClusterServiceFactory;
import org.uberfire.io.IOService;
import org.uberfire.java.nio.IOException;
import org.uberfire.java.nio.file.FileVisitResult;
import org.uberfire.java.nio.file.NoSuchFileException;
import org.uberfire.java.nio.file.Path;
import org.uberfire.java.nio.file.SimpleFileVisitor;
import org.uberfire.java.nio.file.StandardDeleteOption;
import org.uberfire.java.nio.file.attribute.BasicFileAttributes;
import org.uberfire.workbench.model.PerspectiveDefinition;
import org.uberfire.workbench.model.SplashScreenFilter;
import org.uberfire.workbench.services.WorkbenchServices;

import static org.kie.soup.commons.validation.PortablePreconditions.checkNotNull;
import static org.uberfire.java.nio.file.Files.walkFileTree;

@Service
@ApplicationScoped
public class WorkbenchServicesImpl implements WorkbenchServices {

    public static final String PERSPECTIVE_EXTENSION = ".perspective";
    private final XStream xs = new XStream();
    @Inject
    @Named("configIO")
    private IOService ioService;
    @Inject
    private UserServicesImpl userServices;
    @Inject
    @Named("clusterServiceFactory")
    private ClusterServiceFactory clusterServiceFactory;

    @Override
    public void save(final String perspectiveId,
                     final PerspectiveDefinition perspective) {
        final String xml = xs.toXML(perspective);
        final Path perspectivePath = userServices.buildPath("perspectives",
                                                            perspectiveId + PERSPECTIVE_EXTENSION);
        try {
            ioService.startBatch(perspectivePath.getFileSystem());
            ioService.write(perspectivePath,
                            xml);
        } finally {
            ioService.endBatch();
        }
    }

    @Override
    public void save(SplashScreenFilter splashFilter) {
        final String xml = xs.toXML(splashFilter);
        final Path splashFilterPath = userServices.buildPath("splash",
                                                             splashFilter.getName() + ".filter");
        try {
            ioService.startBatch(splashFilterPath.getFileSystem());
            ioService.write(splashFilterPath,
                            xml);
        } finally {
            ioService.endBatch();
        }
    }

    @Override
    public PerspectiveDefinition loadPerspective(final String perspectiveName) {
        final Path perspectivePath = userServices.buildPath("perspectives",
                                                            perspectiveName + PERSPECTIVE_EXTENSION);
        if (ioService.exists(perspectivePath)) {
            final String xml = ioService.readAllString(perspectivePath);
            return (PerspectiveDefinition) xs.fromXML(xml);
        }

        return null;
    }

    @Override
    public Set<PerspectiveDefinition> loadPerspectives() {
        final Set<PerspectiveDefinition> result = new HashSet<PerspectiveDefinition>();
        final Path perspectivesPath = userServices.buildPath("perspectives");
        if (ioService.exists(perspectivesPath)) {

            walkFileTree(perspectivesPath,
                         new SimpleFileVisitor<Path>() {
                             public FileVisitResult visitFile(final Path file,
                                                              final BasicFileAttributes attrs) throws IOException {
                                 try {
                                     checkNotNull("file",
                                                  file);
                                     checkNotNull("attrs",
                                                  attrs);
                                     String fileName = file.getFileName().toString();
                                     if (fileName.endsWith(PERSPECTIVE_EXTENSION) && attrs.isRegularFile()) {
                                         String perspectiveName = fileName.substring(0,
                                                                                fileName.indexOf(PERSPECTIVE_EXTENSION));
                                         PerspectiveDefinition def = loadPerspective(perspectiveName);
                                         if (def != null) {
                                             result.add(def);
                                         }
                                     }
                                 } catch (final Exception ex) {
                                     return FileVisitResult.TERMINATE;
                                 }
                                 return FileVisitResult.CONTINUE;
                             }
                         });
        }
        return result;
    }

    @Override
    public void removePerspectiveState(final String perspectiveId) {
        final Path perspectivePath = userServices.buildPath("perspectives",
                                                            perspectiveId + ".perspective");
        if (ioService.exists(perspectivePath)) {
            ioService.delete(perspectivePath);
        }
    }

    @Override
    public void removePerspectiveStates() {
        final Path perspectivesPath = userServices.buildPath("perspectives");
        if (ioService.exists(perspectivesPath)) {
            try {
                ioService.startBatch(perspectivesPath.getFileSystem());
                ioService.delete(perspectivesPath,
                                 StandardDeleteOption.NON_EMPTY_DIRECTORIES);
            } finally {
                ioService.endBatch();
            }
        }
    }

    @Override
    public SplashScreenFilter loadSplashScreenFilter(String filterName) {
        final Path splashFilterPath = userServices.buildPath("splash",
                                                             filterName + ".filter");

        if (ioService.exists(splashFilterPath)) {
            final String xml = ioService.readAllString(splashFilterPath);
            return (SplashScreenFilter) xs.fromXML(xml);
        }

        return null;
    }

    @Override
    public Map<String, String> loadDefaultEditorsMap() {
        final Map<String, String> map = new HashMap<String, String>();
        try {
            final Path path = getPathToDefaultEditors();
            if (ioService.exists(path)) {
                for (String line : ioService.readAllLines(path)) {
                    if (!line.trim().startsWith("#")) {
                        String[] split = line.split("=");
                        map.put(split[0],
                                split[1]);
                    }
                }
            }

            return map;
        } catch (final NoSuchFileException e) {
            e.printStackTrace();
            return map;
        }
    }

    @Override
    public void saveDefaultEditors(final Map<String, String> properties) {
        final StringBuilder text = new StringBuilder();
        for (String key : properties.keySet()) {
            text.append(String.format("%s=%s",
                                      key,
                                      properties.get(key)));
        }
        final Path path = getPathToDefaultEditors();
        try {
            ioService.startBatch(path.getFileSystem());
            ioService.write(path,
                            text.toString());
        } finally {
            ioService.endBatch();
        }
    }

    @Override
    public boolean isWorkbenchOnCluster() {
        return clusterServiceFactory != null;
    }

    private Path getPathToDefaultEditors() {
        return userServices.buildPath("defaultEditors",
                                      null);
    }
}


text:
title:  "The Amazon Way: Principles 1-7"
date:   2017-05-06 19:43:00
category: post
tags: [leadership, amazon, book-review]
---

I just finished reading ["The Amazon Way - 14 Leadership Principles Behind the World's Most Disruptive Company"][amzn]{:target="_blank"} by John Rossman. The book was recommended to me by my manager at Expedia (a former Amazon employee himself) as a good case study for how Amazon operates. The principles covered in the book are dogma for Amazon employees: from warehouse worker to vice president, each employee is expected to exemplify the principles in every decision they make.

This post explores the first 7 principles and highlights a few insights that I had from each.

## 1. Obsess Over the Customer
  - Let the customer drive everything that you do
    - Jeff Bezos is known to physically bring an empty chair in the room in meetings, to make sure no one forgets the voice of the customer
  - Never leave a bitter taste in the customer's mouth
    - "We noticed you had poor video playback, so here's a full refund for the movie you just rented. We hope you use our service again!"
  - **The flywheel of growth**
    - Traffic —> Sellers —> Selection and Convenience —> Customer Experience —> Traffic…
    - Growth fuels a Lower Cost Structure, which leads to Lower Prices, which also leads to a better customer experience (part of the flywheel of growth)

## 2. Take Ownership of Results
  - You own your dependencies.
    - Control your dependencies, if possible. If not possible to control your dependencies, have strict agreements with them with contracts and Service Level Agreements (SLAs) defined.
  - For each dependency, you should have a hedge against it: if the dependency fails, what will you do to back it up?
    - **"it was a dependency issue" is never a good excuse.**
  - Never say "that's not my job."
    - Everyone is an owner of the business, the health of the business is everyone's job

## 3. Innovate and Simplify
  - Design capabilities "From the user backwards".
    -  For simple users, design simple solutions. Also allow more sophisticated to fiddle with complicated UIs as an "opt-in" feature.
  - Mimicry is often smarter and less risky for businesses…
    - Let the other guy find a market and determine a product, then slide in and make that product better!
  - **Forcing Functions**
    - Managers apply constraints to their organization to force creativity.

## 4. Leaders are Right - A lot
  - Powerpoints are not allowed — 5-7 page essays trimmed down to 2 pages are preferred
    - **The act of writing the essay allows you to digest the idea in a deeper way and uncover corner cases that may have been overlooked otherwise.**
  - Future Press Releases — Press release written in the future that highlights the successes of a product or idea under development
    - A type of forcing function, future press releases hold leaders accountable for their ideas.
  - Set up instrumentation (real-time data collection) to determine product success
    - Decisions should be made from data instead of from instinct.

## 5. Hire and Develop the Best
  - How **"fungible** is a candidate
    - The degree to which a candidate is capable at expanding in to new roles / business areas
  - Every hire is a reflection on those who hired him or her
    - Making a candidate's successes reflect well on those that hired, and candidate's failures reflect poorly, gives the hiring committee more skin in the game.
  - Don't reward B+ players, only A+ are compensated well.
    - Weeds out those who are only "just ok" at their jobs

## 6. Insist on the Highest Standards
  - Everyone should behave as a leader at the company
    - The principles outlined so far seem to apply just to "leaders" in their vocabulary: that's because everyone is supposed to act and behave as a leader at the company
  - **Service level agreements (SLA)**
    - SLAs set expectations for both internal and external facing services. Instrumentation is set up to measure every SLA in real time. Any deviation should be detected and remedied immediately.
  - None of the 14 principles include a "healthy work life balance"...
    - Jeff's expectations are often unreasonably high. If you can't exceed them, you're out.

## 7. Think Big
  - Amazon is still a "Day One" company
    - In Jeff's mind, Amazon still has a long way to go. Every day is "Day One"
  - Optimize for **Free Cash Flow (FCF)** instead of earnings or percentage margins.
    - Your business will invest in different ways to optimize for FCF vs Earnings. FCF fuels innovation, and optimizing for it is an investment in the long term instead of in short term profits.
  - Regret Minimization Framework
    - "Which choice will look best when you consider it not 6 months or 1 year from now, but decades in the future? Chances are that's the right option."

I'll cover the remaining 7 principles in the next installation.

[amzn]: https://www.amazon.com/Amazon-Way-Leadership-Principles-Disruptive/dp/1499296770


text:
function toggleTooltip(event, element) {
  var __x = Event.pointerX(event);
  var __y = Event.pointerY(event);
  //alert(__x+","+__y);
  element.style.top = __y + 5;
  element.style.left = __x - 40;
  element.toggle();
}


text:
// This code is distributed under MIT license. Copyright (c) 2013 George Mamaladze
// See license.txt or http://opensource.org/licenses/mit-license.php

namespace WordFinder.PatriciaTree
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;

    [DebuggerDisplay(
        "{m_Origin.Substring(0,m_StartIndex)} [ {m_Origin.Substring(m_StartIndex,m_PartitionLength)} ] {m_Origin.Substring(m_StartIndex + m_PartitionLength)}"
        )]
    public struct StringPartition : IEnumerable<char>
    {
        private readonly string m_Origin;
        private readonly int m_PartitionLength;
        private readonly int m_StartIndex;

        public StringPartition(string origin)
            : this(origin, 0, origin == null ? 0 : origin.Length)
        {
        }

        public StringPartition(string origin, int startIndex)
            : this(origin, startIndex, origin == null ? 0 : origin.Length - startIndex)
        {
        }

        public StringPartition(string origin, int startIndex, int partitionLength)
        {
            if (origin == null) throw new ArgumentNullException("origin");
            if (startIndex < 0) throw new ArgumentOutOfRangeException("startIndex", "The value must be non negative.");
            if (partitionLength < 0)
                throw new ArgumentOutOfRangeException("partitionLength", "The value must be non negative.");
            this.m_Origin = string.Intern(origin);
            this.m_StartIndex = startIndex;
            int availableLength = this.m_Origin.Length - startIndex;
            this.m_PartitionLength = Math.Min(partitionLength, availableLength);
        }

        public char this[int index]
        {
            get { return this.m_Origin[this.m_StartIndex + index]; }
        }

        public int Length
        {
            get { return this.m_PartitionLength; }
        }

        #region IEnumerable<char> Members

        public IEnumerator<char> GetEnumerator()
        {
            for (int i = 0; i < this.m_PartitionLength; i++)
            {
                yield return this[i];
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        #endregion

        public bool Equals(StringPartition other)
        {
            return string.Equals(this.m_Origin, other.m_Origin) && this.m_PartitionLength == other.m_PartitionLength &&
                   this.m_StartIndex == other.m_StartIndex;
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            return obj is StringPartition && this.Equals((StringPartition)obj);
        }

        public override int GetHashCode()
        {
            unchecked
            {
                int hashCode = (this.m_Origin != null ? this.m_Origin.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ this.m_PartitionLength;
                hashCode = (hashCode * 397) ^ this.m_StartIndex;
                return hashCode;
            }
        }

        public bool StartsWith(StringPartition other)
        {
            if (this.Length < other.Length)
            {
                return false;
            }

            for (int i = 0; i < other.Length; i++)
            {
                if (this[i] != other[i])
                {
                    return false;
                }
            }
            return true;
        }

        public SplitResult Split(int splitAt)
        {
            var head = new StringPartition(this.m_Origin, this.m_StartIndex, splitAt);
            var rest = new StringPartition(this.m_Origin, this.m_StartIndex + splitAt, this.Length - splitAt);
            return new SplitResult(head, rest);
        }

        public ZipResult ZipWith(StringPartition other)
        {
            int splitIndex = 0;
            using (IEnumerator<char> thisEnumerator = this.GetEnumerator())
            using (IEnumerator<char> otherEnumerator = other.GetEnumerator())
            {
                while (thisEnumerator.MoveNext() && otherEnumerator.MoveNext())
                {
                    if (thisEnumerator.Current != otherEnumerator.Current)
                    {
                        break;
                    }
                    splitIndex++;
                }
            }

            SplitResult thisSplitted = this.Split(splitIndex);
            SplitResult otherSplitted = other.Split(splitIndex);

            StringPartition commonHead = thisSplitted.Head;
            StringPartition restThis = thisSplitted.Rest;
            StringPartition restOther = otherSplitted.Rest;
            return new ZipResult(commonHead, restThis, restOther);
        }

        public override string ToString()
        {
            var result = new string(this.ToArray());
            return string.Intern(result);
        }

        public static bool operator ==(StringPartition left, StringPartition right)
        {
            return left.Equals(right);
        }

        public static bool operator !=(StringPartition left, StringPartition right)
        {
            return !(left == right);
        }
    }
}


text:
template: template.html
---

# Markdown


text:
namespace
{
const std::string username = TEST_USER_1_USERNAME;
const std::string password = TEST_USER_1_PASSWORD;
}  // end anonymous namespace

namespace api = mf::api;

BOOST_AUTO_TEST_CASE(UTPollChanges)
{
    boost::asio::io_service io_service;
    auto http_config = mf::http::HttpConfig::Create();
    http_config->SetWorkIoService(&io_service);

    api::SessionMaintainer stm(http_config);

    stm.SetLoginCredentials(api::credentials::Email{username, password});

    using DeviceGetStatusType = mf::api::device::get_status::Request;
    using DeviceGetChangesType = mf::api::device::get_changes::Request;
    using FolderGetInfoType = mf::api::folder::get_info::Request;
    using FileGetInfoType = mf::api::file::get_info::Request;

    using PollChangesType
            = mf::api::PollChanges<DeviceGetStatusType, DeviceGetChangesType,
                                   FolderGetInfoType, FileGetInfoType>;

    // Response types
    using File = typename PollChangesType::File;
    using Folder = typename PollChangesType::Folder;
    using FolderInfo = typename PollChangesType::FolderInfo;
    using FileInfo = typename PollChangesType::FileInfo;

    // Error types
    using DeviceGetStatusErrorType =
            typename PollChangesType::DeviceGetStatusErrorType;
    using DeviceGetChangesErrorType =
            typename PollChangesType::DeviceGetChangesErrorType;
    using GetInfoFileErrorType = typename PollChangesType::FileGetInfoErrorType;
    using GetInfoFolderErrorType =
            typename PollChangesType::FolderGetInfoErrorType;

    auto HandlePollChanges = [this, &io_service](
            uint32_t latest_device_revision,
            const std::vector<File> & deleted_files,
            const std::vector<Folder> & deleted_folders,
            const std::vector<FileInfo> & updated_files_info,
            const std::vector<FolderInfo> & updated_folders_info,
            const std::vector<DeviceGetStatusErrorType> & get_status_errors,
            const std::vector<DeviceGetChangesErrorType> & get_changes_errors,
            const std::vector<GetInfoFileErrorType> & get_info_file_errors,
            const std::vector<GetInfoFolderErrorType> &
                    get_info_folder_errors)  // TODO: Add errors
    {
        if (!get_status_errors.empty())
            BOOST_FAIL("device/get_status returned errors");

        if (!get_changes_errors.empty())
            BOOST_FAIL("device/get_changes returned errors");

        if (!get_info_file_errors.empty())
            BOOST_FAIL("file/get_info returned errors");

        if (!get_info_folder_errors.empty())
            BOOST_FAIL("folder/get_info returned errors");

        for (const auto & updated_file_info : updated_files_info)
        {
            if (updated_file_info.response_data)
            {
                const auto & data = *updated_file_info.response_data;
                std::cout << "Updated File Info: " << data.quickkey
                          << std::endl;
            }
            else
            {
                std::cout << "Updated File Info: Missing data!" << std::endl;
            }
        }

        for (const auto & updated_folder_info : updated_folders_info)
        {
            if (updated_folder_info.response_data)
            {
                const auto & data = *updated_folder_info.response_data;
                std::cout << "Updated Folder Info: " << data.folderkey
                          << std::endl;
            }
            else
            {
                std::cout << "Updated Folder Info: Missing data!" << std::endl;
            }
        }

        for (const auto & deleted_file : deleted_files)
        {
            std::cout << "Deleted File: " << deleted_file.quickkey << std::endl;
        }

        for (const auto & deleted_folder : deleted_folders)
        {
            std::cout << "Deleted Folder: " << deleted_folder.folderkey
                      << std::endl;
        }

        io_service.stop();
    };

    auto work_manager = mf::api::WorkManager::Create(&io_service);

    auto poll_changes = PollChangesType::Create(&stm, 0, work_manager,
                                                std::move(HandlePollChanges));
    poll_changes->Start();

    io_service.run();
}


text:
using System;
using System.Data.Entity.ModelConfiguration.Design.PluralizationServices;
using System.IO;
using System.Xml.Linq;

namespace XData.Data.Objects
{
    // TableName is a plural
    public class SingularPluralNameMap : NameMap
    {
        internal static EnglishPluralizationService pluralizationService = new EnglishPluralizationService();

        public SingularPluralNameMap(XElement nameMapConfig)
            : base(nameMapConfig)
        {
        }

        public SingularPluralNameMap(XElement nameMapConfig, string nameMapVersion)
            : base(nameMapConfig, nameMapVersion)
        {
        }

        internal protected override string GetElementName(string tableName)
        {
            if (ElementTableDictionary.ExistsInSecond(tableName)) return ElementTableDictionary.GetFirstValue(tableName);
            return pluralizationService.Singularize(tableName);
        }

        internal protected override string GetTableName(string elementName)
        {
            if (ElementTableDictionary.ExistsInFirst(elementName)) return ElementTableDictionary.GetSecondValue(elementName);
            return pluralizationService.Pluralize(elementName);
        }

        internal protected override string GetSetName(string elementName)
        {
            if (ElementSetDictionary.ExistsInFirst(elementName)) return ElementSetDictionary.GetSecondValue(elementName);
            return pluralizationService.Pluralize(elementName);
        }

        internal protected override string GetElementNameBySetName(string setName)
        {
            if (ElementSetDictionary.ExistsInSecond(setName)) return ElementSetDictionary.GetFirstValue(setName);
            return GetElementName(setName);
        }

    }
}


text:
//
//  SWOfflineRequestManger.h
//  SWNetworking
//
//  Created by Saman Kumara on 4/13/15.
//  Copyright (c) 2015 Saman Kumara. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//https://github.com/skywite
//

#import <Foundation/Foundation.h>
#import "SWRequestOperation.h"
@interface SWOfflineRequestManger : NSObject

/**
 *  This method need to trigger before start offline request.
 *
 *  @param seconds afte given secon saved request will be deleted automatically
 *
 *  @return return SWOfflineRequestManger object instance
 */
+ (instancetype)requestExpireTime:(long) seconds;

/**
 *  User can get shared instance using this
 *
 *  @return return SWOfflineRequestManger object instance
 */
+ (instancetype)sharedInstance;

/**
 *  users can get currently saved offline requests using this method
 *
 *  @return return NSArray will return NSArray object
 */
-(NSArray *)offlineOparations;

/**
 *  If you want to request to send later you can use this method
 *
 *  @param requestOperation the operation request that you want to save
 *
 *  @return return BOOL will return operation save status
 */
-(BOOL)addRequestForSendLater:(SWRequestOperation *)requestOperation;

/**
 *  if you want to delete reqeust from saved list you need to call this method
 *
 *  @param requestOperation requestOperation the operation request that you want to delete
 */
-(void)removeRequest:(SWRequestOperation *)requestOperation;

/**
 *  Calling this method all the saved request will be deleted
 */
-(void)removeAllRequests;

/**
 *  If you want to catch request when success/fail you need to call this method. you need to set tag relevent reqeust to identify request
 *
 *  @param success success success block
 *  @param fail    fail fail block
 */
-(void)requestSuccessBlock:(void (^)(SWRequestOperation *oparation, id responseObject))success requestFailBlock:(void (^)(SWRequestOperation *oparation,  NSError *error))fail;
@end


text:
/*****  VkBuffer Implementation  *****/

/************************
 ************************
 *****  Interfaces  *****
 ************************
 ************************/

/********************
 *****  System  *****
 ********************/

#include "Vk.h"

/******************
 *****  Self  *****
 ******************/

#include "VkBuffer.h"

/************************
 *****  Supporting  *****
 ************************/

/**************************
 **************************
 *****  Construction  *****
 **************************
 **************************/

VkBuffer::VkBuffer ()
: m_pStorage ((pointer_t)allocate (InitialBufferSize))
, m_sStorage (InitialBufferSize)
{
    m_pConsumerRegion = m_pProducerRegion = m_pStorage;
}

/*************************
 *************************
 *****  Destruction  *****
 *************************
 *************************/

VkBuffer::~VkBuffer () {
    deallocate (m_pStorage);
}

/*********************
 *********************
 *****  Control  *****
 *********************
 *********************/

bool VkBuffer::CompactAndGuarantee (size_t sMinimumProducerRegion) {
    size_t sConsumerRegion = ConsumerRegionSize ();
    if (m_pStorage < m_pConsumerRegion) {
	memcpy (m_pStorage, m_pConsumerRegion, sConsumerRegion);
	m_pConsumerRegion = m_pStorage;
	m_pProducerRegion = m_pStorage + sConsumerRegion;
    }

    size_t sProducerRegion = ProducerRegionSize ();
    if (sProducerRegion < sMinimumProducerRegion) {
	m_sStorage = (sConsumerRegion + sMinimumProducerRegion + BufferGrain - 1)
		   / BufferGrain * BufferGrain;
	m_pStorage = (pointer_t)reallocate (m_pStorage, m_sStorage);
	m_pConsumerRegion = m_pStorage;
	m_pProducerRegion = m_pStorage + sConsumerRegion;
    }

    return true;
}


text:
package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Input definition for planned failover.
 */
public class TestFailoverInput {
    /**
     * Planned failover input properties.
     */
    @JsonProperty(value = "properties")
    private TestFailoverInputProperties properties;

    /**
     * Get planned failover input properties.
     *
     * @return the properties value
     */
    public TestFailoverInputProperties properties() {
        return this.properties;
    }

    /**
     * Set planned failover input properties.
     *
     * @param properties the properties value to set
     * @return the TestFailoverInput object itself.
     */
    public TestFailoverInput withProperties(TestFailoverInputProperties properties) {
        this.properties = properties;
        return this;
    }

}


text:
package model

import "github.com/jack-zh/zgoblog/app/utils"

func generatePublishArticleIndex() {
	arr := make([]int, 0)
	for _, id := range contentsIndex["article"] {
		c := GetContentById(id)
		if c.Status == "publish" {
			arr = append(arr, id)
		}
	}
	contentsIndex["article-publish"] = arr
}

// GetPublishArticleList gets published article list and pager.
func GetPublishArticleList(page, size int) ([]*Content, *utils.Pager) {
	index := contentsIndex["article-publish"]
	pager := utils.NewPager(page, size, len(index))
	articles := make([]*Content, 0)
	if len(index) < 1 {
		return articles, pager
	}
	if page > pager.Pages {
		return articles, pager
	}
	for i := pager.Begin; i <= pager.End; i++ {
		articles = append(articles, GetContentById(index[i-1]))
	}
	return articles, pager
}

// GetArticleList gets articles list and pager no matter article status.
func GetArticleList(page, size int) ([]*Content, *utils.Pager) {
	index := contentsIndex["article"]
	pager := utils.NewPager(page, size, len(index))
	articles := make([]*Content, 0)
	if len(index) < 1 {
		return articles, pager
	}
	if page > pager.Pages {
		return articles, pager
	}
	for i := pager.Begin; i <= pager.End; i++ {
		articles = append(articles, GetContentById(index[i-1]))
	}
	return articles, pager
}

// GetPopularArticleList returns popular articles list.
// Popular articles are ordered by comment number.
func GetPopularArticleList(size int) []*Content {
	index := contentsIndex["article-pop"]
	pager := utils.NewPager(1, size, len(index))
	articles := make([]*Content, 0)
	if len(index) < 1 {
		return articles
	}
	if 1 > pager.Pages {
		return articles
	}
	for i := pager.Begin; i <= pager.End; i++ {
		articles = append(articles, GetContentById(index[i-1]))
	}
	return articles
}

// GetTaggedArticleList returns tagged articles list.
// These articles contains same one tag.
func GetTaggedArticleList(tag string, page, size int) ([]*Content, *utils.Pager) {
	index := contentsIndex["t-"+tag]
	pager := utils.NewPager(page, size, len(index))
	articles := make([]*Content, 0)
	if len(index) < 1 {
		return articles, pager
	}
	if page > pager.Pages {
		return articles, pager
	}
	for i := pager.Begin; i <= pager.End; i++ {
		articles = append(articles, GetContentById(index[i-1]))
	}
	return articles, pager
}


text:
title: Wordpress XML to Hugo MD
date: 2015-07-30
---
I've had a personal family blog in one form of another since 2002. <!--more--> For the last 10 years, give or take, I used [WordPress](https://wordpress.com/).  It's a very fine and handy tool; especially for non-technical types.  That's the real issue... I'm a *technical type*.  I started looking for something simpler, easier to maintain, and more secure.  That led me to *static site generators*.

I won't go into the details, but there [are a few to choose from](http://lmgtfy.com/?q=static+site+generators).  I settled on [Hugo](http://gohugo.io/).  I was mainly interested in it because it seemed easy, was written in [Go](http://golang.org/), and yes, it had a pretty website.

The Conversion
==============

One of the many nice things about WordPress is the ability to export your site into XML (side note, I *loath* XML).  There are some examples and script that do the conversion for you, but what fun would that be?  In the process, I learned that:

1.  Most HTML is Markdown compliant (that is, Markdown "understands" it)
2.  It's hard to tell an HTML-to-MD converter exactly how you want the HTML parsed.

On to the script!  [You can view the script here.](https://gist.github.com/mtik00/75c8f555b49365395e32).  I won't go over it in gory detail, but here are the basics.

WP exports everything, but I was only concerned with the post `body`, the date it was published (`pubDate`), the `category`'s (I called them `tags` in the script), the `title`, and where it should go.  The last part took some predetermined knowledge of how I wanted my Hugo site to be set up (read [`[permalinks]`](http://gohugo.io/extras/permalinks/)).  If you look at the exported XML file, there are *lots* of metadata that I'm ignoring (YMMV).

```python
    tree = ET.parse(xml_path)
    channel = tree.find("channel")
    wp_version_check(channel)

    for post in channel.findall("item"):
        print "post title:", post.find("title").text
```

WP puts all of the posts in a \<channel\> element.  Each post is located inside an \<item\> element.  So far, so good!  Now all we need to do is to loop through each item and grab the data we need.

```python
def wp_to_hugo_date(wp_date):
    """Converts a UTC time string from the WordPress XML to a Hugo time string."""
    date = time.strptime(wp_date, "%a, %d %b %Y %H:%M:%S +0000")
    date = calendar.timegm(date)
    ltime = time.localtime(date)
    date = time.strftime("%Y-%m-%dT%H:%M:%S", ltime)

    date += "%+03i:00" % (-1 * (time.altzone / 3600) if time.daylight else (-1 * (time.timezone / 3600)))
    return ltime, date
```

I'm using this function to convert the `pubDate` from WordPress to the format that Hugo uses.  Nothing real special here, although I'm sure there's a much better way to calculate the time zone.  The string-formatted `pubDate` will go into the posts front matter, and I parse `ltime` to figure out where the post should go.

That's the basics.  I ran this script on my entire WordPress XML dump (only 90+ pages, nothing too big).  It created all of the Markdown posts full of HTML.  It was up to me to then go in and adjust some of the HTML so it was rendered a little better by Hugo.  Most of my time spent was on downloading images, checking them into Git, and reworking the gallery posts to use my new template (which is awesome, because now I can use `{{ gallery path/to/gallery/folder }}` in my markdown).

The point is, however, I was able to have a fully functioning port of my WordPress blog to Hugo in a matter of hours (the script only took a second to run).  Woot!


text:
package org.broadleafcommerce.core.catalog.domain;

import org.broadleafcommerce.common.media.domain.Media;

import java.io.Serializable;

/**
 * @author Jeff Fischer
 */
public interface CategoryMediaXref extends Serializable {

    Long getId();

    void setId(Long id);

    Category getCategory();

    void setCategory(Category category);

    Media getMedia();

    void setMedia(Media media);

    String getKey();

    void setKey(String key);

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:paddingBottom="@dimen/layout_message_horizontal_margin"
    android:paddingLeft="?listPreferredItemPaddingLeft"
    android:paddingRight="?listPreferredItemPaddingRight"
    android:gravity="top|left|start"
    android:paddingTop="@dimen/layout_message_horizontal_margin">

    <ImageView
        android:id="@+id/message_user_icon"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_marginRight="-10dp" />

    <ImageView
        android:id="@+id/message_options"
        android:layout_width="35dp"
        android:layout_height="35dp"
        android:layout_marginRight="-7dp"
        android:clickable="true"
        app:srcCompat="@drawable/ic_arrow_left_chat" />

    <android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        card_view:cardCornerRadius="4dp"
        card_view:cardElevation="2dp"
        card_view:cardBackgroundColor="@android:color/white">

        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center_horizontal"
                android:layout_gravity="center_horizontal"
                android:orientation="horizontal"
                android:paddingLeft="@dimen/layout_message_horizontal_padding"
                android:paddingStart="@dimen/layout_message_horizontal_padding"
                android:paddingTop="@dimen/layout_message_title_vertical_padding"
                android:paddingBottom="@dimen/layout_message_title_vertical_padding"
                android:paddingEnd="@dimen/layout_message_horizontal_padding"
                android:paddingRight="@dimen/layout_message_horizontal_padding">

                <TextView
                    android:id="@+id/message_user_name"
                    style="@style/TextAppearance.AppCompat.Title"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1" />

            </LinearLayout>

            <TextView
                android:id="@+id/message_user"
                style="@style/TextAppearance.AppCompat.Subhead"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="top|start"
                android:gravity="top|start"
                android:paddingBottom="@dimen/layout_message_vertical_padding"
                android:paddingEnd="@dimen/layout_message_horizontal_padding"
                android:paddingLeft="@dimen/layout_message_horizontal_padding"
                android:paddingRight="@dimen/layout_message_horizontal_padding"
                android:paddingStart="@dimen/layout_message_horizontal_padding" />
        </LinearLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>


text:
#ifndef _TIPC_BCAST_H
#define _TIPC_BCAST_H

#include <linux/tipc_config.h>
#include "link.h"
#include "node.h"

/**
 * struct tipc_bcbearer_pair - a pair of bearers used by broadcast link
 * @primary: pointer to primary bearer
 * @secondary: pointer to secondary bearer
 *
 * Bearers must have same priority and same set of reachable destinations
 * to be paired.
 */

struct tipc_bcbearer_pair {
	struct tipc_bearer *primary;
	struct tipc_bearer *secondary;
};

#define	BCBEARER		MAX_BEARERS

/**
 * struct tipc_bcbearer - bearer used by broadcast link
 * @bearer: (non-standard) broadcast bearer structure
 * @media: (non-standard) broadcast media structure
 * @bpairs: array of bearer pairs
 * @bpairs_temp: temporary array of bearer pairs used by tipc_bcbearer_sort()
 * @remains: temporary node map used by tipc_bcbearer_send()
 * @remains_new: temporary node map used tipc_bcbearer_send()
 *
 * Note: The fields labelled "temporary" are incorporated into the bearer
 * to avoid consuming potentially limited stack space through the use of
 * large local variables within multicast routines.  Concurrent access is
 * prevented through use of the spinlock "bclink_lock".
 */
struct tipc_bcbearer {
	struct tipc_bearer bearer;
	struct tipc_media media;
	struct tipc_bcbearer_pair bpairs[MAX_BEARERS];
	struct tipc_bcbearer_pair bpairs_temp[TIPC_MAX_LINK_PRI + 1];
	struct tipc_node_map remains;
	struct tipc_node_map remains_new;
};

/**
 * struct tipc_bclink - link used for broadcast messages
 * @lock: spinlock governing access to structure
 * @link: (non-standard) broadcast link structure
 * @node: (non-standard) node structure representing b'cast link's peer node
 * @bcast_nodes: map of broadcast-capable nodes
 * @retransmit_to: node that most recently requested a retransmit
 *
 * Handles sequence numbering, fragmentation, bundling, etc.
 */
struct tipc_bclink {
	spinlock_t lock;
	struct tipc_link link;
	struct tipc_node node;
	struct sk_buff_head arrvq;
	struct sk_buff_head inputq;
	struct tipc_node_map bcast_nodes;
	struct tipc_node *retransmit_to;
};

struct tipc_node;
extern const char tipc_bclink_name[];

/**
 * tipc_nmap_equal - test for equality of node maps
 */
static inline int tipc_nmap_equal(struct tipc_node_map *nm_a,
				  struct tipc_node_map *nm_b)
{
	return !memcmp(nm_a, nm_b, sizeof(*nm_a));
}

int tipc_bclink_init(struct net *net);
void tipc_bclink_stop(struct net *net);
void tipc_bclink_add_node(struct net *net, u32 addr);
void tipc_bclink_remove_node(struct net *net, u32 addr);
struct tipc_node *tipc_bclink_retransmit_to(struct net *tn);
void tipc_bclink_acknowledge(struct tipc_node *n_ptr, u32 acked);
void tipc_bclink_rcv(struct net *net, struct sk_buff *buf);
u32  tipc_bclink_get_last_sent(struct net *net);
u32  tipc_bclink_acks_missing(struct tipc_node *n_ptr);
void tipc_bclink_update_link_state(struct tipc_node *node,
				   u32 last_sent);
int  tipc_bclink_reset_stats(struct net *net);
int  tipc_bclink_set_queue_limits(struct net *net, u32 limit);
void tipc_bcbearer_sort(struct net *net, struct tipc_node_map *nm_ptr,
			u32 node, bool action);
uint  tipc_bclink_get_mtu(void);
int tipc_bclink_xmit(struct net *net, struct sk_buff_head *list);
void tipc_bclink_wakeup_users(struct net *net);
int tipc_nl_add_bc_link(struct net *net, struct tipc_nl_msg *msg);
int tipc_nl_bc_link_set(struct net *net, struct nlattr *attrs[]);
void tipc_bclink_input(struct net *net);
void tipc_bclink_sync_state(struct tipc_node *n, struct tipc_msg *msg);

#endif


text:
<?php

namespace Illuminate\Contracts\Queue;

interface ClearableQueue
{
    /**
     * Delete all of the jobs from the queue.
     *
     * @param  string  $queue
     * @return int
     */
    public function clear($queue);
}


text:
C and C++ Source Code Snippets

### Compilation

You can compile most of snippets using 'make <name-of-file-without-extension>'

For example:

        $ make ascii
        $ make sort
        $ make time

* Some snippets have a makefile and should be used to compile the code.
* Use cmake if available


text:
package org.sleuthkit.autopsy.casemodule;

import java.awt.Component;
import java.awt.Dialog;
import java.io.File;
import java.text.MessageFormat;
import java.util.logging.Level;
import javax.swing.JComponent;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.WizardDescriptor;
import org.openide.util.HelpCtx;
import org.openide.util.NbBundle;
import org.openide.util.actions.CallableSystemAction;
import org.openide.util.actions.SystemAction;
import org.sleuthkit.autopsy.coreutils.Logger;

/**
 * Action to open the New Case wizard.
 */
 final class NewCaseWizardAction extends CallableSystemAction {

    private WizardDescriptor.Panel<WizardDescriptor>[] panels;

    private static final Logger logger = Logger.getLogger(NewCaseWizardAction.class.getName());

    @Override
    public void performAction() {
        // there's a case open
        if (Case.existsCurrentCase()) {
            // show the confirmation first to close the current case and open the "New Case" wizard panel
            String closeCurrentCase = NbBundle
                    .getMessage(this.getClass(), "NewCaseWizardAction.closeCurCase.confMsg.msg");
            NotifyDescriptor d = new NotifyDescriptor.Confirmation(closeCurrentCase,
                                                                   NbBundle.getMessage(this.getClass(),
                                                                                "NewCaseWizardAction.closeCurCase.confMsg.title"),
                                                                   NotifyDescriptor.YES_NO_OPTION, NotifyDescriptor.WARNING_MESSAGE);
            d.setValue(NotifyDescriptor.NO_OPTION);

            Object res = DialogDisplayer.getDefault().notify(d);
            if (res != null && res == DialogDescriptor.YES_OPTION) {
                try {
                    Case.getCurrentCase().closeCase(); // close the current case
                    newCaseAction(); // start the new case creation process
                } catch (Exception ex) {
                    Logger.getLogger(NewCaseWizardAction.class.getName()).log(Level.WARNING, "Error closing case.", ex); //NON-NLS
                }
            }
        } else {
            newCaseAction();
        }
    }

    /**
     * The method to perform new case creation
     */
    private void newCaseAction() {
        WizardDescriptor wizardDescriptor = new WizardDescriptor(getPanels());
        // {0} will be replaced by WizardDesriptor.Panel.getComponent().getName()
        wizardDescriptor.setTitleFormat(new MessageFormat("{0}"));
        wizardDescriptor.setTitle(NbBundle.getMessage(this.getClass(), "NewCaseWizardAction.newCase.windowTitle.text"));
        Dialog dialog = DialogDisplayer.getDefault().createDialog(wizardDescriptor);
        dialog.setVisible(true);
        dialog.toFront();

        boolean finished = wizardDescriptor.getValue() == WizardDescriptor.FINISH_OPTION; // check if it finishes (it's not cancelled)
        boolean isCancelled = wizardDescriptor.getValue() == WizardDescriptor.CANCEL_OPTION; // check if the "Cancel" button is pressed

        // if the finish button is pressed (not cancelled)
        if (finished) {
            // now start the 'Add Image' wizard
            //TODO fix for local
            AddImageAction addImageAction = SystemAction.get(AddImageAction.class);
            addImageAction.actionPerformed(null);
        }

        // if Cancel button is pressed
        if (isCancelled) {
            String createdDirectory = (String) wizardDescriptor.getProperty("createdDirectory"); //NON-NLS
            if(createdDirectory != null) {
                logger.log(Level.INFO, "Deleting a created case directory due to isCancelled set, dir: " + createdDirectory); //NON-NLS
                Case.deleteCaseDirectory(new File(createdDirectory));
            }
            // if there's case opened, close the case
            if (Case.existsCurrentCase()) {
                // close the previous case if there's any
                CaseCloseAction closeCase = SystemAction.get(CaseCloseAction.class);
                closeCase.actionPerformed(null);
            }
        }
        panels = null; // reset the panel
    }

    /**
     * Initialize panels representing individual wizard's steps and sets
     * various properties for them influencing wizard appearance.
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    private WizardDescriptor.Panel<WizardDescriptor>[] getPanels() {
        if (panels == null) {
            panels = new WizardDescriptor.Panel[]{
                        new NewCaseWizardPanel1(),
                        new NewCaseWizardPanel2()
                    };
            String[] steps = new String[panels.length];
            for (int i = 0; i < panels.length; i++) {
                Component c = panels[i].getComponent();
                // Default step name to component name of panel. Mainly useful
                // for getting the name of the target chooser to appear in the
                // list of steps.
                steps[i] = c.getName();
                if (c instanceof JComponent) { // assume Swing components
                    JComponent jc = (JComponent) c;
                    // Sets step number of a component
                    jc.putClientProperty("WizardPanel_contentSelectedIndex", new Integer(i));
                    // Sets steps names for a panel
                    jc.putClientProperty("WizardPanel_contentData", steps);
                    // Turn on subtitle creation on each step
                    jc.putClientProperty("WizardPanel_autoWizardStyle", Boolean.TRUE);
                    // Show steps on the left side with the image on the background
                    jc.putClientProperty("WizardPanel_contentDisplayed", Boolean.TRUE);
                    // Turn on numbering of all steps
                    jc.putClientProperty("WizardPanel_contentNumbered", Boolean.TRUE);
                }
            }
        }
        return panels;
    }

    @Override
    public String getName() {
        return NbBundle.getMessage(this.getClass(), "NewCaseWizardAction.getName.text");
    }

    @Override
    public String iconResource() {
        return null;
    }

    @Override
    public HelpCtx getHelpCtx() {
        return HelpCtx.DEFAULT_HELP;
    }

    @Override
    protected boolean asynchronous() {
        return false;
    }
}


text:
* Presenter: [Victor Zabalza](https://github.com/zblz/)
* Duration: 15 + 5 min

* Slides: [naima-talk-PyGamma15.pdf](
  https://github.com/gammapy/PyGamma15/blob/gh-pages/talks/naima/naima-talk-PyGamma15.pdf)

## Abstract

The ultimate goal when observing and analyzing the non-thermal spectra from
astrophysical sources is to understand the acceleration and cooling processes
that affect relativistic particle populations. To do so, we must bridge the gap
between the observed photon spectra and the parent particle population that
gave rise to it. In this talk I will give an overview of the general problems
faced when trying to infer the physical processes responsible for the observed
spectra, and will present [naima](https://github.com/zblz/naima), a Python
package that provides an open-source implementation of radiative models and
tools to fit them to nonthermal spectra.

## Outline

* Astrophysical motivation for radiative modelling of sources
* Particle distribution evolution (cooling, escape)
* Overview of high-energy radiation processes with comments on numerical
  implementation
  - Synchrotron
  - Inverse Compton
  - Nonthermal bremsstrahlung
  - Neutral pion decay
* Overview of Naima capabilities for radiative modelling
* Example of their use on a HESS source (preview of tutorial)

## References

* [Zabalza (2015), "naima: a Python package for inference of relativistic
  particle energy distributions from observed nonthermal
  spectra"](http://labs.adsabs.harvard.edu/adsabsadsabs/abs/2015arXiv150903319Z/)
* [Naima documentation](http://naima.readthedocs.org), specially the [Radiative
  Models](http://naima.readthedocs.org/en/latest/radiative.html) and [MCMC
  intro](http://naima.readthedocs.org/en/latest/mcmc.html)
* The details of MCMC sampling with emcee have been covered in the [stats
  talk](https://github.com/gammapy/PyGamma15/tree/gh-pages/talks/analysis-stats)
  and
  [tutorial](https://github.com/gammapy/PyGamma15/tree/gh-pages/tutorials/analysis-stats)
  by Michal Schmelling.
* [Naima tutorial later in the
  week](https://github.com/gammapy/PyGamma15/tree/gh-pages/tutorials/naima)


text:
'use strict';

export default function routes($stateProvider) {
  'ngInject';

  $stateProvider.state('area', {
    url: '/area',
    template: require('./area.html'),
    controller: 'AreaController',
    controllerAs: 'area',
    authenticate: 'admin'
  });

  $stateProvider.state('areaSetUp', {
    url: '/areaSetUp',
    template: require('./areaSetUp.html'),
    controller: 'AreaSetUpController',
    controllerAs: 'areaSetUp',
    authenticate: 'admin'
  });
};


text:
# include <string.h>
# include <fitsio.h>
# include "ctables.h"

static void extractKeyword (char *card, char *keyword);
static int keywordExists (fitsfile *fptr, char *keyword, int *status);

void tbCopyPrimary (fitsfile *template_fptr, fitsfile *fptr, int *status) {

/* Copy the primary header from template_fptr to fptr.
   The current HDU does not need to be the primary HDU, either in the
   template or in the output file.  This function will save the current
   HDUs, move to the primary for both files, copy the header, and then
   move back to the saved HDUs.
arguments:
fitsfile *template_fptr i: CFITSIO descriptor for template table
fitsfile *fptr          i: CFITSIO descriptor for table to receive keywords
int *status             o: CFITSIO status (0 is OK)
*/

        char card[SZ_FITS_STR+1];       /* FITS header record */
        char keyword[SZ_FITS_STR+1];    /* keyword from card */
        int nkeywords;                  /* number of keywords in header */
        int keynum;                     /* keyword number (one indexed) */
        int hdunum, hdutype;
        int save_hdunum, save_template_hdunum;

        /* save the current HDU numbers of the template and new table */
        /* fits_get_hdu_num = ffghdn */
        fits_get_hdu_num (template_fptr, &save_template_hdunum);
        fits_get_hdu_num (fptr, &save_hdunum);

        /* move to the primary header of each file */
        hdunum = 1;
        /* fits_movabs_hdu = ffmahd */
        fits_movabs_hdu (template_fptr, hdunum, &hdutype, status);
        fits_movabs_hdu (fptr, hdunum, &hdutype, status);

        /* fits_get_hdrspace = ffghsp */
        fits_get_hdrspace (template_fptr, &nkeywords, NULL, status);

        /* Copy keywords from the template to the current header, starting
           with keyword number 3 in order to skip SIMPLE and BITPIX.
        */
        for (keynum = 3;  keynum <= nkeywords;  keynum++) {
            /* fits_read_record = ffgrec */
            fits_read_record (template_fptr, keynum, card, status);
            if (strncmp (card, "NAXIS", 5) == 0)
                continue;
            if (strncmp (card, "ORIGIN", 6) == 0)
                continue;
            if (strncmp (card, "IRAF-TLM", 8) == 0)
                continue;
            if (strncmp (card,
                "COMMENT   FITS (Flexible Image Transport System)", 48) == 0)
                continue;
            if (strncmp (card,
                "COMMENT   and Astrophysics', volume 376, page 359", 49) == 0)
                continue;
            extractKeyword (card, keyword);
            if (keywordExists (fptr, keyword, status))
                continue;
            /* fits_write_record = ffprec */
            fits_write_record (fptr, card, status);
        }

        /* fits_write_date = ffpdat */
        fits_write_date (fptr, status);         /* write the DATE keyword */

        /* return to the saved HDU numbers */
        fits_movabs_hdu (template_fptr, save_template_hdunum,
                &hdutype, status);
        fits_movabs_hdu (fptr, save_hdunum, &hdutype, status);
}

void tbCopyHeader (fitsfile *template_fptr, fitsfile *fptr, int *status) {

/* Copy an extension header from template_fptr to fptr.  Keywords in the
   current template HDU will be copied to the current output HDU.
arguments:
fitsfile *template_fptr i: CFITSIO descriptor for template table
fitsfile *fptr          i: CFITSIO descriptor for table to receive keywords
int *status             o: CFITSIO status (0 is OK)
*/

        char card[SZ_FITS_STR+1];       /* FITS header record */
        char keyword[SZ_FITS_STR+1];    /* keyword from card */
        int nkeywords;                  /* number of keywords in header */
        int keynum;                     /* keyword number (one indexed) */

        /* fits_get_hdrspace = ffghsp */
        fits_get_hdrspace (template_fptr, &nkeywords, NULL, status);

        /* Copy keywords from the template to the current header, starting
           with keyword number 3 in order to skip XTENSION and BITPIX.
        */
        for (keynum = 3;  keynum <= nkeywords;  keynum++) {
            /* fits_read_record = ffgrec */
            fits_read_record (template_fptr, keynum, card, status);
            if (strncmp (card, "NAXIS", 5) == 0)
                continue;
            if (strncmp (card, "TTYPE", 5) == 0)
                continue;
            if (strncmp (card, "TFORM", 5) == 0)
                continue;
            if (strncmp (card, "TUNIT", 5) == 0)
                continue;
            if (strncmp (card, "TDISP", 5) == 0)
                continue;
            extractKeyword (card, keyword);
            if (strcmp (keyword, "PCOUNT") == 0)
                continue;
            if (strcmp (keyword, "GCOUNT") == 0)
                continue;
            if (strcmp (keyword, "TFIELDS") == 0)
                continue;
            if (strcmp (keyword, "ORIGIN") == 0)
                continue;
            if (keywordExists (fptr, keyword, status))
                continue;
            /* fits_write_record = ffprec */
            fits_write_record (fptr, card, status);
        }
}

static void extractKeyword (char *card, char *keyword) {

/* Copy the first eight characters of card to keyword, then trim
   trailing blanks.
arguments:
char *card              i: a header record
char *keyword           o: the keyword extracted from 'card'
*/

        int i;

        copyString (keyword, card, 8);
        for (i = strlen (keyword) - 1;  i > 0;  i--) {
            if (keyword[i] == ' ')
                keyword[i] = '\0';
        }
}

static int keywordExists (fitsfile *fptr, char *keyword, int *status) {

/* Does the specified keyword already exist in the current HDU?
   This is not a general-purpose function; it's used in this file only.
   A peculiarity of this function (which is appropriate in the context of
   its use in this file) is that for keywords HISTORY, COMMENT or blank,
   the function value will be 0, i.e. the keywords are considered to
   not exist, even if they do.  This is so that all HISTORY, all COMMENT,
   and all blank keywords will be copied.
arguments:
fitsfile *fptr          i: CFITSIO descriptor for table
char *keyword           i: a keyword name
int *status             o: CFITSIO status (0 is OK); it is not an error
                           if the keyword does not exist

function value          o: 1 if a non-commentary keyword exists, 0 otherwise
*/

        char value[SZ_FITS_STR+1];
        char comment[SZ_FITS_STR+1];
        int flag = 0;

        /* History, comment, and blank keywords are flagged as not existing,
           because we want all of them.
        */
        if (strcmp (keyword, "HISTORY") == 0 ||
            strcmp (keyword, "COMMENT") == 0 ||
            keyword[0] == ' ')
            return 0;

        /* fits_read_keyword = ffgkey */
        fits_read_keyword (fptr, keyword, value, comment, status);
        if (*status == 0) {
            flag = 1;
        } else if (*status == KEY_NO_EXIST) {
            flag = 0;
            *status = 0;
        } else {
            flag = 0;
        }

        return flag;
}


text:
package com.hass.ali.doctorsapp;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;

import java.util.List;

public class PatinetListAdapter extends RecyclerView.Adapter<PatinetListAdapter.MyViewHolder>{

    private List<PatientBean> patienBeanList;
    private Context ctx;
    public PatinetListAdapter(List<PatientBean> patienBeanList, Context ctx) {
        this.patienBeanList = patienBeanList;
        this.ctx=ctx;
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView name,number;

       // public ImageView profilePic;

        public MyViewHolder(View view) {
            super(view);

            this.name = (TextView) view.findViewById(R.id.patient_name);
            this.number = (TextView) view.findViewById(R.id.number);

        }
    }

    @Override
    public PatinetListAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.patient_list_screen_layout, parent, false);
        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(PatinetListAdapter.MyViewHolder holder, final int position) {

        final PatientBean scheBean = patienBeanList.get(position);

        holder.name.setText(scheBean.getPatientName());
        holder.number.setText(scheBean.getContactNo());

    }

    @Override
    public int getItemCount() {
        return patienBeanList.size();
    }

    public void updateList(List<PatientBean> patienBeanList) {
        this.patienBeanList = patienBeanList;
        notifyDataSetChanged();
    }

}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {TimeFilter} from './time-filter';
import {Field} from '@domain/datasource/datasource';

export class TimeAllFilter extends TimeFilter {
  constructor(field: Field) {
    super(field);
    this.type = 'time_all';
  }

  public toServerSpec() {
    return super.toServerSpec();
  } // function - toServerSpec
}


text:
import argparse
import glob
import os
import sys
import traceback

import numpy
import openpyxl

from . import las

class ExcelConverter(object):

    """Provide ability to export LAS data into an Excel spreadsheet.

    Arguments:
        las (:class:`lasio.LASFile` object)

    """

    def __init__(self, las):
        self.set_las(las)

    def set_las(self, las):
        """Set LASFile object.

        Arguments:
            las (:class:`lasio.LASFile` object)

        """
        self.las = las
        self.generate_workbook()
        return self

    def generate_workbook(self):
        """Generate the Excel workbook object.

        Two sheets are created:

        * Header: contains all the header sections and metadata
        * Curves: contains the data

        """
        wb = openpyxl.Workbook()
        header = wb["Sheet"]
        header.title = "Header"
        curves = wb.create_sheet()
        curves.title = "Curves"

        def write_cell(sh, i, j, value):
            c = sh.cell(row=i + 1, column=j + 1)
            c.value = value

        write_cell(header, 0, 0, "Section")
        write_cell(header, 0, 1, "Mnemonic")
        write_cell(header, 0, 2, "Unit")
        write_cell(header, 0, 3, "Value")
        write_cell(header, 0, 4, "Description")

        sections = [
            ("~Version", self.las.version),
            ("~Well", self.las.well),
            ("~Parameter", self.las.params),
            ("~Curves", self.las.curves),
        ]

        n = 1
        for sect_name, sect in sections:
            for i, item in enumerate(sect.values()):
                write_cell(header, n, 0, sect_name)
                write_cell(header, n, 1, item.mnemonic)
                write_cell(header, n, 2, item.unit)
                write_cell(header, n, 3, item.value)
                write_cell(header, n, 4, item.descr)
                n += 1

        for i, curve in enumerate(self.las.curves):
            write_cell(curves, 0, i, curve.mnemonic)
            for j, value in enumerate(curve.data):
                if numpy.isnan(value):
                    write_cell(curves, j + 1, i, "")
                else:
                    write_cell(curves, j + 1, i, value)

        self.workbook = wb
        return self

    def write(self, xlsxfn):
        """Write the Excel workbook to an ``.xlsx`` file.

        Arguments:
            xlsxfn (str): filename (will be overwritten without warning)

        """
        assert xlsxfn.lower().endswith(".xlsx")

        self.workbook.save(xlsxfn)

def main():
    args = get_parser().parse_args(sys.argv[1:])
    lasfn = args.LAS_filename
    xlsxfn = args.XLSX_filename

    l = las.LASFile(lasfn)
    converter = ExcelConverter(l)
    converter.write(xlsxfn)

def get_parser():
    parser = argparse.ArgumentParser(
        "Convert LAS file to XLSX",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    parser.add_argument("LAS_filename")
    parser.add_argument("XLSX_filename")
    return parser

def main_bulk():
    args = get_bulk_parser().parse_args(sys.argv[1:])
    paths = []
    if args.recursive:
        for dirpath, dirnames, filenames in os.walk(args.path):
            paths.append(dirpath)
    else:
        paths.append(args.path)

    for path in paths:
        for lasfn in glob.glob(os.path.join(path, args.glob)):
            xlsxfn = lasfn.lower().replace(".las", ".xlsx")
            print("Converting %s -> %s" % (lasfn, xlsxfn))
            try:
                l = las.LASFile(lasfn, ignore_header_errors=args.ignore_header_errors)
                converter = ExcelConverter(l)
                converter.write(xlsxfn)
            except:
                print(
                    "Failed to convert file. Error message:\n" + traceback.format_exc()
                )

def get_bulk_parser():
    parser = argparse.ArgumentParser(
        "Convert LAS files to XLSX",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    parser.add_argument(
        "-g", "--glob", default="*.las", help="Match LAS files with this pattern"
    )
    parser.add_argument(
        "-r",
        "--recursive",
        action="store_true",
        help="Recurse through subfolders.",
        default=False,
    )
    parser.add_argument(
        "-i",
        "--ignore-header-errors",
        action="store_true",
        help="Ignore header section errors.",
        default=False,
    )
    parser.add_argument("path")
    return parser

if __name__ == "__main__":
    main()


text:
package cn.aezo.springboot.rabbitmq.consumer;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * Created by smalle on 2017/7/23.
 */
@Component
@RabbitListener(queues = "hello")
public class Consumer {

    @RabbitHandler
    public void process(String msg) {
        System.out.println("Consumer: " + msg);
    }
}