text:
package uploads

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"fmt"

	"github.com/materials-commons/gohandy/file"
	"github.com/materials-commons/mcstore/pkg/app"
	"github.com/materials-commons/mcstore/pkg/db/dai"
	"github.com/materials-commons/mcstore/pkg/db/schema"
	"github.com/materials-commons/mcstore/pkg/domain"
	"github.com/materials-commons/mcstore/pkg/testdb"
)

var _ = fmt.Println

var _ = Describe("IDService", func() {

	var (
		users    = dai.NewRUsers(testdb.RSessionMust())
		files    = dai.NewRFiles(testdb.RSessionMust())
		dirs     = dai.NewRDirs(testdb.RSessionMust())
		projects = dai.NewRProjects(testdb.RSessionMust())
		uploads  = dai.NewRUploads(testdb.RSessionMust())
		access   = domain.NewAccess(projects, files, users)
		s        = &idService{
			files:       files,
			dirs:        dirs,
			projects:    projects,
			uploads:     uploads,
			access:      access,
			fops:        file.MockOps(),
			tracker:     requestBlockTracker,
			requestPath: &mockRequestPath{},
		}
		upload *schema.Upload
	)

	BeforeEach(func() {
		s.fops = file.MockOps()
	})

	AfterEach(func() {
		if upload != nil {
			err := uploads.Delete(upload.ID)
			Expect(err).To(BeNil())
			upload = nil
		}
	})

	Describe("ID Method Tests", func() {
		Describe("Access permissions", func() {
			var (
				req IDRequest
			)

			BeforeEach(func() {
				req = IDRequest{
					ProjectID:   "test",
					DirectoryID: "test",
					Host:        "host",
					FileSize:    10,
					ChunkSize:   10,
				}
			})

			Context("Access allowed", func() {
				It("Should allow access to admin user", func() {
					req.User = "admin@mc.org"
					upload, err := s.ID(req)
					Expect(err).To(BeNil(), "Unexpected error: %s", err)
					Expect(upload).NotTo(BeNil(), "upload is nil")
				})

				It("Should allow access to user in project", func() {
					req.User = "test1@mc.org"
					upload, err := s.ID(req)
					Expect(err).To(BeNil(), "Unexpected error: %s", err)
					Expect(upload).NotTo(BeNil())
				})
			})

			Context("Access not allowed", func() {
				It("Should not allow access for users not in project", func() {
					req.User = "test2@mc.org"
					upload, err := s.ID(req)
					Expect(err).NotTo(BeNil())
					Expect(err).To(Equal(app.ErrNoAccess))
					Expect(upload).To(BeNil())
				})
			})

			Context("Invalid directory", func() {
				It("Should not allow access for non existent directory", func() {
					req.User = "test@mc.org" // valid user
					req.DirectoryID = "test@mc.org"
					upload, err := s.ID(req)
					Expect(err).NotTo(BeNil())
					Expect(upload).To(BeNil())
				})
			})
		})

		Describe("Request Parameters", func() {
			Context("Bad Request", func() {
				var req IDRequest

				BeforeEach(func() {
					req = IDRequest{
						User:        "admin@mc.org",
						ProjectID:   "test",
						DirectoryID: "test",
						FileSize:    10,
						ChunkSize:   10,
					}
				})

				It("Should fail on bad project id", func() {
					req.ProjectID = "does-not-exist"
					upload, err := s.ID(req)
					Expect(err).To(HaveOccurred())
					Expect(upload).To(BeNil())
				})

				It("Should fail on bad directory id", func() {
					req.DirectoryID = "does-not-exist"
					upload, err := s.ID(req)
					Expect(err).To(HaveOccurred())
					Expect(upload).To(BeNil())
				})

				It("Should fail on directory id not in project", func() {
					req.DirectoryID = "test2" // in different project (test2)
					upload, err := s.ID(req)
					Expect(err).To(HaveOccurred())
					Expect(upload).To(BeNil())
				})
			})
		})

		Describe("Existing Uploads", func() {
			It("Should find an existing upload", func() {
				var err error
				req := IDRequest{
					ProjectID:   "test",
					DirectoryID: "test",
					Host:        "host",
					Checksum:    "abc124",
					FileSize:    100,
					ChunkSize:   10,
					User:        "test@mc.org",
				}
				upload, err = s.ID(req)
				Expect(err).To(BeNil())
				Expect(upload.File.Blocks.Len()).To(BeNumerically("==", 10))

				// Now submit again with exact same parameters. It should
				// not create a new request
				upload2, err := s.ID(req)
				Expect(err).To(BeNil())
				Expect(upload2.ID).To(Equal(upload.ID))

				// Check that the bitset state is correct.
				Expect(upload2.File.Blocks.Len()).To(BeNumerically("==", 10))
			})
		})
	})

	Describe("Delete Method Tests", func() {
		Context("Access Permissions", func() {
			var (
				req IDRequest
				u   *schema.Upload
			)

			BeforeEach(func() {
				req = IDRequest{
					ProjectID:   "test",
					DirectoryID: "test",
					Host:        "host",
					User:        "test@mc.org",
					FileSize:    10,
					ChunkSize:   10,
				}

				u, _ = s.ID(req)
			})

			AfterEach(func() {
				if u != nil {
					s.Delete(u.ID, req.User)
					u = nil
				}
			})

			It("Should fail on user not in project", func() {
				err := s.Delete(u.ID, "test2@mc.org")
				Expect(err).NotTo(BeNil())
				Expect(err).To(Equal(app.ErrNoAccess))
			})

			It("Should succeed on user in project", func() {
				err := s.Delete(u.ID, "test@mc.org")
				Expect(err).To(BeNil(), "Unexpected error: %s", err)
			})

			It("Should succeed on admin user", func() {
				err := s.Delete(u.ID, "admin@mc.org")
				Expect(err).To(BeNil(), "Unexpected error: %s", err)
			})

			It("Should fail on non-existant user", func() {
				err := s.Delete(u.ID, "no-such-user@doesnot.exist.com")
				Expect(err).NotTo(BeNil())
				Expect(err).To(Equal(app.ErrNoAccess))
			})
		})

		Context("request ID Validation", func() {
			It("Should fail on bad id", func() {
				err := s.Delete("no-such-id", "admin@mc.org")
				Expect(err).NotTo(BeNil())
				Expect(err).To(Equal(app.ErrNotFound))
			})

			It("Should succeed on good id", func() {
				req := IDRequest{
					ProjectID:   "test",
					DirectoryID: "test",
					Host:        "host",
					User:        "admin@mc.org",
					FileSize:    10,
					ChunkSize:   10,
				}

				upload, err := s.ID(req)
				Expect(err).To(BeNil(), "Unexpected error: %s", err)
				Expect(upload).NotTo(BeNil())

				err = s.Delete(upload.ID, "admin@mc.org")
				Expect(err).To(BeNil(), "Unexpected error: %s", err)
			})
		})
	})

	Describe("UploadsForProject Method Tests", func() {
		var (
			req IDRequest
			u   *schema.Upload
		)

		BeforeEach(func() {
			req = IDRequest{
				ProjectID:   "test",
				DirectoryID: "test",
				Host:        "host",
				User:        "test@mc.org",
				FileSize:    10,
				ChunkSize:   10,
			}

			u, _ = s.ID(req)
		})

		AfterEach(func() {
			if u != nil {
				s.Delete(u.ID, req.User)
				u = nil
			}
		})

		Context("Access Permissions", func() {
			It("Should fail on user not in project", func() {
				uploads, err := s.UploadsForProject("test", "test2@mc.org")
				Expect(err).NotTo(BeNil())
				Expect(err).To(Equal(app.ErrNoAccess))
				Expect(uploads).To(BeNil())
			})

			It("Should succeed on user in project", func() {
				uploads, err := s.UploadsForProject("test", "test@mc.org")
				Expect(err).To(BeNil(), "Unexpected error: %s", err)
				Expect(len(uploads)).To(BeNumerically(">", 0))
			})

			It("Should succeed on admin user", func() {
				uploads, err := s.UploadsForProject("test", "admin@mc.org")
				Expect(err).To(BeNil(), "Unexpected error: %s", err)
				Expect(len(uploads)).To(BeNumerically(">", 0))
			})

			It("Should fail on non-existent user", func() {
				uploads, err := s.UploadsForProject("test", "no-such-user@doesnot.exist.com")
				Expect(err).NotTo(BeNil())
				Expect(err).To(Equal(app.ErrNoAccess))
				Expect(uploads).To(BeNil())
			})
		})

		Context("Project ID Validation", func() {
			It("Should fail on bad project", func() {
				uploads, err := s.UploadsForProject("no-such-project", "test@mc.org")
				Expect(err).NotTo(BeNil())
				Expect(err).To(Equal(app.ErrInvalid))
				Expect(uploads).To(BeNil())
			})

			It("Should succeed on good project", func() {
				uploads, err := s.UploadsForProject("test", "test@mc.org")
				Expect(err).To(BeNil(), "Unexpected error: %s", err)
				Expect(len(uploads)).To(BeNumerically(">", 0))
			})
		})
	})
})


text:
package com.yo1000.bluefairy.model.entity;

import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;

/**
 * Created by yoichi.kikuchi on 15/05/07.
 */
public class UserDetailsWithSalt extends org.springframework.security.core.userdetails.User {
    private String salt;

    public UserDetailsWithSalt(String username, String password, String salt, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, authorities);
        this.setSalt(salt);
    }

    public UserDetailsWithSalt(String username, String password, String salt, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
        this.setSalt(salt);
    }

    public String getSalt() {
        return salt;
    }

    protected void setSalt(String salt) {
        this.salt = salt;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.hazelcast.cp.internal.datastructures.lock;

import com.hazelcast.cp.CPGroupId;
import com.hazelcast.cp.internal.datastructures.lock.AcquireResult.AcquireStatus;
import com.hazelcast.cp.internal.datastructures.spi.blocking.BlockingResource;
import com.hazelcast.cp.internal.datastructures.spi.blocking.WaitKeyContainer;
import com.hazelcast.internal.util.BiTuple;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.IdentifiedDataSerializable;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

import static com.hazelcast.cp.internal.datastructures.lock.AcquireResult.AcquireStatus.FAILED;
import static com.hazelcast.cp.internal.datastructures.lock.AcquireResult.AcquireStatus.SUCCESSFUL;
import static com.hazelcast.cp.internal.datastructures.lock.LockOwnershipState.NOT_LOCKED;
import static com.hazelcast.internal.util.UUIDSerializationUtil.readUUID;
import static com.hazelcast.internal.util.UUIDSerializationUtil.writeUUID;
import static com.hazelcast.internal.util.UuidUtil.newUnsecureUUID;
import static java.lang.Math.min;

/**
 * State-machine implementation of the Raft-based lock
 */
public class Lock extends BlockingResource<LockInvocationKey> implements IdentifiedDataSerializable {

    /**
     * Max number of reentrant lock acquires
     */
    private int lockCountLimit;

    /**
     * Current owner of the lock
     */
    private volatile LockInvocationKey owner;

    /**
     * Number of acquires the current lock owner has committed
     */
    private volatile int lockCount;

    /**
     * Uids of the current lock owner's lock() / unlock() invocations,
     * and uid of the previous owner's last unlock() invocation.
     * Used for preventing duplicate execution of lock() / unlock() invocations
     */
    private final Map<BiTuple<LockEndpoint, UUID>, LockOwnershipState> ownerInvocationRefUids = new HashMap<>();

    Lock() {
    }

    Lock(CPGroupId groupId, String name, int lockCountLimit) {
        super(groupId, name);
        this.lockCountLimit = lockCountLimit > 0 ? lockCountLimit : Integer.MAX_VALUE;
    }

    /**
     * Assigns the lock to the endpoint, if the lock is not held. Lock count is
     * incremented if the endpoint already holds the lock. If some other
     * endpoint holds the lock and the second argument is true, a wait key is
     * created and added to the wait queue. Lock count is not incremented if
     * the lock request is a retry of the lock holder. If the lock request is
     * a retry of a lock endpoint that resides in the wait queue with the same
     * invocation uid, a retry wait key wait key is attached to the original
     * wait key. If the lock request is a new request of a lock endpoint that
     * resides in the wait queue with a different invocation uid, the existing
     * wait key is cancelled because it means the caller has stopped waiting
     * for response of the previous invocation. If the invocation uid is same
     * with one of the previous invocations of the current lock owner,
     * memorized result of the previous invocation is returned.
     */
    @SuppressFBWarnings(value = "VO_VOLATILE_INCREMENT", justification = "'lockCount' field is updated only by a single thread.")
    @SuppressWarnings("NonAtomicOperationOnVolatileField")
    AcquireResult acquire(LockInvocationKey key, boolean wait) {
        LockEndpoint endpoint = key.endpoint();
        UUID invocationUid = key.invocationUid();
        LockOwnershipState memorized = ownerInvocationRefUids.get(BiTuple.of(endpoint, invocationUid));
        if (memorized != null) {
            AcquireStatus status = memorized.isLocked() ? SUCCESSFUL : FAILED;
            return new AcquireResult(status, memorized.getFence(), Collections.emptyList());
        }

        if (owner == null) {
            owner = key;
        }

        if (endpoint.equals(owner.endpoint())) {
            if (lockCount == lockCountLimit) {
                ownerInvocationRefUids.put(BiTuple.of(endpoint, invocationUid), NOT_LOCKED);
                return AcquireResult.failed(Collections.emptyList());
            }

            lockCount++;
            ownerInvocationRefUids.put(BiTuple.of(endpoint, invocationUid), lockOwnershipState());
            return AcquireResult.acquired(owner.commitIndex());
        }

        // we must cancel waits keys of previous invocation of the endpoint
        // before adding a new wait key or even if we will not wait
        Collection<LockInvocationKey> cancelledWaitKeys = cancelWaitKeys(endpoint, invocationUid);

        if (wait) {
            addWaitKey(endpoint, key);
            return AcquireResult.waitKeyAdded(cancelledWaitKeys);
        }

        ownerInvocationRefUids.put(BiTuple.of(endpoint, invocationUid), NOT_LOCKED);
        return AcquireResult.failed(cancelledWaitKeys);
    }

    private Collection<LockInvocationKey> cancelWaitKeys(LockEndpoint endpoint, UUID invocationUid) {
        Collection<LockInvocationKey> cancelled = null;
        WaitKeyContainer<LockInvocationKey> container = getWaitKeyContainer(endpoint);
        if (container != null && container.key().isDifferentInvocationOf(endpoint, invocationUid)) {
            cancelled = container.keyAndRetries();
            removeWaitKey(endpoint);
        }

        return cancelled != null ? cancelled : Collections.emptyList();
    }

    /**
     * Releases the lock. The lock is freed when lock count reaches to 0.
     * If the remaining lock count > 0 after a successful release, the lock is
     * still held by the endpoint. The lock is not released if it is a retry of
     * a previous successful release request of the current lock holder. If
     * the lock is assigned to some other endpoint after this release, wait
     * keys of the new lock holder are returned. If the release request fails
     * because the requesting endpoint does not hold the lock, all wait keys
     * of the endpoint are cancelled because that endpoint has stopped waiting
     * for response of its previous lock() invocation.
     */
    ReleaseResult release(LockEndpoint endpoint, UUID invocationUid) {
        return doRelease(endpoint, invocationUid, 1);
    }

    @SuppressWarnings("NonAtomicOperationOnVolatileField")
    private ReleaseResult doRelease(LockEndpoint endpoint, UUID invocationUid, int releaseCount) {
        LockOwnershipState memorized = ownerInvocationRefUids.get(BiTuple.of(endpoint, invocationUid));
        if (memorized != null) {
            return ReleaseResult.successful(memorized);
        }

        if (owner == null || !owner.endpoint().equals(endpoint)) {
            return ReleaseResult.failed(cancelWaitKeys(endpoint, invocationUid));
        }

        lockCount = lockCount - min(lockCount, releaseCount);
        if (lockCount > 0) {
            LockOwnershipState ownership = lockOwnershipState();
            ownerInvocationRefUids.put(BiTuple.of(endpoint, invocationUid), ownership);
            return ReleaseResult.successful(ownership);
        }

        removeInvocationRefUids(endpoint);

        Collection<LockInvocationKey> newOwnerWaitKeys = setNewLockOwner();

        ownerInvocationRefUids.put(BiTuple.of(endpoint, invocationUid), lockOwnershipState());

        return ReleaseResult.successful(lockOwnershipState(), newOwnerWaitKeys);
    }

    private void removeInvocationRefUids(LockEndpoint endpoint) {
        ownerInvocationRefUids.keySet().removeIf(lockEndpointUUIDBiTuple -> lockEndpointUUIDBiTuple.element1.equals(endpoint));
    }

    private Collection<LockInvocationKey> setNewLockOwner() {
        Collection<LockInvocationKey> newOwnerWaitKeys;
        Iterator<WaitKeyContainer<LockInvocationKey>> iter = waitKeyContainersIterator();
        if (iter.hasNext()) {
            WaitKeyContainer<LockInvocationKey> container = iter.next();
            LockInvocationKey newOwner = container.key();
            newOwnerWaitKeys = container.keyAndRetries();

            iter.remove();
            owner = newOwner;
            lockCount = 1;
            ownerInvocationRefUids.put(BiTuple.of(owner.endpoint(), owner.invocationUid()), lockOwnershipState());
        } else {
            owner = null;
            newOwnerWaitKeys = Collections.emptyList();
        }

        return newOwnerWaitKeys;
    }

    LockOwnershipState lockOwnershipState() {
        if (owner == null) {
            return LockOwnershipState.NOT_LOCKED;
        }

        return new LockOwnershipState(owner.commitIndex(), lockCount, owner.sessionId(), owner.endpoint().threadId());
    }

    Lock cloneForSnapshot() {
        Lock clone = new Lock();
        cloneForSnapshot(clone);
        clone.lockCountLimit = this.lockCountLimit;
        clone.owner = this.owner;
        clone.lockCount = this.lockCount;
        clone.ownerInvocationRefUids.putAll(this.ownerInvocationRefUids);

        return clone;
    }

    /**
     * Releases the lock if the current lock holder's session is closed.
     */
    @Override
    protected void onSessionClose(long sessionId, Map<Long, Object> responses) {
        removeInvocationRefUids(sessionId);

        if (owner != null && owner.sessionId() == sessionId) {
            ReleaseResult result = doRelease(owner.endpoint(), newUnsecureUUID(), lockCount);
            for (LockInvocationKey key : result.completedWaitKeys()) {
                responses.put(key.commitIndex(), result.ownership().getFence());
            }
        }
    }

    private void removeInvocationRefUids(long sessionId) {
        ownerInvocationRefUids.keySet().removeIf(t -> t.element1.sessionId() == sessionId);
    }

    /**
     * Returns session id of the current lock holder or an empty collection if
     * the lock is not held
     */
    @Override
    protected Collection<Long> getActivelyAttachedSessions() {
        return owner != null ? Collections.singleton(owner.sessionId()) : Collections.emptyList();
    }

    @Override
    protected void onWaitKeyExpire(LockInvocationKey key) {
        ownerInvocationRefUids.put(BiTuple.of(key.endpoint(), key.invocationUid()), NOT_LOCKED);
    }

    int lockCountLimit() {
        return lockCountLimit;
    }

    int lockCount() {
        return lockCount;
    }

    LockInvocationKey owner() {
        return owner;
    }

    @Override
    public int getFactoryId() {
        return LockDataSerializerHook.F_ID;
    }

    @Override
    public int getClassId() {
        return LockDataSerializerHook.RAFT_LOCK;
    }

    @Override
    public void writeData(ObjectDataOutput out) throws IOException {
        super.writeData(out);
        out.writeInt(lockCountLimit);
        boolean hasOwner = (owner != null);
        out.writeBoolean(hasOwner);
        if (hasOwner) {
            out.writeObject(owner);
        }
        out.writeInt(lockCount);
        out.writeInt(ownerInvocationRefUids.size());
        for (Map.Entry<BiTuple<LockEndpoint, UUID>, LockOwnershipState> e : ownerInvocationRefUids.entrySet()) {
            out.writeObject(e.getKey().element1);
            writeUUID(out, e.getKey().element2);
            out.writeObject(e.getValue());
        }
    }

    @Override
    public void readData(ObjectDataInput in) throws IOException {
        super.readData(in);
        lockCountLimit = in.readInt();
        boolean hasOwner = in.readBoolean();
        if (hasOwner) {
            owner = in.readObject();
        }
        lockCount = in.readInt();
        int ownerInvocationRefUidCount = in.readInt();
        for (int i = 0; i < ownerInvocationRefUidCount; i++) {
            LockEndpoint endpoint = in.readObject();
            UUID invocationUid = readUUID(in);
            LockOwnershipState ownership = in.readObject();
            ownerInvocationRefUids.put(BiTuple.of(endpoint, invocationUid), ownership);
        }
    }

    @Override
    public String toString() {
        return "Lock{" + internalToString() + ", lockCountLimit=" + lockCountLimit + ", owner="
                + owner + ", lockCount=" + lockCount + ", ownerInvocationRefUids=" + ownerInvocationRefUids + '}';
    }

}


text:
/**
* (c) 2014 by Christian Schenk
**/
package de.schenk.jrtrace.enginex.testscripts;

public class DoneListener {

}


text:
const jsonlint = require('@prantlf/jsonlint');
const validator = require('@prantlf/jsonlint/lib/validator');
const sorter = require('@prantlf/jsonlint/lib/sorter');
const printer = require('@prantlf/jsonlint/lib/printer');
const gruntJsonLintTask = require('../lib/grunt-jsonlint-task');

module.exports = (grunt) => {
  grunt.registerMultiTask('jsonlint', 'Validate JSON files.',
    gruntJsonLintTask(grunt, jsonlint, validator, sorter, printer));
};


text:
package org.apache.aries.jpa.support.osgi.impl;

import static org.osgi.service.jpa.EntityManagerFactoryBuilder.JPA_UNIT_NAME;

import java.util.Dictionary;
import java.util.Hashtable;

import javax.persistence.EntityManagerFactory;
import javax.persistence.spi.PersistenceUnitTransactionType;

import org.apache.aries.jpa.supplier.EmSupplier;
import org.apache.aries.jpa.support.impl.EMSupplierImpl;
import org.apache.aries.jpa.support.impl.ResourceLocalJpaTemplate;
import org.apache.aries.jpa.template.JpaTemplate;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.util.tracker.ServiceTracker;

/**
 * Tracks EntityManagerFactory services and publishes a Supplier<EntityManager> for each.
 * IF the persistence unit uses JTA a TMTracker is created. If it uses RESOURCE_LOCAL as
 * ResourceLocalJpaTemplate is created.
 */
@SuppressWarnings("rawtypes")
public class EMFTracker extends ServiceTracker {

    @SuppressWarnings("unchecked")
    public EMFTracker(BundleContext context) {
        super(context, EntityManagerFactory.class, null);
    }

    @SuppressWarnings("unchecked")
    @Override
    public Object addingService(ServiceReference reference) {
        String unitName = (String)reference.getProperty(JPA_UNIT_NAME);
        if (unitName == null) {
            return null;
        }
        BundleContext bContext = reference.getBundle().getBundleContext();
        TrackedEmf tracked = new TrackedEmf();
        tracked.emf = (EntityManagerFactory)bContext.getService(reference);
        tracked.emSupplier = new EMSupplierImpl(tracked.emf);
        tracked.emSupplierReg = bContext.registerService(EmSupplier.class, tracked.emSupplier,
                                                         getEmSupplierProps(unitName));

        if (getTransactionType(tracked.emf) == PersistenceUnitTransactionType.RESOURCE_LOCAL) {
            JpaTemplate txManager = new ResourceLocalJpaTemplate(tracked.emSupplier);
            tracked.rlTxManagerReg = bContext.registerService(JpaTemplate.class, txManager,
                                                          rlTxManProps(unitName));
        } else {
            tracked.tmTracker = new TMTracker(bContext, tracked.emSupplier, unitName);
            tracked.tmTracker.open();
        }
        return tracked;
    }

    /**
     *
     * @param emf
     * @return
     */
    private PersistenceUnitTransactionType getTransactionType(EntityManagerFactory emf) {
        PersistenceUnitTransactionType transactionType = (PersistenceUnitTransactionType) emf.getProperties()
        		.get(PersistenceUnitTransactionType.class.getName());
        if(transactionType == PersistenceUnitTransactionType.RESOURCE_LOCAL) {
        	return PersistenceUnitTransactionType.RESOURCE_LOCAL;
        } else {
        	return PersistenceUnitTransactionType.JTA;
        }
    }

    private Dictionary<String, String> getEmSupplierProps(String unitName) {
        Dictionary<String, String> props = new Hashtable<>();
        props.put(JPA_UNIT_NAME, unitName);
        return props;
    }

    private Dictionary<String, String> rlTxManProps(String unitName) {
        Dictionary<String, String> props = new Hashtable<>();
        props.put(JPA_UNIT_NAME, unitName);
        props.put(TMTracker.TRANSACTION_TYPE, "RESOURCE_LOCAL");
        return props;
    }

    @SuppressWarnings("unchecked")
    @Override
    public void removedService(ServiceReference reference, Object trackedO) {
        TrackedEmf tracked = (TrackedEmf)trackedO;
        if (tracked.tmTracker != null) {
            tracked.tmTracker.close();
        }
        if (tracked.rlTxManagerReg != null) {
            tracked.rlTxManagerReg.unregister();
        }
        tracked.emSupplier.close();
        tracked.emSupplierReg.unregister();
        super.removedService(reference, tracked.emf);
    }

    static class TrackedEmf {
        ServiceRegistration emSupplierReg;
        EMSupplierImpl emSupplier;
        ServiceRegistration rlTxManagerReg;
        EntityManagerFactory emf;
        TMTracker tmTracker;
    }
}


text:
package com.simsilica.state;

import org.slf4j.*;

import com.jme3.app.Application;
import com.jme3.app.state.BaseAppState;
import com.jme3.util.MemoryUtils;

import com.simsilica.lemur.core.VersionedHolder;

/**
 *  Uses the DebugHudState to display memory usage.
 *
 *  @author    Paul Speed
 */
public class MemoryDebugState extends BaseAppState {

    public static String HEAP = "Heap";
    public static String DIRECT = "Direct";

    private static float BYTE_TO_MB = 1f/(1024 * 1024);

    static Logger log = LoggerFactory.getLogger(MemoryDebugState.class);

    private DebugHudState hud;
    private DebugHudState.Location location = DebugHudState.Location.Right;
    private boolean detailedStats;

    // Making direct memory usage display optional and off by default.
    // I guess some time on JDK 1.7+, the heap memory issues must have been
    // fixed because now this seems to be managed differently and will
    // always show as 100%.  -XX:MaxDirectMemorySize no longer seems to have
    // any affect on the max size reported by the JVM.
    private boolean includeDirectMem;

    private float updateInterval;
    private float nextUpdate;

    private VersionedHolder<String> heap;
    private long lastHeapUsage;
    private long lastHeapTotal;

    private VersionedHolder<String> direct;
    private long lastDirectUsage;
    private long lastDirectTotal;

    /**
     *  Creates a MemoryDebugState that will put memory stats in the
     *  right debug panel and update them once a second.
     */
    public MemoryDebugState() {
        this(DebugHudState.Location.Right, 1, false, false);
    }

    /**
     *  Creates a MemoryDebugState that will put memory stats  in the specified
     *  location and update them as often as the specified updateInterval in seconds.
     *  If detailedStats is true then the raw memory values (in megabytes) are displayed
     *  with the percentage.  If detailedStats is false then only the percentage is
     *  displayed.  If includeDirectMem is true then a direct memory usage line is
     *  displayed though this seems to be pretty unncessary on modern JVMs.
     */
    public MemoryDebugState( DebugHudState.Location location, float updateInterval,
                             boolean detailedStats, boolean includeDirectMem ) {
        this.location = location;
        this.updateInterval = updateInterval;
        this.detailedStats = detailedStats;
        this.includeDirectMem = includeDirectMem;
    }

    public void setDetailedStats( boolean detailedStats ) {
        this.detailedStats = detailedStats;

        // Trigger a refresh next update
        lastHeapUsage = 0;
        lastDirectUsage = 0;

        // Trigger an update
        nextUpdate = 0;
    }

    public boolean getDetailedStats() {
        return detailedStats;
    }

    @Override
    protected void initialize( Application app ) {
        hud = getState(DebugHudState.class);
        if( hud == null ) {
            throw new RuntimeException("MemoryDebugState requires the DebugHudState");
        }
    }

    @Override
    protected void cleanup( Application app ) {
    }

    @Override
    protected void onEnable() {
        this.heap = hud.createDebugValue(HEAP, location);
        if( includeDirectMem ) {
            this.direct = hud.createDebugValue(DIRECT, location);
        }
    }

    protected void updateMemoryStats() {
        Runtime rt = Runtime.getRuntime();

        long free = rt.freeMemory();
        long total = rt.totalMemory();
        long max = rt.maxMemory();
        long used = total - free;

        if( lastHeapUsage != used || lastHeapTotal != max ) {
            lastHeapUsage = used;
            lastHeapTotal = max;
            float percent = 100f * used / max;

            String p = String.format("%.2f%%", percent);
            if( detailedStats ) {
                String mb = String.format("%.2f/%.2f mb", used * BYTE_TO_MB, max * BYTE_TO_MB);
                heap.setObject(p + " (" + mb + ")");
            } else {
                heap.setObject(p);
            }
        }

        if( includeDirectMem ) {
            long directTotal = MemoryUtils.getDirectMemoryTotalCapacity();
            long directUsage = MemoryUtils.getDirectMemoryUsage();
            if( lastDirectUsage != directUsage || lastDirectTotal != directTotal ) {
                lastDirectUsage = directUsage;
                lastDirectTotal = directTotal;
                float percent = 100f * directUsage / directTotal;

                String p = String.format("%.2f%%", percent);
                if( detailedStats ) {
                    String mb = String.format("%.2f/%.2f mb", directUsage * BYTE_TO_MB, directTotal * BYTE_TO_MB);
                    direct.setObject(p + " (" + mb + ")");
                    // The count seems to be unhelpful
                    //direct.setObject(p + " (" + mb + ") #" + MemoryUtils.getDirectMemoryCount());
                } else {
                    direct.setObject(p);
                }
            }
        }

    }

    @Override
    public void update( float tpf ) {
        nextUpdate -= tpf;
        if( nextUpdate <= 0 ) {
            updateMemoryStats();
            nextUpdate = updateInterval;
        }
    }

    @Override
    protected void onDisable() {
        hud.removeDebugValue(HEAP);
        if( includeDirectMem ) {
            hud.removeDebugValue(DIRECT);
        }
    }
}


text:
'use strict';

describe('nrgiCommoditiesMethodSrvc', function () {
    beforeEach(module('app'));

    var nrgiCommoditiesMethodSrvc;
    var $q, nrgiCommoditiesSrvc;
    var $qDeferStub, $qDeferSpy, expectedPromise;

    beforeEach(inject(function (_nrgiCommoditiesMethodSrvc_, _$q_, _nrgiCommoditiesSrvc_) {
        $q = _$q_;
        nrgiCommoditiesSrvc = _nrgiCommoditiesSrvc_;
        nrgiCommoditiesMethodSrvc = _nrgiCommoditiesMethodSrvc_;
    }));

    describe('#createCommodity', function () {
        var rgiCommoditySrvcStub;

        it('resolves the deferred in positive case', function () {
            expectedPromise = 'POSITIVE';

            rgiCommoditySrvcStub = sinon.stub(nrgiCommoditiesSrvc.prototype, '$save', function() {
                return {
                    then: function(callback) {
                        callback();
                    }
                };
            });

            $qDeferSpy = sinon.spy();
            $qDeferStub = sinon.stub($q, 'defer', function() {
                return {
                    resolve: $qDeferSpy,
                    promise: expectedPromise
                };
            });

            nrgiCommoditiesMethodSrvc.createCommodity([expectedPromise]).should.be.equal(expectedPromise);
            $qDeferSpy.called.should.be.equal(true);
        });

        it('resolves the deferred in positive case', function () {
            expectedPromise = 'NEGATIVE';
            var REJECT_RESPONSE = {
                data: {reason: 'REJECT_INSERTION'}
            };

            rgiCommoditySrvcStub = sinon.stub(nrgiCommoditiesSrvc.prototype, '$save', function() {
                return {
                    then: function(callbackPositive, callbackNegative) {
                        callbackNegative(REJECT_RESPONSE);
                    }
                };
            });

            $qDeferSpy = sinon.spy();
            $qDeferStub = sinon.stub($q, 'defer', function() {
                return {
                    reject: $qDeferSpy,
                    promise: expectedPromise
                };
            });

            nrgiCommoditiesMethodSrvc.createCommodity([expectedPromise]).should.be.equal(expectedPromise);
            $qDeferSpy.should.have.been.calledWith(REJECT_RESPONSE.data.reason);
        });

        afterEach(function () {
            rgiCommoditySrvcStub.restore();
        });
    });

    describe('#updateCommodity', function () {
        it('resolves the deferred in positive case', function () {
            expectedPromise = 'POSITIVE';

            $qDeferSpy = sinon.spy();
            $qDeferStub = sinon.stub($q, 'defer', function() {
                return {
                    resolve: $qDeferSpy,
                    promise: expectedPromise
                };
            });

            nrgiCommoditiesMethodSrvc.updateCommodity({
                $update: function() {
                    return {
                        then: function(callbackPositive) {
                            callbackPositive();
                        }
                    };
                }
            }).should.be.equal(expectedPromise);

            $qDeferSpy.called.should.be.equal(true);
        });

        //console.log('COMMODITIES METHOD SERVICE: MISSING NEGATIVE UPDATE CASE')

        it('rejects the deferred in negative case', function () {
             expectedPromise = 'NEGATIVE';
             var REASON = 'REASON';

             $qDeferSpy = sinon.spy();
             $qDeferStub = sinon.stub($q, 'defer', function() {
                 return {
                     reject: $qDeferSpy,
                     promise: expectedPromise
                 };
             });

             nrgiCommoditiesMethodSrvc.updateCommodity({
                 $update: function() {
                     return {
                         then: function(uselessCallbackPositive, callbackNegative) {
                             callbackNegative({
                                 data: {reason: REASON}
                             });
                         }
                     };
                 }
             }).should.be.equal(expectedPromise);

             $qDeferSpy.should.have.been.calledWith(REASON);
        });
    });

    describe('#deleteCommodity', function () {
        var rgiCommoditySrvcStub;

        it('resolves the deferred in positive case', function () {
            expectedPromise = 'POSITIVE';

            rgiCommoditySrvcStub = sinon.stub(nrgiCommoditiesSrvc.prototype, '$delete', function() {
                return {
                    then: function(callback) {
                        callback();
                    }
                };
            });

            $qDeferSpy = sinon.spy();
            $qDeferStub = sinon.stub($q, 'defer', function() {
                return {
                    resolve: $qDeferSpy,
                    promise: expectedPromise
                };
            });

            nrgiCommoditiesMethodSrvc.deleteCommodity([expectedPromise]).should.be.equal(expectedPromise);
            $qDeferSpy.called.should.be.equal(true);
        });

        //console.log('COMMODITIES METHOD SERVICE: MISSING NEGATIVE DELETE CASE')

        it('resolves the deferred in negative case', function () {
             expectedPromise = 'NEGATIVE';
             var REJECT_RESPONSE = {
                 data: {reason: 'REJECT_INSERTION'}
             };

             rgiCommoditySrvcStub = sinon.stub(nrgiCommoditiesSrvc.prototype, '$delete', function() {
                 return {
                     then: function(callbackPositive, callbackNegative) {
                         callbackNegative(REJECT_RESPONSE);
                     }
                 };
             });

             $qDeferSpy = sinon.spy();
             $qDeferStub = sinon.stub($q, 'defer', function() {
                 return {
                     reject: $qDeferSpy,
                     promise: expectedPromise
                 };
             });

             nrgiCommoditiesMethodSrvc.deleteCommodity([expectedPromise]).should.be.equal(expectedPromise);
             $qDeferSpy.should.have.been.calledWith(REJECT_RESPONSE.data.reason);
        });

        afterEach(function () {
            $qDeferStub.restore();
            //nrgiCommoditiesSrvc.restore();
        });
    });

    afterEach(function () {
        $qDeferStub.restore();
    });
});


text:
extern "Java"
{
  namespace javax
  {
    namespace swing
    {
        class ListSelectionModel;
      namespace event
      {
          class ListSelectionListener;
      }
    }
  }
}

class javax::swing::ListSelectionModel : public ::java::lang::Object
{

public:
  virtual void setSelectionMode(jint) = 0;
  virtual jint getSelectionMode() = 0;
  virtual void clearSelection() = 0;
  virtual jint getMinSelectionIndex() = 0;
  virtual jint getMaxSelectionIndex() = 0;
  virtual jboolean isSelectedIndex(jint) = 0;
  virtual jboolean isSelectionEmpty() = 0;
  virtual void setSelectionInterval(jint, jint) = 0;
  virtual void addSelectionInterval(jint, jint) = 0;
  virtual void removeSelectionInterval(jint, jint) = 0;
  virtual void insertIndexInterval(jint, jint, jboolean) = 0;
  virtual void removeIndexInterval(jint, jint) = 0;
  virtual jint getAnchorSelectionIndex() = 0;
  virtual void setAnchorSelectionIndex(jint) = 0;
  virtual jint getLeadSelectionIndex() = 0;
  virtual void setLeadSelectionIndex(jint) = 0;
  virtual void setValueIsAdjusting(jboolean) = 0;
  virtual jboolean getValueIsAdjusting() = 0;
  virtual void addListSelectionListener(::javax::swing::event::ListSelectionListener *) = 0;
  virtual void removeListSelectionListener(::javax::swing::event::ListSelectionListener *) = 0;
  static const jint SINGLE_SELECTION = 0;
  static const jint SINGLE_INTERVAL_SELECTION = 1;
  static const jint MULTIPLE_INTERVAL_SELECTION = 2;
  static ::java::lang::Class class$;
} __attribute__ ((java_interface));

#endif // __javax_swing_ListSelectionModel__


text:
wordpress_id: 515
title: "POTD: Naked In the Night"
wordpress_url: http://spaetzel.com/PermaLink,guid,394.aspx
layout: post
---

        Sorry to all of you surfers who come looking for something else. But the title just
        seemed to fit. This small tree exposed, with no leaves. It is lit by a nearby streetlight,
        came out very cool.


text:
/**
 * @constructor
 * @extends {WebInspector.View}
 * @param {!WebInspector.CanvasProfileHeader} profile
 */
WebInspector.CanvasProfileView = function(profile)
{
    WebInspector.View.call(this);
    this.registerRequiredCSS("canvasProfiler.css");
    this._profile = profile;
    this._traceLogId = profile.traceLogId();
    this.element.addStyleClass("canvas-profile-view");

    this._linkifier = new WebInspector.Linkifier();
    this._splitView = new WebInspector.SplitView(false, "canvasProfileViewSplitLocation", 300);

    var replayImageContainer = this._splitView.firstElement();
    replayImageContainer.id = "canvas-replay-image-container";
    this._replayImageElement = replayImageContainer.createChild("image", "canvas-replay-image");
    this._debugInfoElement = replayImageContainer.createChild("div");

    var replayInfoContainer = this._splitView.secondElement();
    var controlsContainer = replayInfoContainer.createChild("div", "status-bar");
    var logGridContainer = replayInfoContainer.createChild("div", "canvas-replay-log");

    this._createControlButton(controlsContainer, "canvas-replay-first-step", WebInspector.UIString("First call."), this._onReplayFirstStepClick.bind(this));
    this._createControlButton(controlsContainer, "canvas-replay-prev-step", WebInspector.UIString("Previous call."), this._onReplayStepClick.bind(this, false));
    this._createControlButton(controlsContainer, "canvas-replay-next-step", WebInspector.UIString("Next call."), this._onReplayStepClick.bind(this, true));
    this._createControlButton(controlsContainer, "canvas-replay-prev-draw", WebInspector.UIString("Previous drawing call."), this._onReplayDrawingCallClick.bind(this, false));
    this._createControlButton(controlsContainer, "canvas-replay-next-draw", WebInspector.UIString("Next drawing call."), this._onReplayDrawingCallClick.bind(this, true));
    this._createControlButton(controlsContainer, "canvas-replay-last-step", WebInspector.UIString("Last call."), this._onReplayLastStepClick.bind(this));

    this._replayContextSelector = new WebInspector.StatusBarComboBox(this._onReplayContextChanged.bind(this));
    this._replayContextSelector.createOption("<screenshot auto>", WebInspector.UIString("Show screenshot of the last replayed resource."), "");
    controlsContainer.appendChild(this._replayContextSelector.element);

    /** @type {!Object.<string, boolean>} */
    this._replayContexts = {};
    /** @type {!Object.<string, CanvasAgent.ResourceState>} */
    this._currentResourceStates = {};

    var columns = { 0: {}, 1: {}, 2: {} };
    columns[0].title = "#";
    columns[0].sortable = true;
    columns[0].width = "5%";
    columns[1].title = WebInspector.UIString("Call");
    columns[1].sortable = true;
    columns[1].width = "75%";
    columns[1].disclosure = true;
    columns[2].title = WebInspector.UIString("Location");
    columns[2].sortable = true;
    columns[2].width = "20%";

    this._logGrid = new WebInspector.DataGrid(columns);
    this._logGrid.element.addStyleClass("fill");
    this._logGrid.show(logGridContainer);
    this._logGrid.addEventListener(WebInspector.DataGrid.Events.SelectedNode, this._replayTraceLog.bind(this));

    /** @type {!Array.<WebInspector.DataGridNode>} */
    this._logGridNodes = [];
    /** @type {!Array.<WebInspector.DataGridNode>} */
    this._drawCallGroups = [];

    this._splitView.show(this.element);
    this._requestTraceLog();
}

/**
 * @const
 * @type {number}
 */
WebInspector.CanvasProfileView.TraceLogPollingInterval = 500;

WebInspector.CanvasProfileView.prototype = {
    dispose: function()
    {
        this._logGridNodes = [];
        this._drawCallGroupNodes = [];
        this._linkifier.reset();
    },

    get statusBarItems()
    {
        return [];
    },

    get profile()
    {
        return this._profile;
    },

    /**
     * @override
     * @return {Array.<Element>}
     */
    elementsToRestoreScrollPositionsFor: function()
    {
        return [this._logGrid.scrollContainer];
    },

    /**
     * @param {Element} parent
     * @param {string} className
     * @param {string} title
     * @param {function(this:WebInspector.CanvasProfileView)} clickCallback
     */
    _createControlButton: function(parent, className, title, clickCallback)
    {
        var button = parent.createChild("button", "status-bar-item");
        button.addStyleClass(className);
        button.title = title;
        button.createChild("img");
        button.addEventListener("click", clickCallback, false);
    },

    _onReplayContextChanged: function()
    {
        /**
         * @param {?Protocol.Error} error
         * @param {CanvasAgent.ResourceState} resourceState
         */
        function didReceiveResourceState(error, resourceState)
        {
            this._enableWaitIcon(false);
            if (error)
                return;

            this._currentResourceStates[resourceState.id] = resourceState;

            var selectedContextId = this._replayContextSelector.selectedOption().value;
            if (selectedContextId === resourceState.id)
                this._replayImageElement.src = resourceState.imageURL;
        }

        var selectedContextId = this._replayContextSelector.selectedOption().value || "auto";
        var resourceState = this._currentResourceStates[selectedContextId];
        if (resourceState)
            this._replayImageElement.src = resourceState.imageURL;
        else {
            this._enableWaitIcon(true);
            this._replayImageElement.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; // Empty transparent image.
            CanvasAgent.getResourceState(this._traceLogId, selectedContextId, didReceiveResourceState.bind(this));
        }
    },

    /**
     * @param {boolean} forward
     */
    _onReplayStepClick: function(forward)
    {
        var index = this._selectedCallIndex();
        if (index === -1)
            return;
        var nextNode = this._logGridNodes[forward ? index + 1 : index - 1] || this._logGridNodes[index];
        nextNode.revealAndSelect();
    },

    /**
     * @param {boolean} forward
     */
    _onReplayDrawingCallClick: function(forward)
    {
        var index = this._selectedDrawCallGroupIndex();
        if (index === -1)
            return;
        var nextNode = this._drawCallGroups[forward ? index + 1 : index - 1] || this._drawCallGroups[index];
        nextNode.revealAndSelect();
    },

    _onReplayFirstStepClick: function()
    {
        var firstNode = this._logGrid.rootNode().children[0];
        if (firstNode)
            firstNode.revealAndSelect();
    },

    _onReplayLastStepClick: function()
    {
        var lastNode = this._logGrid.rootNode().children.peekLast();
        if (lastNode)
            lastNode.revealAndSelect();
    },

    /**
     * @param {boolean} enable
     */
    _enableWaitIcon: function(enable)
    {
        function showWaitIcon()
        {
            this._replayImageElement.addStyleClass("wait");
            this._debugInfoElement.addStyleClass("hidden");
            delete this._showWaitIconTimer;
        }

        if (enable && this._replayImageElement.src && !this._showWaitIconTimer)
            this._showWaitIconTimer = setTimeout(showWaitIcon.bind(this), 250);
        else {
            if (this._showWaitIconTimer) {
                clearTimeout(this._showWaitIconTimer);
                delete this._showWaitIconTimer;
            }
            this._replayImageElement.enableStyleClass("wait", enable);
            this._debugInfoElement.enableStyleClass("hidden", enable);
        }
    },

    _replayTraceLog: function()
    {
        var index = this._selectedCallIndex();
        if (index === -1 || index === this._lastReplayCallIndex)
            return;
        this._lastReplayCallIndex = index;
        var time = Date.now();
        /**
         * @param {?Protocol.Error} error
         * @param {CanvasAgent.ResourceState} resourceState
         */
        function didReplayTraceLog(error, resourceState)
        {
            if (index !== this._selectedCallIndex())
                return;

            this._enableWaitIcon(false);
            if (error)
                return;

            this._currentResourceStates = {};
            this._currentResourceStates["auto"] = resourceState;
            this._currentResourceStates[resourceState.id] = resourceState;

            this._debugInfoElement.textContent = "Replay time: " + (Date.now() - time) + "ms";
            this._onReplayContextChanged();
        }
        this._enableWaitIcon(true);
        CanvasAgent.replayTraceLog(this._traceLogId, index, didReplayTraceLog.bind(this));
    },

    /**
     * @param {?Protocol.Error} error
     * @param {CanvasAgent.TraceLog} traceLog
     */
    _didReceiveTraceLog: function(error, traceLog)
    {
        this._enableWaitIcon(false);
        if (error || !traceLog)
            return;
        var calls = traceLog.calls;
        for (var i = 0, n = calls.length; i < n; ++i) {
            var call = calls[i];
            this._requestReplayContextInfo(call.contextId);
            var index = traceLog.startOffset + i;
            var gridNode = this._createCallNode(index, call);
            this._appendCallNode(gridNode);
        }
        if (traceLog.alive)
            setTimeout(this._requestTraceLog.bind(this), WebInspector.CanvasProfileView.TraceLogPollingInterval);
        this._profile._updateCapturingStatus(traceLog);
        this._onReplayLastStepClick(); // Automatically replay the last step.
    },

    _requestTraceLog: function()
    {
        this._enableWaitIcon(true);
        CanvasAgent.getTraceLog(this._traceLogId, this._logGridNodes.length, undefined, this._didReceiveTraceLog.bind(this));
    },

    /**
     * @param {string} contextId
     */
    _requestReplayContextInfo: function(contextId)
    {
        if (this._replayContexts[contextId])
            return;
        this._replayContexts[contextId] = true;
        /**
         * @param {?Protocol.Error} error
         * @param {CanvasAgent.ResourceInfo} resourceInfo
         */
        function didReceiveResourceInfo(error, resourceInfo)
        {
            if (error) {
                delete this._replayContexts[contextId];
                return;
            }
            this._replayContextSelector.createOption(resourceInfo.description, WebInspector.UIString("Show screenshot of this context's canvas."), contextId);
        }
        CanvasAgent.getResourceInfo(contextId, didReceiveResourceInfo.bind(this));
    },

    /**
     * @return {number}
     */
    _selectedCallIndex: function()
    {
        var node = this._logGrid.selectedNode;
        while (node) {
            if (typeof node.index === "number")
                return node.index;
            node = node.children.peekLast();
        }
        return -1;
    },

    /**
     * @return {number}
     */
    _selectedDrawCallGroupIndex: function()
    {
        for (var node = this._logGrid.selectedNode; node; node = node.children.peekLast()) {
            if (typeof node.drawCallGroupIndex === "number")
                return node.drawCallGroupIndex;
        }
        for (var node = this._logGrid.selectedNode; node; node = node.parent) {
            if (typeof node.drawCallGroupIndex === "number")
                return node.drawCallGroupIndex;
        }
        return -1;
    },

    /**
     * @param {!WebInspector.DataGridNode} gridNode
     */
    _appendCallNode: function(gridNode)
    {
        var drawCallGroup = this._drawCallGroups.peekLast();
        if (drawCallGroup) {
            var lastNode = drawCallGroup.children.peekLast();
            if (lastNode && lastNode.call.isDrawingCall)
                drawCallGroup = null;
        }
        if (!drawCallGroup) {
            var index = this._drawCallGroups.length;
            var data = {};
            data[0] = "";
            data[1] = "Draw call group #" + (index + 1);
            data[2] = "";
            drawCallGroup = new WebInspector.DataGridNode(data);
            drawCallGroup.selectable = true;
            drawCallGroup.drawCallGroupIndex = index;
            this._drawCallGroups.push(drawCallGroup);
            this._logGrid.rootNode().appendChild(drawCallGroup);
        }
        drawCallGroup.appendChild(gridNode);
    },

    /**
     * @param {number} index
     * @param {CanvasAgent.Call} call
     * @return {!WebInspector.DataGridNode}
     */
    _createCallNode: function(index, call)
    {
        var data = {};
        data[0] = index + 1;
        data[1] = call.functionName || "context." + call.property;
        data[2] = "";
        if (call.sourceURL) {
            // FIXME(62725): stack trace line/column numbers are one-based.
            var lineNumber = Math.max(0, call.lineNumber - 1) || 0;
            var columnNumber = Math.max(0, call.columnNumber - 1) || 0;
            data[2] = this._linkifier.linkifyLocation(call.sourceURL, lineNumber, columnNumber);
        }

        if (call.arguments) {
            var args = call.arguments.map(function(argument) {
                return argument.description;
            });
            data[1] += "(" + args.join(", ") + ")";
        } else
            data[1] += " = " + call.value.description;

        if (typeof call.result !== "undefined")
            data[1] += " => " + call.result.description;

        var node = new WebInspector.DataGridNode(data);
        node.index = index;
        node.selectable = true;
        node.call = call;
        this._logGridNodes[index] = node;
        return node;
    },

    __proto__: WebInspector.View.prototype
}

/**
 * @constructor
 * @extends {WebInspector.ProfileType}
 */
WebInspector.CanvasProfileType = function()
{
    WebInspector.ProfileType.call(this, WebInspector.CanvasProfileType.TypeId, WebInspector.UIString("Capture Canvas Frame"));
    this._nextProfileUid = 1;
    this._recording = false;
    this._lastProfileHeader = null;

    this._capturingModeSelector = new WebInspector.StatusBarComboBox(this._dispatchViewUpdatedEvent.bind(this));
    this._capturingModeSelector.element.title = WebInspector.UIString("Canvas capture mode.");
    this._capturingModeSelector.createOption(WebInspector.UIString("Single Frame"), WebInspector.UIString("Capture a single canvas frame."), "");
    this._capturingModeSelector.createOption(WebInspector.UIString("Consecutive Frames"), WebInspector.UIString("Capture consecutive canvas frames."), "1");

    /** @type {!Object.<string, Element>} */
    this._frameOptions = {};

    /** @type {!Object.<string, boolean>} */
    this._framesWithCanvases = {};

    this._frameSelector = new WebInspector.StatusBarComboBox(this._dispatchViewUpdatedEvent.bind(this));
    this._frameSelector.element.title = WebInspector.UIString("Frame containing the canvases to capture.");
    this._frameSelector.element.addStyleClass("hidden");
    WebInspector.runtimeModel.contextLists().forEach(this._addFrame, this);
    WebInspector.runtimeModel.addEventListener(WebInspector.RuntimeModel.Events.FrameExecutionContextListAdded, this._frameAdded, this);
    WebInspector.runtimeModel.addEventListener(WebInspector.RuntimeModel.Events.FrameExecutionContextListRemoved, this._frameRemoved, this);

    this._decorationElement = document.createElement("div");
    this._decorationElement.addStyleClass("profile-canvas-decoration");
    this._decorationElement.addStyleClass("hidden");
    this._decorationElement.textContent = WebInspector.UIString("There is an uninstrumented canvas on the page. Reload the page to instrument it.");
    var reloadPageButton = this._decorationElement.createChild("button");
    reloadPageButton.type = "button";
    reloadPageButton.textContent = WebInspector.UIString("Reload");
    reloadPageButton.addEventListener("click", this._onReloadPageButtonClick.bind(this), false);

    this._dispatcher = new WebInspector.CanvasDispatcher(this);

    // FIXME: enable/disable by a UI action?
    CanvasAgent.enable(this._updateDecorationElement.bind(this));
    WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, this._updateDecorationElement, this);
}

WebInspector.CanvasProfileType.TypeId = "CANVAS_PROFILE";

WebInspector.CanvasProfileType.prototype = {
    get statusBarItems()
    {
        return [this._capturingModeSelector.element, this._frameSelector.element];
    },

    get buttonTooltip()
    {
        if (this._isSingleFrameMode())
            return WebInspector.UIString("Capture next canvas frame.");
        else
            return this._recording ? WebInspector.UIString("Stop capturing canvas frames.") : WebInspector.UIString("Start capturing canvas frames.");
    },

    /**
     * @override
     * @param {WebInspector.ProfilesPanel} profilesPanel
     * @return {boolean}
     */
    buttonClicked: function(profilesPanel)
    {
        if (this._recording) {
            this._recording = false;
            this._stopFrameCapturing();
        } else if (this._isSingleFrameMode()) {
            this._recording = false;
            this._runSingleFrameCapturing(profilesPanel);
        } else {
            this._recording = true;
            this._startFrameCapturing(profilesPanel);
        }
        profilesPanel.setRecordingProfile(WebInspector.CanvasProfileType.TypeId, this._recording);
        return this._recording;
    },

    /**
     * @param {WebInspector.ProfilesPanel} profilesPanel
     */
    _runSingleFrameCapturing: function(profilesPanel)
    {
        var frameId = this._selectedFrameId();
        CanvasAgent.captureFrame(frameId, this._didStartCapturingFrame.bind(this, profilesPanel, frameId));
    },

    /**
     * @param {WebInspector.ProfilesPanel} profilesPanel
     */
    _startFrameCapturing: function(profilesPanel)
    {
        var frameId = this._selectedFrameId();
        CanvasAgent.startCapturing(frameId, this._didStartCapturingFrame.bind(this, profilesPanel, frameId));
    },

    _stopFrameCapturing: function()
    {
        if (!this._lastProfileHeader)
            return;
        var profileHeader = this._lastProfileHeader;
        var traceLogId = profileHeader.traceLogId();
        this._lastProfileHeader = null;
        function didStopCapturing()
        {
            profileHeader._updateCapturingStatus();
        }
        CanvasAgent.stopCapturing(traceLogId, didStopCapturing.bind(this));
    },

    /**
     * @param {WebInspector.ProfilesPanel} profilesPanel
     * @param {string|undefined} frameId
     * @param {?Protocol.Error} error
     * @param {CanvasAgent.TraceLogId} traceLogId
     */
    _didStartCapturingFrame: function(profilesPanel, frameId, error, traceLogId)
    {
        if (error || this._lastProfileHeader && this._lastProfileHeader.traceLogId() === traceLogId)
            return;
        var profileHeader = new WebInspector.CanvasProfileHeader(this, WebInspector.UIString("Trace Log %d", this._nextProfileUid), this._nextProfileUid, traceLogId, frameId);
        ++this._nextProfileUid;
        this._lastProfileHeader = profileHeader;
        profilesPanel.addProfileHeader(profileHeader);
        profileHeader._updateCapturingStatus();
    },

    get treeItemTitle()
    {
        return WebInspector.UIString("CANVAS PROFILE");
    },

    get description()
    {
        return WebInspector.UIString("Canvas calls instrumentation");
    },

    /**
     * @override
     * @return {Element}
     */
    decorationElement: function()
    {
        return this._decorationElement;
    },

    /**
     * @override
     */
    reset: function()
    {
        this._nextProfileUid = 1;
    },

    setRecordingProfile: function(isProfiling)
    {
        this._recording = isProfiling;
    },

    /**
     * @override
     * @param {string=} title
     * @return {WebInspector.ProfileHeader}
     */
    createTemporaryProfile: function(title)
    {
        title = title || WebInspector.UIString("Capturing\u2026");
        return new WebInspector.CanvasProfileHeader(this, title);
    },

    /**
     * @override
     * @param {ProfilerAgent.ProfileHeader} profile
     * @return {WebInspector.ProfileHeader}
     */
    createProfile: function(profile)
    {
        return new WebInspector.CanvasProfileHeader(this, profile.title, -1);
    },

    _updateDecorationElement: function()
    {
        /**
         * @param {?Protocol.Error} error
         * @param {boolean} result
         */
        function callback(error, result)
        {
            var hideWarning = (error || !result);
            this._decorationElement.enableStyleClass("hidden", hideWarning);
        }
        CanvasAgent.hasUninstrumentedCanvases(callback.bind(this));
    },

    /**
     * @param {MouseEvent} event
     */
    _onReloadPageButtonClick: function(event)
    {
        PageAgent.reload(event.shiftKey);
    },

    /**
     * @return {boolean}
     */
    _isSingleFrameMode: function()
    {
        return !this._capturingModeSelector.selectedOption().value;
    },

    /**
     * @param {WebInspector.Event} event
     */
    _frameAdded: function(event)
    {
        var contextList = /** @type {WebInspector.FrameExecutionContextList} */ (event.data);
        this._addFrame(contextList);
    },

    /**
     * @param {WebInspector.FrameExecutionContextList} contextList
     */
    _addFrame: function(contextList)
    {
        var frameId = contextList.frameId;
        var option = document.createElement("option");
        option.text = contextList.displayName;
        option.title = contextList.url;
        option.value = frameId;

        this._frameOptions[frameId] = option;

        if (this._framesWithCanvases[frameId]) {
            this._frameSelector.addOption(option);
            this._dispatchViewUpdatedEvent();
        }
    },

    /**
     * @param {WebInspector.Event} event
     */
    _frameRemoved: function(event)
    {
        var contextList = /** @type {WebInspector.FrameExecutionContextList} */ (event.data);
        var frameId = contextList.frameId;
        var option = this._frameOptions[frameId];
        if (option && this._framesWithCanvases[frameId]) {
            this._frameSelector.removeOption(option);
            this._dispatchViewUpdatedEvent();
        }
        delete this._frameOptions[frameId];
        delete this._framesWithCanvases[frameId];
    },

    /**
     * @param {string} frameId
     */
    _contextCreated: function(frameId)
    {
        if (this._framesWithCanvases[frameId])
            return;
        this._framesWithCanvases[frameId] = true;
        var option = this._frameOptions[frameId];
        if (option) {
            this._frameSelector.addOption(option);
            this._dispatchViewUpdatedEvent();
        }
    },

    /**
     * @param {NetworkAgent.FrameId=} frameId
     * @param {CanvasAgent.TraceLogId=} traceLogId
     */
    _traceLogsRemoved: function(frameId, traceLogId)
    {
        var sidebarElementsToDelete = [];
        var sidebarElements = /** @type {!Array.<WebInspector.ProfileSidebarTreeElement>} */ ((this.treeElement && this.treeElement.children) || []);
        for (var i = 0, n = sidebarElements.length; i < n; ++i) {
            var header = /** @type {WebInspector.CanvasProfileHeader} */ (sidebarElements[i].profile);
            if (!header)
                continue;
            if (frameId && frameId !== header.frameId())
                continue;
            if (traceLogId && traceLogId !== header.traceLogId())
                continue;
            sidebarElementsToDelete.push(sidebarElements[i]);
        }
        for (var i = 0, n = sidebarElementsToDelete.length; i < n; ++i)
            sidebarElementsToDelete[i].ondelete();
    },

    /**
     * @return {string|undefined}
     */
    _selectedFrameId: function()
    {
        var option = this._frameSelector.selectedOption();
        return option ? option.value : undefined;
    },

    _dispatchViewUpdatedEvent: function()
    {
        this._frameSelector.element.enableStyleClass("hidden", this._frameSelector.size() <= 1);
        this.dispatchEventToListeners(WebInspector.ProfileType.Events.ViewUpdated);
    },

    __proto__: WebInspector.ProfileType.prototype
}

/**
 * @constructor
 * @implements {CanvasAgent.Dispatcher}
 * @param {WebInspector.CanvasProfileType} profileType
 */
WebInspector.CanvasDispatcher = function(profileType)
{
    this._profileType = profileType;
    InspectorBackend.registerCanvasDispatcher(this);
}

WebInspector.CanvasDispatcher.prototype = {
    /**
     * @param {string} frameId
     */
    contextCreated: function(frameId)
    {
        this._profileType._contextCreated(frameId);
    },

    /**
     * @param {NetworkAgent.FrameId=} frameId
     * @param {CanvasAgent.TraceLogId=} traceLogId
     */
    traceLogsRemoved: function(frameId, traceLogId)
    {
        this._profileType._traceLogsRemoved(frameId, traceLogId);
    }
}

/**
 * @constructor
 * @extends {WebInspector.ProfileHeader}
 * @param {!WebInspector.CanvasProfileType} type
 * @param {string} title
 * @param {number=} uid
 * @param {CanvasAgent.TraceLogId=} traceLogId
 * @param {NetworkAgent.FrameId=} frameId
 */
WebInspector.CanvasProfileHeader = function(type, title, uid, traceLogId, frameId)
{
    WebInspector.ProfileHeader.call(this, type, title, uid);
    /** @type {CanvasAgent.TraceLogId} */
    this._traceLogId = traceLogId || "";
    this._frameId = frameId;
    this._alive = true;
    this._traceLogSize = 0;
}

WebInspector.CanvasProfileHeader.prototype = {
    /**
     * @return {CanvasAgent.TraceLogId}
     */
    traceLogId: function()
    {
        return this._traceLogId;
    },

    /**
     * @return {NetworkAgent.FrameId|undefined}
     */
    frameId: function()
    {
        return this._frameId;
    },

    /**
     * @override
     * @return {WebInspector.ProfileSidebarTreeElement}
     */
    createSidebarTreeElement: function()
    {
        return new WebInspector.ProfileSidebarTreeElement(this, WebInspector.UIString("Trace Log %d"), "profile-sidebar-tree-item");
    },

    /**
     * @override
     * @param {WebInspector.ProfilesPanel} profilesPanel
     */
    createView: function(profilesPanel)
    {
        return new WebInspector.CanvasProfileView(this);
    },

    /**
     * @override
     * @param {!WebInspector.ProfilesPanel} profilesPanel
     */
    dispose: function(profilesPanel)
    {
        if (this._traceLogId) {
            CanvasAgent.dropTraceLog(this._traceLogId);
            clearTimeout(this._requestStatusTimer);
            if (this._alive)
                profilesPanel.setRecordingProfile(WebInspector.CanvasProfileType.TypeId, false);
            this._alive = false;
        }
    },

    /**
     * @param {CanvasAgent.TraceLog=} traceLog
     */
    _updateCapturingStatus: function(traceLog)
    {
        if (!this.sidebarElement || !this._traceLogId)
            return;

        if (traceLog) {
            this._alive = traceLog.alive;
            this._traceLogSize = traceLog.totalAvailableCalls;
        }

        this.sidebarElement.subtitle = this._alive ? WebInspector.UIString("Capturing\u2026 %d calls", this._traceLogSize) : WebInspector.UIString("Captured %d calls", this._traceLogSize);
        this.sidebarElement.wait = this._alive;

        if (this._alive) {
            clearTimeout(this._requestStatusTimer);
            this._requestStatusTimer = setTimeout(this._requestCapturingStatus.bind(this), WebInspector.CanvasProfileView.TraceLogPollingInterval);
        }
    },

    _requestCapturingStatus: function()
    {
        /**
         * @param {?Protocol.Error} error
         * @param {CanvasAgent.TraceLog} traceLog
         */
        function didReceiveTraceLog(error, traceLog)
        {
            if (error)
                return;
            this._alive = traceLog.alive;
            this._traceLogSize = traceLog.totalAvailableCalls;
            this._updateCapturingStatus();
        }
        CanvasAgent.getTraceLog(this._traceLogId, 0, 0, didReceiveTraceLog.bind(this));
    },

    __proto__: WebInspector.ProfileHeader.prototype
}


text:
<?php
// {$setting_id}[$id] - Contains the setting id, this is what it will be stored in the db as.
// $class - optional class value
// $id - setting id
// $options[$id] value from the db

$profiles = array(
'Facebook',
'Twitter',
'RSS',
'Email',
);

if(!empty($options[$id])){
	$profiles = array();
	foreach($options[$id] as $k=>$v){
		$profiles[] = $k;
	}

}

?>
<?php _e("Enter your social profile url's. Drag & Drop the icons to reorder. Remember to save your changes. Learn how to add your own custom icons.", 'seed_ucp'); ?>

	<?php foreach($profiles as $k=>$v){ ?>

<img style="width:24px;vertical-align:middle;cursor:move" src="<?php echo SEED_UCP_PLUGIN_URL.'themes/default/images/icons1/'.strtolower($v).'.png'; ?>"> <?php echo "<input autocomplete='off' placeholder='$v'  class='regular-text' name='{$setting_id}[$id][$v]' type='text' value='" . esc_attr( $options[ $id ][$v] ) . "' />"; ?>

	<?php } ?>


text:
<resources>
    <string name="app_name">CollapseRelativeLayout</string>
</resources>


text:
@implementation NSString (RSEmail)

- (BOOL)isEmail {
    BOOL stricterFilter = YES;
    NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
    NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
    NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}

@end


text:
layout: post
date: 2017-09-12
title: "NOVIA D ART CALISTA Sleeveless Court Train Sheath/Column"
category: NOVIA D ART
tags: [NOVIA D ART,Sheath/Column,V-neck,Court Train,Sleeveless]
---
### NOVIA D ART CALISTA
Just **$619.00**
###   Sleeveless Court Train Sheath/Column

BRANDS	NOVIA D ART

Silhouette	Sheath/Column

Neckline	V-neck

Hemline/Train	Court Train

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/novia-d-art/46895-novia-d-art-calista.html](https://www.readybrides.com/en/novia-d-art/46895-novia-d-art-calista.html)


text:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeFixes;
using System.Threading.Tasks;
using System.Linq;

namespace RefactoringEssentials.CSharp.Diagnostics
{
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    [NotPortedYet]
    public class CS0126ReturnMustBeFollowedByAnyExpression : DiagnosticAnalyzer
    {
        internal const string DiagnosticId = "CS0126ReturnMustBeFollowedByAnyExpression";
        const string Description = "Since 'function' doesn't return void, a return keyword must be followed by an object expression";
        const string MessageFormat = "";
        const string Category = DiagnosticAnalyzerCategories.CompilerErrors;

        static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Description, MessageFormat, Category, DiagnosticSeverity.Error, true, "CS0126: A method with return type cannot return without value.");

        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
        {
            get
            {
                return ImmutableArray.Create(Rule);
            }
        }

        public override void Initialize(AnalysisContext context)
        {
            //context.RegisterSyntaxNodeAction(
            //	(nodeContext) => {
            //		Diagnostic diagnostic;
            //		if (TryGetDiagnostic (nodeContext, out diagnostic)) {
            //			nodeContext.ReportDiagnostic(diagnostic);
            //		}
            //	},
            //	new SyntaxKind[] { SyntaxKind.None }
            //);
        }

        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);
            if (nodeContext.IsFromGeneratedCode())
                return false;
            //var node = nodeContext.Node as ;
            //diagnostic = Diagnostic.Create (descriptor, node.GetLocation ());
            //return true;
            return false;
        }

        //		internal static IType GetRequestedReturnType (BaseSemanticModel ctx, AstNode returnStatement, out AstNode entityNode)
        //		{
        //			entityNode = returnStatement.GetParent(p => p is LambdaExpression || p is AnonymousMethodExpression || !(p is Accessor) && p is EntityDeclaration);
        //			if (entityNode == null)
        //				return SpecialType.UnknownType;
        //			if (entityNode is EntityDeclaration) {
        //				var rr = ctx.Resolve(entityNode) as MemberResolveResult;
        //				if (rr == null)
        //					return SpecialType.UnknownType;
        //				if (((EntityDeclaration)entityNode).HasModifier(Modifiers.Async))
        //					return TaskType.UnpackTask(ctx.Compilation, rr.Member.ReturnType);
        //				return rr.Member.ReturnType;
        //			}
        //			bool isAsync = false;
        //			if (entityNode is LambdaExpression)
        //				isAsync = ((LambdaExpression)entityNode).IsAsync;
        //			if (entityNode is AnonymousMethodExpression)
        //				isAsync = ((AnonymousMethodExpression)entityNode).IsAsync;
        //			foreach (var type in TypeGuessing.GetValidTypes(ctx.Resolver, entityNode)) {
        //				if (type.Kind != TypeKind.Delegate)
        //					continue;
        //				var invoke = type.GetDelegateInvokeMethod();
        //				if (invoke != null) {
        //					return isAsync ? TaskType.UnpackTask(ctx.Compilation, invoke.ReturnType) : invoke.ReturnType;
        //				}
        //			}
        //			return SpecialType.UnknownType;
        //		}

        //		class GatherVisitor : GatherVisitorBase<CS0126ReturnMustBeFollowedByAnyExpression>
        //		{
        //			//string currentMethodName;

        //			public GatherVisitor(SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
        //				: base(semanticModel, addDiagnostic, cancellationToken)
        //			{
        //			}

        ////			bool skip;
        ////
        ////			public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
        ////			{
        ////				var primitiveType = methodDeclaration.ReturnType as PrimitiveType;
        ////				skip = (primitiveType != null && primitiveType.Keyword == "void");
        ////				currentMethodName = methodDeclaration.Name;
        ////				base.VisitMethodDeclaration(methodDeclaration);
        ////			}
        ////
        ////			public override void VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration)
        ////			{
        ////				currentMethodName = constructorDeclaration.Name;
        ////				skip = true;
        ////				base.VisitConstructorDeclaration(constructorDeclaration);
        ////			}
        ////
        ////			public override void VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration)
        ////			{
        ////				currentMethodName = "~" + destructorDeclaration.Name;
        ////				skip = true;
        ////				base.VisitDestructorDeclaration(destructorDeclaration);
        ////			}
        ////
        ////			public override void VisitAccessor(Accessor accessor)
        ////			{
        ////				bool old = skip;
        ////				skip = accessor.Role != PropertyDeclaration.GetterRole && accessor.Role != IndexerDeclaration.GetterRole;
        ////				base.VisitAccessor(accessor);
        ////				skip = old;
        ////			}
        ////
        ////			static bool AnonymousMethodMayReturnVoid(BaseSemanticModel ctx, Expression anonymousMethodExpression)
        ////			{
        ////				foreach (var type in TypeGuessing.GetValidTypes(ctx.Resolver, anonymousMethodExpression)) {
        ////					if (type.Kind != TypeKind.Delegate)
        ////						continue;
        ////					var invoke = type.GetDelegateInvokeMethod();
        ////					if (invoke != null && invoke.ReturnType.IsKnownType(KnownTypeCode.Void))
        ////						return true;
        ////				}
        ////				return false;
        ////			}
        ////
        ////
        ////			public override void VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression)
        ////			{
        ////				bool old = skip;
        ////				skip = AnonymousMethodMayReturnVoid(ctx, anonymousMethodExpression);
        ////				base.VisitAnonymousMethodExpression(anonymousMethodExpression);
        ////				skip = old;
        ////			}
        ////
        ////			public override void VisitLambdaExpression(LambdaExpression lambdaExpression)
        ////			{
        ////				bool old = skip;
        ////				skip = AnonymousMethodMayReturnVoid(ctx, lambdaExpression);
        ////				base.VisitLambdaExpression(lambdaExpression);
        ////				skip = old;
        ////			}
        ////
        ////			public override void VisitReturnStatement(ReturnStatement returnStatement)
        ////			{
        ////				base.VisitReturnStatement(returnStatement);
        ////				if (skip)
        ////					return;
        ////
        ////				if (returnStatement.Expression.IsNull) {
        ////					var entity = returnStatement.GetParent<EntityDeclaration>();
        ////					if (entity is Accessor)
        ////						entity = entity.GetParent<EntityDeclaration>();
        ////					if (entity == null)
        ////						return;
        ////					AstNode entityNode;
        ////					var rr = GetRequestedReturnType (ctx, returnStatement, out entityNode);
        ////					if (rr.Kind == TypeKind.Void)
        ////						return;
        ////					var actions = new List<CodeAction>();
        ////					if (rr.Kind != TypeKind.Unknown) {
        ////						actions.Add(new CodeAction(ctx.TranslateString("Return default value"), script => {
        ////							Expression p;
        ////							if (rr.IsKnownType(KnownTypeCode.Boolean)) {
        ////								p = new PrimitiveExpression(false);
        ////							} else if (rr.IsKnownType(KnownTypeCode.String)) {
        ////								p = new PrimitiveExpression("");
        ////							} else if (rr.IsKnownType(KnownTypeCode.Char)) {
        ////								p = new PrimitiveExpression(' ');
        ////							} else if (rr.IsReferenceType == true) {
        ////								p = new NullReferenceExpression();
        ////							} else if (rr.GetDefinition() != null &&
        ////								rr.GetDefinition().KnownTypeCode < KnownTypeCode.DateTime) {
        ////								p = new PrimitiveExpression(0x0);
        ////							} else {
        ////								p = new DefaultValueExpression(ctx.CreateTypeSystemAstBuilder(returnStatement).ConvertType(rr));
        ////							}
        ////
        ////							script.Replace(returnStatement, new ReturnStatement(p));
        ////						}, returnStatement));
        ////					}
        ////					var method = returnStatement.GetParent<MethodDeclaration>();
        ////					if (method != null) {
        ////						actions.Add(new CodeAction(ctx.TranslateString("Change method return type to 'void'"), script => {
        ////							script.Replace(method.ReturnType, new PrimitiveType("void"));
        ////						}, returnStatement));
        ////					}
        ////
        ////					AddDiagnosticAnalyzer(new CodeIssue(
        ////						returnStatement,
        ////						string.Format(ctx.TranslateString("`{0}': A return keyword must be followed by any expression when method returns a value"), currentMethodName),
        ////						actions
        ////					));
        ////				}
        ////			}
        //		}
    }

    [ExportCodeFixProvider(LanguageNames.CSharp), System.Composition.Shared]
    [NotPortedYet]
    public class CS0126ReturnMustBeFollowedByAnyExpressionFixProvider : CodeFixProvider
    {
        public override ImmutableArray<string> FixableDiagnosticIds
        {
            get
            {
                return ImmutableArray.Create(CS0126ReturnMustBeFollowedByAnyExpression.DiagnosticId);
            }
        }

        public override FixAllProvider GetFixAllProvider()
        {
            return WellKnownFixAllProviders.BatchFixer;
        }

        public async override Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var document = context.Document;
            var cancellationToken = context.CancellationToken;
            var span = context.Span;
            var diagnostics = context.Diagnostics;
            var root = await document.GetSyntaxRootAsync(cancellationToken);
            var diagnostic = diagnostics.First();
            var node = root.FindNode(context.Span);
            //if (!node.IsKind(SyntaxKind.BaseList))
            //	continue;
            var newRoot = root.RemoveNode(node, SyntaxRemoveOptions.KeepNoTrivia);
            context.RegisterCodeFix(CodeActionFactory.Create(node.Span, diagnostic.Severity, diagnostic.GetMessage(), document.WithSyntaxRoot(newRoot)), diagnostic);
        }
    }
}


text:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Solution {

	public static void main(String[] args) {
		Scanner read = new Scanner(System.in);

		String s = read.nextLine();
		int k = read.nextInt();

		int[] w = new int[26];
		int maxValue = Integer.MIN_VALUE;
		for (int i = 0; i < 26; ++i) {
			w[i] = read.nextInt();
			if (w[i] > maxValue) {
				maxValue = w[i];
			}
		}

		Map<Character, Integer> letterValues = new HashMap<Character, Integer>();
		int indexCounter = 0;
		for (char c = 'a'; c <= 'z'; ++c) {
			letterValues.put(c, w[indexCounter]);
			indexCounter++;
		}

		int totalValue = 0;
		for (int i = 1; i <= s.length(); ++i) {
			char c = s.charAt(i-1);
			totalValue += i * letterValues.get(c);
		}

		for (int i = s.length()+1; i <= s.length()+k; ++i) {
			totalValue += i * maxValue;
		}

		System.out.println(totalValue);

		// Close scanner
		read.close();
	}

}


text:
class FontNotoSansBuginese < Cask
  version 'latest'
  sha256 :no_check

  url 'https://www.google.com/get/noto/pkgs/NotoSansBuginese-unhinted.zip'
  homepage 'http://www.google.com/get/noto'

  font 'NotoSansBuginese-Regular.ttf'
end


text:
<?php

namespace App\Http\Controllers\Web;

use App\Entities\User;
use App\Http\Controllers\Controller;
use App\Http\Requests\User\EditRequest;
use App\Http\Requests\User\PasswordRequest;
use App\Repositories\Criteria\OrderBy;
use App\Repositories\Criteria\Where;
use App\Repositories\UserRepository;
use App\Services\UserService;
use Illuminate\Support\MessageBag;

class UserController extends Controller
{
    private $repository;

    /**
     * UserController constructor.
     *
     * @param UserRepository $repository
     */
    public function __construct(UserRepository $repository)
    {
        $this->repository = $repository;
    }

    public function index()
    {
        $per_page = 100;
        $offset = (request('page', 1) - 1) * $per_page + 1;

        $this->repository->pushCriteria(new Where('status', User::ST_ACTIVE));
        $this->repository->pushCriteria(new OrderBy('solved', 'desc'));
        $this->repository->pushCriteria(new OrderBy('submit', 'asc'));

        $users = $this->repository->paginate($per_page);

        return view('web.user.index', ['users' => $users, 'offset' => $offset]);
    }

    public function show($username)
    {
        /** @var User $user */
        $user = (new UserService())->findByName($username);

        if (!$user->isActive()) {
            return back()->withErrors('User is not found!');
        }

        if ($user) {
            return view('web.user.view')->with('user', $user);
        }

        return redirect(route('home'));
    }

    public function profile()
    {
        $user = auth()->user();

        if ($user) {
            return view('web.user.edit')->with('user', $user);
        }

        return redirect(route('home'));
    }

    public function edit(EditRequest $request)
    {
        /** @var User $user */
        $user = auth()->user();

        if ($user) {
            $user->update($request->all());

            return redirect()->back();
        }

        return redirect(route('home'));
    }

    public function editPassword()
    {
        $user = auth()->user();
        if ($user) {
            return view('web.user.password')->with('user', $user);
        }

        return redirect(route('home'));
    }

    public function password(PasswordRequest $request)
    {
        /** @var User $user */
        $user = auth()->user();
        if ($user) {
            if (app('hash')->make($request->input('password')) === $user->password) {
                $user->password = app('hash')->make($request->input('password_new'));
                $user->save();

                return redirect()->back()->with('success', trans('user.message.password_change_success'));
            }
            $errors = new MessageBag(['password' => trans('user.message.password_not_match')]);

            return redirect()->back()->withErrors($errors);
        }
    }
}


text:
from collections import OrderedDict
import os.path
import re
from typing import Union, List, Callable, Tuple, Optional, Dict, Sequence, TYPE_CHECKING

from typing_extensions import Literal, Final

from cantools.typechecking import (
    Formats,
    Choices,
    SignalMappingType,
    SignalDictType,
    ByteOrder,
)

if TYPE_CHECKING:
    from cantools.database import Database
    from cantools.database.can.attribute import Attribute
    from cantools.database.can.message import Message
    from cantools.database.can.node import Node
    from cantools.database.can.signal import Signal
    from cantools.database.diagnostics import Data

try:
    import bitstruct.c
except ImportError:
    import bitstruct

def format_or(items: List[Union[int, str]]) -> str:
    string_items = [str(item) for item in items]

    if len(string_items) == 1:
        return string_items[0]
    else:
        return '{} or {}'.format(', '.join(string_items[:-1]),
                                 string_items[-1])

def format_and(items: List[Union[int, str]]) -> str:
    string_items = [str(item) for item in items]

    if len(string_items) == 1:
        return str(string_items[0])
    else:
        return '{} and {}'.format(', '.join(string_items[:-1]),
                                  string_items[-1])

def start_bit(data: Union["Data", "Signal"]) -> int:
    if data.byte_order == 'big_endian':
        return 8 * (data.start // 8) + (7 - (data.start % 8))
    else:
        return data.start

def _encode_fields(fields: Sequence[Union["Signal", "Data"]],
                   data: SignalMappingType,
                   scaling: bool,
                   ) -> Dict[str, Union[int, float]]:
    unpacked = {}
    for field in fields:
        value = data[field.name]

        if isinstance(value, (float, int)):
            _transform = float if field.is_float else round
            if scaling:
                if field.offset == 0 and field.scale == 1:
                    # treat special case to avoid introduction of unnecessary rounding error
                    unpacked[field.name] = _transform(value)  # type: ignore[operator]
                    continue

                unpacked[field.name] = _transform((value - field.offset) / field.scale)  # type: ignore[operator]
                continue

            unpacked[field.name] = _transform(value)  # type: ignore[operator]
            continue

        unpacked[field.name] = field.choice_string_to_number(str(value))

    return unpacked

def encode_data(data: SignalMappingType,
                fields: Sequence[Union["Signal", "Data"]],
                formats: Formats,
                scaling: bool
                ) -> int:
    if len(fields) == 0:
        return 0

    unpacked = _encode_fields(fields, data, scaling)
    big_packed = formats.big_endian.pack(unpacked)
    little_packed = formats.little_endian.pack(unpacked)
    packed_union = int.from_bytes(big_packed, "big") | int.from_bytes(little_packed, "little")

    return packed_union

def decode_data(data: bytes,
                expected_length: int,
                fields: Sequence[Union["Signal", "Data"]],
                formats: Formats,
                decode_choices: bool,
                scaling: bool,
                allow_truncated: bool,
                ) -> SignalDictType:

    actual_length = len(data)
    if allow_truncated and actual_length < expected_length:
        data = data.ljust(expected_length, b"\xFF")

    unpacked = {
        **formats.big_endian.unpack(bytes(data)),
        **formats.little_endian.unpack(bytes(data[::-1])),
    }

    if allow_truncated and actual_length < expected_length:
        # remove fields that are outside available data bytes
        valid_bit_count = actual_length * 8
        for field in fields:
            if field.byte_order == "little_endian":
                sequential_startbit = field.start
            else:
                # Calculate startbit with inverted indices.
                # Function body of ``sawtooth_to_network_bitnum()``
                # is inlined for improved performance.
                sequential_startbit = (8 * (field.start // 8)) + (7 - (field.start % 8))

            if sequential_startbit + field.length > valid_bit_count:
                del unpacked[field.name]

    decoded = {}
    for field in fields:
        try:
            value = unpacked[field.name]

            if decode_choices:
                try:
                    decoded[field.name] = field.choices[value]  # type: ignore[index]
                    continue
                except (KeyError, TypeError):
                    pass

            if scaling:
                decoded[field.name] = field.scale * value + field.offset
                continue
            else:
                decoded[field.name] = value

        except KeyError:
            if not allow_truncated:
                raise

    return decoded

def create_encode_decode_formats(datas: Sequence[Union["Data", "Signal"]], number_of_bytes: int) -> Formats:
    format_length = (8 * number_of_bytes)

    def get_format_string_type(data: Union["Data", "Signal"]) -> str:
        if data.is_float:
            return 'f'
        elif data.is_signed:
            return 's'
        else:
            return 'u'

    def padding_item(length: int) -> Tuple[str, str, None]:
        fmt = 'p{}'.format(length)
        padding_mask = '1' * length

        return fmt, padding_mask, None

    def data_item(data: Union["Data", "Signal"]) -> Tuple[str, str, str]:
        fmt = '{}{}'.format(get_format_string_type(data),
                            data.length)
        padding_mask = '0' * data.length

        return fmt, padding_mask, data.name

    def fmt(items: List[Tuple[str, str, Optional[str]]]) -> str:
        return ''.join([item[0] for item in items])

    def names(items:  List[Tuple[str, str, Optional[str]]]) -> List[str]:
        return [item[2] for item in items if item[2] is not None]

    def padding_mask(items: List[Tuple[str, str, Optional[str]]]) -> int:
        try:
            return int(''.join([item[1] for item in items]), 2)
        except ValueError:
            return 0

    def create_big() -> Tuple[str, int, List[str]]:
        items: List[Tuple[str, str, Optional[str]]] = []
        start = 0

        # Select BE fields
        be_datas = [data for data in datas if data.byte_order == "big_endian"]

        # Ensure BE fields are sorted in network order
        sorted_datas = sorted(be_datas, key = lambda data: sawtooth_to_network_bitnum(data.start))

        for data in sorted_datas:

            padding_length = (start_bit(data) - start)

            if padding_length > 0:
                items.append(padding_item(padding_length))

            items.append(data_item(data))
            start = (start_bit(data) + data.length)

        if start < format_length:
            length = format_length - start
            items.append(padding_item(length))

        return fmt(items), padding_mask(items), names(items)

    def create_little() -> Tuple[str, int, List[str]]:
        items: List[Tuple[str, str, Optional[str]]] = []
        end = format_length

        for data in datas[::-1]:
            if data.byte_order == 'big_endian':
                continue

            padding_length = end - (data.start + data.length)

            if padding_length > 0:
                items.append(padding_item(padding_length))

            items.append(data_item(data))
            end = data.start

        if end > 0:
            items.append(padding_item(end))

        value = padding_mask(items)

        if format_length > 0:
            length = len(''.join([item[1] for item in items]))
            _packed = bitstruct.pack('u{}'.format(length), value)
            value = int.from_bytes(_packed, "little")

        return fmt(items), value, names(items)

    big_fmt, big_padding_mask, big_names = create_big()
    little_fmt, little_padding_mask, little_names = create_little()

    try:
        big_compiled = bitstruct.c.compile(big_fmt, big_names)
    except Exception as e:
        big_compiled = bitstruct.compile(big_fmt, big_names)

    try:
        little_compiled = bitstruct.c.compile(little_fmt, little_names)
    except Exception as e:
        little_compiled = bitstruct.compile(little_fmt, little_names)

    return Formats(big_compiled,
                   little_compiled,
                   big_padding_mask & little_padding_mask)

def sawtooth_to_network_bitnum(sawtooth_bitnum: int) -> int:
    '''Convert SawTooth bit number to Network bit number

    Byte     |   0   |   1   |
    Sawtooth |7 ... 0|15... 8|
    Network  |0 ... 7|8 ...15|
    '''
    return (8 * (sawtooth_bitnum // 8)) + (7 - (sawtooth_bitnum % 8))

def cdd_offset_to_dbc_start_bit(cdd_offset: int, bit_length: int, byte_order: ByteOrder) -> int:
    '''Convert CDD/c-style field bit offset to DBC field start bit convention.

    BigEndian (BE) fields are located by their MSBit's sawtooth index.
    LitteleEndian (LE) fields located by their LSBit's sawtooth index.
    '''
    if byte_order == "big_endian":
        # Note: Allow for BE fields that are smaller or larger than 8 bits.
        return (8 * (cdd_offset // 8)) + min(7, (cdd_offset % 8) + bit_length - 1)
    else:
        return cdd_offset

def prune_signal_choices(signal: "Signal") -> None:
    '''Shorten the names of the signal choices of a single signal

    For signals with multiple named values this means removing the
    longest common prefix that ends with an underscore and for which
    the removal still result the named signal values to be valid
    python identifiers. For signals with a single named choice, this
    means removing all leading segments between underscores which
    occur before a segment that contains a digit.

    Examples:

    ..code:: text

       MyMessage_MySignal_Uint32_Choice1, MyMessage_MySignal_Uint32_Choice2
       -> Choice1, Choice2
       MyMessage_MySignal_Uint32_NotAvailable
       -> NotAvailable

    '''

    if signal.choices is None:
        # no named choices
        return

    if len(signal.choices) == 1:
        # signal exhibits only a single named value: Use the longest
        # postfix starting with an underscore that does not contain
        # digits as the new name. If no such suffix exists, leave the
        # choice alone...
        key = next(iter(signal.choices.keys()))
        choice = next(iter(signal.choices.values()))
        m = re.match(r'^[0-9A-Za-z_]*?_([A-Za-z_]+)$', str(choice))
        val = str(choice)
        if m:
            val = m.group(1)

        if isinstance(choice, str):
            signal.choices[key] = val
        else:
            # assert isinstance(choice, NamedSignalValue)
            choice._name = val
        return

    # if there are multiple choices, remove the longest common prefix
    # that ends with an underscore from all of them provided that the
    # names of the choices stay valid identifiers
    choice_values = [ str(x) for x in signal.choices.values() ]
    full_prefix = os.path.commonprefix(choice_values)
    i = full_prefix.rfind('_')

    if i >= 0:
        full_prefix = full_prefix[0:i]
    else:
        # full_prefix does not contain an underscore
        # but the following algorithm assumes it does
        # and would strip too much
        return

    if not full_prefix:
        # the longest possible prefix is empty, i.e., there is nothing
        # to strip from the names of the signal choices
        return

    full_prefix_segments = full_prefix.split('_')

    # find the longest prefix of the choices which keeps all
    # names valid python identifiers
    prefix = ''
    n = 0
    valid_name_re = re.compile('^[a-zA-Z_][a-zA-Z0-9_]*$')
    for i in range(len(full_prefix_segments), -1, -1):
        if i == 0:
            # there is no such non-empty prefix
            return

        prefix = '_'.join(full_prefix_segments[:i]) + '_'
        n = len(prefix)

        if all([valid_name_re.match(x[n:]) for x in choice_values]):
            break

    # remove the prefix from the choice names
    for key, choice in signal.choices.items():
        if isinstance(choice, str):
            signal.choices[key] = choice[n:]
        else:
            # assert isinstance(choice, NamedSignalValue)
            choice._name = choice._name[n:]

def prune_database_choices(database: "Database") -> None:
    '''
    Prune names of all named signal values of all signals of a database
    '''
    for message in database.messages:

        for signal in message.signals:
            prune_signal_choices(signal)

        if message.contained_messages is not None:
            for cm in message.contained_messages:
                for cs in cm.signals:
                    prune_signal_choices(cs)

SORT_SIGNALS_DEFAULT: Final = 'default'
type_sort_signals = Union[Callable[[List["Signal"]], List["Signal"]], Literal['default'], None]

type_sort_attribute = Union[
    Tuple[Literal['dbc'],     "Attribute", None,   None,      None],
    Tuple[Literal['node'],    "Attribute", "Node", None,      None],
    Tuple[Literal['message'], "Attribute", None,   "Message", None],
    Tuple[Literal['signal'],  "Attribute", None,   "Message", "Signal"],
]

type_sort_attributes = Union[Callable[[List[type_sort_attribute]], List[type_sort_attribute]], Literal['default'], None]

type_sort_choices = Union[Callable[[Choices], Choices], None]

def sort_signals_by_start_bit(signals: List["Signal"]) -> List["Signal"]:
    return list(sorted(signals, key=start_bit))

def sort_signals_by_start_bit_reversed(signals: List["Signal"]) -> List["Signal"]:
    return list(reversed(sorted(signals, key=start_bit)))

def sort_signals_by_name(signals: List["Signal"]) -> List["Signal"]:
    return list(sorted(signals, key=lambda s: s.name))

def sort_signals_by_start_bit_and_mux(signals: List["Signal"]) -> List["Signal"]:
    # sort by start bit
    signals = sorted(signals, key=start_bit)
    # but unmuxed values come first
    signals = sorted(signals, key=lambda s: bool(s.multiplexer_ids))
    # and group by mux... -1 is fine as the "no mux" case because even negative
    # multiplexors get cast to unsigned in the .dbc
    signals = sorted(
        signals, key=lambda s: s.multiplexer_ids[0] if s.multiplexer_ids else -1
    )

    return signals

def sort_choices_by_value(choices: Choices) -> Choices:
    return OrderedDict(sorted(choices.items(), key=lambda x: x[0]))

def sort_choices_by_value_descending(choices: Choices) -> Choices:
    return OrderedDict(sorted(choices.items(), key=lambda x: x[0], reverse=True))