text:
module IndexOrderHelper

  def sortable_field(name, field, options = {}, html_options = {})

    options.merge!({
      :action                => :index,
      :index_order_field     => field.to_s,
      :index_order_direction => get_sortable_field_order(field.to_s)[:index_order_direction],
      :filter                => @filter
    })
    link_to(name, options, html_options)
  end

  private

  def get_sortable_field_order(field_name)
    order_hash = {:index_order_field => field_name}
    if @index_order_field == field_name
      order_hash[:index_order_direction] = (@index_order_direction == 'ASC' ? 'DESC' : 'ASC')
    else
      order_hash[:index_order_direction] = 'ASC'
    end
    order_hash
  end
end


text:
namespace chromecast {
namespace shell {

namespace {

const int kMaxMessageQueueSize = 50;
static const int64_t kDelayBetweenReconnectionInMillis = 100;

const char kSetAssistantMessageHandlerMethodName[] =
    "setAssistantMessageHandler";
const char kSendAssistantRequestMethodName[] = "sendAssistantRequest";

}  // namespace

AssistantBindings::AssistantBindings(content::RenderFrame* frame,
                                     const base::Value& feature_config)
    : CastBinding(frame),
      feature_config_(feature_config.Clone()),
      message_client_binding_(this),
      weak_factory_(this) {
  weak_this_ = weak_factory_.GetWeakPtr();
}

AssistantBindings::~AssistantBindings() {}

void AssistantBindings::OnMessage(base::Value message) {
  if (assistant_message_handler_.IsEmpty()) {
    return;
  }

  v8::Isolate* isolate = blink::MainThreadIsolate();
  v8::MicrotasksScope microtasks_scope(
      isolate, v8::MicrotasksScope::kDoNotRunMicrotasks);
  v8::HandleScope handle_scope(isolate);
  blink::WebLocalFrame* web_frame = render_frame()->GetWebFrame();
  v8::Local<v8::Context> context = web_frame->MainWorldScriptContext();
  v8::Context::Scope context_scope(context);

  v8::Local<v8::Function> handler = v8::Local<v8::Function>::New(
      isolate, std::move(assistant_message_handler_));

  std::string json;
  base::JSONWriter::Write(message, &json);
  v8::Local<v8::Value> message_val =
      gin::Converter<std::string>::ToV8(isolate, json);

  v8::Local<v8::Value> argv[] = {message_val};
  web_frame->CallFunctionEvenIfScriptDisabled(handler, context->Global(),
                                              std::size(argv), argv);

  assistant_message_handler_ =
      v8::UniquePersistent<v8::Function>(isolate, handler);
}

void AssistantBindings::Install(v8::Local<v8::Object> cast_platform,
                                v8::Isolate* isolate) {
  DVLOG(1) << "Installing AssistantBindings";

  InstallBinding(isolate, cast_platform, kSetAssistantMessageHandlerMethodName,
                 &AssistantBindings::SetAssistantMessageHandler,
                 base::Unretained(this));
  InstallBinding(isolate, cast_platform, kSendAssistantRequestMethodName,
                 &AssistantBindings::SendAssistantRequest,
                 base::Unretained(this));
}

void AssistantBindings::SetAssistantMessageHandler(
    v8::Local<v8::Function> assistant_message_handler) {
  v8::Isolate* isolate = blink::MainThreadIsolate();
  assistant_message_handler_ =
      v8::UniquePersistent<v8::Function>(isolate, assistant_message_handler);
  ReconnectMessagePipe();
}

void AssistantBindings::SendAssistantRequest(const std::string& request) {
  if (assistant_message_handler_.IsEmpty()) {
    v8::Isolate* isolate = blink::MainThreadIsolate();
    isolate->ThrowException(
        v8::String::NewFromUtf8(isolate,
                                "Error: assistant message handler is not set.",
                                v8::NewStringType::kInternalized)
            .ToLocalChecked());
    return;
  }
  if (!message_pipe_.is_bound()) {
    if (v8_to_assistant_queue_.size() < kMaxMessageQueueSize) {
      v8_to_assistant_queue_.push_back(request);
    } else {
      LOG(WARNING) << "Messages sending to assistant overflow, will drop "
                      "upcoming messages";
    }
    return;
  }

  v8_to_assistant_queue_.push_back(request);
  FlushV8ToAssistantQueue();
}

void AssistantBindings::ReconnectMessagePipe() {
  if (message_client_binding_.is_bound())
    message_client_binding_.reset();
  if (message_pipe_.is_bound())
    message_pipe_.reset();
  LOG(INFO) << "Creating message pipe";
  base::Value* app_id =
      feature_config_.FindKeyOfType("app_id", base::Value::Type::STRING);
  DCHECK(app_id) << "Couldn't get app_id from feature config";
  GetMojoInterface()->CreateMessagePipe(
      app_id->GetString(), message_client_binding_.BindNewPipeAndPassRemote(),
      message_pipe_.BindNewPipeAndPassReceiver());

  reconnect_assistant_timer_.Stop();
}

void AssistantBindings::OnAssistantConnectionError() {
  LOG(WARNING) << "Disconnected from assistant. Will reconnect every "
               << kDelayBetweenReconnectionInMillis << " milliseconds";
  assistant_.reset();
  reconnect_assistant_timer_.Start(
      FROM_HERE, base::Milliseconds(kDelayBetweenReconnectionInMillis), this,
      &AssistantBindings::ReconnectMessagePipe);
}

void AssistantBindings::FlushV8ToAssistantQueue() {
  DCHECK(message_pipe_.is_bound());

  for (auto& request : v8_to_assistant_queue_) {
    auto value = base::JSONReader::Read(request);
    if (!value) {
      LOG(ERROR) << "Unable to parse Assistant message JSON.";
      continue;
    }
    message_pipe_->SendMessage(std::move(*value));
  }
  v8_to_assistant_queue_.clear();
}

const mojo::Remote<chromecast::mojom::AssistantMessageService>&
AssistantBindings::GetMojoInterface() {
  if (!assistant_.is_bound()) {
    render_frame()->GetBrowserInterfaceBroker()->GetInterface(
        assistant_.BindNewPipeAndPassReceiver());
    assistant_.set_disconnect_handler(base::BindOnce(
        &AssistantBindings::OnAssistantConnectionError, weak_this_));
  }
  return assistant_;
}

}  // namespace shell
}  // namespace chromecast

redpajama_set_name: RedPajamaGithub


text:
(function($){

  function expandInfo(event) {
    var target = $("#"+this.dataset.target);
    if (target.hasClass("hide")) {
      target.removeClass('hide');
    } else {
      target.addClass('hide');
    }
  }

  $('.expandable_heading').click(expandInfo);

})(django.jQuery);


text:
package java.security;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.concurrent.ConcurrentHashMap;

/**
 * The BasicPermission class extends the Permission class, and
 * can be used as the base class for permissions that want to
 * follow the same naming convention as BasicPermission.
 *

 * The name for a BasicPermission is the name of the given permission
 * (for example, "exit",
 * "setFactory", "print.queueJob", etc). The naming
 * convention follows the  hierarchical property naming convention.
 * An asterisk may appear by itself, or if immediately preceded by a "."
 * may appear at the end of the name, to signify a wildcard match.
 * For example, "*" and "java.*" signify a wildcard match, while "*java", "a*b",
 * and "java*" do not.
 *

 * The action string (inherited from Permission) is unused.
 * Thus, BasicPermission is commonly used as the base class for
 * "named" permissions
 * (ones that contain a name but no actions list; you either have the
 * named permission or you don't.)
 * Subclasses may implement actions on top of BasicPermission,
 * if desired.
 *
 * @see java.security.Permission
 * @see java.security.Permissions
 * @see java.security.PermissionCollection
 * @see java.lang.SecurityManager
 *
 * @author Marianne Mueller
 * @author Roland Schemers
 * @since 1.2
 */

public abstract class BasicPermission extends Permission
    implements java.io.Serializable
{

    @java.io.Serial
    private static final long serialVersionUID = 6279438298436773498L;

    // does this permission have a wildcard at the end?
    private transient boolean wildcard;

    // the name without the wildcard on the end
    private transient String path;

    // is this permission the old-style exitVM permission (pre JDK 1.6)?
    private transient boolean exitVM;

    /**
     * initialize a BasicPermission object. Common to all constructors.
     */
    private void init(String name) {
        if (name == null)
            throw new NullPointerException("name can't be null");

        int len = name.length();

        if (len == 0) {
            throw new IllegalArgumentException("name can't be empty");
        }

        char last = name.charAt(len - 1);

        // Is wildcard or ends with ".*"?
        if (last == '*' && (len == 1 || name.charAt(len - 2) == '.')) {
            wildcard = true;
            if (len == 1) {
                path = "";
            } else {
                path = name.substring(0, len - 1);
            }
        } else {
            if (name.equals("exitVM")) {
                wildcard = true;
                path = "exitVM.";
                exitVM = true;
            } else {
                path = name;
            }
        }
    }

    /**
     * Creates a new BasicPermission with the specified name.
     * Name is the symbolic name of the permission, such as
     * "setFactory",
     * "print.queueJob", or "topLevelWindow", etc.
     *
     * @param name the name of the BasicPermission.
     *
     * @throws NullPointerException if {@code name} is {@code null}.
     * @throws IllegalArgumentException if {@code name} is empty.
     */
    public BasicPermission(String name) {
        super(name);
        init(name);
    }

    /**
     * Creates a new BasicPermission object with the specified name.
     * The name is the symbolic name of the BasicPermission, and the
     * actions String is currently unused.
     *
     * @param name the name of the BasicPermission.
     * @param actions ignored.
     *
     * @throws NullPointerException if {@code name} is {@code null}.
     * @throws IllegalArgumentException if {@code name} is empty.
     */
    public BasicPermission(String name, String actions) {
        super(name);
        init(name);
    }

    /**
     * Checks if the specified permission is "implied" by
     * this object.
     *

     * More specifically, this method returns true if:
     *

     *
 {@code p}'s class is the same as this object's class, and
     *
 {@code p}'s name equals or (in the case of wildcards)
     *      is implied by this object's
     *      name. For example, "a.b.*" implies "a.b.c".
     *

     *
     * @param p the permission to check against.
     *
     * @return true if the passed permission is equal to or
     * implied by this permission, false otherwise.
     */
    @Override
    public boolean implies(Permission p) {
        if ((p == null) || (p.getClass() != getClass()))
            return false;

        BasicPermission that = (BasicPermission) p;

        if (this.wildcard) {
            if (that.wildcard) {
                // one wildcard can imply another
                return that.path.startsWith(path);
            } else {
                // make sure ap.path is longer so a.b.* doesn't imply a.b
                return (that.path.length() > this.path.length()) &&
                    that.path.startsWith(this.path);
            }
        } else {
            if (that.wildcard) {
                // a non-wildcard can't imply a wildcard
                return false;
            }
            else {
                return this.path.equals(that.path);
            }
        }
    }

    /**
     * Checks two BasicPermission objects for equality.
     * Checks that {@code obj}'s class is the same as this object's class
     * and has the same name as this object.
     *
     * @param obj the object we are testing for equality with this object.
     * @return true if {@code obj}'s class is the same as this object's class
     *  and has the same name as this BasicPermission object, false otherwise.
     */
    @Override
    public boolean equals(Object obj) {
        if (obj == this)
            return true;

        if ((obj == null) || (obj.getClass() != getClass()))
            return false;

        BasicPermission bp = (BasicPermission) obj;

        return getName().equals(bp.getName());
    }

    /**
     * Returns the hash code value for this object.
     * The hash code used is the hash code of the name, that is,
     * {@code getName().hashCode()}, where {@code getName} is
     * from the Permission superclass.
     *
     * @return a hash code value for this object.
     */
    @Override
    public int hashCode() {
        return this.getName().hashCode();
    }

    /**
     * Returns the canonical string representation of the actions,
     * which currently is the empty string "", since there are no actions for
     * a BasicPermission.
     *
     * @return the empty string "".
     */
    @Override
    public String getActions() {
        return "";
    }

    /**
     * Returns a new PermissionCollection object for storing BasicPermission
     * objects.
     *
     *
BasicPermission objects must be stored in a manner that allows them
     * to be inserted in any order, but that also enables the
     * PermissionCollection {@code implies} method
     * to be implemented in an efficient (and consistent) manner.
     *
     * @return a new PermissionCollection object suitable for
     * storing BasicPermissions.
     */
    @Override
    public PermissionCollection newPermissionCollection() {
        return new BasicPermissionCollection(this.getClass());
    }

    /**
     * readObject is called to restore the state of the BasicPermission from
     * a stream.
     *
     * @param  s the {@code ObjectInputStream} from which data is read
     * @throws IOException if an I/O error occurs
     * @throws ClassNotFoundException if a serialized class cannot be loaded
     */
    @java.io.Serial
    private void readObject(ObjectInputStream s)
         throws IOException, ClassNotFoundException
    {
        s.defaultReadObject();
        // init is called to initialize the rest of the values.
        init(getName());
    }

    /**
     * Returns the canonical name of this BasicPermission.
     * All internal invocations of getName should invoke this method, so
     * that the pre-JDK 1.6 "exitVM" and current "exitVM.*" permission are
     * equivalent in equals/hashCode methods.
     *
     * @return the canonical name of this BasicPermission.
     */
    final String getCanonicalName() {
        return exitVM ? "exitVM.*" : getName();
    }
}

/**
 * A BasicPermissionCollection stores a collection
 * of BasicPermission permissions. BasicPermission objects
 * must be stored in a manner that allows them to be inserted in any
 * order, but enable the implies function to evaluate the implies
 * method in an efficient (and consistent) manner.
 *
 * A BasicPermissionCollection handles comparing a permission like "a.b.c.d.e"
 * with a Permission such as "a.b.*", or "*".
 *
 * @see java.security.Permission
 * @see java.security.Permissions
 *
 *
 * @author Roland Schemers
 *
 * @serial include
 */

final class BasicPermissionCollection
    extends PermissionCollection
    implements java.io.Serializable
{

    @java.io.Serial
    private static final long serialVersionUID = 739301742472979399L;

    /**
     * Key is name, value is permission. All permission objects in
     * collection must be of the same type.
     * Not serialized; see serialization section at end of class.
     */
    private transient ConcurrentHashMap<String, Permission> perms;

    /**
     * This is set to {@code true} if this BasicPermissionCollection
     * contains a BasicPermission with '*' as its permission name.
     *
     * @see #serialPersistentFields
     */
    private boolean all_allowed;

    /**
     * The class to which all BasicPermissions in this
     * BasicPermissionCollection belong.
     *
     * @see #serialPersistentFields
     */
    private Class<?> permClass;

    /**
     * Create an empty BasicPermissionCollection object.
     *
     */
    public BasicPermissionCollection(Class<?> clazz) {
        perms = new ConcurrentHashMap<>(11);
        all_allowed = false;
        permClass = clazz;
    }

    /**
     * Adds a permission to the BasicPermissions. The key for the hash is
     * permission.path.
     *
     * @param permission the Permission object to add.
     *
     * @throws    IllegalArgumentException   if the permission is not a
     *                                       BasicPermission, or if
     *                                       the permission is not of the
     *                                       same Class as the other
     *                                       permissions in this collection.
     *
     * @throws    SecurityException   if this BasicPermissionCollection object
     *                                has been marked readonly
     */
    @Override
    public void add(Permission permission) {
        if (!(permission instanceof BasicPermission basicPermission))
            throw new IllegalArgumentException("invalid permission: "+
                                               permission);
        if (isReadOnly())
            throw new SecurityException("attempt to add a Permission to a readonly PermissionCollection");

        // make sure we only add new BasicPermissions of the same class
        // Also check null for compatibility with deserialized form from
        // previous versions.
        if (permClass == null) {
            // adding first permission
            permClass = basicPermission.getClass();
        } else {
            if (basicPermission.getClass() != permClass)
                throw new IllegalArgumentException("invalid permission: " +
                                                permission);
        }

        String canonName = basicPermission.getCanonicalName();
        perms.put(canonName, permission);

        // No sync on all_allowed; staleness OK
        if (!all_allowed) {
            if (canonName.equals("*"))
                all_allowed = true;
        }
    }

    /**
     * Check and see if this set of permissions implies the permissions
     * expressed in "permission".
     *
     * @param permission the Permission object to compare
     *
     * @return true if "permission" is a proper subset of a permission in
     * the set, false if not.
     */
    @Override
    public boolean implies(Permission permission) {
        if (!(permission instanceof BasicPermission basicPermission))
            return false;

        // random subclasses of BasicPermission do not imply each other
        if (basicPermission.getClass() != permClass)
            return false;

        // short circuit if the "*" Permission was added
        if (all_allowed)
            return true;

        // strategy:
        // Check for full match first. Then work our way up the
        // path looking for matches on a.b..*

        String path = basicPermission.getCanonicalName();
        //System.out.println("check "+path);

        Permission x = perms.get(path);

        if (x != null) {
            // we have a direct hit!
            return x.implies(permission);
        }

        // work our way up the tree...
        int last, offset;

        offset = path.length()-1;

        while ((last = path.lastIndexOf('.', offset)) != -1) {

            path = path.substring(0, last+1) + "*";
            //System.out.println("check "+path);

            x = perms.get(path);

            if (x != null) {
                return x.implies(permission);
            }
            offset = last -1;
        }

        // we don't have to check for "*" as it was already checked
        // at the top (all_allowed), so we just return false
        return false;
    }

    /**
     * Returns an enumeration of all the BasicPermission objects in the
     * container.
     *
     * @return an enumeration of all the BasicPermission objects.
     */
    @Override
    public Enumeration<Permission> elements() {
        return perms.elements();
    }

    // Need to maintain serialization interoperability with earlier releases,
    // which had the serializable field:
    //
    // @serial the Hashtable is indexed by the BasicPermission name
    //
    // private Hashtable permissions;
    /**
     * @serialField permissions java.util.Hashtable
     *    The BasicPermissions in this BasicPermissionCollection.
     *    All BasicPermissions in the collection must belong to the same class.
     *    The Hashtable is indexed by the BasicPermission name; the value
     *    of the Hashtable entry is the permission.
     * @serialField all_allowed boolean
     *   This is set to {@code true} if this BasicPermissionCollection
     *   contains a BasicPermission with '*' as its permission name.
     * @serialField permClass java.lang.Class
     *   The class to which all BasicPermissions in this
     *   BasicPermissionCollection belongs.
     */
    @java.io.Serial
    private static final ObjectStreamField[] serialPersistentFields = {
        new ObjectStreamField("permissions", Hashtable.class),
        new ObjectStreamField("all_allowed", Boolean.TYPE),
        new ObjectStreamField("permClass", Class.class),
    };

    /*
     * @serialData Default fields.
     */

    /**
     * Writes the contents of the perms field out as a Hashtable for
     * serialization compatibility with earlier releases. all_allowed
     * and permClass unchanged.
     *
     * @param  out the {@code ObjectOutputStream} to which data is written
     * @throws IOException if an I/O error occurs
     */
    @java.io.Serial
    private void writeObject(ObjectOutputStream out) throws IOException {
        // Don't call out.defaultWriteObject()

        // Copy perms into a Hashtable
        Hashtable<String, Permission> permissions =
                new Hashtable<>(perms.size()*2);

        permissions.putAll(perms);

        // Write out serializable fields
        ObjectOutputStream.PutField pfields = out.putFields();
        pfields.put("all_allowed", all_allowed);
        pfields.put("permissions", permissions);
        pfields.put("permClass", permClass);
        out.writeFields();
    }

    /**
     * readObject is called to restore the state of the
     * BasicPermissionCollection from a stream.
     *
     * @param  in the {@code ObjectInputStream} from which data is read
     * @throws IOException if an I/O error occurs
     * @throws ClassNotFoundException if a serialized class cannot be loaded
     */
    @java.io.Serial
    private void readObject(java.io.ObjectInputStream in)
         throws IOException, ClassNotFoundException
    {
        // Don't call defaultReadObject()

        // Read in serialized fields
        ObjectInputStream.GetField gfields = in.readFields();

        // Get permissions
        // writeObject writes a Hashtable<String, Permission> for the
        // permissions key, so this cast is safe, unless the data is corrupt.
        @SuppressWarnings("unchecked")
        Hashtable<String, Permission> permissions =
                (Hashtable<String, Permission>)gfields.get("permissions", null);
        perms = new ConcurrentHashMap<>(permissions.size()*2);
        perms.putAll(permissions);

        // Get all_allowed
        all_allowed = gfields.get("all_allowed", false);

        // Get permClass
        permClass = (Class<?>) gfields.get("permClass", null);

        if (permClass == null) {
            // set permClass
            Enumeration<Permission> e = permissions.elements();
            if (e.hasMoreElements()) {
                Permission p = e.nextElement();
                permClass = p.getClass();
            }
        }
    }
}


text:
.class public Lcom/android/systemui/util/leak/TrackedGarbage;
.super Ljava/lang/Object;
.source "TrackedGarbage.java"

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/android/systemui/util/leak/TrackedGarbage$LeakReference;
    }
.end annotation

# instance fields
.field private final mGarbage:Ljava/util/HashSet;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/HashSet",
            "<",
            "Lcom/android/systemui/util/leak/TrackedGarbage$LeakReference;",
            ">;"
        }
    .end annotation
.end field

.field private final mRefQueue:Ljava/lang/ref/ReferenceQueue;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/lang/ref/ReferenceQueue",
            "<",
            "Ljava/lang/Object;",
            ">;"
        }
    .end annotation
.end field

.field private final mTrackedCollections:Lcom/android/systemui/util/leak/TrackedCollections;

# direct methods
.method public constructor <init>(Lcom/android/systemui/util/leak/TrackedCollections;)V
    .locals 1

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    new-instance v0, Ljava/util/HashSet;

    invoke-direct {v0}, Ljava/util/HashSet;-><init>()V

    iput-object v0, p0, Lcom/android/systemui/util/leak/TrackedGarbage;->mGarbage:Ljava/util/HashSet;

    new-instance v0, Ljava/lang/ref/ReferenceQueue;

    invoke-direct {v0}, Ljava/lang/ref/ReferenceQueue;-><init>()V

    iput-object v0, p0, Lcom/android/systemui/util/leak/TrackedGarbage;->mRefQueue:Ljava/lang/ref/ReferenceQueue;

    iput-object p1, p0, Lcom/android/systemui/util/leak/TrackedGarbage;->mTrackedCollections:Lcom/android/systemui/util/leak/TrackedCollections;

    return-void
.end method

.method private cleanUp()V
    .locals 2

    :goto_0
    iget-object v1, p0, Lcom/android/systemui/util/leak/TrackedGarbage;->mRefQueue:Ljava/lang/ref/ReferenceQueue;

    invoke-virtual {v1}, Ljava/lang/ref/ReferenceQueue;->poll()Ljava/lang/ref/Reference;

    move-result-object v0

    if-eqz v0, :cond_0

    iget-object v1, p0, Lcom/android/systemui/util/leak/TrackedGarbage;->mGarbage:Ljava/util/HashSet;

    invoke-virtual {v1, v0}, Ljava/util/HashSet;->remove(Ljava/lang/Object;)Z

    goto :goto_0

    :cond_0
    return-void
.end method

.method private isOld(JJ)Z
    .locals 3

    const-wide/32 v0, 0xea60

    add-long/2addr v0, p1

    cmp-long v0, v0, p3

    if-gez v0, :cond_0

    const/4 v0, 0x1

    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method

# virtual methods
.method public declared-synchronized countOldGarbage()I
    .locals 8

    monitor-enter p0

    :try_start_0
    invoke-direct {p0}, Lcom/android/systemui/util/leak/TrackedGarbage;->cleanUp()V

    invoke-static {}, Landroid/os/SystemClock;->uptimeMillis()J

    move-result-wide v0

    const/4 v4, 0x0

    iget-object v5, p0, Lcom/android/systemui/util/leak/TrackedGarbage;->mGarbage:Ljava/util/HashSet;

    invoke-interface {v5}, Ljava/lang/Iterable;->iterator()Ljava/util/Iterator;

    move-result-object v3

    :cond_0
    :goto_0
    invoke-interface {v3}, Ljava/util/Iterator;->hasNext()Z

    move-result v5

    if-eqz v5, :cond_1

    invoke-interface {v3}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v2

    check-cast v2, Lcom/android/systemui/util/leak/TrackedGarbage$LeakReference;

    invoke-static {v2}, Lcom/android/systemui/util/leak/TrackedGarbage$LeakReference;->-get1(Lcom/android/systemui/util/leak/TrackedGarbage$LeakReference;)J

    move-result-wide v6

    invoke-direct {p0, v6, v7, v0, v1}, Lcom/android/systemui/util/leak/TrackedGarbage;->isOld(JJ)Z
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    move-result v5

    if-eqz v5, :cond_0

    add-int/lit8 v4, v4, 0x1

    goto :goto_0

    :cond_1
    monitor-exit p0

    return v4

    :catchall_0
    move-exception v5

    monitor-exit p0

    throw v5
.end method

.method public declared-synchronized dump(Ljava/io/PrintWriter;)V
    .locals 11

    monitor-enter p0

    :try_start_0
    invoke-direct {p0}, Lcom/android/systemui/util/leak/TrackedGarbage;->cleanUp()V

    invoke-static {}, Landroid/os/SystemClock;->uptimeMillis()J

    move-result-wide v4

    new-instance v0, Landroid/util/ArrayMap;

    invoke-direct {v0}, Landroid/util/ArrayMap;-><init>()V

    new-instance v1, Landroid/util/ArrayMap;

    invoke-direct {v1}, Landroid/util/ArrayMap;-><init>()V

    iget-object v8, p0, Lcom/android/systemui/util/leak/TrackedGarbage;->mGarbage:Ljava/util/HashSet;

    invoke-interface {v8}, Ljava/lang/Iterable;->iterator()Ljava/util/Iterator;

    move-result-object v7

    :cond_0
    :goto_0
    invoke-interface {v7}, Ljava/util/Iterator;->hasNext()Z

    move-result v8

    if-eqz v8, :cond_1

    invoke-interface {v7}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v6

    check-cast v6, Lcom/android/systemui/util/leak/TrackedGarbage$LeakReference;

    invoke-static {v6}, Lcom/android/systemui/util/leak/TrackedGarbage$LeakReference;->-get0(Lcom/android/systemui/util/leak/TrackedGarbage$LeakReference;)Ljava/lang/Class;

    move-result-object v9

    invoke-static {v6}, Lcom/android/systemui/util/leak/TrackedGarbage$LeakReference;->-get0(Lcom/android/systemui/util/leak/TrackedGarbage$LeakReference;)Ljava/lang/Class;

    move-result-object v8

    const/4 v10, 0x0

    invoke-static {v10}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v10

    invoke-virtual {v0, v8, v10}, Landroid/util/ArrayMap;->getOrDefault(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v8

    check-cast v8, Ljava/lang/Integer;

    invoke-virtual {v8}, Ljava/lang/Integer;->intValue()I

    move-result v8

    add-int/lit8 v8, v8, 0x1

    invoke-static {v8}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v8

    invoke-virtual {v0, v9, v8}, Landroid/util/ArrayMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

    invoke-static {v6}, Lcom/android/systemui/util/leak/TrackedGarbage$LeakReference;->-get1(Lcom/android/systemui/util/leak/TrackedGarbage$LeakReference;)J

    move-result-wide v8

    invoke-direct {p0, v8, v9, v4, v5}, Lcom/android/systemui/util/leak/TrackedGarbage;->isOld(JJ)Z

    move-result v8

    if-eqz v8, :cond_0

    invoke-static {v6}, Lcom/android/systemui/util/leak/TrackedGarbage$LeakReference;->-get0(Lcom/android/systemui/util/leak/TrackedGarbage$LeakReference;)Ljava/lang/Class;

    move-result-object v9

    invoke-static {v6}, Lcom/android/systemui/util/leak/TrackedGarbage$LeakReference;->-get0(Lcom/android/systemui/util/leak/TrackedGarbage$LeakReference;)Ljava/lang/Class;

    move-result-object v8

    const/4 v10, 0x0

    invoke-static {v10}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v10

    invoke-virtual {v1, v8, v10}, Landroid/util/ArrayMap;->getOrDefault(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v8

    check-cast v8, Ljava/lang/Integer;

    invoke-virtual {v8}, Ljava/lang/Integer;->intValue()I

    move-result v8

    add-int/lit8 v8, v8, 0x1

    invoke-static {v8}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v8

    invoke-virtual {v1, v9, v8}, Landroid/util/ArrayMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    goto :goto_0

    :catchall_0
    move-exception v8

    monitor-exit p0

    throw v8

    :cond_1
    :try_start_1
    invoke-virtual {v0}, Landroid/util/ArrayMap;->entrySet()Ljava/util/Set;

    move-result-object v8

    invoke-interface {v8}, Ljava/lang/Iterable;->iterator()Ljava/util/Iterator;

    move-result-object v3

    :goto_1
    invoke-interface {v3}, Ljava/util/Iterator;->hasNext()Z

    move-result v8

    if-eqz v8, :cond_2

    invoke-interface {v3}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v2

    check-cast v2, Ljava/util/Map$Entry;

    invoke-interface {v2}, Ljava/util/Map$Entry;->getKey()Ljava/lang/Object;

    move-result-object v8

    check-cast v8, Ljava/lang/Class;

    invoke-virtual {v8}, Ljava/lang/Class;->getName()Ljava/lang/String;

    move-result-object v8

    invoke-virtual {p1, v8}, Ljava/io/PrintWriter;->print(Ljava/lang/String;)V

    const-string/jumbo v8, ": "

    invoke-virtual {p1, v8}, Ljava/io/PrintWriter;->print(Ljava/lang/String;)V

    invoke-interface {v2}, Ljava/util/Map$Entry;->getValue()Ljava/lang/Object;

    move-result-object v8

    invoke-virtual {p1, v8}, Ljava/io/PrintWriter;->print(Ljava/lang/Object;)V

    const-string/jumbo v8, " total, "

    invoke-virtual {p1, v8}, Ljava/io/PrintWriter;->print(Ljava/lang/String;)V

    invoke-interface {v2}, Ljava/util/Map$Entry;->getKey()Ljava/lang/Object;

    move-result-object v8

    const/4 v9, 0x0

    invoke-static {v9}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v9

    invoke-virtual {v1, v8, v9}, Landroid/util/ArrayMap;->getOrDefault(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v8

    invoke-virtual {p1, v8}, Ljava/io/PrintWriter;->print(Ljava/lang/Object;)V

    const-string/jumbo v8, " old"

    invoke-virtual {p1, v8}, Ljava/io/PrintWriter;->print(Ljava/lang/String;)V

    invoke-virtual {p1}, Ljava/io/PrintWriter;->println()V
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_0

    goto :goto_1

    :cond_2
    monitor-exit p0

    return-void
.end method

.method public declared-synchronized track(Ljava/lang/Object;)V
    .locals 3

    monitor-enter p0

    :try_start_0
    invoke-direct {p0}, Lcom/android/systemui/util/leak/TrackedGarbage;->cleanUp()V

    iget-object v0, p0, Lcom/android/systemui/util/leak/TrackedGarbage;->mGarbage:Ljava/util/HashSet;

    new-instance v1, Lcom/android/systemui/util/leak/TrackedGarbage$LeakReference;

    iget-object v2, p0, Lcom/android/systemui/util/leak/TrackedGarbage;->mRefQueue:Ljava/lang/ref/ReferenceQueue;

    invoke-direct {v1, p1, v2}, Lcom/android/systemui/util/leak/TrackedGarbage$LeakReference;-><init>(Ljava/lang/Object;Ljava/lang/ref/ReferenceQueue;)V

    invoke-virtual {v0, v1}, Ljava/util/HashSet;->add(Ljava/lang/Object;)Z

    iget-object v0, p0, Lcom/android/systemui/util/leak/TrackedGarbage;->mTrackedCollections:Lcom/android/systemui/util/leak/TrackedCollections;

    iget-object v1, p0, Lcom/android/systemui/util/leak/TrackedGarbage;->mGarbage:Ljava/util/HashSet;

    const-string/jumbo v2, "Garbage"

    invoke-virtual {v0, v1, v2}, Lcom/android/systemui/util/leak/TrackedCollections;->track(Ljava/util/Collection;Ljava/lang/String;)V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    monitor-exit p0

    return-void

    :catchall_0
    move-exception v0

    monitor-exit p0

    throw v0
.end method


text:
- Patch update: GHSA-rm36-94g8-835r - Race Condition in Grunt

## 1.6.0 - TBD

- jsonpath library is moved to new package jsonave.
- predicate library is retired.  Use combination of lodash methods negate,
  partialRight and has.
- objectset.merge, objectset.deepValue, object.deepValue, object.isObject,
  arrayset.remove, methods are retired.  Each has lodash equivalent.

## 1.5.0 - June 12, 2015

- jsonpath `wrap` options functionality is modified.  See README.
- jsonpath `emptyValue` option is added.
- jsonpath functions can be specified during evaluation call
- predicate.not is added.

## v1.4.2 - March 29, 2015

- jsonpath library is added

## v1.4.1 - March 8, 2015

- object.deepValue(obj, deepProperty);
- objectset.deepValue(obj, deepProperty, value)
- predicate.hasProperty
- predicate.hasNoProperty
- predicate.inValueSet
- predicate.hasNoProperties
- predicate.propertyValue
- predicate.falsyPropertyValue
- predicate.or
- predicate.and
- examples are added to documentation

## v1.4.0 - February 27, 2015

This is the initial release of blue-button-util.js library.  It includes javascript utility methods.

- object.exists()
- datetime.dateToModel(dt)
- datetime.modelToDate(dt)
- datetime.modelToDateTime(dt)
- arrayset.append(arr, arrToAppend)
- objectset.compact(obj)
- objectset.merge(obj, src)


text:
declare namespace simpleDiff {
    type Path = Array<string | number>;

    interface AddEvent {
        oldPath: Path;
        newPath: Path;
        type: 'add';
        oldValue: undefined;
        newValue: unknown;
    }

    interface RemoveEvent {
        oldPath: Path;
        newPath: Path;
        type: 'remove';
        oldValue: unknown;
        newValue: undefined;
    }

    interface ChangeEvent {
        oldPath: Path;
        newPath: Path;
        type: 'change';
        oldValue: unknown;
        newValue: unknown;
    }

    interface AddItemEvent {
        oldPath: Path;
        newPath: Path;
        type: 'add-item';
        oldIndex: -1;
        curIndex: -1;
        newIndex: number;
        newValue: unknown;
    }

    interface RemoveItemEvent {
        oldPath: Path;
        newPath: Path;
        type: 'remove-item';
        oldIndex: number;
        curIndex: number;
        newIndex: -1;
        oldValue: unknown;
    }

    interface MoveItemEvent {
        oldPath: Path;
        newPath: Path;
        type: 'move-item';
        oldIndex: number;
        curIndex: number;
        newIndex: number;
    }

    type Event =
        | AddEvent
        | RemoveEvent
        | ChangeEvent
        | AddItemEvent
        | RemoveItemEvent
        | MoveItemEvent;

    interface Options {
        idProp?: string | undefined;
        idProps?: {
            [path: string]: string;
        } | undefined;
        comparators?: Array<[
            unknown,
            (
                oldValue: unknown,
                newValue: unknown,
                options: { oldPath: Path; newPath: Path }
            ) => boolean
        ]> | undefined;
        ignore?: ((
            oldValue: unknown,
            newValue: unknown,
            options: { oldPath: Path; newPath: Path }
        ) => boolean) | undefined;
        callback?: ((event: Event) => void) | undefined;
        addEvent?: string | undefined;
        changeEvent?: string | undefined;
        removeEvent?: string | undefined;
        addItemEvent?: string | undefined;
        removeItemEvent?: string | undefined;
        moveItemEvent?: string | undefined;
    }
}

declare function simpleDiff(oldObj: unknown, newObj: unknown, options?: simpleDiff.Options): simpleDiff.Event[];

export as namespace simpleDiff;
export = simpleDiff;


text:
layout: category
category: 读书
tag: 小说
permalink: /blog/tag/小说/
group: horizontal
---


text:
package com.intellij.codeInsight.highlighting;

import com.intellij.openapi.editor.Editor;
import com.intellij.psi.*;
import com.intellij.psi.impl.light.LightRecordMember;
import com.intellij.util.Consumer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Collections;
import java.util.List;

import static com.intellij.util.ObjectUtils.tryCast;

public class HighlightRecordComponentsRecordFactory extends HighlightUsagesHandlerFactoryBase {
  @Nullable
  @Override
  public HighlightUsagesHandlerBase<?> createHighlightUsagesHandler(@NotNull Editor editor,
                                                                    @NotNull PsiFile file,
                                                                    @NotNull PsiElement target) {
    if (!(target instanceof PsiIdentifier)) return null;
    PsiElement parent = target.getParent();
    if (!(parent instanceof PsiReferenceExpression)) return null;
    PsiElement resolved = ((PsiReferenceExpression)parent).resolve();
    if (!(resolved instanceof LightRecordMember)) return null;

    LightRecordMember member = (LightRecordMember)resolved;
    PsiRecordComponent component = member.getRecordComponent();
    return new RecordComponentHighlightUsagesHandler(editor, file, component);
  }

  private static class RecordComponentHighlightUsagesHandler extends HighlightUsagesHandlerBase<PsiRecordComponent> {
    private final PsiRecordComponent myComponent;

    RecordComponentHighlightUsagesHandler(Editor editor, PsiFile file, PsiRecordComponent component) {
      super(editor, file);
      myComponent = component;
    }

    @Override
    public @NotNull List<PsiRecordComponent> getTargets() {
      return Collections.singletonList(myComponent);
    }

    @Override
    protected void selectTargets(@NotNull List<? extends PsiRecordComponent> targets, @NotNull Consumer<? super List<? extends PsiRecordComponent>> selectionConsumer) {
      selectionConsumer.consume(targets);
    }

    @Override
    public void computeUsages(@NotNull List<? extends PsiRecordComponent> targets) {
      assert targets.size() == 1;
      PsiRecordComponent record = targets.get(0);
      PsiIdentifier nameIdentifier = record.getNameIdentifier();
      if (nameIdentifier != null) {
        addOccurrence(nameIdentifier);
        final String name = nameIdentifier.getText();
        Consumer<PsiExpression> onOccurence = (expr) -> addOccurrence(expr);
        JavaRecursiveElementWalkingVisitor visitor = new JavaRecursiveElementWalkingVisitor() {
          @Override
          public void visitReferenceExpression(@NotNull PsiReferenceExpression expression) {
            super.visitReferenceExpression(expression);
            if (isReferenceToRecordComponent(name, expression)) {
              onOccurence.consume(expression);
            }
          }
        };
        myComponent.getContainingFile().accept(visitor);
      }
    }

    private boolean isReferenceToRecordComponent(String name, PsiReferenceExpression referenceExpression) {
      if (!name.equals(referenceExpression.getReferenceName())) return false;
      LightRecordMember recordMember = tryCast(referenceExpression.resolve(), LightRecordMember.class);
      if (recordMember == null) return false;
      return recordMember.getRecordComponent() == myComponent;
    }
  }
}


text:
module.exports = Em.View.extend({
  templateName: 'map',

  _eventMarkers: {},

  _update: function() {
    if(!this._map) return;

    this._rerenderEvents();
  }.observes('controller.filteredContent'),

  _updatePosition: function() {
    if(!this._map) return;

    var eventId = this.get('controller.currentEvent');
    this._panMapTo(eventId);
  }.observes('controller.currentEvent'),

  didInsertElement: function() {
  	this._map = L.map('map').setView([51.525, -0.09], 12);

    this._rerenderEvents();

  	L.tileLayer('http://{s}tile.stamen.com/toner/{z}/{x}/{y}.png', {
	    attribution: 'Ember Hackathon Wooooop',
	    maxZoom: 18,
	    subdomains: ["", "a.", "b.", "c.", "d."],
	    scheme: "xyz"
	  }).addTo(this._map);
  },

  _rerenderEvents: function() {
  	var _self = this;
    _self._cleanup();

    var events = this.get('controller.filteredContent');

    events.forEach(function(event) {
    	var marker = _self._toMarker(event);

		marker.addTo(_self._map)

		_self._eventMarkers[event.id] = marker;
    })
  },

  _cleanup: function() {
    var self = this;

   	$.each(this._eventMarkers, function(eventId, eventMarker) {
   		self._map.removeLayer(eventMarker);
   	})
  },

  _toMarker: function(event) {
  	var marker = L.marker([event.latitude, event.longitude]);
    var text = "" + event.title + "
" + event.address;
    marker.bindPopup(text).openPopup();

    return marker;
  },

  _panMapTo: function(eventId) {
    var marker = this._eventMarkers[eventId];
    console.log(marker);

    this._map.panTo(marker.getLatLng());
    this._map.setZoom(14);
  }
})


text:
var v = require('./visiting');

//rest api post 수신 (from json to json)

exports.doAction = function (req, res) {

	console.log("doAction start");

	actionProcess(req.body).then(data => {
		    return res.json(data);
		  }).catch(err => {
		    return res.status(err.code || 500).json(err);
	});

};

let actionProcess = (response) => {

	  return new Promise((resolved, rejected) => {
	    // Send the input to the conversation service

		  let processed = postProcess(response);
	        if(processed){
	          // return 값이 Promise 일 경우
	          if(typeof processed.then === 'function'){
	            processed.then(response => {
	              resolved(response);
	            }).catch(err => {
	              rejected(err);
	            })
	          }
	          // return 값이 변경된 data일 경우
	          else{
	            resolved(processed);
	          }
	        }
	        else{
	          // return 값이 없을 경우
	          resolved(response);
	        }
	  })
}

let postProcess = response => {
	  console.log("Conversation Output : " + response.output.text);
	  console.log("--------------------------------------------------");
	  if(response.context && response.context.action){
	    return v.doAction(response, response.context.action);
	  }
}


text:
angular.module('stroll.services', [])

.factory('', function () {

  return {
  };
});


text:
class AddUserIdToGivingGames < ActiveRecord::Migration
  def change
    add_column :giving_games, :user_id, :integer
  end
end


text:
package org.softeg.slartus.forpdaplus;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import org.softeg.slartus.forpdaapi.ProfileApi;
import org.softeg.slartus.forpdaapi.classes.LoginFormData;
import org.softeg.slartus.forpdaplus.common.AppLog;

import java.lang.ref.WeakReference;

import timber.log.Timber;

/**
 * User: slinkin
 * Date: 08.02.12
 * Time: 7:18
 */
public class LoginDialog {
    private String capTime;
    private String capSig;
    private final EditText username_edit;
    private final EditText password_edit;
    private final CheckBox privacy_checkbox;
    private final View mView;
    private final ImageView mImageView;
    private final ProgressBar mProgressBar;

    private final Context mContext;

    LoginDialog(Context context) {
        mContext = context;
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        assert inflater != null;
        mView = inflater.inflate(R.layout.login, null);

        mImageView = mView.findViewById(R.id.cap_img);
        mProgressBar = mView.findViewById(R.id.progressBar2);
        username_edit = mView.findViewById(R.id.username_edit);
        password_edit = mView.findViewById(R.id.password_edit);
        privacy_checkbox = mView.findViewById(R.id.privacy_checkbox);
        new CapTask(App.getContext()).execute();
        loadData();
    }

    protected View getView() {
        return mView;
    }

    void connect() {
        saveData();
        LoginTask loginTask = new LoginTask(mContext,
                username_edit.getText().toString(), password_edit.getText().toString(),
                privacy_checkbox.isChecked(),
                ((EditText) mView.findViewById(R.id.cap_value_ed)).getText().toString(),
                capTime, capSig);
        loginTask.execute(username_edit.getText().toString(), password_edit.getText().toString(),
                Boolean.toString(privacy_checkbox.isChecked()));
    }

    private void saveData() {
        App.getInstance().getPreferences().edit()
                .putBoolean("LoginPrivacy", privacy_checkbox.isChecked())
                .putString("Login", username_edit.getText().toString())
                .apply();
    }

    protected void loadData() {
        privacy_checkbox.setChecked(App.getInstance().getPreferences().getBoolean("LoginPrivacy", false));
        username_edit.setText(App.getInstance().getPreferences().getString("Login", ""));
    }

    public static void showDialog(final Context context) {
        final LoginDialog loginDialog = new LoginDialog(context);
        MaterialDialog dialog = new MaterialDialog.Builder(context)
                .title(R.string.login)
                .customView(loginDialog.getView(), true)
                .positiveText(R.string.login)
                .negativeText(R.string.cancel)
                .onPositive((dialog1, which) -> loginDialog.connect())
                .build();
        Window window = dialog.getWindow();
        assert window != null;
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        dialog.show();
    }

    public static void logout(Context context) {
        LogoutTask logoutTask = new LogoutTask(context);
        logoutTask.execute();
        App.getInstance().getPreferences().edit()
                .putBoolean("isRecdRepImage", false)
                .putString("repPlusImage", "https://s.4pda.to/ShmfPSURw3VD2aNlTerb3hvYwGCMxd4z0muJ.gif")
                .apply();
    }

    public class CapTask extends AsyncTask<String, Void, LoginFormData> {

        private final WeakReference<Context> context;

        CapTask(Context context) {
            this.context = new WeakReference<>(context);
        }

        @Override
        protected LoginFormData doInBackground(String... params) {
            try {
                return ProfileApi.getLoginForm(this.context.get());
            } catch (Exception e) {
                LoginFormData loginFormData = new LoginFormData();
                loginFormData.setError(e);
                return loginFormData;
            }
        }

        // can use UI thread here
        protected void onPreExecute() {
            mView.findViewById(R.id.progressBar2).setVisibility(View.VISIBLE);
        }

        protected void onCancelled() {
            Toast.makeText(mContext, R.string.canceled,
                    Toast.LENGTH_SHORT).show();
        }

        // can use UI thread here
        protected void onPostExecute(final LoginFormData loginFormData) {

            if (loginFormData.getError() == null) {
                ImageLoader.getInstance().displayImage(loginFormData.getCapPath(), mImageView, new SimpleImageLoadingListener() {
                    @Override
                    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                        Toast.makeText(mContext, R.string.failed_load_captcha, Toast.LENGTH_SHORT).show();
                        mProgressBar.setVisibility(View.GONE);
                    }

                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                        mProgressBar.setVisibility(View.GONE);
                    }
                });
                capTime = loginFormData.getCapTime();
                capSig = loginFormData.getCapSig();
            } else {

                AppLog.e(mContext, loginFormData.getError());

            }
        }

    }

    public static class LoginTask extends AsyncTask<String, Void, Boolean> {

        WeakReference<Context> mContext;
        private final MaterialDialog dialog;
        private final String login;
        private final String password;
        private final Boolean privacy;
        private final String capVal;
        private final String capTime;
        private final String capSig;

        LoginTask(Context context,
                  String login, String password, Boolean privacy,
                  String capVal, String capTime, String capSig) {
            mContext = new WeakReference<>(context);
            this.login = login;
            this.password = password;
            this.privacy = privacy;
            this.capVal = capVal;
            this.capTime = capTime;
            this.capSig = capSig;
            dialog = new MaterialDialog.Builder(mContext.get())
                    .progress(true, 0)
                    .cancelable(false)
                    .content(R.string.performing_login)
                    .build();
        }

        @Override
        protected Boolean doInBackground(String... params) {
            try {

                return Client.getInstance().login(login, password, privacy, capVal, capTime, capSig);
            } catch (Exception e) {

                ex = e;
                return false;
            }
        }

        // can use UI thread here
        protected void onPreExecute() {
            this.dialog.show();
        }

        protected void onCancelled() {
            Toast.makeText(mContext.get(), R.string.canceled,
                    Toast.LENGTH_SHORT).show();
        }

        private Exception ex;

        // can use UI thread here
        protected void onPostExecute(final Boolean success) {
            App.getInstance().getPreferences().edit().putBoolean("needLoadRepImage", success).apply();

            try {
                if (this.dialog.isShowing()) {
                    this.dialog.dismiss();
                }
                if (success) {
                    Toast.makeText(mContext.get(), R.string.login_performed,
                            Toast.LENGTH_SHORT).show();
                } else {
                    if (ex != null)
                        AppLog.e(mContext.get(), ex);
                    else
                        new MaterialDialog.Builder(mContext.get())
                                .title(R.string.error)
                                .content(Client.getInstance().getLoginFailedReason())
                                .positiveText(R.string.ok)
                                .show();
                }
            } catch (Throwable ex) {
                Timber.e(ex);
            }
        }

    }

    public static class LogoutTask extends AsyncTask<String, Void, Boolean> {

        WeakReference<Context> mContext;
        private final MaterialDialog dialog;

        LogoutTask(Context context) {
            mContext = new WeakReference<>(context);
            dialog = new MaterialDialog.Builder(context)
                    .progress(true, 0)
                    .cancelable(true)
                    .content(R.string.performing_logout)
                    .build();
        }

        @Override
        protected Boolean doInBackground(String... params) {
            try {

                return Client.getInstance().logout();
            } catch (Throwable e) {
                AppLog.e(mContext.get(), e);
                ex = e;
                return false;
            }
        }

        // can use UI thread here
        protected void onPreExecute() {
            this.dialog.show();
        }

        protected void onCancelled() {
            Toast.makeText(mContext.get(), R.string.canceled,
                    Toast.LENGTH_SHORT).show();
        }

        private Throwable ex;

        private void doOnUserChangedListener() {

        }

        // can use UI thread here
        protected void onPostExecute(final Boolean success) {
            if (this.dialog.isShowing()) {
                this.dialog.dismiss();
            }
            doOnUserChangedListener();
            App.getInstance().getPreferences().edit().putBoolean("needLoadRepImage", !success).apply();
            if (success) {
                Toast.makeText(mContext.get(), R.string.logout_performed,
                        Toast.LENGTH_SHORT).show();
            } else {
                if (ex != null)
                    AppLog.i(mContext.get(), ex);

            }
        }
    }
}


text:
/* SPDX-License-Identifier: MIT */

/**
 * Cloudflare Worker script acting as a reverse proxy.
 *
 * @see https://developers.cloudflare.com/workers/
 */

import { getAssetFromKV } from "@cloudflare/kv-asset-handler";
import * as configs from "../config";
import { createRelay, resolveRoute } from "../core";
import { transform } from "./transform";

async function handleEvent(event: FetchEvent) {
  const request = event.request;
  const url = new URL(event.request.url);
  const { pathname: path, hostname } = url;

  const config =
    hostname === new URL(configs.prod.app.origin).hostname
      ? configs.prod
      : configs.test;
  const version = hostname.match(/^(\d+)-/)?.[1];
  const api = {
    hostname: new URL(config.api.origin).hostname,
    pathname: version ? `/api_${version}` : "/api",
  };

  // Serve static assets from KV storage
  // https://github.com/cloudflare/kv-asset-handler
  if (
    path.startsWith("/static/") ||
    path.startsWith("/favicon.") ||
    path.startsWith("/logo") ||
    path.startsWith("/manifest.") ||
    path.startsWith("/robots.") ||
    path.endsWith(".png")
  ) {
    try {
      return getAssetFromKV(event, {
        cacheControl: { bypassCache: config.app.env !== "prod" },
      });
    } catch (err) {
      console.error(err);
    }
  }

  // GraphQL API and authentication
  if (
    path === "/api" ||
    path.startsWith("/api/") ||
    path.startsWith("/auth/")
  ) {
    url.hostname = api.hostname;
    url.pathname = `${api.pathname}${path}`;
    return fetch(new Request(url.toString(), request));
  }

  // Image resizing
  if (path.startsWith("/img/")) {
    url.hostname = api.hostname;
    return fetch(new Request(url.toString(), request));
  }

  // Fetch index.html page from KV storage
  url.pathname = "/index.html";
  const resPromise = getAssetFromKV(
    { ...event, request: new Request(url.toString(), request) },
    { cacheControl: { bypassCache: config.app.env !== "prod" } },
  );

  // Find application route matching the URL pathname
  const apiBaseUrl = `https://${api.hostname}${api.pathname}`;
  const relay = createRelay({ baseUrl: apiBaseUrl, request });
  const route = await resolveRoute({ path, relay });

  if (route.redirect) {
    return Response.redirect(route.redirect, route.status);
  }

  if (route.error) {
    relay.commitUpdate(function (store) {
      const root = store.getRoot();
      root.setValue(route.error?.stack, "error");
    });
  }

  // Inject page metadata such as <title>, <meta name="description" contents="..." />, etc.
  // and serialized API response <script id="data" type="application/json">...</script>
  // https://developer.mozilla.org/docs/Web/HTML/Element/script#embedding_data_in_html
  const res = transform(await resPromise, route, relay, config);
  return new Response(res.body, {
    status: (route.error as unknown as { status: number })?.status || 200,
    headers: res.headers,
  });
}

addEventListener("fetch", function (event: FetchEvent) {
  event.respondWith(handleEvent(event));
});


text:
package com.mcxtzhang.asm;

import com.sun.xml.internal.ws.org.objectweb.asm.ClassAdapter;
import com.sun.xml.internal.ws.org.objectweb.asm.ClassReader;
import com.sun.xml.internal.ws.org.objectweb.asm.ClassWriter;

import java.io.File;
import java.io.FileOutputStream;

public class Generator {
    public static void main(String[] args) throws Exception {
        ClassReader cr = new ClassReader("Person");
        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
        ClassAdapter classAdapter = new AddSecurityCheckClassAdapter(cw);
        cr.accept(classAdapter, ClassReader.SKIP_DEBUG);
        byte[] data = cw.toByteArray();
        File file = new File("Person.class");
        FileOutputStream fout = new FileOutputStream(file);
        fout.write(data);
        fout.close();
    }
}


text:
package org.apache.shardingsphere.shardingscaling.core.config;

import lombok.Getter;
import lombok.Setter;

/**
 * Scaling configuration.
 */
@Setter
@Getter
public final class ScalingConfiguration {

    private RuleConfiguration ruleConfiguration;

    private JobConfiguration jobConfiguration;
}


text:
<?php

namespace OAuthServer\Model\Entity;

use Cake\ORM\Entity;
use Cake\ORM\TableRegistry;
use Cake\Utility\Security;
use Cake\Utility\Text;

class Client extends Entity
{
    /**
     * Create a new, pretty (as in moderately, not beautiful - that can't be guaranteed ;-) random client secret
     *
     * @return void
     */
    public function generateSecret()
    {
        $this->client_secret = Security::hash(Text::uuid(), 'sha1', true);
        $this->_original['client_secret'] = $this->client_secret;
    }

    /**
     * @return \Cake\Datasource\EntityInterface|mixed|null
     */
    protected function _getParent()
    {
        if (empty($this->parent_model)) {
            return null;
        }
        $parent_table = TableRegistry::get($this->parent_model);
        return $parent_table->get($this->parent_id);
    }

    /**
     * @param string $name Existing name
     * @return string
     */
    protected function _getName($name)
    {
        $parent = $this->parent;

        return $parent ? $parent->name : $name;
    }
}


text:
#ifndef ACCELERATORLOGIC_H
#define ACCELERATORLOGIC_H

#include <Engine/Logic.h>

/**
 * @brief Accelerates Body%s that are in contact with the AcceleratorLogic's #actor in the
 * direction that they are moving.
 */
class AcceleratorLogic : public Logic {
    Q_OBJECT

    /**
     * @brief How much the contacting Body%s are accelerated each frame.
     * @default{3.0f}
     */
    Q_PROPERTY(float acceleration READ getAcceleration WRITE setAcceleration
            NOTIFY accelerationChanged)
public:
    /**
     * @brief Returns #acceleration.
     */
    float getAcceleration() const { return mAcceleration; }
    /**
     * @brief Sets #acceleration.
     * @param value Float to set #acceleration to
     */
    void setAcceleration(float value);

    /**
     * @brief Checks the AcceleratorLogic has an #actor with a Body.
     */
    virtual void init() override;

    /**
     * @brief Uses Body::applyForceToCenter() to accelerate Body%s in contact with #actor.
     */
    virtual void update() override;

signals:
    /**
     * @brief Emitted when #acceleration changes.
     */
    void accelerationChanged();

private:
    float mAcceleration = 3.0f;
};
Q_DECLARE_METATYPE(AcceleratorLogic*)

#endif // ACCELERATORLOGIC_H


text:
/**
 * Test the repo list item
 */

import React from 'react';
import { shallow, render } from 'enzyme';
import { IntlProvider } from 'react-intl';

import ListItem from 'components/ListItem';
import { RepoListItem } from '../index';

const renderComponent = (props = {}) =>
  render(
    <IntlProvider locale="en">
      <RepoListItem {...props} />
    </IntlProvider>
  );

describe('<RepoListItem />', () => {
  let item;

  // Before each test reset the item data for safety
  beforeEach(() => {
    item = {
      owner: {
        login: 'mxstbr',
      },
      html_url: 'https://github.com/mxstbr/react-boilerplate',
      name: 'react-boilerplate',
      open_issues_count: 20,
      full_name: 'mxstbr/react-boilerplate',
    };
  });

  it('should render a ListItem', () => {
    const renderedComponent = shallow(<RepoListItem item={item} />);
    expect(renderedComponent.find(ListItem).length).toBe(1);
  });

  it('should not render the current username', () => {
    const renderedComponent = renderComponent({
      item,
      currentUser: item.owner.login,
    });
    expect(renderedComponent.text()).not.toContain(item.owner.login);
  });

  it('should render usernames that are not the current one', () => {
    const renderedComponent = renderComponent({
      item,
      currentUser: 'nikgraf',
    });
    expect(renderedComponent.text()).toContain(item.owner.login);
  });

  it('should render the repo name', () => {
    const renderedComponent = renderComponent({ item });
    expect(renderedComponent.text()).toContain(item.name);
  });

  it('should render the issue count', () => {
    const renderedComponent = renderComponent({ item });
    expect(renderedComponent.text()).toContain(item.open_issues_count);
  });

  it('should render the IssueIcon', () => {
    const renderedComponent = renderComponent({ item });
    expect(renderedComponent.find('svg').length).toBe(1);
  });
});


text:
/* $NetBSD: bus_dma.c,v 1.2.4.2 2000/06/30 16:27:31 simonb Exp $	*/

/*
 * This file was taken from from next68k/dev/bus_dma.c, which was originally
 * taken from alpha/common/bus_dma.c.
 * It should probably be re-synced when needed.
 * original cvs id: NetBSD: bus_dma.c,v 1.13 1999/11/13 00:30:40 thorpej Exp
 */

/*-
 * Copyright (c) 1997, 1998 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
 * NASA Ames Research Center.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the NetBSD
 *	Foundation, Inc. and its contributors.
 * 4. Neither the name of The NetBSD Foundation nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/cdefs.h>			/* RCS ID & Copyright macro defns */

__KERNEL_RCSID(0, "$NetBSD: bus_dma.c,v 1.2.4.2 2000/06/30 16:27:31 simonb Exp $");

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/device.h>
#include <sys/malloc.h>
#include <sys/proc.h>
#include <sys/mbuf.h>
#include <sys/kcore.h>

#include <vm/vm.h>
#include <vm/vm_kern.h>

#include <uvm/uvm_extern.h>

#include <machine/cpu.h>
#include <machine/pmap.h>
#define _MVME68K_BUS_DMA_PRIVATE
#include <machine/bus.h>
#include <m68k/cacheops.h>

extern	phys_ram_seg_t mem_clusters[];

int	_bus_dmamap_load_buffer_direct_common __P((bus_dma_tag_t,
	    bus_dmamap_t, void *, bus_size_t, struct proc *, int,
	    paddr_t *, int *, int));

/*
 * Common function for DMA map creation.  May be called by bus-specific
 * DMA map creation functions.
 */
int
_bus_dmamap_create(t, size, nsegments, maxsegsz, boundary, flags, dmamp)
	bus_dma_tag_t t;
	bus_size_t size;
	int nsegments;
	bus_size_t maxsegsz;
	bus_size_t boundary;
	int flags;
	bus_dmamap_t *dmamp;
{
	struct mvme68k_bus_dmamap *map;
	void *mapstore;
	size_t mapsize;

	/*
	 * Allcoate and initialize the DMA map.  The end of the map
	 * is a variable-sized array of segments, so we allocate enough
	 * room for them in one shot.
	 *
	 * Note we don't preserve the WAITOK or NOWAIT flags.  Preservation
	 * of ALLOCNOW notifes others that we've reserved these resources,
	 * and they are not to be freed.
	 *
	 * The bus_dmamap_t includes one bus_dma_segment_t, hence
	 * the (nsegments - 1).
	 */
	mapsize = sizeof(struct mvme68k_bus_dmamap) +
	    (sizeof(bus_dma_segment_t) * (nsegments - 1));
	if ((mapstore = malloc(mapsize, M_DMAMAP,
	    (flags & BUS_DMA_NOWAIT) ? M_NOWAIT : M_WAITOK)) == NULL)
		return (ENOMEM);

	bzero(mapstore, mapsize);
	map = (struct mvme68k_bus_dmamap *)mapstore;
	map->_dm_size = size;
	map->_dm_segcnt = nsegments;
	map->_dm_maxsegsz = maxsegsz;
	map->_dm_boundary = boundary;
	map->_dm_flags = flags & ~(BUS_DMA_WAITOK|BUS_DMA_NOWAIT);
	map->dm_mapsize = 0;		/* no valid mappings */
	map->dm_nsegs = 0;

	*dmamp = map;
	return (0);
}

/*
 * Common function for DMA map destruction.  May be called by bus-specific
 * DMA map destruction functions.
 */
void
_bus_dmamap_destroy(t, map)
	bus_dma_tag_t t;
	bus_dmamap_t map;
{

	free(map, M_DMAMAP);
}

/*
 * Utility function to load a linear buffer.  lastaddrp holds state
 * between invocations (for multiple-buffer loads).  segp contains
 * the starting segment on entrance, and the ending segment on exit.
 * first indicates if this is the first invocation of this function.
 */
int
_bus_dmamap_load_buffer_direct_common(t, map, buf, buflen, p, flags,
    lastaddrp, segp, first)
	bus_dma_tag_t t;
	bus_dmamap_t map;
	void *buf;
	bus_size_t buflen;
	struct proc *p;
	int flags;
	paddr_t *lastaddrp;
	int *segp;
	int first;
{
	bus_size_t sgsize;
	bus_addr_t curaddr, lastaddr, baddr, bmask;
	vaddr_t vaddr = (vaddr_t)buf;
	int seg;

	lastaddr = *lastaddrp;
	bmask = ~(map->_dm_boundary - 1);

	for (seg = *segp; buflen > 0 ; ) {
		/*
		 * Get the physical address for this segment.
		 */
		if (p != NULL)
			(void) pmap_extract(p->p_vmspace->vm_map.pmap,
			    vaddr, &curaddr);
		else
			(void) pmap_extract(pmap_kernel(),vaddr, &curaddr);

		/*
		 * Compute the segment size, and adjust counts.
		 */
		sgsize = NBPG - ((u_long)vaddr & PGOFSET);
		if (buflen < sgsize)
			sgsize = buflen;

		/*
		 * Make sure we don't cross any boundaries.
		 */
		if (map->_dm_boundary > 0) {
			baddr = (curaddr + map->_dm_boundary) & bmask;
			if (sgsize > (baddr - curaddr))
				sgsize = (baddr - curaddr);
		}

		/*
		 * Insert chunk into a segment, coalescing with
		 * the previous segment if possible.
		 */
		if (first) {
			map->dm_segs[seg].ds_addr = curaddr;
			map->dm_segs[seg].ds_len = sgsize;
			first = 0;
		} else {
			if (curaddr == lastaddr &&
			    (map->dm_segs[seg].ds_len + sgsize) <=
			     map->_dm_maxsegsz &&
			    (map->_dm_boundary == 0 ||
			     (map->dm_segs[seg].ds_addr & bmask) ==
			     (curaddr & bmask)))
				map->dm_segs[seg].ds_len += sgsize;
			else {
				if (++seg >= map->_dm_segcnt)
					break;
				map->dm_segs[seg].ds_addr = curaddr;
				map->dm_segs[seg].ds_len = sgsize;
			}
		}

		lastaddr = curaddr + sgsize;
		vaddr += sgsize;
		buflen -= sgsize;
	}

	*segp = seg;
	*lastaddrp = lastaddr;

	/*
	 * Did we fit?
	 */
	if (buflen != 0) {
		/*
		 * If there is a chained window, we will automatically
		 * fall back to it.
		 */
		return (EFBIG);		/* XXX better return value here? */
	}

	return (0);
}

/*
 * Common function for loading a direct-mapped DMA map with a linear
 * buffer.  Called by bus-specific DMA map load functions with the
 * OR value appropriate for indicating "direct-mapped" for that
 * chipset.
 */
int
_bus_dmamap_load_direct(t, map, buf, buflen, p, flags)
	bus_dma_tag_t t;
	bus_dmamap_t map;
	void *buf;
	bus_size_t buflen;
	struct proc *p;
	int flags;
{
	paddr_t lastaddr;
	int seg, error;

	/*
	 * Make sure that on error condition we return "no valid mappings".
	 */
	map->dm_mapsize = 0;
	map->dm_nsegs = 0;

	if (buflen > map->_dm_size)
		return (EINVAL);

	seg = 0;
	error = _bus_dmamap_load_buffer_direct_common(t, map, buf, buflen,
	    p, flags, &lastaddr, &seg, 1);
	if (error == 0) {
		map->dm_mapsize = buflen;
		map->dm_nsegs = seg + 1;
	}
	return (error);
}

/*
 * Like _bus_dmamap_load_direct_common(), but for mbufs.
 */
int
_bus_dmamap_load_mbuf_direct(t, map, m0, flags)
	bus_dma_tag_t t;
	bus_dmamap_t map;
	struct mbuf *m0;
	int flags;
{
	paddr_t lastaddr;
	int seg, error, first;
	struct mbuf *m;

	/*
	 * Make sure that on error condition we return "no valid mappings."
	 */
	map->dm_mapsize = 0;
	map->dm_nsegs = 0;

#ifdef DIAGNOSTIC
	if ((m0->m_flags & M_PKTHDR) == 0)
		panic("_bus_dmamap_load_mbuf_direct_common: no packet header");
#endif

	if (m0->m_pkthdr.len > map->_dm_size)
		return (EINVAL);

	first = 1;
	seg = 0;
	error = 0;
	for (m = m0; m != NULL && error == 0; m = m->m_next) {
		error = _bus_dmamap_load_buffer_direct_common(t, map,
		    m->m_data, m->m_len, NULL, flags, &lastaddr, &seg, first);
		first = 0;
	}
	if (error == 0) {
		map->dm_mapsize = m0->m_pkthdr.len;
		map->dm_nsegs = seg + 1;
	}
	return (error);
}

/*
 * Like _bus_dmamap_load_direct_common(), but for uios.
 */
int
_bus_dmamap_load_uio_direct(t, map, uio, flags)
	bus_dma_tag_t t;
	bus_dmamap_t map;
	struct uio *uio;
	int flags;
{
	paddr_t lastaddr;
	int seg, i, error, first;
	bus_size_t minlen, resid;
	struct proc *p = NULL;
	struct iovec *iov;
	caddr_t addr;

	/*
	 * Make sure that on error condition we return "no valid mappings."
	 */
	map->dm_mapsize = 0;
	map->dm_nsegs = 0;

	resid = uio->uio_resid;
	iov = uio->uio_iov;

	if (uio->uio_segflg == UIO_USERSPACE) {
		p = uio->uio_procp;
#ifdef DIAGNOSTIC
		if (p == NULL)
			panic("_bus_dmamap_load_direct_common: USERSPACE but no proc");
#endif
	}

	first = 1;
	seg = 0;
	error = 0;
	for (i = 0; i < uio->uio_iovcnt && resid != 0 && error == 0; i++) {
		/*
		 * Now at the first iovec to load.  Load each iovec
		 * until we have exhausted the residual count.
		 */
		minlen = resid < iov[i].iov_len ? resid : iov[i].iov_len;
		addr = (caddr_t)iov[i].iov_base;

		error = _bus_dmamap_load_buffer_direct_common(t, map,
		    addr, minlen, p, flags, &lastaddr, &seg, first);
		first = 0;

		resid -= minlen;
	}
	if (error == 0) {
		map->dm_mapsize = uio->uio_resid;
		map->dm_nsegs = seg + 1;
	}
	return (error);
}

/*
 * Like _bus_dmamap_load_direct_common(), but for raw memory.
 */
int
_bus_dmamap_load_raw_direct(t, map, segs, nsegs, size, flags)
	bus_dma_tag_t t;
	bus_dmamap_t map;
	bus_dma_segment_t *segs;
	int nsegs;
	bus_size_t size;
	int flags;
{
	/* @@@ This routine doesn't enforce map boundary requirement
	 * @@@ perhaps it should return an error instead of panicing
	 */

#ifdef DIAGNOSTIC
	if (map->_dm_size < size) {
		panic("_bus_dmamap_load_raw_direct: size is too large for map");
	}
	if (map->_dm_segcnt < nsegs) {
		panic("_bus_dmamap_load_raw_direct: too many segments for map");
	}
#endif

	{
		int i;
		for (i=0;i<nsegs;i++) {
#ifdef DIAGNOSTIC
			if (map->_dm_maxsegsz < map->dm_segs[i].ds_len) {
				panic("_bus_dmamap_load_raw_direct: segment too large for map");
			}
#endif
			map->dm_segs[i] = segs[i];
		}
	}

	map->dm_nsegs   = nsegs;
	map->dm_mapsize = size;

	return (0);
}

/*
 * Common function for unloading a DMA map.  May be called by
 * chipset-specific DMA map unload functions.
 */
void
_bus_dmamap_unload(t, map)
	bus_dma_tag_t t;
	bus_dmamap_t map;
{

	/*
	 * No resources to free; just mark the mappings as
	 * invalid.
	 */
	map->dm_mapsize = 0;
	map->dm_nsegs = 0;
}

/*
 * Common function for DMA map synchronization.  May be called
 * by chipset-specific DMA map synchronization functions.
 */
void
_bus_dmamap_sync(t, map, offset, len, ops)
	bus_dma_tag_t t;
	bus_dmamap_t map;
	bus_addr_t offset;
	bus_size_t len;
	int ops;
{
	/* flush/purge the cache.
	 * assumes pointers are aligned
	 * @@@ should probably be fixed to use offset and len args.
	 */

#if defined(DIAGNOSTIC) || defined(M68040)	/* XXX: Until 030/060 catered for */

	if (ops & BUS_DMASYNC_PREWRITE) {
		int i;
		for(i=0;i<map->dm_nsegs;i++) {
			bus_addr_t p = map->dm_segs[i].ds_addr;
			bus_addr_t e = p+map->dm_segs[i].ds_len;
#ifdef DIAGNOSTIC
			if ((p % 16) || (e % 16)) {
				panic("unaligned address in _bus_dmamap_sync "
				    "while flushing.\n"
				    "address=0x%08lx, end=0x%08lx, ops=0x%x",
				    p, e, ops);
			}
#endif
/*
 * Need stuff for 030 & 060
 */
#ifdef M68040
			if (mmutype == MMU_68040) {
				while((p<e)&&(!p%NBPG)) {
					DCFL(p);	/* flush cache line */
					p += 16;
				}
				while(p+NBPG<=e) {
					DCFP(p);	/* flush page */
					p += NBPG;
				}
				while(p<e) {
					DCFL(p);	/* flush cache line */
					p += 16;
				}
			}
#endif
#ifdef DIAGNOSTIC
			if (p != e) {
				panic("overrun in _bus_dmamap_sync while "
				    "flushing.\n"
				    "address=0x%08lx, end=0x%08lx, ops=0x%x",
				    p, e, ops);
			}
#endif
		}
	}

	if (ops & BUS_DMASYNC_POSTREAD) {
		int i;
		for(i=0;i<map->dm_nsegs;i++) {
			bus_addr_t p = map->dm_segs[i].ds_addr;
			bus_addr_t e = p+map->dm_segs[i].ds_len;
#ifdef DIAGNOSTIC
			if ((p % 16) || (e % 16)) {
				panic("unaligned address in _bus_dmamap_sync "
				    "while purging.\n"
				    "address=0x%08lx, end=0x%08lx, ops=0x%x",
				    p, e, ops);
			}
#endif
#ifdef M68040
			if (mmutype == MMU_68040) {
				while((p<e)&&(!p%NBPG)) {
					DCPL(p);	/* purge cache line */
					p += 16;
				}
				while(p+NBPG<=e) {
					DCPP(p);	/* purge page */
					p += NBPG;
				}
				while(p<e) {
					DCPL(p);	/* purge cache line */
					p += 16;
				}
			}
#endif
#ifdef DIAGNOSTIC
			if (p != e) {
				panic("overrun in _bus_dmamap_sync while "
				    "flushing.\n"
				    "address=0x%08lx, end=0x%08lx, ops=0x%x",
				    p, e, ops);
			}
#endif
		}
	}
#endif
}

/*
 * Common function for DMA-safe memory allocation.  May be called
 * by bus-specific DMA memory allocation functions.
 */
int
_bus_dmamem_alloc(t, size, alignment, boundary, segs, nsegs, rsegs, flags)
	bus_dma_tag_t t;
	bus_size_t size, alignment, boundary;
	bus_dma_segment_t *segs;
	int nsegs;
	int *rsegs;
	int flags;
{
	extern paddr_t avail_start, avail_end;
	paddr_t curaddr, lastaddr, high;
	vm_page_t m;
	struct pglist mlist;
	int curseg, error;

	/* Always round the size. */
	size = round_page(size);

	/*
	 * Assume any memory will do (this includes off-board RAM)
	 */
	high = avail_end;

	if ( (flags & BUS_DMA_ONBOARD_RAM) != 0 ) {
		/*
		 * Constrain the memory to 'onboard' RAM only
		 */
		high = mem_clusters[0].size;
	}

	if ( (flags & BUS_DMA_24BIT) != 0 && (high & 0xff000000u) != 0 ) {
		/*
		 * We need to constrain the memory to a 24-bit address
		 */
		high = 0x01000000u;
	}

	high -= PAGE_SIZE;

	/*
	 * Allocate pages from the VM system.
	 *
	 * XXXSCW: This will be sub-optimal if the base-address of offboard
	 * RAM is significantly higher than the end-address of onboard RAM.
	 * (Due to how uvm_pglistalloc() is implemented.)
	 *
	 * uvm_pglistalloc() also currently ignores the 'nsegs' parameter,
	 * and always returns only one (contiguous) segment.
	 */
	TAILQ_INIT(&mlist);
	error = uvm_pglistalloc(size, avail_start, high, alignment, boundary,
	    &mlist, nsegs, (flags & BUS_DMA_NOWAIT) == 0);
	if (error)
		return (error);

	/*
	 * Compute the location, size, and number of segments actually
	 * returned by the VM code.
	 */
	m = mlist.tqh_first;
	curseg = 0;
	lastaddr = segs[curseg].ds_addr = VM_PAGE_TO_PHYS(m);
	segs[curseg].ds_len = PAGE_SIZE;
	m = m->pageq.tqe_next;

	for (; m != NULL; m = m->pageq.tqe_next) {
		if ( curseg > nsegs ) {
#ifdef DIAGNOSTIC
			printf("_bus_dmamem_alloc: too many segments!\n");
#ifdef DEBUG
			panic("_bus_dmamem_alloc");
#endif
#endif
			uvm_pglistfree(&mlist);
			return (-1);
		}

		curaddr = VM_PAGE_TO_PHYS(m);
#ifdef DIAGNOSTIC
		if (curaddr < avail_start || curaddr >= high) {
			printf("vm_page_alloc_memory returned non-sensical"
			    " address 0x%lx\n", curaddr);
			panic("_bus_dmamem_alloc");
		}
#endif
		if (curaddr == (lastaddr + PAGE_SIZE))
			segs[curseg].ds_len += PAGE_SIZE;
		else {
			curseg++;
			segs[curseg].ds_addr = curaddr;
			segs[curseg].ds_len = PAGE_SIZE;
		}
		lastaddr = curaddr;
	}

	*rsegs = curseg + 1;

	return (0);
}

/*
 * Common function for freeing DMA-safe memory.  May be called by
 * bus-specific DMA memory free functions.
 */
void
_bus_dmamem_free(t, segs, nsegs)
	bus_dma_tag_t t;
	bus_dma_segment_t *segs;
	int nsegs;
{
	vm_page_t m;
	bus_addr_t addr;
	struct pglist mlist;
	int curseg;

	/*
	 * Build a list of pages to free back to the VM system.
	 */
	TAILQ_INIT(&mlist);
	for (curseg = 0; curseg < nsegs; curseg++) {
		for (addr = segs[curseg].ds_addr;
		    addr < (segs[curseg].ds_addr + segs[curseg].ds_len);
		    addr += PAGE_SIZE) {
			m = PHYS_TO_VM_PAGE(addr);
			TAILQ_INSERT_TAIL(&mlist, m, pageq);
		}
	}

	uvm_pglistfree(&mlist);
}

/*
 * Common function for mapping DMA-safe memory.  May be called by
 * bus-specific DMA memory map functions.
 */
int
_bus_dmamem_map(t, segs, nsegs, size, kvap, flags)
	bus_dma_tag_t t;
	bus_dma_segment_t *segs;
	int nsegs;
	size_t size;
	caddr_t *kvap;
	int flags;
{
	vaddr_t va;
	bus_addr_t addr;
	int curseg;

	size = round_page(size);

	va = uvm_km_valloc(kernel_map, size);

	if (va == 0)
		return (ENOMEM);

	*kvap = (caddr_t)va;

	for (curseg = 0; curseg < nsegs; curseg++) {
		for (addr = segs[curseg].ds_addr;
		    addr < (segs[curseg].ds_addr + segs[curseg].ds_len);
		    addr += NBPG, va += NBPG, size -= NBPG) {
			if (size == 0)
				panic("_bus_dmamem_map: size botch");

			pmap_enter(pmap_kernel(), va, addr,
			    VM_PROT_READ | VM_PROT_WRITE,
			    VM_PROT_READ | VM_PROT_WRITE | PMAP_WIRED);

			/* Cache-inhibit the page if necessary */
			if ( (flags & BUS_DMA_COHERENT) != 0 )
				_pmap_set_page_cacheinhibit(pmap_kernel(), va);
		}
	}

	if ( (flags & BUS_DMA_COHERENT) != 0 )
		TBIAS();

	return (0);
}

/*
 * Common function for unmapping DMA-safe memory.  May be called by
 * bus-specific DMA memory unmapping functions.
 */
void
_bus_dmamem_unmap(t, kva, size)
	bus_dma_tag_t t;
	caddr_t kva;
	size_t size;
{
	caddr_t va;
	size_t s;

#ifdef DIAGNOSTIC
	if ((u_long)kva & PGOFSET)
		panic("_bus_dmamem_unmap");
#endif

	size = round_page(size);

	/*
	 * Re-enable cacheing on the range
	 * XXXSCW: There should be some way to indicate that the pages
	 * were mapped DMA_MAP_COHERENT in the first place...
	 */
	for (s = 0, va = kva; s < size; s += PAGE_SIZE, va += PAGE_SIZE)
		_pmap_set_page_cacheable(pmap_kernel(), (vaddr_t)va);

	uvm_km_free(kernel_map, (vaddr_t)kva, size);
}

/*
 * Common functin for mmap(2)'ing DMA-safe memory.  May be called by
 * bus-specific DMA mmap(2)'ing functions.
 */
paddr_t
_bus_dmamem_mmap(t, segs, nsegs, off, prot, flags)
	bus_dma_tag_t t;
	bus_dma_segment_t *segs;
	int nsegs;
	off_t off;
	int prot, flags;
{
	int i;

	for (i = 0; i < nsegs; i++) {
#ifdef DIAGNOSTIC
		if (off & PGOFSET)
			panic("_bus_dmamem_mmap: offset unaligned");
		if (segs[i].ds_addr & PGOFSET)
			panic("_bus_dmamem_mmap: segment unaligned");
		if (segs[i].ds_len & PGOFSET)
			panic("_bus_dmamem_mmap: segment size not multiple"
			    " of page size");
#endif
		if (off >= segs[i].ds_len) {
			off -= segs[i].ds_len;
			continue;
		}

		/*
		 * XXXSCW: What about BUS_DMA_COHERENT ??
		 */

		return (m68k_btop((caddr_t)segs[i].ds_addr + off));
	}

	/* Page not found. */
	return (-1);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">

  <key id="label" for="edge" attr.name="label" attr.type="string" />
  <key id="labels" for="node" attr.name="labels" attr.type="string" />

  <key id="surname" for="node" attr.name="surname" attr.type="string" />
  <key id="name" for="node" attr.name="name" attr.type="string" />
  <key id="id" for="node" attr.name="id" attr.type="long" />
  <key id="since" for="edge" attr.name="since" attr.type="string" />

  <graph id="G" edgedefault="directed">
    <node id="p1" labels=":ENTITY:Person">
      <data key="labels">:ENTITY:Person</data>
      <data key="id">100</data>
      <data key="name">Bronislav</data>
      <data key="surname">Orlov</data>
    </node>
    <node id="p2" labels=":ENTITY:Person">
      <data key="labels">:ENTITY:Person</data>
      <data key="id">101</data>
      <data key="name">Rajesh</data>
      <data key="surname">Nagarkar</data>
    </node>
    <node id="p3" labels=":ENTITY:Person">
      <data key="labels">:ENTITY:Person</data>
      <data key="id">102</data>
      <data key="name">Anna</data>
      <data key="surname">Schroeder</data>
    </node>
    <node id="p4" labels=":ENTITY:Person">
      <data key="labels">:ENTITY:Person</data>
      <data key="id">103</data>
      <data key="name">Amanda</data>
      <data key="surname">Herman</data>
    </node>
    <node id="p5" labels=":ENTITY:Person">
      <data key="labels">:ENTITY:Person</data>
      <data key="id">104</data>
      <data key="name">Ludovico</data>
      <data key="surname">Adamo</data>
    </node>
    <node id="p6" labels=":ENTITY:Person">
      <data key="labels">:ENTITY:Person</data>
      <data key="id">105</data>
      <data key="name">Jack</data>
      <data key="surname">Sparrow</data>
    </node>

    <node id="t1" labels=":ENTITY:Technology">
      <data key="labels">:ENTITY:Technology</data>
      <data key="name">Java EE</data>
    </node>
    <node id="t2" labels=":ENTITY:Technology">
      <data key="labels">:ENTITY:Technology</data>
      <data key="name">Neo4j</data>
    </node>
    <node id="t3" labels=":Technology:ENTITY">
      <data key="labels">:Technology:ENTITY</data>
      <data key="name">Bootstrap</data>
    </node>

    <node id="r1" labels="ENTITY:Recipe">
      <data key="labels">:ENTITY:CookingRecipe</data>
      <data key="name">Macarons</data>
    </node>

    <edge id="e2" source="p1" target="p2" label="friend">
      <data key="label">friend</data>
    </edge>
    <edge id="e3" source="p1" target="p3" label="friend">
      <data key="label">friend</data>
    </edge>
    <edge id="e4" source="p3" target="p4" label="friend">
      <data key="label">friend</data>
    </edge>
    <edge id="e5" source="p4" target="t2" label="expertIn">
      <data key="label">expertIn</data>
    </edge>
    <edge id="e6" source="p2" target="p5" label="friend">
      <data key="label">friend</data>
      <data key="since">Dec 2017</data>
    </edge>
    <edge id="e7" source="p5" target="t1" label="expertIn">
      <data key="label">expertIn</data>
    </edge>
    <edge id="e8" source="p2" target="t3" label="expertIn">
      <data key="label">expertIn</data>
    </edge>
  </graph>
</graphml>