text:
static char *FMOD_ErrorString(int errcode)
{
	switch (errcode)
	{
		case FMOD_ERR_NONE:				return "No errors";
		case FMOD_ERR_BUSY:				return "Cannot call this command after FSOUND_Init.  Call FSOUND_Close first.";
		case FMOD_ERR_UNINITIALIZED:	return "This command failed because FSOUND_Init was not called";
		case FMOD_ERR_PLAY:				return "Playing the sound failed.";
		case FMOD_ERR_INIT:				return "Error initializing output device.";
		case FMOD_ERR_ALLOCATED:		return "The output device is already in use and cannot be reused.";
		case FMOD_ERR_OUTPUT_FORMAT:	return "Soundcard does not support the features needed for this soundsystem (16bit stereo output)";
		case FMOD_ERR_COOPERATIVELEVEL:	return "Error setting cooperative level for hardware.";
		case FMOD_ERR_CREATEBUFFER:		return "Error creating hardware sound buffer.";
		case FMOD_ERR_FILE_NOTFOUND:	return "File not found";
		case FMOD_ERR_FILE_FORMAT:		return "Unknown file format";
		case FMOD_ERR_FILE_BAD:			return "Error loading file";
		case FMOD_ERR_MEMORY:			return "Not enough memory ";
		case FMOD_ERR_VERSION:			return "The version number of this file format is not supported";
		case FMOD_ERR_INVALID_PARAM:	return "An invalid parameter was passed to this function";
		case FMOD_ERR_NO_EAX:			return "Tried to use an EAX command on a non EAX enabled channel or output.";
		case FMOD_ERR_CHANNEL_ALLOC:	return "Failed to allocate a new channel";
		case FMOD_ERR_RECORD:			return "Recording not supported on this device";
		case FMOD_ERR_MEDIAPLAYER:		return "Required Mediaplayer codec is not installed";

		default :						return "Unknown error";
	};
}

#endif

redpajama_set_name: RedPajamaGithub


text:
package org.apache.hadoop.hdfs;

import java.net.ConnectException;

public class NoAliveNamenodeException extends ConnectException {
  public NoAliveNamenodeException() {
    super("There are no more alive Namenodes in the system.");
  }

  public NoAliveNamenodeException(String msg) {
    super(msg);
  }
}


text:
import gql from 'graphql-tag';

export default gql`
  query getProjectByEnvironmentId($id: Int!) {
    environment: environmentById(id: $id) {
      id
      name
      project {
        name
        openshift {
          name
        }
        gitUrl
      }
    }
  }
`;


text:
<!DOCTYPE html>
<head>
<script src="../resources/runner.js"></script>
<script src="resources/util_performance_test.js"></script>
</head>
<body onload="startPerformanceTest(
    'fetch',
    'sendBenchmark',
    'blob',
    true,
    true,
    true)">
</body>
</html>


text:
if ! command -v brew >/dev/null; then
  echo "Installing Homebrew"
  /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  eval "$(/opt/homebrew/bin/brew shellenv)"
fi


text:
namespace ExitGames.Client.Photon
{
    using System;
    using System.Collections;
    using UnityEngine;
    using SupportClassPun = ExitGames.Client.Photon.SupportClass;

    #if !(UNITY_WEBGL || NETFX_CORE)
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    #endif

    /// <summary>
    /// Yield Instruction to Wait for real seconds. Very important to keep connection working if Time.TimeScale is altered, we still want accurate network events
    /// </summary>
    public sealed class WaitForRealSeconds : CustomYieldInstruction
    {
        private readonly float _endTime;

        public override bool keepWaiting
        {
            get { return this._endTime > Time.realtimeSinceStartup; }
        }

        public WaitForRealSeconds(float seconds)
        {
            this._endTime = Time.realtimeSinceStartup + seconds;
        }
    }

    /// <summary>
    /// Internal class to encapsulate the network i/o functionality for the realtime libary.
    /// </summary>
    public class SocketWebTcp : IPhotonSocket, IDisposable
    {
        private WebSocket sock;

        private readonly object syncer = new object();

        public SocketWebTcp(PeerBase npeer) : base(npeer)
        {
            this.ServerAddress = npeer.ServerAddress;
            if (this.ReportDebugOfLevel(DebugLevel.INFO))
            {
                this.Listener.DebugReturn(DebugLevel.INFO, "new SocketWebTcp() for Unity. Server: " + this.ServerAddress);
            }

            //this.Protocol = ConnectionProtocol.WebSocket;
            this.PollReceive = false;
        }

        public void Dispose()
        {
            this.State = PhotonSocketState.Disconnecting;

            if (this.sock != null)
            {
                try
                {
                    if (this.sock.Connected) this.sock.Close();
                }
                catch (Exception ex)
                {
                    this.EnqueueDebugReturn(DebugLevel.INFO, "Exception in Dispose(): " + ex);
                }
            }

            this.sock = null;
            this.State = PhotonSocketState.Disconnected;
        }

        GameObject websocketConnectionObject;
        public override bool Connect()
        {
            //bool baseOk = base.Connect();
            //if (!baseOk)
            //{
            //    return false;
            //}

            this.State = PhotonSocketState.Connecting;

            if (this.websocketConnectionObject != null)
            {
                UnityEngine.Object.Destroy(this.websocketConnectionObject);
            }

            this.websocketConnectionObject = new GameObject("websocketConnectionObject");
            MonoBehaviour mb = this.websocketConnectionObject.AddComponent<MonoBehaviourExt>();
            this.websocketConnectionObject.hideFlags = HideFlags.HideInHierarchy;
            UnityEngine.Object.DontDestroyOnLoad(this.websocketConnectionObject);

            #if UNITY_WEBGL || NETFX_CORE
            this.sock = new WebSocket(new Uri(this.ConnectAddress), this.SerializationProtocol);
            this.sock.Connect();

            mb.StartCoroutine(this.ReceiveLoop());
            #else

            mb.StartCoroutine(this.DetectIpVersionAndConnect(mb));

            #endif
            return true;
        }

        #if !(UNITY_WEBGL || NETFX_CORE)
        private bool ipVersionDetectDone;
        private IEnumerator DetectIpVersionAndConnect(MonoBehaviour mb)
        {
            Uri uri = null;
            try
            {
                uri = new Uri(this.ConnectAddress);
            }
            catch (Exception ex)
            {
                if (this.ReportDebugOfLevel(DebugLevel.ERROR))
                {
                    this.Listener.DebugReturn(DebugLevel.ERROR, "Failed to create a URI from ConnectAddress (" + ConnectAddress + "). Exception: " + ex);
                }
            }

            if (uri != null && uri.HostNameType == UriHostNameType.Dns)
            {
                ipVersionDetectDone = false;

                ThreadPool.QueueUserWorkItem(this.DetectIpVersion, uri.Host);

                while (!this.ipVersionDetectDone)
                {
                    yield return new WaitForRealSeconds(0.1f);
                }
            }

            if (this.AddressResolvedAsIpv6)
            {
                this.ConnectAddress += "&IPv6";
            }

            if (this.ReportDebugOfLevel(DebugLevel.INFO))
            {
                this.Listener.DebugReturn(DebugLevel.INFO, "DetectIpVersionAndConnect() AddressResolvedAsIpv6: " + this.AddressResolvedAsIpv6 + " ConnectAddress: " + ConnectAddress);
            }

            this.sock = new WebSocket(new Uri(this.ConnectAddress), this.SerializationProtocol);
            this.sock.Connect();

            mb.StartCoroutine(this.ReceiveLoop());
        }

        // state has to be the hostname string
        private void DetectIpVersion(object state)
        {
            string host = state as string;
            IPAddress[] ipAddresses;
            try
            {
                ipAddresses = Dns.GetHostAddresses(host);
                foreach (IPAddress ipAddress in ipAddresses)
                {
                    if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
                    {
                        this.AddressResolvedAsIpv6 = true;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                this.Listener.DebugReturn(DebugLevel.INFO, "DetectIpVersionAndConnect (uri: " + host + "= thread failed: " + ex);
            }

            this.ipVersionDetectDone = true;
        }
        #endif

        public override bool Disconnect()
        {
            if (this.ReportDebugOfLevel(DebugLevel.INFO))
            {
                this.Listener.DebugReturn(DebugLevel.INFO, "SocketWebTcp.Disconnect()");
            }

            this.State = PhotonSocketState.Disconnecting;

            lock (this.syncer)
            {
                if (this.sock != null)
                {
                    try
                    {
                        this.sock.Close();
                    }
                    catch (Exception ex)
                    {
                        this.Listener.DebugReturn(DebugLevel.ERROR, "Exception in Disconnect(): " + ex);
                    }
                    this.sock = null;
                }
            }

            if (this.websocketConnectionObject != null)
            {
                UnityEngine.Object.Destroy(this.websocketConnectionObject);
            }

            this.State = PhotonSocketState.Disconnected;
            return true;
        }

        /// <summary>
        /// used by TPeer*
        /// </summary>
        public override PhotonSocketError Send(byte[] data, int length)
        {
            if (this.State != PhotonSocketState.Connected)
            {
                return PhotonSocketError.Skipped;
            }

            try
            {
                if (data.Length > length)
                {
                    byte[] trimmedData = new byte[length];
                    Buffer.BlockCopy(data, 0, trimmedData, 0, length);
                    data = trimmedData;
                }

                if (this.ReportDebugOfLevel(DebugLevel.ALL))
                {
                    this.Listener.DebugReturn(DebugLevel.ALL, "Sending: " + SupportClassPun.ByteArrayToString(data));
                }

                if (this.sock != null)
                {
                    this.sock.Send(data);
                }
            }
            catch (Exception e)
            {
                this.Listener.DebugReturn(DebugLevel.ERROR, "Cannot send to: " + this.ServerAddress + ". " + e.Message);

                this.HandleException(StatusCode.Exception);
                return PhotonSocketError.Exception;
            }

            return PhotonSocketError.Success;
        }

        public override PhotonSocketError Receive(out byte[] data)
        {
            data = null;
            return PhotonSocketError.NoData;
        }

        internal const int ALL_HEADER_BYTES = 9;
        internal const int TCP_HEADER_BYTES = 7;
        internal const int MSG_HEADER_BYTES = 2;

        public IEnumerator ReceiveLoop()
        {
            //this.Listener.DebugReturn(DebugLevel.INFO, "ReceiveLoop()");
            if (this.sock != null)
            {
                while (this.sock != null && !this.sock.Connected && this.sock.Error == null)
                {
                    yield return new WaitForRealSeconds(0.1f);
                }

                if (this.sock != null)
                {
                    if (this.sock.Error != null)
                    {
                        this.Listener.DebugReturn(DebugLevel.ERROR, "Exiting receive thread. Server: " + this.ServerAddress + ":" + this.ServerPort + " Error: " + this.sock.Error);
                        this.HandleException(StatusCode.ExceptionOnConnect);
                    }
                    else
                    {
                        // connected
                        if (this.ReportDebugOfLevel(DebugLevel.ALL))
                        {
                            this.Listener.DebugReturn(DebugLevel.ALL, "Receiving by websocket. this.State: " + this.State);
                        }

                        this.State = PhotonSocketState.Connected;
                        this.peerBase.OnConnect();

                        while (this.State == PhotonSocketState.Connected)
                        {
                            if (this.sock != null)
                            {
                                if (this.sock.Error != null)
                                {
                                    this.Listener.DebugReturn(DebugLevel.ERROR, "Exiting receive thread (inside loop). Server: " + this.ServerAddress + ":" + this.ServerPort + " Error: " + this.sock.Error);
                                    this.HandleException(StatusCode.ExceptionOnReceive);
                                    break;
                                }
                                else
                                {
                                    byte[] inBuff = this.sock.Recv();
                                    if (inBuff == null || inBuff.Length == 0)
                                    {
                                        // nothing received. wait a bit, try again
                                        yield return new WaitForRealSeconds(0.02f);
                                        continue;
                                    }

                                    if (this.ReportDebugOfLevel(DebugLevel.ALL))
                                    {
                                        this.Listener.DebugReturn(DebugLevel.ALL, "TCP << " + inBuff.Length + " = " + SupportClassPun.ByteArrayToString(inBuff));
                                    }

                                    if (inBuff.Length > 0)
                                    {
                                        try
                                        {
                                            this.HandleReceivedDatagram(inBuff, inBuff.Length, false);
                                        }
                                        catch (Exception e)
                                        {
                                            if (this.State != PhotonSocketState.Disconnecting && this.State != PhotonSocketState.Disconnected)
                                            {
                                                if (this.ReportDebugOfLevel(DebugLevel.ERROR))
                                                {
                                                    this.EnqueueDebugReturn(DebugLevel.ERROR, "Receive issue. State: " + this.State + ". Server: '" + this.ServerAddress + "' Exception: " + e);
                                                }

                                                this.HandleException(StatusCode.ExceptionOnReceive);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            this.Disconnect();
        }

        private class MonoBehaviourExt : MonoBehaviour { }
    }
}

#endif


text:
using System.Security.Cryptography;
using System.Text;

using SmsGatewayClient.Common;

namespace SmsGatewayClient.CMPP.Messages
{
    internal class CmppConnectMessage : CmppMessage
    {
        public CmppConnectMessage()
        {
            CommandId = CmppCommandId.CMPP_CONNECT;
        }

        [ProtocolDesc(Name = "Source_Addr", Description = "源地址即SP_Id", Size = 6)]
        public string SourceAddr { get; set; }

        [ProtocolDesc(Name = "AuthenticatorSource", Description = "MD5(Source_Addr+9字节的0 +shared secret+timestamp)", Size = 16)]
        public byte[] AuthenticatorSource { get; set; }

        [ProtocolDesc(Name = "Version", Description = "版本号", Size = 1)]
        public uint Version { get; set; }

        [ProtocolDesc(Name = "Timestamp", Description = "时间戳,MMddHHmmss", Size = 4)]
        public uint Timestamp { get; set; }

        protected override byte[] GetBody()
        {
            return BitHelper.ToProtocolBinaryArray(this);
        }

        public static byte[] Sign(string cpId, string password, string timestamp)
        {
            var secret = Encoding.UTF8.GetBytes(password);
            var timestampBytes = Encoding.UTF8.GetBytes(timestamp);

            var origin = new byte[6 + 9 + secret.Length + timestampBytes.Length];

            var index = BitHelper.Padding(cpId, origin, 6) + 9;
            index = BitHelper.Padding(secret, origin, index);
            index = BitHelper.Padding(timestampBytes, origin, index);

            return MD5.Create().ComputeHash(origin);
        }

        public override string ToString()
        {
            return string.Format("CMPP_CONNECT:[Sequence_Id={0},Source_Addr={1},AuthenticatorSource={2},Version={3},Timestamp={4}]",
                                    SequenceId,
                                    SourceAddr,
                                    StringHelper.Hex(AuthenticatorSource),
                                    Version,
                                    Timestamp);
        }
    }
}


text:
import * as ko from "knockout";

export class SystemMessage {
    public messageId: number;
    public message: KnockoutObservable<string>;
    constructor(messageId: number, message: string) {
        this.messageId = messageId;
        this.message = ko.observable(message);
    }
}


text:
namespace P4Tools {

namespace P4Testgen {

Continuation::Return::Return(const IR::Node* expr) : expr(expr) {}

bool Continuation::Return::operator==(const Continuation::Return& other) const {
    return expr ? other.expr && **expr == **other.expr : !other.expr;
}

Continuation::PropertyUpdate::PropertyUpdate(cstring propertyName, PropertyValue property)
    : propertyName(propertyName), property(property) {}

bool Continuation::PropertyUpdate::operator==(const Continuation::PropertyUpdate& other) const {
    return propertyName == other.propertyName && property == other.property;
}

Continuation::Guard::Guard(const IR::Expression* cond) : cond(cond) {}

bool Continuation::Guard::operator==(const Continuation::Guard& other) const {
    return *cond == *other.cond;
}

bool Continuation::Body::empty() const { return cmds.empty(); }

const Continuation::Command Continuation::Body::next() const {
    if (!cmds.empty()) {
        return cmds.front();
    }

    BUG("Empty continuation body");
}

void Continuation::Body::push(Command cmd) { cmds.emplace_front(cmd); }

void Continuation::Body::pop() {
    BUG_CHECK(!cmds.empty(), "Attempted to pop an empty command stack");
    cmds.pop_front();
}

void Continuation::Body::clear() { cmds.clear(); }

bool Continuation::Body::operator==(const Continuation::Body& other) const {
    return cmds == other.cmds;
}

Continuation::Body::Body(std::initializer_list<Command> cmds) : cmds(cmds) {}

Continuation::Body::Body(const std::vector<Command>& cmds) {
    for (auto it = cmds.rbegin(); it != cmds.rend(); ++it) {
        push(*it);
    }
}

/// This isn't a full-fledged capture-avoiding substitution, but should be good enough for our
/// needs. In particular, since the variables being substituted are freshly/uniquely generated, we
/// shouldn't have to worry about variable capture, and our continuations are created in a way that
/// we shouldn't have to worry about accidentally replacing lvalues.
class VariableSubstitution : public Transform {
 private:
    /// The variable being substituted.
    const IR::PathExpression* var;

    /// The expression being substituted for. Expressions in the metalanguage include P4
    /// non-expressions, so this expression does not necessarily need to be an instance of
    /// IR::Expression.
    const IR::Node* expr;

 public:
    const IR::Node* postorder(IR::PathExpression* pathExpr) override {
        if (*var == *pathExpr) {
            return expr;
        }
        return pathExpr;
    }

    /// Creates a pass that will substitute @expr for @var.
    VariableSubstitution(const IR::PathExpression* var, const IR::Node* expr)
        : var(var), expr(expr) {}
};

Continuation::Body Continuation::apply(boost::optional<const IR::Node*> value_opt) const {
    BUG_CHECK(!(value_opt && !parameterOpt),
              "Supplied a value to a continuation with no parameters.");
    BUG_CHECK(!(!value_opt && parameterOpt),
              "Continuation %1% has a parameter of type %2%, but no argument provided.",
              (*parameterOpt), (*parameterOpt)->type->node_type_name());

    // No need to substitute if this continuation is parameterless.
    if (!parameterOpt) {
        return body;
    }

    const auto* paramType = (*parameterOpt)->type;
    const IR::Type* argType = nullptr;
    if (const auto* valueExpr = (*value_opt)->to<IR::Expression>()) {
        argType = valueExpr->type;
    } else if ((*value_opt)->is<IR::ParserState>()) {
        argType = IR::Type_State::get();
    } else {
        BUG("Unexpected node passed to continuation: %1%", *value_opt);
    }

    // We step into an action enum type when resolving switch expressions. However, we return a bit
    // of unknown width. So, for this particular continuation, we have to take on the type of the
    // argument.
    // TODO: Resolve this in a cleaner fashion. Maybe we should not step at all?
    if (paramType->is<IR::Type_ActionEnum>()) {
        paramType = argType;
    }

    BUG_CHECK(
        paramType->equiv(*argType),
        "Continuation %1% has parameter of type %2%, but was given an argument %3% of type %4%",
        (*parameterOpt), paramType, *value_opt, argType);

    // Create a copy of this continuation's body, with the value substituted for the continuation's
    // parameter.
    Body result;

    struct SubstVisitor : public boost::static_visitor<Command> {
        VariableSubstitution subst;

        Command operator()(const IR::Node* node) { return node->apply(subst); }

        Command operator()(const TraceEvent* event) { return event->apply(subst); }

        Command operator()(Return ret) {
            if (!ret.expr) {
                return ret;
            }
            return Return{(*ret.expr)->apply(subst)};
        }

        Command operator()(Exception e) { return e; }

        Command operator()(PropertyUpdate p) { return p; }

        Command operator()(Guard g) { return Guard{g.cond->apply(subst)}; }

        /// Creates a visitor for Commands that substitutes the given value for the given
        /// parameter.
        SubstVisitor(const IR::PathExpression* param, const IR::Node* value)
            : subst(param, value) {}
    } subst(*parameterOpt, *value_opt);

    for (const auto& cmd : body.cmds) {
        result.cmds.push_back(boost::apply_visitor(subst, cmd));
    }

    return result;
}

const Continuation::Parameter* Continuation::genParameter(const IR::Type* type, cstring name,
                                                          const NamespaceContext* ctx) {
    auto varName = ctx->genName(name, '*');
    return new Parameter(new IR::PathExpression(type, new IR::Path(varName)));
}

}  // namespace P4Testgen

}  // namespace P4Tools


text:
{% extends "success.html" %}

{% block dns_nav %}{% endblock %}


text:
import hashlib

from sqlalchemy import (
    Column,
    ForeignKey,
    Integer,
    String,
    DateTime,
    func,
    event,
    )
from sqlalchemy.orm import relationship, backref

from ..app import db

class Cluster(db.Model):
    """
    A cluster of documents, usually generated by automatic analysis.
    A cluster consists of some metadata and a collection of documents
    within that cluster. A document can be long to many clusters.

    A cluster has a fingerprint, which is an md5 hash of the sorted
    document ids in the cluster. Always call `recalculate_fingerprint`
    after updating the members of the cluster.
    """
    __tablename__ = "clusters"

    id           = Column(Integer, primary_key=True)
    fingerprint  = Column(String(32), index=True, nullable=False, unique=True)
    created_at   = Column(DateTime(timezone=True), index=True, unique=False, nullable=False, server_default=func.now())

    # associations
    # the members of this cluster, instances of ClusteredDocument
    members      = relationship("ClusteredDocument", lazy=False, backref='cluster', cascade='all, delete-orphan', passive_deletes=True)

    @property
    def documents(self):
        return [cd.document for cd in self.members]

    def recalculate_fingerprint(self):
        self.fingerprint = Cluster.make_fingerprint(m.document.id for m in self.members)

    def __len__(self):
        return len(self.members)

    def __repr__(self):
        return "<Cluster id=%s, %d docs, fingerprint=%s>" % (self.id, len(self), self.fingerprint,)

    @classmethod
    def make_fingerprint(cls, doc_ids):
        m = hashlib.md5()
        for i in sorted(doc_ids):
            m.update(str(i))
        return m.hexdigest()

    @classmethod
    def find_or_create(cls, fingerprint=None, docs=None):
        """ Find an existing cluster that has these documents, or create one. """
        if not fingerprint:
            if not docs:
                raise ValueError("Need one of fingerprint or docs")
            fingerprint = cls.make_fingerprint(d.id for d in docs)

        cluster = cls.query.filter(cls.fingerprint == fingerprint).first()
        if cluster is None:
            cluster = cls()
            cluster.members = [ClusteredDocument(document=d) for d in docs]
            cluster.recalculate_fingerprint()

        return cluster

class ClusteredDocument(db.Model):
    """
    Links a document to a cluster.
    """
    __tablename__ = "clustered_documents"

    id         = Column(Integer, primary_key=True)
    cluster_id = Column(Integer, ForeignKey('clusters.id', ondelete='CASCADE'), index=True, nullable=False)
    doc_id     = Column(Integer, ForeignKey('documents.id', ondelete='CASCADE'), index=True, nullable=False)

    # associations
    document   = relationship("Document", backref=backref('clusters', cascade='all, delete-orphan'), lazy=False)

    def __repr__(self):
        return "<ClusteredDocument id=%s, cluster=%s, document=%s>" % (self.id, self.cluster, self.document,)


text:
@implementation PuzzlesTiler

+(id)sharedTiler {
    static PuzzlesTiler *sharedTiler = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedTiler = [[self alloc] init];
    });
    return sharedTiler;
}

-(void)tileImage:(UIImage *)image withGrid:(KKGrid)grid size:(CGSize)size completion:(void (^)(NSArray<Tile *> *, NSError*))completionBlock{

    //set tiles destination path
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *directoryPath = [paths objectAtIndex:0];
    NSString *tilesDestinationPath = [directoryPath stringByAppendingPathComponent:@"tiles"];
    NSString *prefix = @"tile";

    [[NSFileManager defaultManager] removeItemAtPath:tilesDestinationPath error:nil];
    [[NSFileManager defaultManager] createDirectoryAtPath:tilesDestinationPath withIntermediateDirectories:false attributes:nil error:nil];

    NSString *imagePath = [tilesDestinationPath stringByAppendingPathComponent:@"orig.png"];
    NSError *error = nil;

    //calculate zoom that aspect fits grid size
    float heightRatio = size.height/image.size.height;
    float widthRatio = size.width/image.size.width;
    float scaleRatio = image.size.height > image.size.width ? heightRatio : widthRatio;

    //calculate tile size
    float tileWidth = grid.cols != 0 ? floor(image.size.width/grid.cols) : floor(image.size.width);
    float tileHeight = grid.rows != 0 ? floor(image.size.height/grid.rows) : floor(image.size.height);

    //crop image
    UIImage *croppedImage = [image crop:(CGRect){0.0, 0.0, tileWidth * grid.cols, tileHeight * grid.rows}];
    [UIImagePNGRepresentation(croppedImage) writeToFile:imagePath options:(NSDataWritingAtomic) error:&error];

    //check if file succesfully written
    if (error){
        completionBlock(nil, error);
        return;
    }

    EKTilesMaker *tilesMaker = [EKTilesMaker new];
    [tilesMaker setSourceImagePath:imagePath];
    [tilesMaker setOutputFolderPath:tilesDestinationPath];
    [tilesMaker setOutputFileName:prefix];
    [tilesMaker setTileSize:(CGSize){tileWidth,tileHeight}];
    [tilesMaker setOutputFileType:OutputFileTypePNG];
    [tilesMaker setCompletionBlock:^{

        //remove original image from disk
        NSError *error = nil;
        [[NSFileManager defaultManager] removeItemAtPath:imagePath error:&error];

        //check if file succesfully removed
        if (error){
            completionBlock(nil, error);
            return;
        }

        NSArray *tileFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:tilesDestinationPath error:&error];

        if (error){
            completionBlock(nil, error);
            return;
        }

        NSMutableArray *ret = [NSMutableArray array];
        for (NSString *tileFile in tileFiles) {

            //create tile image view
            Tile *tile = [[Tile alloc] initWithImage:[UIImage imageWithContentsOfFile:[tilesDestinationPath stringByAppendingPathComponent:tileFile]]];
            tile.contentMode = UIViewContentModeScaleAspectFill;

            [tile setFrame:(CGRect){0.0, 0.0, floor(scaleRatio * tileWidth), floor(scaleRatio * tileHeight)}];
            [ret addObject:tile];
        }

        completionBlock([NSArray arrayWithArray:ret], nil);
    }];

    [tilesMaker createTiles];
}

@end


text:
<?php

namespace tourze\Html\Element;

use tourze\Html\Element;

/**
 * 内联元素
 *
 * @package tourze\Html\Element
 */
interface InlineElement extends Element
{

}


text:
from django.core.management.base import BaseCommand

from djwepay.api import get_wepay_model

from optparse import make_option

from wepay.exceptions import WePayError

class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option('--object_name', default='', dest='obj_name',
                    help='Provide the name of the object you want to refresh. '
                    'Ex. --object_name=credit_card'),
        make_option('--ids', default='', dest='ids', help='Provide comma separated '
                    'ids of the objects you want to refresh. All by default'),
    )
    help = 'Retrieves current information from WePay and updates objects'

    def handle(self, *args, **kwargs):
        obj_name = kwargs.get('obj_name')
        ids = kwargs.get('ids', '')
        model = get_wepay_model(obj_name)
        if model is None:
            print "Unrecognized object name: %s " % obj_name
            exit()
        pks = [int(x) for x in ids.split(',') if x]
        if hasattr(model.objects, 'accessible'):
            objects = model.objects.accessible()
        else:
            objects = model.objects.all()
        if pks:
            objects.filter(pk__in=pks)
        for obj in objects:
            method = getattr(obj, "api_%s" % obj_name)
            try:
                method()
                print "Updated object with id: %s" % obj.pk
            except WePayError, e:
                if e.code == 1011:
                    if obj_name == 'user':
                        obj.access_token = None
                        obj.save()
                    print "access token revoked for the object with id: %s" % obj.pk
                else:
                    print "problem updating object with id: %s" % obj.pk
                print e