text:
package com.orientechnologies.orient.server.distributed;

import com.orientechnologies.common.collection.OMultiValue;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.command.OCommandDistributedReplicateRequest;
import com.orientechnologies.orient.server.distributed.ODistributedServerLog.DIRECTION;
import com.orientechnologies.orient.server.distributed.task.OAbstractRemoteTask;
import com.orientechnologies.orient.server.distributed.task.OAbstractReplicatedTask;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Asynchronous response manager
 *
 * @author Luca Garulli (l.garulli--at--orientechnologies.com)
 *
 */
public class ODistributedResponseManager {
  public static final int                        ADDITIONAL_TIMEOUT_CLUSTER_SHAPE = 10000;
  private static final String                    NO_RESPONSE                      = "waiting-for-response";
  private final ODistributedServerManager        dManager;
  private final ODistributedRequest              request;
  private final long                             sentOn;
  private final HashMap<String, Object>          responses                        = new HashMap<String, Object>();
  private final boolean                          groupResponsesByResult;
  private final List<List<ODistributedResponse>> responseGroups                   = new ArrayList<List<ODistributedResponse>>();
  private final int                              expectedSynchronousResponses;
  private final long                             synchTimeout;
  private final long                             totalTimeout;
  private final Lock                             synchronousResponsesLock         = new ReentrantLock();
  private final Condition                        synchronousResponsesArrived      = synchronousResponsesLock.newCondition();
  private final int                              quorum;
  private final boolean                          waitForLocalNode;
  private volatile int                           receivedResponses                = 0;
  private volatile int                           discardedResponses               = 0;
  private volatile boolean                       receivedCurrentNode;
  private Object                                 responseLock                     = new Object();

  public ODistributedResponseManager(final ODistributedServerManager iManager, final ODistributedRequest iRequest,
      final Collection<String> expectedResponses, final int iExpectedSynchronousResponses, final int iQuorum,
      final boolean iWaitForLocalNode, final long iSynchTimeout, final long iTotalTimeout, final boolean iGroupResponsesByResult) {
    this.dManager = iManager;
    this.request = iRequest;
    this.sentOn = System.currentTimeMillis();
    this.expectedSynchronousResponses = iExpectedSynchronousResponses;
    this.quorum = iQuorum;
    this.waitForLocalNode = iWaitForLocalNode;
    this.synchTimeout = iSynchTimeout;
    this.totalTimeout = iTotalTimeout;
    this.groupResponsesByResult = iGroupResponsesByResult;

    for (String node : expectedResponses)
      responses.put(node, NO_RESPONSE);

    if (groupResponsesByResult)
      responseGroups.add(new ArrayList<ODistributedResponse>());
  }

  /**
   * Not synchronized, it's called when a message arrives
   *
   * @param response
   *          Received response to collect
   * @return True if all the nodes responded, otherwise false
   */
  public boolean collectResponse(final ODistributedResponse response) {
    final String executorNode = response.getExecutorNodeName();

    synchronized (responseLock) {
      if (!responses.containsKey(executorNode)) {
        ODistributedServerLog.warn(this, response.getSenderNodeName(), executorNode, DIRECTION.IN,
            "received response for request (%s) from unexpected node. Expected are: %s", request, getExpectedNodes());

        Orient.instance().getProfiler()
            .updateCounter("distributed.node.unexpectedNodeResponse", "Number of responses from unexpected nodes", +1);

        return false;
      }

      Orient.instance().getProfiler()
          .stopChrono("distributed.node.latency", "Latency of distributed messages", sentOn, "distributed.node.latency");

      Orient
          .instance()
          .getProfiler()
          .stopChrono("distributed.node." + executorNode + ".latency", "Latency of distributed messages per node", sentOn,
              "distributed.node.*.latency");

      boolean completed = false;
      responses.put(executorNode, response);
      receivedResponses++;

      if (waitForLocalNode && response.isExecutedOnLocalNode())
        receivedCurrentNode = true;

      if (ODistributedServerLog.isDebugEnabled())
        ODistributedServerLog
            .debug(
                this,
                response.getSenderNodeName(),
                executorNode,
                DIRECTION.IN,
                "received response '%s' for request (%s) (receivedCurrentNode=%s receivedResponses=%d expectedSynchronousResponses=%d quorum=%d)",
                response, request, receivedCurrentNode, receivedResponses, expectedSynchronousResponses, quorum);

      if (response.getPayload() instanceof ODiscardedResponse)
        discardedResponses++;
      else if (groupResponsesByResult) {
        // PUT THE RESPONSE IN THE RIGHT RESPONSE GROUP
        // TODO: AVOID TO KEEP ALL THE RESULT FOR THE SAME RESP GROUP, BUT RATHER THE FIRST ONE + COUNTER
        boolean foundBucket = false;
        for (int i = 0; i < responseGroups.size(); ++i) {
          final List<ODistributedResponse> responseGroup = responseGroups.get(i);

          if (responseGroup.isEmpty())
            // ABSENT
            foundBucket = true;
          else {
            final Object rgPayload = responseGroup.get(0).getPayload();
            final Object responsePayload = response.getPayload();

            if (rgPayload == null && responsePayload == null)
              // BOTH NULL
              foundBucket = true;
            else if (rgPayload != null) {
              if (rgPayload.equals(responsePayload))
                // SAME RESULT
                foundBucket = true;
              else if (rgPayload instanceof Collection && responsePayload instanceof Collection) {
                if (OMultiValue.equals((Collection) rgPayload, (Collection) responsePayload))
                  // COLLECTIONS WITH THE SAME VALUES
                  foundBucket = true;
              }
            }
          }

          if (foundBucket) {
            responseGroup.add(response);
            break;
          }
        }

        if (!foundBucket) {
          // CREATE A NEW BUCKET
          final ArrayList<ODistributedResponse> newBucket = new ArrayList<ODistributedResponse>();
          responseGroups.add(newBucket);
          newBucket.add(response);
        }
      }

      completed = getExpectedResponses() == receivedResponses;

      if (receivedResponses >= expectedSynchronousResponses && (!waitForLocalNode || receivedCurrentNode)) {
        if (completed || isMinimumQuorumReached(false)) {
          // NOTIFY TO THE WAITER THE RESPONSE IS COMPLETE NOW
          notifyWaiters();
        }
      }
      return completed;
    }
  }

  public void notifyWaiters() {
    synchronousResponsesLock.lock();
    try {
      synchronousResponsesArrived.signalAll();
    } finally {
      synchronousResponsesLock.unlock();
    }
  }

  public long getMessageId() {
    return request.getId();
  }

  public long getSentOn() {
    return sentOn;
  }

  @SuppressWarnings("unchecked")
  public ODistributedResponse merge(final ODistributedResponse merged) {
    final StringBuilder executor = new StringBuilder(64);
    HashSet<Object> mergedPayload = new HashSet<Object>();

    for (Map.Entry<String, Object> entry : responses.entrySet()) {
      if (entry.getValue() != NO_RESPONSE) {
        // APPEND THE EXECUTOR
        if (executor.length() > 0)
          executor.append(',');
        executor.append(entry.getKey());

        // MERGE THE RESULTSET
        final ODistributedResponse response = (ODistributedResponse) entry.getValue();
        final Object payload = response.getPayload();
        mergedPayload = (HashSet<Object>) OMultiValue.add(mergedPayload, payload);
      }
    }

    merged.setExecutorNodeName(executor.toString());
    merged.setPayload(mergedPayload);

    return merged;
  }

  public int getExpectedSynchronousResponses() {
    return expectedSynchronousResponses;
  }

  public int getQuorum() {
    return quorum;
  }

  /**
   * Waits until the minimum responses are collected or timeout occurs. If "waitForLocalNode" wait also for local node.
   *
   * @return True if the received responses are major or equals then the expected synchronous responses, otherwise false
   * @throws InterruptedException
   */
  public boolean waitForSynchronousResponses() throws InterruptedException {
    final long beginTime = System.currentTimeMillis();

    synchronousResponsesLock.lock();
    try {

      long currentTimeout = synchTimeout;
      while (currentTimeout > 0 && ((waitForLocalNode && !receivedCurrentNode) || receivedResponses < expectedSynchronousResponses)) {
        // WAIT FOR THE RESPONSES
        synchronousResponsesArrived.await(currentTimeout, TimeUnit.MILLISECONDS);

        if ((!waitForLocalNode || receivedCurrentNode) && (receivedResponses >= expectedSynchronousResponses))
          // OK
          break;

        if (Thread.currentThread().isInterrupted()) {
          // INTERRUPTED
          ODistributedServerLog.warn(this, dManager.getLocalNodeName(), null, DIRECTION.NONE,
              "thread has been interrupted wait for request (%s)", request);
          Thread.currentThread().interrupt();
          break;
        }

        final long now = System.currentTimeMillis();
        final long elapsed = now - beginTime;
        currentTimeout = synchTimeout - elapsed;

        // CHECK IF ANY NODE ARE UNREACHABLE IN THE MEANWHILE
        int synchronizingNodes = 0;
        int missingActiveNodes = 0;

        synchronized (responseLock) {
          for (Iterator<Map.Entry<String, Object>> iter = responses.entrySet().iterator(); iter.hasNext();) {
            final Map.Entry<String, Object> curr = iter.next();

            if (curr.getValue() == NO_RESPONSE) {
              // ANALYZE THE NODE WITHOUT A RESPONSE
              final ODistributedServerManager.DB_STATUS dbStatus = dManager.getDatabaseStatus(curr.getKey(), getDatabaseName());
              switch (dbStatus) {
              case SYNCHRONIZING:
                synchronizingNodes++;
                missingActiveNodes++;
                break;
              case ONLINE:
                missingActiveNodes++;
                break;
              }
            }
          }
        }

        if (missingActiveNodes == 0) {
          // NO MORE ACTIVE NODES TO WAIT
          ODistributedServerLog.debug(this, dManager.getLocalNodeName(), null, DIRECTION.NONE,
              "no more active nodes to wait for request (%s): anticipate timeout (saved %d ms)", request, currentTimeout);
          break;
        }

        final long lastClusterChange = dManager.getLastClusterChangeOn();
        if (lastClusterChange > 0 && now - lastClusterChange < (synchTimeout + ADDITIONAL_TIMEOUT_CLUSTER_SHAPE)) {
          // CHANGED CLUSTER SHAPE DURING WAIT: ENLARGE TIMEOUT
          currentTimeout = synchTimeout;
          ODistributedServerLog.debug(this, dManager.getLocalNodeName(), null, DIRECTION.NONE,
              "cluster shape changed during request (%s): enlarge timeout +%dms, wait again for %dms", request, synchTimeout,
              currentTimeout);
          continue;
        } else if (synchronizingNodes > 0) {
          // SOME NODE IS SYNCHRONIZING: WAIT FOR THEM
          currentTimeout = synchTimeout;
          ODistributedServerLog.debug(this, dManager.getLocalNodeName(), null, DIRECTION.NONE,
              "%d nodes are in synchronization mode during request (%s): enlarge timeout +%dms, wait again for %dms",
              synchronizingNodes, request, synchTimeout, currentTimeout);
        }
      }

      return receivedResponses >= expectedSynchronousResponses;

    } finally {
      synchronousResponsesLock.unlock();

      Orient
          .instance()
          .getProfiler()
          .stopChrono("distributed.synchResponses", "Time to collect all the synchronous responses from distributed nodes",
              beginTime);
    }
  }

  public boolean isWaitForLocalNode() {
    return waitForLocalNode;
  }

  public boolean isReceivedCurrentNode() {
    return receivedCurrentNode;
  }

  public ODistributedResponse getFinalResponse() {
    synchronized (responseLock) {

      manageConflicts();

      if (receivedResponses == 0)
        throw new ODistributedException("No response received from any of nodes " + getExpectedNodes() + " for request " + request);

      // MANAGE THE RESULT BASED ON RESULT STRATEGY
      switch (request.getTask().getResultStrategy()) {
      case ANY:
        // DEFAULT: RETURN BEST ANSWER
        break;

      case UNION: {
        // COLLECT ALL THE RESPONSE IN A MAP OF <NODE, RESULT>
        final Map<String, Object> payloads = new HashMap<String, Object>();
        for (Map.Entry<String, Object> entry : responses.entrySet())
          if (entry.getValue() != NO_RESPONSE)
            payloads.put(entry.getKey(), ((ODistributedResponse) entry.getValue()).getPayload());

        final ODistributedResponse response = (ODistributedResponse) getReceivedResponses().iterator().next();
        response.setExecutorNodeName(responses.keySet().toString());
        response.setPayload(payloads);
        return response;
      }
      }

      final int bestResponsesGroupIndex = getBestResponsesGroup();
      final List<ODistributedResponse> bestResponsesGroup = responseGroups.get(bestResponsesGroupIndex);
      return bestResponsesGroup.get(0);
    }
  }

  public String getDatabaseName() {
    return request.getDatabaseName();
  }

  public void timeout() {
    synchronized (responseLock) {
      manageConflicts();
    }
  }

  /**
   * Returns the list of node names that didn't provide a response.
   */
  public List<String> getMissingNodes() {
    synchronized (responseLock) {
      final List<String> missingNodes = new ArrayList<String>();
      for (Map.Entry<String, Object> entry : responses.entrySet())
        if (entry.getValue() == NO_RESPONSE)
          missingNodes.add(entry.getKey());
      return missingNodes;
    }
  }

  public Set<String> getExpectedNodes() {
    synchronized (responseLock) {
      return new HashSet<String>(responses.keySet());
    }
  }

  /**
   * Returns the list of node names that provided a response.
   */
  public List<String> getRespondingNodes() {
    final List<String> respondedNodes = new ArrayList<String>();
    synchronized (responseLock) {
      for (Map.Entry<String, Object> entry : responses.entrySet())
        if (entry.getValue() != NO_RESPONSE)
          respondedNodes.add(entry.getKey());
    }
    return respondedNodes;
  }

  /**
   * Returns all the responses in conflict.
   *
   * @return
   */
  protected List<ODistributedResponse> getConflictResponses() {
    final List<ODistributedResponse> servers = new ArrayList<ODistributedResponse>();
    int bestGroupSoFar = getBestResponsesGroup();
    for (int i = 0; i < responseGroups.size(); ++i) {
      if (i != bestGroupSoFar) {
        for (ODistributedResponse r : responseGroups.get(i))
          servers.add(r);
      }
    }
    return servers;
  }

  protected int getExpectedResponses() {
    return responses.size();
  }

  protected int getMissingResponses() {
    return getExpectedResponses() - receivedResponses;
  }

  protected int getReceivedResponsesCount() {
    return receivedResponses;
  }

  protected long getTotalTimeout() {
    return totalTimeout;
  }

  /**
   * Returns the biggest response group.
   *
   * @return
   */
  protected int getBestResponsesGroup() {
    int maxCoherentResponses = 0;
    int bestGroupSoFar = 0;
    for (int i = 0; i < responseGroups.size(); ++i) {
      final int currentGroupSize = responseGroups.get(i).size();
      if (currentGroupSize > maxCoherentResponses) {
        maxCoherentResponses = currentGroupSize;
        bestGroupSoFar = i;
      }
    }
    return bestGroupSoFar;
  }

  protected boolean isMinimumQuorumReached(final boolean iCheckAvailableNodes) {
    if (isWaitForLocalNode() && !isReceivedCurrentNode()) {
      ODistributedServerLog.warn(this, dManager.getLocalNodeName(), dManager.getLocalNodeName(), DIRECTION.IN,
          "no response received from local node about request %s", request);
      return false;
    }

    if (quorum == 0)
      return true;

    if (!groupResponsesByResult)
      return receivedResponses >= quorum;

    for (List<ODistributedResponse> group : responseGroups)
      if (group.size() + discardedResponses >= quorum)
        return true;

    if (receivedResponses < quorum && iCheckAvailableNodes) {
      final ODistributedConfiguration dbConfig = dManager.getDatabaseConfiguration(getDatabaseName());
      if (!dbConfig.getFailureAvailableNodesLessQuorum("*")) {
        // CHECK IF ANY NODE IS OFFLINE
        int availableNodes = 0;
        for (Map.Entry<String, Object> r : responses.entrySet()) {
          if (dManager.isNodeAvailable(r.getKey(), getDatabaseName()))
            availableNodes++;
        }

        if (availableNodes < quorum) {
          ODistributedServerLog.warn(this, dManager.getLocalNodeName(), null, DIRECTION.NONE,
              "overridden quorum (%d) for request (%s) because available nodes (%d) are less than quorum, received responses: %s",
              quorum, request, availableNodes, responses);
          return true;
        }
      }
    }

    return false;
  }

  /**
   * Returns the received response objects.
   */
  protected List<ODistributedResponse> getReceivedResponses() {
    final List<ODistributedResponse> parsed = new ArrayList<ODistributedResponse>();
    for (Object r : responses.values())
      if (r != NO_RESPONSE)
        parsed.add((ODistributedResponse) r);
    return parsed;
  }

  protected void manageConflicts() {
    if (!groupResponsesByResult || request.getTask().getQuorumType() == OCommandDistributedReplicateRequest.QUORUM_TYPE.NONE)
      // NO QUORUM
      return;

    if (dManager.getNodeStatus() != ODistributedServerManager.NODE_STATUS.ONLINE)
      // CURRENT NODE OFFLINE: JUST RETURN
      return;

    final int bestResponsesGroupIndex = getBestResponsesGroup();
    final List<ODistributedResponse> bestResponsesGroup = responseGroups.get(bestResponsesGroupIndex);

    final int maxCoherentResponses = bestResponsesGroup.size();
    final int conflicts = getExpectedResponses() - (maxCoherentResponses + discardedResponses);

    if (isMinimumQuorumReached(true)) {
      // QUORUM SATISFIED

      if (responseGroups.size() == 1)
        // NO CONFLICT
        return;

      if (checkNoWinnerCase(bestResponsesGroup))
        return;

      fixNodesInConflict(bestResponsesGroup, conflicts);

    } else {
      // QUORUM HASN'T BEEN REACHED
      ODistributedServerLog
          .warn(
              this,
              dManager.getLocalNodeName(),
              null,
              DIRECTION.NONE,
              "detected %d node(s) in timeout or in conflict and quorum (%d) has not been reached, rolling back changes for request (%s)",
              conflicts, quorum, request);

      final StringBuilder msg = new StringBuilder(256);
      msg.append("Quorum " + getQuorum() + " not reached for request (" + request + "). Elapsed="
          + (System.currentTimeMillis() - sentOn) + "ms");
      final List<ODistributedResponse> res = getConflictResponses();
      if (res.isEmpty())
        msg.append(" No server in conflict. ");
      else {
        msg.append(" Servers in timeout/conflict are:");
        for (ODistributedResponse r : res) {
          msg.append("\n - ");
          msg.append(r.getExecutorNodeName());
          msg.append(": ");
          msg.append(r.getPayload());
        }
        msg.append("\n");
      }

      msg.append("Received: ");
      msg.append(responses);

      ODistributedServerLog.warn(this, dManager.getLocalNodeName(), null, DIRECTION.NONE, msg.toString());

      undoRequest();

      throw new ODistributedException(msg.toString());
    }
  }

  protected void undoRequest() {
    for (ODistributedResponse r : getReceivedResponses()) {
      ODistributedServerLog.warn(this, dManager.getLocalNodeName(), null, DIRECTION.NONE,
          "sending undo message for request (%s) to server %s", request, r.getExecutorNodeName());

      final OAbstractRemoteTask task = request.getTask();
      if (task instanceof OAbstractReplicatedTask) {
        final OAbstractRemoteTask undoTask = ((OAbstractReplicatedTask) task).getUndoTask(request, r.getPayload());

        if (undoTask != null)
          dManager.sendRequest(request.getDatabaseName(), null, Collections.singleton(r.getExecutorNodeName()), undoTask,
              ODistributedRequest.EXECUTION_MODE.NO_RESPONSE);
      }
    }
  }

  protected void fixNodesInConflict(final List<ODistributedResponse> bestResponsesGroup, final int conflicts) {
    // NO FIFTY/FIFTY CASE: FIX THE CONFLICTED NODES BY OVERWRITING THE RECORD WITH THE WINNER'S RESULT
    ODistributedServerLog.warn(this, dManager.getLocalNodeName(), null, DIRECTION.NONE,
        "detected %d conflicts, but the quorum (%d) has been reached. Fixing remote records. Request (%s)", conflicts, quorum,
        request);

    final ODistributedResponse goodResponse = bestResponsesGroup.get(0);

    for (List<ODistributedResponse> responseGroup : responseGroups) {
      if (responseGroup != bestResponsesGroup) {
        // CONFLICT GROUP: FIX THEM ONE BY ONE
        for (ODistributedResponse r : responseGroup) {
          ODistributedServerLog.warn(this, dManager.getLocalNodeName(), null, DIRECTION.NONE,
              "fixing response (%s) for request (%s) in server %s to be: %s", r, request, r.getExecutorNodeName(), goodResponse);

          final OAbstractRemoteTask fixTask = ((OAbstractReplicatedTask) request.getTask()).getFixTask(request, request.getTask(),
              r.getPayload(), goodResponse.getPayload());

          if (fixTask != null)
            dManager.sendRequest(request.getDatabaseName(), null, Collections.singleton(r.getExecutorNodeName()), fixTask,
                ODistributedRequest.EXECUTION_MODE.NO_RESPONSE);
        }
      }
    }
  }

  protected boolean checkNoWinnerCase(final List<ODistributedResponse> bestResponsesGroup) {
    // CHECK IF THERE ARE 2 PARTITIONS EQUAL IN SIZE
    final int maxCoherentResponses = bestResponsesGroup.size();

    if (maxCoherentResponses < quorum)
      return false;

    for (List<ODistributedResponse> responseGroup : responseGroups) {
      if (responseGroup != bestResponsesGroup && responseGroup.size() == maxCoherentResponses) {
        final List<String> a = new ArrayList<String>();
        Object aResponse = null;
        for (ODistributedResponse r : bestResponsesGroup) {
          a.add(r.getExecutorNodeName());
          aResponse = r.getPayload();
        }

        final List<String> b = new ArrayList<String>();
        Object bResponse = null;
        for (ODistributedResponse r : responseGroup) {
          b.add(r.getExecutorNodeName());
          bResponse = r.getPayload();
        }

        final StringBuilder details = new StringBuilder();
        details.append(" A=").append(aResponse);
        details.append(", B=").append(bResponse);

        ODistributedServerLog
            .error(
                this,
                dManager.getLocalNodeName(),
                null,
                DIRECTION.NONE,
                "detected possible split brain network where 2 groups of servers A%s and B%s have different contents. Cannot decide who is the winner even if the quorum (%d) has been reached. Request (%s) responses:%s",
                a, b, quorum, request, details);

        // DON'T FIX RECORDS BECAUSE THERE ISN'T A CLEAR WINNER
        return true;
      }
    }
    return false;
  }
}


text:
#include "camera.h"

namespace framework
{

Camera::Camera()
{
}

Camera::~Camera()
{
}

void Camera::init( int width, int height )
{
	m_camera.SetPerspective(65.0f, (float)width/(float)height, 0.1f, 1000.0f);
	m_orientation.ident();
	m_position = vector3(0, 0, 0);
}

const matrix44& Camera::getView()
{
	m_view.set_translation(m_position);
	vector3 dir = vector3(0, 0, 1);
	dir = m_orientation.rotate(dir);
	m_view.lookatRh(m_position + dir, vector3(0, 1, 0));
	m_view.invert_simple();

	return m_view;
}

void Camera::updateResolution( int width, int height )
{
	m_camera.SetAspectRatio((float)width/(float)height);
}

const matrix44& Camera::getProjection()
{
	return m_camera.GetProjection();
}

}

redpajama_set_name: RedPajamaGithub


text:
**Version: 0.0.1**
[demo](http://kingmax521.github.io/jQuery.circleProgressBar)
<br>

已经有很多强大的环形进度条插件了,比如progressbar.js, Knob等等,但是canvas的毛刺问题导致小的
图形很丑。而支持SVG的插件又不兼容IE8,毕竟IE8还有很大的市场占有。
jQuery.circleProgressBar.js基于Raphael,支持SVG和VML,所以可以在IE8上也有完美的图形。
有了这个插件,就不用催设计师的稿子了.....

Practical progress bars with animated SVG(VML) paths.
This plugin is based on Rapael.js and supports all major browsers including **IE8+**.
#### Installing options:

```javascript
$('.percent').percentageLoader({
    //percentage value container
    valElement: 'p',
    //ring width
    strokeWidth: 20,
    //background ring color
    bgColor: '#d9d9d9',
    //ring color
    ringColor: '#d53f3f',
    //text color
    textColor: '#9a9a9a',
    fontSize: '12px',
    fontWeight: 'normal'
});
```

**Example**

```html
<div class="percent">
    <p>8%</p>
</div>
```

```javascript
$('.percent').percentageLoader({
    strokeWidth: 8,
});
```

# Contributing

# Thanks
This is my first plugin, so...Thanks a lot for your help!


text:
package com.intellij.psi.search.scope.packageSet;

import com.intellij.ProjectTopics;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.ModuleListener;
import com.intellij.openapi.project.Project;
import com.intellij.util.Function;
import com.intellij.util.messages.MessageBus;
import org.jetbrains.annotations.NotNull;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class UpdatingScopeOnProjectStructureChangeListener implements ProjectComponent, ModuleListener {
  public UpdatingScopeOnProjectStructureChangeListener(MessageBus messageBus) {
    messageBus.connect().subscribe(ProjectTopics.MODULES, this);
  }

  @Override
  public void modulesRenamed(@NotNull Project project,
                             @NotNull List<Module> modules,
                             @NotNull Function<Module, String> oldNameProvider) {
    Map<String, String> moduleMap = modules.stream().collect(Collectors.toMap(oldNameProvider::fun, Module::getName));
    for (NamedScopesHolder holder : NamedScopesHolder.getAllNamedScopeHolders(project)) {
      NamedScope[] oldScopes = holder.getEditableScopes();
      NamedScope[] newScopes = new NamedScope[oldScopes.length];
      for (int i = 0; i < oldScopes.length; i++) {
        newScopes[i] = renameModulesIn(oldScopes[i], moduleMap);
      }
      if (!Arrays.equals(newScopes, oldScopes)) {
        holder.setScopes(newScopes);
      }
    }
  }

  private static NamedScope renameModulesIn(NamedScope scope, Map<String, String> nameMapping) {
    PackageSet oldSet = scope.getValue();
    if (oldSet == null) return scope;

    PackageSet newSet = oldSet.map(packageSet -> {
      if (packageSet instanceof PatternBasedPackageSet) {
        String modulePattern = ((PatternBasedPackageSet)packageSet).getModulePattern();
        String newName = nameMapping.get(modulePattern);
        if (newName != null) {
          return ((PatternBasedPackageSet)packageSet).updateModulePattern(modulePattern, newName);
        }
      }
      return packageSet;
    });
    if (newSet != oldSet) {
      return new NamedScope(scope.getName(), newSet);
    }
    return scope;
  }
}


text:
#define C_KINO_SCOREPOSTING
#define C_KINO_SCOREPOSTINGSCORER
#define C_KINO_RAWPOSTING
#define C_KINO_TOKEN
#include "KinoSearch/Util/ToolSet.h"

#include "KinoSearch/Index/Posting/ScorePosting.h"
#include "KinoSearch/Analysis/Token.h"
#include "KinoSearch/Analysis/Inversion.h"
#include "KinoSearch/Index/Posting/RawPosting.h"
#include "KinoSearch/Index/PostingList.h"
#include "KinoSearch/Index/PostingPool.h"
#include "KinoSearch/Index/Similarity.h"
#include "KinoSearch/Plan/FieldType.h"
#include "KinoSearch/Search/Compiler.h"
#include "KinoSearch/Search/Matcher.h"
#include "KinoSearch/Store/InStream.h"
#include "KinoSearch/Util/MemoryPool.h"

#define FIELD_BOOST_LEN  1
#define FREQ_MAX_LEN     C32_MAX_BYTES
#define MAX_RAW_POSTING_LEN(_text_len, _freq) \
        (              sizeof(RawPosting) \
                     + _text_len                /* term text content */ \
                     + FIELD_BOOST_LEN          /* field boost byte */ \
                     + FREQ_MAX_LEN             /* freq c32 */ \
                     + (C32_MAX_BYTES * _freq)  /* positions deltas */ \
        )

ScorePosting*
ScorePost_new(Similarity *sim)
{
    ScorePosting *self = (ScorePosting*)VTable_Make_Obj(SCOREPOSTING);
    return ScorePost_init(self, sim);
}

ScorePosting*
ScorePost_init(ScorePosting *self, Similarity *sim)
{
    MatchPost_init((MatchPosting*)self, sim);
    self->norm_decoder = Sim_Get_Norm_Decoder(sim);
    self->freq         = 0;
    self->weight       = 0.0;
    self->prox         = NULL;
    self->prox_cap     = 0;
    return self;
}

void
ScorePost_destroy(ScorePosting *self)
{
    FREEMEM(self->prox);
    SUPER_DESTROY(self, SCOREPOSTING);
}

uint32_t*
ScorePost_get_prox(ScorePosting *self) { return self->prox; }

void
ScorePost_add_inversion_to_pool(ScorePosting *self, PostingPool *post_pool,
                                Inversion *inversion, FieldType *type,
                                int32_t doc_id, float doc_boost,
                                float length_norm)
{
    MemoryPool     *mem_pool = PostPool_Get_Mem_Pool(post_pool);
    Similarity     *sim = self->sim;
    float           field_boost = doc_boost * FType_Get_Boost(type) * length_norm;
    const uint8_t   field_boost_byte  = Sim_Encode_Norm(sim, field_boost);
    Token         **tokens;
    uint32_t        freq;

    Inversion_Reset(inversion);
    while ( (tokens = Inversion_Next_Cluster(inversion, &freq)) != NULL ) {
        Token   *token          = *tokens;
        uint32_t raw_post_bytes = MAX_RAW_POSTING_LEN(token->len, freq);
        RawPosting *raw_posting = RawPost_new(
            MemPool_Grab(mem_pool, raw_post_bytes), doc_id, freq,
            token->text, token->len
        );
        char *const start  = raw_posting->blob + token->len;
        char *dest         = start;
        uint32_t last_prox = 0;
        uint32_t i;

        // Field_boost.
        *((uint8_t*)dest) = field_boost_byte;
        dest++;

        // Positions.
        for (i = 0; i < freq; i++) {
            Token *const t = tokens[i];
            const uint32_t prox_delta = t->pos - last_prox;
            NumUtil_encode_c32(prox_delta, &dest);
            last_prox = t->pos;
        }

        // Resize raw posting memory allocation.
        raw_posting->aux_len = dest - start;
        raw_post_bytes = dest - (char*)raw_posting;
        MemPool_Resize(mem_pool, raw_posting, raw_post_bytes);
        PostPool_Feed(post_pool, &raw_posting);
    }
}

void
ScorePost_reset(ScorePosting *self)
{
    self->doc_id   = 0;
    self->freq     = 0;
    self->weight   = 0.0;
}

void
ScorePost_read_record(ScorePosting *self, InStream *instream)
{
    uint32_t  num_prox;
    uint32_t  position = 0;
    uint32_t *positions;
    const size_t max_start_bytes = (C32_MAX_BYTES * 2) + 1;
    char *buf = InStream_Buf(instream, max_start_bytes);
    const uint32_t doc_code = NumUtil_decode_c32(&buf);
    const uint32_t doc_delta = doc_code >> 1;

    // Apply delta doc and retrieve freq.
    self->doc_id   += doc_delta;
    if (doc_code & 1)
        self->freq = 1;
    else
        self->freq = NumUtil_decode_c32(&buf);

    // Decode boost/norm byte.
    self->weight = self->norm_decoder[ *(uint8_t*)buf ];
    buf++;

    // Read positions.
    num_prox = self->freq;
    if (num_prox > self->prox_cap) {
        self->prox = (uint32_t*)REALLOCATE(self->prox,
            num_prox * sizeof(uint32_t));
        self->prox_cap = num_prox;
    }
    positions = self->prox;

    InStream_Advance_Buf(instream, buf);
    buf = InStream_Buf(instream, num_prox * C32_MAX_BYTES);
    while (num_prox--) {
        position += NumUtil_decode_c32(&buf);
        *positions++ = position;
    }

    InStream_Advance_Buf(instream, buf);
}

RawPosting*
ScorePost_read_raw(ScorePosting *self, InStream *instream,
                   int32_t last_doc_id, CharBuf *term_text,
                   MemoryPool *mem_pool)
{
    char *const    text_buf       = (char*)CB_Get_Ptr8(term_text);
    const size_t   text_size      = CB_Get_Size(term_text);
    const uint32_t doc_code       = InStream_Read_C32(instream);
    const uint32_t delta_doc      = doc_code >> 1;
    const int32_t  doc_id         = last_doc_id + delta_doc;
    const uint32_t freq           = (doc_code & 1)
                                  ? 1
                                  : InStream_Read_C32(instream);
    size_t raw_post_bytes         = MAX_RAW_POSTING_LEN(text_size, freq);
    void *const allocation        = MemPool_Grab(mem_pool, raw_post_bytes);
    RawPosting *const raw_posting = RawPost_new(allocation, doc_id, freq,
        text_buf, text_size);
    uint32_t num_prox = freq;
    char *const start = raw_posting->blob + text_size;
    char *dest        = start;
    UNUSED_VAR(self);

    // Field_boost.
    *((uint8_t*)dest) = InStream_Read_U8(instream);
    dest++;

    // Read positions.
    while (num_prox--) {
        dest += InStream_Read_Raw_C64(instream, dest);
    }

    // Resize raw posting memory allocation.
    raw_posting->aux_len = dest - start;
    raw_post_bytes       = dest - (char*)raw_posting;
    MemPool_Resize(mem_pool, raw_posting, raw_post_bytes);

    return raw_posting;
}

ScorePostingScorer*
ScorePost_make_matcher(ScorePosting *self, Similarity *sim,
                       PostingList *plist, Compiler *compiler,
                       bool_t need_score)
{
    ScorePostingScorer *matcher
        = (ScorePostingScorer*)VTable_Make_Obj(SCOREPOSTINGSCORER);
    UNUSED_VAR(self);
    UNUSED_VAR(need_score);
    return ScorePostScorer_init(matcher, sim, plist, compiler);
}

ScorePostingScorer*
ScorePostScorer_init(ScorePostingScorer *self, Similarity *sim,
                     PostingList *plist, Compiler *compiler)
{
    uint32_t i;

    // Init.
    TermScorer_init((TermScorer*)self, sim, plist, compiler);

    // Fill score cache.
    self->score_cache = (float*)MALLOCATE(TERMSCORER_SCORE_CACHE_SIZE * sizeof(float));
    for (i = 0; i < TERMSCORER_SCORE_CACHE_SIZE; i++) {
        self->score_cache[i] = Sim_TF(sim, (float)i) * self->weight;
    }

    return self;
}

float
ScorePostScorer_score(ScorePostingScorer* self)
{
    ScorePosting *const posting = (ScorePosting*)self->posting;
    const uint32_t freq = posting->freq;

    // Calculate initial score based on frequency of term.
    float score = (freq < TERMSCORER_SCORE_CACHE_SIZE)
        ? self->score_cache[freq] // cache hit
        : Sim_TF(self->sim, (float)freq) * self->weight;

    // Factor in field-length normalization and doc/field/prox boost.
    score *= posting->weight;

    return score;
}

void
ScorePostScorer_destroy(ScorePostingScorer *self)
{
    FREEMEM(self->score_cache);
    SUPER_DESTROY(self, SCOREPOSTINGSCORER);
}

/* Copyright 2007-2011 Marvin Humphrey
 *
 * This program is free software; you can redistribute it and/or modify
 * under the same terms as Perl itself.
 */


text:
<?php

/**
 * CamelCase
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @package    ##PACKAGE##
 * @subpackage ##SUBPACKAGE##
 * @author     ##NAME## <##EMAIL##>
 * @version    SVN: $Id: CamelCase.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class CamelCase extends BaseCamelCase
{

}


text:
<!doctype html>
 <html lang='en'>
 <head>
 	<meta charset='utf-8'>
 	<title>Google Fonts with regular pdfmake</title>
 	<script src='pdfmake.min.js'></script>
 	<script src='../build/script/ofl/junge.js'></script><!-- the font data -->
 	<script src='../build/script/ofl/junge.map.js'></script><!-- the font-style mapping -->
 </head>
 <body>
    <input type="button" onclick="openPdf()" value="Open PDF"></input>
     <script type="">
        /* Do not forget to set the defaultStyle to the font name you included above */
        function openPdf() {
            var docDefinition = {
                content: 'Lorem ipsum dolor sit amet...',
                defaultStyle: {
            		font: Object.keys(pdfMake.fonts)[0]
            	}
            };
            pdfMake.createPdf(docDefinition).open();
        }
     </script>
 </body>
</html>


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DominionCardTracker.Models.Tables;
using System.Data.SqlClient;
using Dapper;

namespace DominionCardTracker.DataLayer.Repositories
{
    public class CardSetRepository
    {
        public List<CardSet> SelectAll()
        {
            using (var connection = new SqlConnection(ConfigurationSettings.GetConnectionString()))
            {
                return connection.Query<CardSet>("CardSetSelectAll", commandType: CommandType.StoredProcedure).ToList();
            }
        }

        public void Insert(CardSet cardSet)
        {
            using (var connection = new SqlConnection(ConfigurationSettings.GetConnectionString()))
            {
                DynamicParameters p = new DynamicParameters();
                p.Add("@CardSetName", cardSet.CardSetName);

                connection.Execute("CardSetInsert", p, commandType: CommandType.StoredProcedure);
            }
        }
    }
}


text:
package noop.graph;

import noop.model.Clazz;
import noop.model.Library;
import noop.model.Method;
import noop.model.Project;
import org.junit.Test;

import java.util.UUID;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

/**
 * @author alexeagle@google.com (Alex Eagle)
 */
public class VertexCreatingVisitorTest {
  @Test
  public void shouldCreateVerticesForEveryElementUnderAProject() {
    Project p = new Project("example", "p", "MIT license");
    UUID uid = UUID.randomUUID();
    Library l = new Library(uid, "l");
    Clazz c = new Clazz("c");
    Method m = new Method("m");
    Library l2 = new Library(UUID.randomUUID(), "l2");

    p.addLibrary(l);
    p.addLibrary(l2);
    l.addClazz(c);
    c.addBlock(m);

    p.accept(new VertexCreatingVisitor());

    assertEquals(l, l.getElements().get(0));
    assertEquals(c, l.getElements().get(1));
    assertEquals(m, l.getElements().get(2));
    assertEquals(new Vertex(uid, 0), l.vertex);
    assertEquals(new Vertex(uid, 1), c.vertex);
    assertEquals(new Vertex(uid, 2), m.vertex);
    assertFalse(l2.vertex.libraryUid.equals(uid));
  }
}


text:
@interface MapViewController ()
@property (nonatomic) IBOutlet UIBarButtonItem* revealButtonItem;
@end

@implementation MapViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self customSetup];
}

- (void)customSetup
{
    SWRevealViewController *revealViewController = self.revealViewController;
    if ( revealViewController )
    {
        [self.revealButtonItem setTarget: self.revealViewController];
        [self.revealButtonItem setAction: @selector( revealToggle: )];
        [self.navigationController.navigationBar addGestureRecognizer: self.revealViewController.panGestureRecognizer];
    }
}

#pragma mark state preservation / restoration

- (void)encodeRestorableStateWithCoder:(NSCoder *)coder
{
    NSLog(@"%s", __PRETTY_FUNCTION__);

    // Save what you need here

    [super encodeRestorableStateWithCoder:coder];
}

- (void)decodeRestorableStateWithCoder:(NSCoder *)coder
{
    NSLog(@"%s", __PRETTY_FUNCTION__);

    // Restore what you need here

    [super decodeRestorableStateWithCoder:coder];
}

- (void)applicationFinishedRestoringState
{
    NSLog(@"%s", __PRETTY_FUNCTION__);

    // Call whatever function you need to visually restore
    [self customSetup];
}

@end


text:
<?xml version="1.0"?>

<!DOCTYPE chapter SYSTEM "cruise_help.dtd">
<chapter title="Concurrent Modifications to Go's Configuration">

Go handles concurrent modifications to its configuration. Multiple modifications are merged and saved successfully. Modifications to the same area of configuration would result in a conflict.

    <note>Note: Configuration file is maintained in
        git
        version control system. Go leverages git's merge feature to merge changes from multiple users.
        As expected, concurrent changes to the same section by users would result in a conflict.
    </note>

In case of a successful merge, user would see a success message as below:

In case of a conflict, Go provides an interface with the latest version of config along with the changes made by the user. As an example, if the same job was re-named by two users
                concurrently, the changes from first user would be successfully saved while the second user would see a page similar to the one displayed in the image below.

User needs to re-apply their changes displayed on the left-hand pane, to the editable version on the right and save again.

If two users make similar changes to a pipeline using the 'Edit Pipeline' UI, the second user would see the error as displayed below.

User should backup the required changes from the page. Clicking on 'RELOAD' button, would discard user's changes and reload the page with latest version of the pipeline configuration.
                User should re-apply his/her changes from backup and save again.

</chapter>


text:
package de.tu_berlin.cit.intercloud.webapp.layout;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;

/**
 * Frame that is used as top header
 *
 * @author Alexander Stanik
 *
 */
@SuppressWarnings("serial")
public class TopFrame extends WebPage {

	public TopFrame() {
		add(new Label("applicationtitle", "Intercloud SLA Mediator Webapp"));
	}

}


text:
namespace component_updater {

// The extension id is: cmahhnpholdijhjokonmfdjbfmklppij
constexpr uint8_t kFlocComponentPublicKeySHA256[32] = {
    0x2c, 0x07, 0x7d, 0xf7, 0xeb, 0x38, 0x97, 0x9e, 0xae, 0xdc, 0x53,
    0x91, 0x5c, 0xab, 0xff, 0x89, 0xbc, 0xf0, 0xd9, 0x30, 0xd2, 0x2e,
    0x8f, 0x68, 0x3a, 0xf9, 0x21, 0x91, 0x9f, 0xc1, 0x84, 0xa1};

constexpr char kFlocComponentFetcherManifestName[] =
    "Federated Learning of Cohorts";

FlocComponentInstallerPolicy::FlocComponentInstallerPolicy(
    federated_learning::FlocSortingLshClustersService*
        floc_sorting_lsh_clusters_service)
    : floc_sorting_lsh_clusters_service_(floc_sorting_lsh_clusters_service) {}

FlocComponentInstallerPolicy::~FlocComponentInstallerPolicy() = default;

bool FlocComponentInstallerPolicy::SupportsGroupPolicyEnabledComponentUpdates()
    const {
  return true;
}

// Public data is delivered via this component, no need for encryption.
bool FlocComponentInstallerPolicy::RequiresNetworkEncryption() const {
  return false;
}

update_client::CrxInstaller::Result
FlocComponentInstallerPolicy::OnCustomInstall(
    const base::Value& manifest,
    const base::FilePath& install_dir) {
  return update_client::CrxInstaller::Result(0);  // Nothing custom here.
}

void FlocComponentInstallerPolicy::OnCustomUninstall() {}

void FlocComponentInstallerPolicy::ComponentReady(
    const base::Version& version,
    const base::FilePath& install_dir,
    base::Value manifest) {
  DCHECK(!install_dir.empty());

  floc_sorting_lsh_clusters_service_->OnSortingLshClustersFileReady(
      install_dir.Append(federated_learning::kSortingLshClustersFileName),
      version);
}

// Called during startup and installation before ComponentReady().
bool FlocComponentInstallerPolicy::VerifyInstallation(
    const base::Value& manifest,
    const base::FilePath& install_dir) const {
  if (!base::PathExists(install_dir))
    return false;

  absl::optional<int> floc_component_format =
      manifest.FindIntKey(federated_learning::kManifestFlocComponentFormatKey);
  if (!floc_component_format ||
      *floc_component_format !=
          federated_learning::kCurrentFlocComponentFormatVersion) {
    return false;
  }

  return true;
}

base::FilePath FlocComponentInstallerPolicy::GetRelativeInstallDir() const {
  return base::FilePath(federated_learning::kTopLevelDirectoryName);
}

void FlocComponentInstallerPolicy::GetHash(std::vector<uint8_t>* hash) const {
  hash->assign(std::begin(kFlocComponentPublicKeySHA256),
               std::end(kFlocComponentPublicKeySHA256));
}

std::string FlocComponentInstallerPolicy::GetName() const {
  return kFlocComponentFetcherManifestName;
}

update_client::InstallerAttributes
FlocComponentInstallerPolicy::GetInstallerAttributes() const {
  return update_client::InstallerAttributes();
}

void RegisterFlocComponent(
    ComponentUpdateService* cus,
    federated_learning::FlocSortingLshClustersService*
        floc_sorting_lsh_clusters_service) {
  auto installer = base::MakeRefCounted<ComponentInstaller>(
      std::make_unique<FlocComponentInstallerPolicy>(
          floc_sorting_lsh_clusters_service));
  installer->Register(cus, base::OnceClosure());
}

}  // namespace component_updater


text:
package com.pushtorefresh.storio.contentresolver.operation.put;

import android.support.annotation.NonNull;

import com.pushtorefresh.storio.contentresolver.StorIOContentResolver;

/**
 * Defines behavior of Put Operation (insert or update)
 *
 * @param <T> type of objects to put
 * @see {@link DefaultPutResolver} default implementation
 */
public abstract class PutResolver<T> {

    /**
     * Performs Put Operation of some {@link android.content.ContentValues} into {@link StorIOContentResolver}
     *
     * @param storIOContentResolver instance of {@link StorIOContentResolver}
     * @param object                non-null object of required type to put
     * @return non-null result of Put Operation
     */
    @NonNull
    public abstract PutResult performPut(@NonNull StorIOContentResolver storIOContentResolver, @NonNull T object);
}


text:
from flask import render_template, request, redirect, session, jsonify
from mongoengine import ValidationError

from flask_reveal import app
from social.apps.flask_app.utils import login_required
from social.apps.flask_app.models import User, UserSocialAuth
from models import Logic

def checkuser(username):
    '''Check the current user privileges'''
    try:
        qs = User.objects(username=username, id=session.get('user_id'))
        match = UserSocialAuth.objects(user__in=qs).first()
    except ValidationError:
        return False
    if not match:
        return False
    if match.provider == session.get('social_auth_last_login_backend'):
        return match
    else:
        return False

def comb(immutablemultidict):
    '''Construction dict'''
    query = {}
    for k, v in immutablemultidict.iteritems():
        query.update({k[5:-1]: v})
    return query

def get_gravatar(user):
    '''Get gravatar's Avatar'''
    import urllib
    import hashlib
    domain = 'http://' + request.url.split('/')[2] + '/'
    email = user[0].email
    if not email:
        email = 'ciici123@hotmail.com'
    default = "static/images/default-profile-picture.png"
    size = 140
    gravatar_url = "http://www.gravatar.com/avatar/" + \
        hashlib.md5(email.lower()).hexdigest() + "?"
    gravatar_url += urllib.urlencode({'d': default, 's': str(size)})
    return gravatar_url

@app.route('/')
def index():
    return render_template("index.html")

@app.route('/<string:username>/')
#@login_required
def home(username):
    if checkuser(username):
        decks = Logic.objects(username=username).order_by("+pubtime")
        if not decks:
            return render_template("home.html")
    else:
        decks = Logic.objects(
            username=username, published=True).order_by("+pubtime")
        if not decks:
            user = User.objects(username=username)
            if user:
                gravatar_url = get_gravatar(user)
                return render_template(
                    "noyet.html", username=username, img=gravatar_url,
                    msg='{} hasn"t published any decks yet :'.format(username))
            return render_template("404.html")
    return render_template("home.html", decks=decks, username=username)

@app.route('/<string:username>/<string:title>')
@login_required
def deck(username, title):
    if checkuser(username):
        deck = Logic.objects(username=username, title=title)
        if not deck:
            return render_template("home.html")
        other_deck = Logic.objects(username=username, title__ne=title)[:4]

    else:
        deck = Logic.objects(username=username, title=title, published=True)
        if not deck:
            user = User.objects(username=username)
            if len(user):
                gravatar_url = get_gravatar(user)
                return render_template(
                    "noyet.html", username=username, img=gravatar_url,
                    msg='{} hasn"t published any decks yet :'.format(username))
            return render_template("404.html")
        other_deck = Logic.objects(
            username=username, title__ne=title, published=True)[:4]
    Logic.objects(username=username, title=title).update_one(inc__views=1)
    deck = deck[0]
    return render_template("deck.html", username=username, data=deck, other=other_deck)

@app.route('/<string:username>/<string:title>/edit')
@login_required
def edit(username, title):
    user = User.objects(username=username)
    gravatar_url = get_gravatar(user)
    if not checkuser(username):
        return render_template(
            "noyet.html", username=username, img=gravatar_url,
            msg='You hasn"t operating authority yet :')
    qs = Logic.objects(username=username, title=title)
    if not qs:
        return render_template(
            "noyet.html", username=username, img=gravatar_url,
            msg='{You hasn"t published this deck!')
    return render_template("edit.html", data=qs[0], username=username)

@app.route('/api/decks/<deskname>', methods=['PUT', 'DELETE'])
@login_required
def deck_api(deskname):
    if request.method == 'PUT':
        ppt = request.form
        up = {}
        for k, v in comb(ppt).iteritems():
            if v == 'true':
                v = True
            elif v == 'false':
                v = False
            up['set__{}'.format(k)] = v
        Logic.objects(tid=deskname[:-5]).update(upsert=True, **up)
        return jsonify(message=1)
    else:
        Logic.objects(tid=deskname[:-5]).delete()
        return "", 200

@app.route('/<string:username>/new')
@login_required
def new(username):
    gid = Logic.objects.count() + 1
    uid = Logic.objects(username=username).count() + 1
    if checkuser(username):
        deskname = Logic.objects(username=username).order_by("+pubtime")
        new_desk = 'desk-' + str(uid)
        Logic(title=new_desk, tid=gid, username=username).save()
    else:
        user = User.objects(username=username)
        if len(user):
            gravatar_url = get_gravatar(user)
            return render_template(
                "noyet.html", username=username, img=gravatar_url,
                msg='You do not has edit {} authority yet :('.format(username))
    return redirect('/{}/{}/edit'.format(username, new_desk))

@app.route('/login_redir')
def login_redir():
    openid_username = request.args.get('openid_username', None)
    claimid = request.args.get('claimid', '/')
    if not openid_username:
        return redirect(claimid)

@app.route('/tos')
def tos():
    return render_template('tos.html')


text:
#import "OTCResolvedObject.h"

/** An financial symbols starting with the dollar sign extracted from the Tweet text.
    Similar to hashtags, an entity comes with the following attributes:

  |   Property Key   |                      Description                             |
  | :--------------: | :----------------------------------------------------------: |
  |       text       |                    The symbol text                           |
  |     indices      |      The character positions the URL was extracted from      |
  */
@interface OTCFinancialSymbol : OTCResolvedObject

#pragma mark Initialization
+ ( instancetype ) financialSymbolWithJSON: ( NSDictionary* )_JSONDict;

@end

/*=============================================================================================┐
|                                                                                |
|                                   The BSD 3-Clause License                                   |
|                                                                                |
|                            Copyright (c) 2015, Tong Guo (NSTongG)                            |
|                                     All rights reserved.                                     |
|                                                                                |
|     Redistribution and use in source and binary forms, with or without modification, are     |
|                  permitted provided that the following conditions are met:                   |
|                                                                                |
|    1. Redistributions of source code must retain the above copyright notice, this list of    |
|                           conditions and the following disclaimer.                           |
|                                                                                |
|  2. Redistributions in binary form must reproduce the above copyright notice, this list of   |
|     conditions and the following disclaimer in the documentation and/or other materials      |
|                               provided with the distribution.                                |
|                                                                                |
|  3. Neither the name of the copyright holder nor the names of its contributors may be used   |
|   to endorse or promote products derived from this software without specific prior written   |
|                                         permission.                                          |
|                                                                                |
|     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY      |
|   EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF    |
|  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE  |
|  COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,   |
|      EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF      |
|    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)    |
|   HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR   |
|      TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS      |
|                 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                 |
|                                                                                |
└=============================================================================================*/


text:
package io.gravitee.rest.api.management.rest.resource;

import static java.lang.String.format;

import io.gravitee.common.data.domain.Page;
import io.gravitee.common.http.MediaType;
import io.gravitee.rest.api.management.rest.model.Pageable;
import io.gravitee.rest.api.management.rest.model.PagedResult;
import io.gravitee.rest.api.management.rest.model.Subscription;
import io.gravitee.rest.api.management.rest.resource.param.ListStringParam;
import io.gravitee.rest.api.management.rest.resource.param.ListSubscriptionStatusParam;
import io.gravitee.rest.api.management.rest.security.Permission;
import io.gravitee.rest.api.management.rest.security.Permissions;
import io.gravitee.rest.api.model.*;
import io.gravitee.rest.api.model.parameters.Key;
import io.gravitee.rest.api.model.parameters.ParameterReferenceType;
import io.gravitee.rest.api.model.permissions.RolePermission;
import io.gravitee.rest.api.model.permissions.RolePermissionAction;
import io.gravitee.rest.api.model.subscription.SubscriptionQuery;
import io.gravitee.rest.api.service.*;
import io.gravitee.rest.api.validator.CustomApiKey;
import io.swagger.annotations.*;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.*;
import javax.ws.rs.container.ResourceContext;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import org.apache.commons.lang3.StringUtils;

/**
 * @author David BRASSELY (david.brassely at graviteesource.com)
 * @author Nicolas GERAUD (nicolas.geraud at graviteesource.com)
 * @author GraviteeSource Team
 */
@Api(tags = { "API Subscriptions" })
public class ApiSubscriptionsResource extends AbstractResource {

    @Inject
    private SubscriptionService subscriptionService;

    @Inject
    private ApplicationService applicationService;

    @Inject
    private PlanService planService;

    @Context
    private ResourceContext resourceContext;

    @Inject
    private UserService userService;

    @Inject
    private ApiKeyService apiKeyService;

    @Inject
    private ParameterService parameterService;

    @SuppressWarnings("UnresolvedRestParam")
    @PathParam("api")
    @ApiParam(name = "api", hidden = true)
    private String api;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "List subscriptions for the API", notes = "User must have the READ_SUBSCRIPTION permission to use this service")
    @ApiResponses(
        {
            @ApiResponse(code = 200, message = "Paged result of API's subscriptions", response = PagedResult.class),
            @ApiResponse(code = 500, message = "Internal server error"),
        }
    )
    @Permissions({ @Permission(value = RolePermission.API_SUBSCRIPTION, acls = RolePermissionAction.READ) })
    public PagedResult<SubscriptionEntity> getApiSubscriptions(
        @BeanParam SubscriptionParam subscriptionParam,
        @Valid @BeanParam Pageable pageable,
        @ApiParam(allowableValues = "keys", value = "Expansion of data to return in subscriptions") @QueryParam(
            "expand"
        ) List<String> expand
    ) {
        // Transform query parameters to a subscription query
        SubscriptionQuery subscriptionQuery = subscriptionParam.toQuery();
        subscriptionQuery.setApi(api);

        Page<SubscriptionEntity> subscriptions = subscriptionService.search(subscriptionQuery, pageable.toPageable());

        if (expand != null && !expand.isEmpty()) {
            for (String e : expand) {
                switch (e) {
                    case "keys":
                        subscriptions
                            .getContent()
                            .forEach(
                                subscriptionEntity -> {
                                    final List<String> keys = apiKeyService
                                        .findBySubscription(subscriptionEntity.getId())
                                        .stream()
                                        .filter(apiKeyEntity -> !apiKeyEntity.isExpired() && !apiKeyEntity.isRevoked())
                                        .map(ApiKeyEntity::getKey)
                                        .collect(Collectors.toList());
                                    subscriptionEntity.setKeys(keys);
                                }
                            );
                        break;
                    default:
                        break;
                }
            }
        }

        PagedResult<SubscriptionEntity> result = new PagedResult<>(subscriptions, pageable.getSize());
        result.setMetadata(subscriptionService.getMetadata(subscriptions.getContent()).getMetadata());
        return result;
    }

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Subscribe to a plan", notes = "User must have the MANAGE_SUBSCRIPTIONS permission to use this service")
    @ApiResponses(
        {
            @ApiResponse(code = 201, message = "Subscription successfully created", response = Subscription.class),
            @ApiResponse(code = 400, message = "Bad custom API Key format or custom API Key definition disabled"),
            @ApiResponse(code = 500, message = "Internal server error"),
        }
    )
    @Permissions({ @Permission(value = RolePermission.API_SUBSCRIPTION, acls = RolePermissionAction.CREATE) })
    public Response createSubscriptionToApi(
        @ApiParam(name = "application", required = true) @NotNull @QueryParam("application") String application,
        @ApiParam(name = "plan", required = true) @NotNull @QueryParam("plan") String plan,
        @ApiParam(name = "customApiKey") @CustomApiKey @QueryParam("customApiKey") String customApiKey
    ) {
        if (
            StringUtils.isNotEmpty(customApiKey) &&
            !parameterService.findAsBoolean(Key.PLAN_SECURITY_APIKEY_CUSTOM_ALLOWED, ParameterReferenceType.ENVIRONMENT)
        ) {
            return Response.status(Response.Status.BAD_REQUEST).entity("You are not allowed to provide a custom API Key").build();
        }

        NewSubscriptionEntity newSubscriptionEntity = new NewSubscriptionEntity(plan, application);

        // Create subscription
        SubscriptionEntity subscription = subscriptionService.create(newSubscriptionEntity, customApiKey);

        if (subscription.getStatus() == SubscriptionStatus.PENDING) {
            ProcessSubscriptionEntity process = new ProcessSubscriptionEntity();
            process.setId(subscription.getId());
            process.setAccepted(true);
            process.setStartingAt(new Date());
            process.setCustomApiKey(customApiKey);
            subscription = subscriptionService.process(process, getAuthenticatedUser());
        }

        return Response
            .created(
                this.getRequestUriBuilder()
                    .path(subscription.getId())
                    .replaceQueryParam("application", null)
                    .replaceQueryParam("plan", null)
                    .build()
            )
            .entity(convert(subscription))
            .build();
    }

    @GET
    @Path("export")
    @Produces(MediaType.TEXT_PLAIN)
    @ApiOperation(value = "Export API logs as CSV")
    @ApiResponses({ @ApiResponse(code = 200, message = "API logs as CSV"), @ApiResponse(code = 500, message = "Internal server error") })
    @Permissions({ @Permission(value = RolePermission.API_LOG, acls = RolePermissionAction.READ) })
    public Response exportApiSubscriptionsLogsAsCSV(@BeanParam SubscriptionParam subscriptionParam, @Valid @BeanParam Pageable pageable) {
        final PagedResult<SubscriptionEntity> subscriptions = getApiSubscriptions(subscriptionParam, pageable, null);
        return Response
            .ok(subscriptionService.exportAsCsv(subscriptions.getData(), subscriptions.getMetadata()))
            .header(HttpHeaders.CONTENT_DISPOSITION, format("attachment;filename=subscriptions-%s-%s.csv", api, System.currentTimeMillis()))
            .build();
    }

    @Path("{subscription}")
    public ApiSubscriptionResource getApiSubscriptionResource() {
        return resourceContext.getResource(ApiSubscriptionResource.class);
    }

    private Subscription convert(SubscriptionEntity subscriptionEntity) {
        Subscription subscription = new Subscription();

        subscription.setId(subscriptionEntity.getId());
        subscription.setCreatedAt(subscriptionEntity.getCreatedAt());
        subscription.setUpdatedAt(subscriptionEntity.getUpdatedAt());
        subscription.setStartingAt(subscriptionEntity.getStartingAt());
        subscription.setEndingAt(subscriptionEntity.getEndingAt());
        subscription.setProcessedAt(subscriptionEntity.getProcessedAt());
        subscription.setProcessedBy(subscriptionEntity.getProcessedBy());
        subscription.setReason(subscriptionEntity.getReason());
        subscription.setStatus(subscriptionEntity.getStatus());
        subscription.setSubscribedBy(
            new Subscription.User(
                subscriptionEntity.getSubscribedBy(),
                userService.findById(subscriptionEntity.getSubscribedBy()).getDisplayName()
            )
        );

        PlanEntity plan = planService.findById(subscriptionEntity.getPlan());
        subscription.setPlan(new Subscription.Plan(plan.getId(), plan.getName()));

        ApplicationEntity application = applicationService.findById(subscriptionEntity.getApplication());
        subscription.setApplication(
            new Subscription.Application(
                application.getId(),
                application.getName(),
                application.getType(),
                application.getDescription(),
                new Subscription.User(application.getPrimaryOwner().getId(), application.getPrimaryOwner().getDisplayName())
            )
        );

        subscription.setClosedAt(subscriptionEntity.getClosedAt());

        return subscription;
    }

    private static class SubscriptionParam {

        @QueryParam("plan")
        @ApiParam(value = "plan")
        private ListStringParam plans;

        @QueryParam("application")
        @ApiParam(value = "application")
        private ListStringParam applications;

        @QueryParam("status")
        @DefaultValue("accepted,pending,paused")
        @ApiModelProperty(dataType = "string", allowableValues = "accepted, pending, rejected, closed", value = "Subscription status")
        private ListSubscriptionStatusParam status;

        @QueryParam("api_key")
        private String apiKey;

        public ListStringParam getPlans() {
            return plans;
        }

        public void setPlans(ListStringParam plans) {
            this.plans = plans;
        }

        public ListStringParam getApplications() {
            return applications;
        }

        public void setApplications(ListStringParam applications) {
            this.applications = applications;
        }

        public ListSubscriptionStatusParam getStatus() {
            return status;
        }

        public void setStatus(ListSubscriptionStatusParam status) {
            this.status = status;
        }

        public String getApiKey() {
            return apiKey;
        }

        public void setApiKey(String apiKey) {
            this.apiKey = apiKey;
        }

        private SubscriptionQuery toQuery() {
            SubscriptionQuery query = new SubscriptionQuery();

            if (plans != null && plans.getValue() != null) {
                query.setPlans(plans.getValue());
            }

            if (status != null) {
                query.setStatuses(status.getStatus());
            }

            if (applications != null && applications.getValue() != null) {
                query.setApplications(applications.getValue());
            }

            query.setApiKey(this.apiKey);

            return query;
        }
    }
}


text:
package com.jjzcru.luft.presentation.view.view.player;

import com.jjzcru.luft.presentation.model.PlayerModel;

public interface PlayerPutView {
    /**
     * Render a player list in the UI.
     *
     * @param playerModel The details of {@link PlayerModel} that will be shown.
     */
    void renderPlayerDetail(PlayerModel playerModel);

    void finish();
}


text:
typedef NS_ENUM(NSInteger, StatsTwoColumnTableViewCellSelectType) {
    StatsTwoColumnTableViewCellSelectTypeCategory,
    StatsTwoColumnTableViewCellSelectTypeDetail,
    StatsTwoColumnTableViewCellSelectTypeTag,
    StatsTwoColumnTableViewCellSelectTypeURL
};

@interface StatsTwoColumnTableViewCell : StatsStandardBorderedTableViewCell

@property (nonatomic, copy) NSString *leftText;
@property (nonatomic, copy) NSString *rightText;
@property (nonatomic, strong) NSURL *imageURL;
@property (nonatomic, assign) BOOL showCircularIcon;
@property (nonatomic, assign) NSUInteger indentLevel;
@property (nonatomic, assign) BOOL selectable;
@property (nonatomic, assign) StatsTwoColumnTableViewCellSelectType selectType;
@property (nonatomic, assign) BOOL indentable;
@property (nonatomic, assign) BOOL expandable;
@property (nonatomic, assign) BOOL expanded;

- (void)doneSettingProperties;

@end


text:
/*!
 * jQuery hawkAjax plugin
 * Author: Thomas Sileo
 * Licensed under the MIT license
 */
(function($, window){
// TODO a better resolveURL
function resolveURL(url) {
  var base_url = window.location.protocol+"//"+window.location.host;
  var doc      = document
    , old_base = doc.getElementsByTagName('base')[0]
    , old_href = old_base && old_base.href
    , doc_head = doc.head || doc.getElementsByTagName('head')[0]
    , our_base = old_base || doc_head.appendChild(doc.createElement('base'))
    , resolver = doc.createElement('a')
    , resolved_url
    ;
  our_base.href = base_url;
  resolver.href = url;
  resolved_url  = resolver.href; // browser magic at work here
  if (old_base) old_base.href = old_href;
  else doc_head.removeChild(our_base);
  return resolved_url;
}
$.extend({
    //$.hawkAjax({id: "", key: "", algorithm: "sha1"}, {url: "/api/path"})
    // see directly below for possible 'options'
    hawkAjax: function (credentials, options) {
        deferred = $.Deferred();
        var beforeSend = function(req) {
            hawkData = hawk.client.header(resolveURL(options.url), options.method || "GET", {credentials: credentials});
            req.setRequestHeader("Authorization", hawkData.field);
            req.artifacts = hawkData.artifacts;
        };
        // TODO extend the "headers" options instead of before send.
        options = $.extend(options, {beforeSend: beforeSend});
        $.ajax(options).done(function(jqXHR, textStatus, req) {
            if (req.status == 200) {
                valid = hawk.client.authenticate(req, credentials, req.artifacts, {});
                if (valid) {
                    deferred.resolve(jqXHR, textStatus, req);
                } else {
                    console.log("Hawk error: response not authenticated");
                    // TODO a better textStatus
                    deferred.reject(jqXHR, "unauthenticated", req);
                };
            };
        }).fail(function(jqXHR, textStatus, req) {
            deferred.reject(jqXHR, textStatus, req);
        });
        return deferred.promise();
    }
});
})(jQuery, this);


text:
namespace scheduler {

VirtualTimeDomain::VirtualTimeDomain(TimeDomain::Observer* observer,
                                     base::TimeTicks initial_time)
    : TimeDomain(observer), now_(initial_time), task_queue_manager_(nullptr) {}

VirtualTimeDomain::~VirtualTimeDomain() {}

void VirtualTimeDomain::OnRegisterWithTaskQueueManager(
    TaskQueueManager* task_queue_manager) {
  task_queue_manager_ = task_queue_manager;
  DCHECK(task_queue_manager_);
}

LazyNow VirtualTimeDomain::CreateLazyNow() const {
  base::AutoLock lock(lock_);
  return LazyNow(now_);
}

base::TimeTicks VirtualTimeDomain::Now() const {
  base::AutoLock lock(lock_);
  return now_;
}

base::TimeTicks VirtualTimeDomain::ComputeDelayedRunTime(
    base::TimeTicks time_domain_now,
    base::TimeDelta delay) const {
  return time_domain_now + delay;
}

void VirtualTimeDomain::RequestWakeup(base::TimeTicks now,
                                      base::TimeDelta delay) {
  // We don't need to do anything here because the caller of AdvanceTo is
  // responsible for calling TaskQueueManager::MaybeScheduleImmediateWork if
  // needed.
}

bool VirtualTimeDomain::MaybeAdvanceTime() {
  return false;
}

void VirtualTimeDomain::AsValueIntoInternal(
    base::trace_event::TracedValue* state) const {}

void VirtualTimeDomain::AdvanceTo(base::TimeTicks now) {
  base::AutoLock lock(lock_);
  DCHECK_GE(now, now_);
  now_ = now;
}

void VirtualTimeDomain::RequestDoWork() {
  task_queue_manager_->MaybeScheduleImmediateWork(FROM_HERE);
}

const char* VirtualTimeDomain::GetName() const {
  return "VirtualTimeDomain";
}

}  // namespace scheduler


text:
import AuthenticatedRoute from 'ghost-admin/routes/authenticated';
import {inject as service} from '@ember/service';

export default AuthenticatedRoute.extend({
    notifications: service(),

    afterModel(/*model, transition*/) {
        this.notifications.clearAll();
        this.session.invalidate();
    },

    buildRouteInfoMetadata() {
        return {
            titleToken: 'Sign Out'
        };
    }
});


text:
Simple Eye Tracker
==================

Super-simple C API to the [Tobii EyeX eye tracker](http://www.tobii.com/en/eye-experience/eyex/), suitable for binding in scripting languages. See Tracker.h for the list of available functions. If you're interested in calling this API from Dragon NaturallySpeaking, check out my [blog post](http://handsfreecoding.org/?p=16).

Please see the releases page for a precompiled DLL. To compile the DLL yourself:
1. Install Microsoft Visual Studio 2013 (may also work with later versions).
2. Clone the repository into the samples subdirectory of the EyeX SDK.
3. `cd` into the repository.
4. Run `cmd /k "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat" x86` to start a sub-shell with `msbuild` available.
5. Run `msbuild /p:configuration=release /p:platform=win32` to build Tracker.dll, which will now appear in the "release" directory.


text:
require 'rails_helper'

describe AmrDataFeedImportLog, type: :system, include_application_helper: true do

  let!(:admin)           { create(:admin) }
  let(:sheffield_config) { create(:amr_data_feed_config, description: 'Sheffield') }

  before(:each) do
    sign_in(admin)
    visit root_path
    click_on 'Manage'
    click_on 'Reports'
  end

  it 'shows a benchmark result run and allows the user to drill down' do
    error_messages = "Oh no!"
    log_1 = create(:amr_data_feed_import_log, amr_data_feed_config: sheffield_config, error_messages: error_messages, import_time: 1.day.ago)
    log_2 = create(:amr_data_feed_import_log, amr_data_feed_config: sheffield_config, records_imported: 200, import_time: 1.day.ago)

    click_on 'AMR File imports report'
    expect(page).to have_content('Amr Data Feed Import Logs')
    expect(page).to have_content(nice_date_times(log_1.import_time))
    expect(page).to have_content(nice_date_times(log_2.import_time))

    expect(page).to have_content(200)
    expect(page).to have_content(error_messages)
  end
end