text:
<configuration>

  <conversionRule conversionWord="coloredLevel" converterClass="play.api.Logger$ColoredLevel" />

  <!-- Appender configuration for each output stream -->
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%date [%coloredLevel] - %message%n%xException</pattern>
    </encoder>
  </appender>

  <!-- Logger configuration -->
  <logger name="limit-test" level="INFO">
    <appender-ref ref="STDOUT"/>
  </logger>

  <!-- Logger configuration -->
  <logger name="request-rate-limit" level="TRACE">
    <appender-ref ref="STDOUT"/>
  </logger>

</configuration>

redpajama_set_name: RedPajamaGithub


text:
#include "SimulatorWindow.h"

#include "cocos2d.h"
#include "glfw3native.h"
#include "resource.h"
#include "runtime/Runtime.h"
#include "ConfigParser.h"

#include <string>
#include <vector>
using namespace std;
using namespace cocos2d;

WNDPROC g_oldProc=NULL;
bool g_landscape=false;
bool g_windTop = true;
CCSize g_screenSize;
GLView* g_eglView=NULL;
INT_PTR CALLBACK AboutDialogCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);

void createViewMenu()
{
    HMENU hSysMenu = GetSystemMenu(glfwGetWin32Window(g_eglView->getWindow()), FALSE);
    HMENU viewMenu = GetSubMenu(hSysMenu, 8);
    for (int i = ConfigParser::getInstance()->getScreenSizeCount() - 1; i >= 0; --i)
    {
        SimulatorScreenSize size = ConfigParser::getInstance()->getScreenSize(i);
        wstring menuName;
        menuName.assign(size.title.begin(), size.title.end());

        MENUITEMINFO item;
        ZeroMemory(&item, sizeof(item));
        item.cbSize = sizeof(item);
        item.fMask = MIIM_FTYPE | MIIM_ID | MIIM_STRING;
        item.fType = MFT_STRING;
        item.wID = ID_VIEW_SIZE + i;
        item.dwTypeData = (LPTSTR)menuName.c_str();
        item.cch = menuName.length();

        InsertMenuItem(viewMenu, 0, TRUE, &item);
    }
}

void updateMenu()
{
    HMENU hSysMenu = GetSystemMenu(glfwGetWin32Window(g_eglView->getWindow()), FALSE);
    HMENU viewMenu = GetSubMenu(hSysMenu, 8);
    HMENU viewControl = GetSubMenu(hSysMenu, 9);

    if (g_landscape)
    {
        CheckMenuItem(viewMenu, ID_VIEW_PORTRAIT, MF_BYCOMMAND | MF_UNCHECKED);
        CheckMenuItem(viewMenu, ID_VIEW_LANDSCAPE, MF_BYCOMMAND | MF_CHECKED);
    }
    else
    {
        CheckMenuItem(viewMenu, ID_VIEW_PORTRAIT, MF_BYCOMMAND | MF_CHECKED);
        CheckMenuItem(viewMenu, ID_VIEW_LANDSCAPE, MF_BYCOMMAND | MF_UNCHECKED);
    }

    if (g_windTop)
    {
        ::SetWindowPos(glfwGetWin32Window(g_eglView->getWindow()),HWND_TOPMOST,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);
        CheckMenuItem(viewControl, ID_CONTROL_TOP, MF_BYCOMMAND | MF_CHECKED);

    }else
    {
        ::SetWindowPos(glfwGetWin32Window(g_eglView->getWindow()),HWND_NOTOPMOST,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);
        CheckMenuItem(viewControl, ID_CONTROL_TOP, MF_BYCOMMAND | MF_UNCHECKED);
    }
    int width = g_screenSize.width;
    int height = g_screenSize.height;
    if (height > width)
    {
        int w = width;
        width = height;
        height = w;
    }

    int count = ConfigParser::getInstance()->getScreenSizeCount();
    for (int i = 0; i < count; ++i)
    {
        bool bSel = false;

        SimulatorScreenSize size = ConfigParser::getInstance()->getScreenSize(i);
        if (size.width == width && size.height == height)
        {
            bSel = true;
        }
        CheckMenuItem(viewMenu, i, MF_BYPOSITION | (bSel? MF_CHECKED : MF_UNCHECKED));
    }

    int scale=g_eglView->getFrameZoomFactor()*100;
    CheckMenuItem(viewMenu, ID_VIEW_ZOOMOUT100, MF_BYCOMMAND | MF_UNCHECKED);
    CheckMenuItem(viewMenu, ID_VIEW_ZOOMOUT75, MF_BYCOMMAND | MF_UNCHECKED);
    CheckMenuItem(viewMenu, ID_VIEW_ZOOMOUT50, MF_BYCOMMAND | MF_UNCHECKED);
    CheckMenuItem(viewMenu, ID_VIEW_ZOOMOUT25, MF_BYCOMMAND | MF_UNCHECKED);
    switch (scale)
    {
    case 100:
        CheckMenuItem(viewMenu, ID_VIEW_ZOOMOUT100, MF_BYCOMMAND | MF_CHECKED);
        break;
    case 75:
        CheckMenuItem(viewMenu, ID_VIEW_ZOOMOUT75, MF_BYCOMMAND | MF_CHECKED);
        break;
    case 50:
        CheckMenuItem(viewMenu, ID_VIEW_ZOOMOUT50, MF_BYCOMMAND | MF_CHECKED);
        break;
    case 25:
        CheckMenuItem(viewMenu, ID_VIEW_ZOOMOUT25, MF_BYCOMMAND | MF_CHECKED);
        break;
    default:
        break;
    }
}

/*@brief updateView*/
void updateView()
{

    auto policy = g_eglView->getResolutionPolicy();
    auto designSize = g_eglView->getDesignResolutionSize();

    if (g_landscape)
    {
        g_eglView->setFrameSize(g_screenSize.width, g_screenSize.height);
    }
    else
    {
        g_eglView->setFrameSize(g_screenSize.height, g_screenSize.width);
    }

    g_eglView->setDesignResolutionSize(designSize.width, designSize.height, policy);

    updateMenu();
}

void onViewChangeOrientation(int viewMenuID)
{
    if (viewMenuID == ID_VIEW_PORTRAIT && g_landscape)
    {
        g_landscape = false;
        updateView();
    }
    else if (viewMenuID == ID_VIEW_LANDSCAPE && !g_landscape)
    {
        g_landscape = true;
        updateView();
    }
}

void onViewZoomOut(int viewMenuID)
{
    float scale = 1.0;
    switch (viewMenuID)
    {
    case ID_VIEW_ZOOMOUT100:
        scale=1.0;
        break;
    case ID_VIEW_ZOOMOUT75:
        scale=0.75;
        break;
    case ID_VIEW_ZOOMOUT50:
        scale=0.50;
        break;
    case ID_VIEW_ZOOMOUT25:
        scale=0.25;
        break;
    default:
        break;
    }
    g_eglView->setFrameZoomFactor(scale);
    updateView();
}

void onViewChangeFrameSize(int viewMenuID)
{
    int index = viewMenuID - ID_VIEW_SIZE;
    if (index >= 0 && index < ConfigParser::getInstance()->getScreenSizeCount())
    {
        SimulatorScreenSize size = ConfigParser::getInstance()->getScreenSize(index);
        g_screenSize.width = size.width;
        g_screenSize.height = size.height;
        updateView();
    }
}

void onHelpAbout()
{
    DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_DIALOG_ABOUT), glfwGetWin32Window(g_eglView->getWindow()), AboutDialogCallback);
}

void shutDownApp()
{
    HWND hWnd=glfwGetWin32Window(g_eglView->getWindow());
    ::SendMessage(hWnd,WM_CLOSE,NULL,NULL);
}

void reStart()
{
    PROCESS_INFORMATION info;
    STARTUPINFO startup;
    TCHAR szPath[128]={0};
    TCHAR *szCmdLine=NULL;
    GetModuleFileName(NULL, szPath, sizeof(szPath));
    szCmdLine = GetCommandLine();
    GetStartupInfo(&startup);
    BOOL bSucc = CreateProcess(szPath, szCmdLine, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &startup, &info);
    if(bSucc)
    {
        ExitProcess(-1);
    }
}
/*@brief new windows process*/
LRESULT CALLBACK SNewWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    int wmId, wmEvent;
    switch (message)
    {
    case WM_KEYDOWN:
        if (wParam == VK_F5)
        {
            reStart();
             break;
        }
    case WM_SYSCOMMAND:
        {
            wmId    = LOWORD(wParam);
            wmEvent = HIWORD(wParam);

            switch (wmId)
            {
            case ID_CONTROL_TOP:
                g_windTop = !g_windTop;
                updateView();
                break;
            case ID_FILE_EXIT:
                shutDownApp();
                break;

            case ID_VIEW_PORTRAIT:
            case ID_VIEW_LANDSCAPE:
                onViewChangeOrientation(wmId);
                break;

            case ID_VIEW_ZOOMOUT100:
            case ID_VIEW_ZOOMOUT75:
            case ID_VIEW_ZOOMOUT50:
            case ID_VIEW_ZOOMOUT25:
                onViewZoomOut(wmId);
                break;

            case ID_CONTROL_RELOAD:
                reStart();
                break;

            case ID_HELP_ABOUT:
                onHelpAbout();
                break;
            default:
                if (wmId >= ID_VIEW_SIZE && wmId <= ID_VIEW_SIZE + ConfigParser::getInstance()->getScreenSizeCount() - 1)
                {
                    onViewChangeFrameSize(wmId);
                    break;
                }
                //return 0;
            }
        }
        break;
    }
    return g_oldProc(hWnd, message, wParam, lParam);
}

/*@brief AboutDialog Callback*/
INT_PTR CALLBACK AboutDialogCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
    UNREFERENCED_PARAMETER(lParam);
    switch (message)
    {
    case WM_INITDIALOG:
        return (INT_PTR)TRUE;

    case WM_COMMAND:
        if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
        {
            EndDialog(hDlg, LOWORD(wParam));
            return (INT_PTR)TRUE;
        }
        break;
    }
    return (INT_PTR)FALSE;
}

void createSimulator(const char* viewName, float width, float height, bool isLandscape, float frameZoomFactor)
{
    if (g_eglView)
    {
        return;
    }

    g_landscape = isLandscape;
    if(height > width)
    {
        float tmpvalue =width;
        width = height;
        height = tmpvalue;
    }
    g_screenSize.width = width;
    g_screenSize.height = height;

    if(!g_landscape)
    {
        float tmpvalue =width;
        width = height;
        height = tmpvalue;
    }
    g_windTop = true;

    g_eglView = GLView::createWithRect(viewName,Rect(0,0,width,height),frameZoomFactor);
    auto director = Director::getInstance();
    director->setOpenGLView(g_eglView);

    HWND hWnd=glfwGetWin32Window(g_eglView->getWindow());
    HMENU hMenu = LoadMenu(GetModuleHandle(NULL), MAKEINTRESOURCE(IDR_MENU_COCOS));
    HMENU hSysMenu = GetSystemMenu(hWnd, FALSE);
    HMENU hviewMenu = GetSubMenu(hMenu,1);
    HMENU hcontrolMenu = GetSubMenu(hMenu,2);
    AppendMenu(hSysMenu,MF_SEPARATOR,0,NULL);
    if (hSysMenu != INVALID_HANDLE_VALUE && hMenu != INVALID_HANDLE_VALUE)
    {
        AppendMenu(hSysMenu, MF_POPUP, (UINT)hviewMenu, TEXT("view"));
        AppendMenu(hSysMenu, MF_POPUP, (UINT)hcontrolMenu, TEXT("control"));
    }
    //SetMenu(hWnd, hMenu);
    createViewMenu();
    updateMenu();

    g_oldProc = (WNDPROC)SetWindowLong(hWnd, GWL_WNDPROC, (LONG)SNewWndProc);
    if (g_oldProc==0)
    {
        printf("SetWindowLong NewWndProc Error:%d\n",GetLastError());
    }

}


text:
using CoachLancer.Data.Models;
using Microsoft.AspNet.Identity.Owin;
using System;
using System.Threading.Tasks;
namespace CoachLancer.Web.Auth.Contracts
{
    public interface ISignInService : IDisposable
    {
        Task SignInAsync(User user, bool isPersistent, bool rememberBrowser);

        Task<bool> HasBeenVerifiedAsync();

        Task<string> GetVerifiedUserIdAsync();

        Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout);

        Task<SignInStatus> TwoFactorSignInAsync(string provider, string code, bool isPersistent, bool rememberBrowser);

        Task<bool> SendTwoFactorCodeAsync(string provider);

        Task<SignInStatus> ExternalSignInAsync(ExternalLoginInfo loginInfo, bool isPersistent);
    }
}


text:
package io.atomix.copycat.server.state;

import io.atomix.copycat.client.request.*;
import io.atomix.copycat.client.response.*;
import io.atomix.copycat.client.response.Response.Status;
import io.atomix.copycat.server.TestStateMachine.TestCommand;
import io.atomix.copycat.server.TestStateMachine.TestQuery;
import io.atomix.copycat.server.request.*;
import io.atomix.copycat.server.response.*;
import io.atomix.copycat.server.storage.TestEntry;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.util.UUID;

import static org.testng.Assert.*;

/**
 * Passive state tests.
 */
@Test
public class PassiveStateTest extends AbstractStateTest<PassiveState> {
  @BeforeMethod
  @Override
  void beforeMethod() throws Throwable {
    super.beforeMethod();
    state = new PassiveState(serverState);
  }

  public void testAccept() throws Throwable {
    runOnServer(() -> {
      AcceptRequest request = AcceptRequest.builder().withAddress(members.get(0)).withSession(1).build();
      AcceptResponse response = state.accept(request).get();
      assertIllegalMemberStateError(response);
    });
  }

  public void testKeepAlive() throws Throwable {
    runOnServer(() -> {
      KeepAliveRequest request = KeepAliveRequest.builder()
          .withCommandSequence(1)
          .withEventVersion(1)
          .withSession(1)
          .build();
      KeepAliveResponse response = state.keepAlive(request).get();
      assertIllegalMemberStateError(response);
    });
  }

  public void testApplyCommits() throws Throwable {
    runOnServer(() -> {
      state.applyCommits(3);

      // TODO more assertions
      threadAssertEquals(serverState.getCommitIndex(), 3L);
    });
  }

  public void testDoAppendEntries() throws Throwable {
    // TODO
  }

  public void testDoCheckPreviousEntry() throws Throwable {
    // TODO
  }

  public void testAppendUpdatesLeaderAndTerm() throws Throwable {
    runOnServer(() -> {
      serverState.setTerm(1);
      AppendRequest request = AppendRequest.builder()
          .withTerm(2)
          .withLeader(members.get(1).hashCode())
          .withLogIndex(0)
          .withLogTerm(0)
          .withCommitIndex(0)
          .withGlobalIndex(0)
          .build();

      AppendResponse response = state.append(request).get();

      threadAssertEquals(serverState.getTerm(), 2L);
      threadAssertEquals(serverState.getLeader(), members.get(1));
      threadAssertEquals(serverState.getLastVotedFor(), 0);
      threadAssertEquals(response.term(), 2L);
      threadAssertTrue(response.succeeded());
    });
  }

  public void testAppendTermAndLeaderUpdated() throws Throwable {
    runOnServer(() -> {
      int leader = serverState.getCluster().getActiveMembers().iterator().next().getAddress().hashCode();
      serverState.setTerm(1);
      AppendRequest request = AppendRequest.builder()
        .withTerm(2)
        .withLeader(leader)
        .withCommitIndex(0)
        .withGlobalIndex(0)
        .build();

      AppendResponse response = state.append(request).get();

      assertEquals(response.status(), Status.OK);
      assertTrue(response.succeeded());
      assertEquals(serverState.getTerm(), 2L);
      assertEquals(serverState.getLeader().hashCode(), leader);
      assertEquals(response.term(), 2L);
    });
  }

  public void testRejectAppendOnTerm() throws Throwable {
    runOnServer(() -> {
      serverState.setTerm(2);
      append(2, 2);

      AppendRequest request = AppendRequest.builder()
        .withTerm(1)
        .withLeader(serverState.getCluster().getActiveMembers().iterator().next().getAddress().hashCode())
        .withLogIndex(2)
        .withLogTerm(2)
        .withCommitIndex(0)
        .withGlobalIndex(0)
        .build();

      AppendResponse response = state.append(request).get();

      assertEquals(response.status(), Status.OK);
      assertFalse(response.succeeded());
      assertEquals(response.term(), 2L);
      assertEquals(response.logIndex(), 2L);
    });
  }

  public void testRejectAppendOnMissingLogIndex() throws Throwable {
    runOnServer(() -> {
      serverState.setTerm(2);
      append(1, 2);

      AppendRequest request = AppendRequest.builder()
        .withTerm(2)
        .withLeader(serverState.getCluster().getActiveMembers().iterator().next().getAddress().hashCode())
        .withLogIndex(2)
        .withLogTerm(2)
        .withCommitIndex(0)
        .withGlobalIndex(0)
        .build();

      AppendResponse response = state.append(request).get();

      assertEquals(response.status(), Status.OK);
      assertFalse(response.succeeded());
      assertEquals(response.term(), 2L);
      assertEquals(response.logIndex(), 1L);
    });
  }

  public void testRejectAppendOnSkippedLogIndex() throws Throwable {
    runOnServer(() -> {
      serverState.setTerm(1);
      serverState.getLog().skip(1);

      AppendRequest request = AppendRequest.builder()
        .withTerm(1)
        .withLeader(serverState.getCluster().getActiveMembers().iterator().next().getAddress().hashCode())
        .withLogIndex(1)
        .withLogTerm(1)
        .withCommitIndex(0)
        .withGlobalIndex(0)
        .withEntries(new TestEntry().setIndex(2).setTerm(1))
        .build();

      AppendResponse response = state.append(request).get();

      assertEquals(response.status(), Status.OK);
      assertFalse(response.succeeded());
      assertEquals(response.term(), 1L);
      assertEquals(response.logIndex(), 0L);
    });
  }

  public void testRejectAppendOnInconsistentLogTerm() throws Throwable {
    runOnServer(() -> {
      serverState.setTerm(2);
      append(2, 1);

      AppendRequest request = AppendRequest.builder()
        .withTerm(2)
        .withLeader(serverState.getCluster().getActiveMembers().iterator().next().getAddress().hashCode())
        .withLogIndex(2)
        .withLogTerm(2)
        .withCommitIndex(0)
        .withGlobalIndex(0)
        .build();

      AppendResponse response = state.append(request).get();

      assertEquals(response.status(), Status.OK);
      assertFalse(response.succeeded());
      assertEquals(response.term(), 2L);
      assertEquals(response.logIndex(), 1L);
    });
  }

  public void testAppendOnEmptyLog() throws Throwable {
    runOnServer(() -> {
      serverState.setTerm(1);

      AppendRequest request = AppendRequest.builder()
        .withTerm(1)
        .withLeader(serverState.getCluster().getActiveMembers().iterator().next().getAddress().hashCode())
        .withLogIndex(0)
        .withLogTerm(0)
        .withCommitIndex(0)
        .withGlobalIndex(0)
        .withEntries(new TestEntry().setIndex(1).setTerm(1))
        .build();

      AppendResponse response = state.append(request).get();

      assertEquals(response.status(), Status.OK);
      assertTrue(response.succeeded());
      assertEquals(response.term(), 1L);
      assertEquals(response.logIndex(), 1L);

      assertEquals(serverState.getLog().length(), 1L);
      assertNotNull(get(1));
    });
  }

  public void testAppendOnNonEmptyLog() throws Throwable {
    runOnServer(() -> {
      serverState.setTerm(1);
      append(1, 1);

      AppendRequest request = AppendRequest.builder()
        .withTerm(1)
        .withLeader(serverState.getCluster().getActiveMembers().iterator().next().getAddress().hashCode())
        .withLogIndex(0)
        .withLogTerm(0)
        .withCommitIndex(0)
        .withGlobalIndex(0)
        .withEntries(new TestEntry().setIndex(2).setTerm(1))
        .build();

      AppendResponse response = state.append(request).get();

      assertEquals(response.status(), Status.OK);
      assertTrue(response.succeeded());
      assertEquals(response.term(), 1L);
      assertEquals(response.logIndex(), 2L);

      assertEquals(serverState.getLog().length(), 2L);
      assertNotNull(get(2));
    });
  }

  public void testAppendOnPartiallyConflictingEntries() throws Throwable {
    runOnServer(() -> {
      serverState.setTerm(1);
      append(1, 1);
      append(2, 2);

      AppendRequest request = AppendRequest.builder()
        .withTerm(3)
        .withLeader(serverState.getCluster().getActiveMembers().iterator().next().getAddress().hashCode())
        .withLogIndex(1)
        .withLogTerm(1)
        .withCommitIndex(0)
        .withGlobalIndex(0)
        .withEntries(new TestEntry().setIndex(2).setTerm(2), new TestEntry().setIndex(3).setTerm(3), new TestEntry().setIndex(4).setTerm(3))
        .build();

      AppendResponse response = state.append(request).get();

      assertEquals(response.status(), Status.OK);
      assertTrue(response.succeeded());
      assertEquals(response.term(), 3L);
      assertEquals(response.logIndex(), 4L);

      assertEquals(serverState.getLog().length(), 4L);
      assertEquals(get(2).getTerm(), 2L);
      assertEquals(get(3).getTerm(), 3L);
      assertEquals(get(4).getTerm(), 3L);
    });
  }

  public void testAppendSkippedEntries() throws Throwable {
    runOnServer(() -> {
      serverState.setTerm(1);
      append(1, 1);

      AppendRequest request = AppendRequest.builder()
        .withTerm(1)
        .withLeader(serverState.getCluster().getActiveMembers().iterator().next().getAddress().hashCode())
        .withLogIndex(1)
        .withLogTerm(1)
        .withCommitIndex(0)
        .withGlobalIndex(0)
        .withEntries(new TestEntry().setIndex(2).setTerm(1), new TestEntry().setIndex(4).setTerm(1))
        .build();

      AppendResponse response = state.append(request).get();

      assertEquals(response.status(), Status.OK);
      assertTrue(response.succeeded());
      assertEquals(response.term(), 1L);
      assertEquals(response.logIndex(), 4L);

      assertEquals(serverState.getLog().length(), 4L);
      assertNotNull(get(2));
      assertNull(get(3));
      assertNotNull(get(4));
    });
  }

  public void testCommandWithoutLeader() throws Throwable {
    runOnServer(() -> {
      CommandRequest request = CommandRequest.builder().withSession(1).withCommand(new TestCommand("test")).build();
      CommandResponse response = state.command(request).get();
      assertNoLeaderError(response);
    });
  }

  public void testJoinWithoutLeader() throws Throwable {
    runOnServer(() -> {
      JoinRequest request = JoinRequest.builder().withMember(members.get(0)).build();
      JoinResponse response = state.join(request).get();
      assertNoLeaderError(response);
    });
  }

  public void testLeaveWithoutLeader() throws Throwable {
    runOnServer(() -> {
      LeaveRequest request = LeaveRequest.builder().withMember(members.get(0)).build();
      LeaveResponse response = state.leave(request).get();
      assertNoLeaderError(response);
    });
  }

  public void testQueryWithoutLeader() throws Throwable {
    runOnServer(() -> {
      QueryRequest request = QueryRequest.builder().withSession(1).withQuery(new TestQuery()).build();
      QueryResponse response = state.query(request).get();
      assertNoLeaderError(response);
    });
  }

  public void testRegister() throws Throwable {
    runOnServer(() -> {
      RegisterRequest request = RegisterRequest.builder().withClient(UUID.randomUUID()).build();
      RegisterResponse response = state.register(request).get();
      assertIllegalMemberStateError(response);
    });
  }

  public void testUnregister() throws Throwable {
    runOnServer(() -> {
      UnregisterRequest request = UnregisterRequest.builder().withSession(1).build();
      UnregisterResponse response = state.unregister(request).get();
      assertIllegalMemberStateError(response);
    });
  }

  public void testConnect() throws Throwable {
    runOnServer(() -> {
      ConnectRequest request = ConnectRequest.builder().withSession(1).build();
      ConnectResponse response = state.connect(request, null).get();
      assertIllegalMemberStateError(response);
    });
  }

  public void testPoll() throws Throwable {
    runOnServer(() -> {
      PollRequest request = PollRequest.builder().withCandidate(1).withLogIndex(1).withLogTerm(1).withTerm(1).build();
      PollResponse response = state.poll(request).get();
      assertIllegalMemberStateError(response);
    });
  }

  public void testPublish() throws Throwable {
    runOnServer(() -> {
      PublishRequest request = PublishRequest.builder().withSession(1).withEventVersion(1).build();
      PublishResponse response = state.publish(request).get();
      assertIllegalMemberStateError(response);
    });
  }

  public void testVote() throws Throwable {
    runOnServer(() -> {
      VoteRequest request = VoteRequest.builder().withCandidate(1).withLogIndex(1).withLogTerm(1).withTerm(1).build();
      VoteResponse response = state.vote(request).get();
      assertIllegalMemberStateError(response);
    });
  }

}


text:
"""
Vert
====

Vert is a Python package which attempts to provide a standardized interface for graphs. It does so by separating the
graph into two separate layers of abstraction:

* The graph store: This is where the graph is actually stored and represented. It may be a graph database, another graph
  library's data structure, or one of vert's built-in graph store objects.
* The graph interface: This is where you, the programmer, can access the graph via an intuitive object-oriented
  interface using familiar data types such as Graph, Vertex, and Edge.

Because vert is structured along these distinct layers of abstraction, it is possible to write code that utilizes
and operates on a graph without regard for the underlying storage mechanisms. Storage mechanisms can be freely swapped
out for each other at the point where the graph object is initialized, and, aside from differences in performance and
persistence, the rest of your code will never know the difference. Support for new graph storage mechanisms can be
added simply by creating a class that supports the GraphStore interface. This means you never have to worry about vendor
lock-in, and updating your code to use the latest technology is as simple as a one-line change.
"""

from . import stores, graphs

from .stores.base import GraphStore, VertexID, EdgeID, DirectedEdgeID, UndirectedEdgeID, Label
from .stores.dbm import DBMGraphStore
from .stores.memory import MemoryGraphStore
from .graphs import Graph, Vertex, Edge, DirectedEdge, UndirectedEdge

from .__about__ import __title__, __summary__, __url__, __version__, __status__, __author__, __maintainer__, \
    __credits__, __email__, __license__, __copyright__

__all__ = [
    '__title__',
    '__summary__',
    '__url__',
    '__version__',
    '__status__',
    '__author__',
    '__maintainer__',
    '__credits__',
    '__email__',
    '__license__',
    '__copyright__',
    'stores',
    'graphs',
    'GraphStore',
    'VertexID',
    'EdgeID',
    'DirectedEdgeID',
    'UndirectedEdgeID',
    'Label',
    'DBMGraphStore',
    'MemoryGraphStore',
    'Graph',
    'Vertex',
    'Edge',
]


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateLogMessagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('log_messages', function (Blueprint $table) {
            $table->increments('id');

            $table->integer('issue_id')->unsigned();
            $table->integer('source_user_id')->unsigned();

            $table->text("message");

            $table->foreign('source_user_id')->references('id')
                ->on('users')->onDelete('cascade')->onUpdate('cascade');

            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('log_messages', function (Blueprint $table) {
            $table->dropForeign('log_messages_source_user_id_foreign');
        });

        Schema::dropIfExists('log_messages');
    }
}


text:
package com.android.myeyepetizer.multitype;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.myeyepetizer.R;

import me.drakeet.multitype.ItemViewBinder;

/**
 * Created by Administrator on 2017/8/25.
 */

public class GreyAreaBinder extends ItemViewBinder<GreyArea, GreyAreaBinder.ViewHolder> {

    @NonNull
    @Override
    protected ViewHolder onCreateViewHolder(@NonNull LayoutInflater inflater, @NonNull ViewGroup parent) {
        View view = inflater.inflate(R.layout.item_grey_area, parent, false);
        return new ViewHolder(view);
    }

    @Override
    protected void onBindViewHolder(@NonNull ViewHolder holder, @NonNull GreyArea item) {

    }

    class ViewHolder extends RecyclerView.ViewHolder {

        public ViewHolder(View itemView) {
            super(itemView);
        }

    }

}


text:
// Template Source: BaseEntityRequest.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

package com.microsoft.graph.requests;

import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.models.Place;
import java.util.Arrays;
import java.util.EnumSet;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.microsoft.graph.core.IBaseClient;
import com.microsoft.graph.http.BaseRequest;
import com.microsoft.graph.http.HttpMethod;

// **NOTE** This file was generated by a tool and any changes will be overwritten.

/**
 * The class for the Place Request.
 */
public class PlaceRequest extends BaseRequest<Place> {

    /**
     * The request for the Place
     *
     * @param requestUrl     the request URL
     * @param client         the service client
     * @param requestOptions the options for this request
     * @param responseClass  the class of the response
     */
    public PlaceRequest(@Nonnull final String requestUrl,
            @Nonnull final IBaseClient<?> client,
            @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions,
            @Nonnull final Class<? extends Place> responseClass) {
        super(requestUrl, client, requestOptions, responseClass);
    }

    /**
     * The request for the Place
     *
     * @param requestUrl     the request URL
     * @param client         the service client
     * @param requestOptions the options for this request
     */
    public PlaceRequest(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
        super(requestUrl, client, requestOptions, Place.class);
    }

    /**
     * Gets the Place from the service
     *
     * @return a future with the result
     */
    @Nonnull
    public java.util.concurrent.CompletableFuture<Place> getAsync() {
        return sendAsync(HttpMethod.GET, null);
    }

    /**
     * Gets the Place from the service
     *
     * @return the Place from the request
     * @throws ClientException this exception occurs if the request was unable to complete for any reason
     */
    @Nullable
    public Place get() throws ClientException {
       return send(HttpMethod.GET, null);
    }

    /**
     * Delete this item from the service
     *
     * @return a future with the deletion result
     */
    @Nonnull
    public java.util.concurrent.CompletableFuture<Place> deleteAsync() {
        return sendAsync(HttpMethod.DELETE, null);
    }

    /**
     * Delete this item from the service
     * @return the resulting response if the service returns anything on deletion
     *
     * @throws ClientException if there was an exception during the delete operation
     */
    @Nullable
    public Place delete() throws ClientException {
        return send(HttpMethod.DELETE, null);
    }

    /**
     * Patches this Place with a source
     *
     * @param sourcePlace the source object with updates
     * @return a future with the result
     */
    @Nonnull
    public java.util.concurrent.CompletableFuture<Place> patchAsync(@Nonnull final Place sourcePlace) {
        return sendAsync(HttpMethod.PATCH, sourcePlace);
    }

    /**
     * Patches this Place with a source
     *
     * @param sourcePlace the source object with updates
     * @return the updated Place
     * @throws ClientException this exception occurs if the request was unable to complete for any reason
     */
    @Nullable
    public Place patch(@Nonnull final Place sourcePlace) throws ClientException {
        return send(HttpMethod.PATCH, sourcePlace);
    }

    /**
     * Creates a Place with a new object
     *
     * @param newPlace the new object to create
     * @return a future with the result
     */
    @Nonnull
    public java.util.concurrent.CompletableFuture<Place> postAsync(@Nonnull final Place newPlace) {
        return sendAsync(HttpMethod.POST, newPlace);
    }

    /**
     * Creates a Place with a new object
     *
     * @param newPlace the new object to create
     * @return the created Place
     * @throws ClientException this exception occurs if the request was unable to complete for any reason
     */
    @Nullable
    public Place post(@Nonnull final Place newPlace) throws ClientException {
        return send(HttpMethod.POST, newPlace);
    }

    /**
     * Creates a Place with a new object
     *
     * @param newPlace the object to create/update
     * @return a future with the result
     */
    @Nonnull
    public java.util.concurrent.CompletableFuture<Place> putAsync(@Nonnull final Place newPlace) {
        return sendAsync(HttpMethod.PUT, newPlace);
    }

    /**
     * Creates a Place with a new object
     *
     * @param newPlace the object to create/update
     * @return the created Place
     * @throws ClientException this exception occurs if the request was unable to complete for any reason
     */
    @Nullable
    public Place put(@Nonnull final Place newPlace) throws ClientException {
        return send(HttpMethod.PUT, newPlace);
    }

    /**
     * Sets the select clause for the request
     *
     * @param value the select clause
     * @return the updated request
     */
     @Nonnull
     public PlaceRequest select(@Nonnull final String value) {
         addSelectOption(value);
         return this;
     }

    /**
     * Sets the expand clause for the request
     *
     * @param value the expand clause
     * @return the updated request
     */
     @Nonnull
     public PlaceRequest expand(@Nonnull final String value) {
         addExpandOption(value);
         return this;
     }

}


text:
![](https://travis-ci.org/vampirewalk/ObjectGraph-Xcode.svg?branch=master)
[![Twitter: @vampirewalk666](https://img.shields.io/badge/contact-%40vampirewalk-blue.svg)](https://twitter.com/vampirewalk666)

ObjectGraph can show oriented graph of dependencies between classes in your project.
This plugin is based on [objc_dep](https://github.com/nst/objc_dep) and [Graphviz](http://www.graphviz.org/).

![Screenshot](https://raw.githubusercontent.com/vampirewalk/ObjectGraph-Xcode/master/ScreenShot.png)

![Example](https://raw.githubusercontent.com/vampirewalk/ObjectGraph-Xcode/master/ObjectGraph.png)

- Black arrows: imports
- Red arrows: .pch imports
- Blue arrows: two ways imports

## Usage
The default path of source code parsing is project root path, you can set new path by clicking "Set Source Path Path...".
For example, if you just want to parse your product class, not test class or external library class in Pods directory, you can set path to directory which contains your product class and execute "Draw Object Graph" again.

## Install
First step, install Graphviz via Homebrew
```
brew install graphviz
```
or MacPorts
```
sudo port install graphviz
```
Second, install ObjectGraph-Xcode via [Alcatraz](http://alcatraz.io/)
or
Clone and build the project, then restart Xcode.

## Uninstall
Uninstall it via [Alcatraz](http://alcatraz.io/)
or
```
Run rm -r ~/Library/Application\ Support/Developer/Shared/Xcode/Plug-ins/ObjectGraph.xcplugin/
```

## Thanks
Thanks to kattrali, I get inspiration and import some code from [cocoapods-xcode-plugin](https://github.com/kattrali/cocoapods-xcode-plugin).


text:
<?php

namespace Illuminate\Database\Events;

use Illuminate\Database\Migrations\Migration;
use Illuminate\Contracts\Database\Events\MigrationEvent as MigrationEventContract;

abstract class MigrationEvent implements MigrationEventContract
{
    /**
     * An migration instance.
     *
     * @var \Illuminate\Database\Migrations\Migration
     */
    public $migration;

    /**
     * The migration method that was called.
     *
     * @var string
     */
    public $method;

    /**
     * Create a new event instance.
     *
     * @param  \Illuminate\Database\Migrations\Migration  $migration
     * @param  string  $method
     * @return void
     */
    public function __construct(Migration $migration, $method)
    {
        $this->method = $method;
        $this->migration = $migration;
    }
}


text:
using Microsoft.VisualStudio.Modeling;

namespace NuPattern.Library.Automation
{
    /// <summary>
    /// Change rule for <see cref="ValidationExtension"/> domain class.
    /// </summary>
    [RuleOn(typeof(ValidationExtension), FireTime = TimeToFire.TopLevelCommit)]
    internal class ValidationExtensionChangeRule : ChangeRule
    {
        /// <summary>
        /// Handles the property change event for the set of validation properties.
        /// </summary>
        /// <param name="e">The event args.</param>
        public override void ElementPropertyChanged(ElementPropertyChangedEventArgs e)
        {
            Guard.NotNull(() => e, e);

            if ((e.DomainProperty.Id == ValidationExtension.ValidationOnBuildDomainPropertyId)
                || (e.DomainProperty.Id == ValidationExtension.ValidationOnCustomEventDomainPropertyId)
                || (e.DomainProperty.Id == ValidationExtension.ValidationOnMenuDomainPropertyId)
                || (e.DomainProperty.Id == ValidationExtension.ValidationOnSaveDomainPropertyId))
            {
                // Ensure we are not in deserialization mode.
                if (!e.ModelElement.Store.TransactionManager.CurrentTransaction.IsSerializing)
                {
                    ValidationExtension validationExtension = (ValidationExtension)e.ModelElement;
                    if (validationExtension != null)
                    {
                        validationExtension.EnsureValidationExtensionAutomation();
                    }
                }
            }
        }
    }
}


text:
"""IP address helper functions.

This file contains alternative implementations of the following functions
normally provided by the system:

  - inet_(ntop|pton)
  - inet_(ntoa|aton)
  - (hton|ntoh)(sl)
"""

import errno
import os
import re
import struct
import sys

from google.appengine.api.remote_socket._remote_socket_error import *

AF_UNSPEC = 0
AF_UNIX = 1
AF_INET = 2
AF_INET6 = 30

def _TypeName(obj):
  if obj is None:
    return 'None'
  return type(obj).__name__

def _LongestRun(seq, value):
  """Finds the longest run (i.e. repeated adjacent values) of value in seq.

  Args:
    seq: A sequence to scan for runs.
    value: A value to scan for in seq.

  Returns:
    A tuple of the offset and run length for the longest run of value within
    seq, or (-1, 0) if value does not occur within seq.
  """
  off = -1
  max_run = 0
  i = 0
  while i < len(seq):
    run = 0
    while i + run < len(seq) and seq[i+run] == value:
      run += 1
    if run > max_run:
      off = i
      max_run = run
    i += 1 + run
  return off, max_run

def _GetBase(text):
  if text[:2].lower() == '0x':
    return 16
  elif text[:1] == '0':
    return 8
  return 10

def ntohs(integer):
  """ntohs(integer) -> integer

  Convert a 16-bit integer from network to host byte order.
  """
  if sys.byteorder == 'big':
    return integer
  if not isinstance(integer, (int, long)):
    raise TypeError('an integer is required')
  if integer < 0:
    raise OverflowError("can't convert negative number to unsigned long")
  if integer >= (1<<16):
    raise OverflowError('signed integer is greater than maximum')
  return int(
      ((integer&0xff00)>>8)|
      ((integer&0x00ff)<<8))

def ntohl(integer):
  """ntohl(integer) -> integer

  Convert a 32-bit integer from network to host byte order.
  """
  if sys.byteorder == 'big':
    return integer
  if not isinstance(integer, (int, long)):
    raise TypeError('expected int/long, %s found' % _TypeName(integer))
  if integer < 0:
    raise OverflowError('can\'t convert negative number to unsigned long')
  if integer >= (1<<32):
    raise OverflowError('long int larger than 32 bits')
  return int(
      ((integer&0xff000000)>>24)|
      ((integer&0x00ff0000)>>8)|
      ((integer&0x0000ff00)<<8)|
      ((integer&0x000000ff)<<24))

def htons(integer):
  """htons(integer) -> integer

  Convert a 16-bit integer from host to network byte order.
  """
  return ntohs(integer)

def htonl(integer):
  """htonl(integer) -> integer

  Convert a 32-bit integer from host to network byte order.
  """
  return ntohl(integer)

def inet_aton(ip_string):
  """inet_aton(string) -> packed 32-bit IP representation

  Convert an IP address in string format (123.45.67.89) to the 32-bit packed
  binary format used in low-level network functions.
  """

  if not isinstance(ip_string, basestring):
    raise error('inet_aton() argument 1 must be string, not %s' %
                _TypeName(ip_string))
  try:
    ret = 0
    bits = 32
    parts = [int(s, _GetBase(s)) for s in ip_string.split('.')]
    assert len(parts) >= 1 and len(parts) <= 4
    for n in parts[:-1]:
      assert n >= 0 and n <= 0xff
      bits -= 8
      ret |= ((n & 0xff) << bits)
    assert parts[-1] >= 0 and parts[-1] < (1 << bits)
    ret |= parts[-1]
    return struct.pack('!L', ret)
  except:
    raise error('illegal IP address string passed to inet_aton')

def inet_ntoa(packed_ip):
  """inet_ntoa(packed_ip) -> ip_address_string

  Convert an IP address from 32-bit packed binary format to string format
  """

  if not isinstance(packed_ip, basestring):
    raise TypeError('inet_ntoa() argument 1 must be string or read-only '
                    'buffer, not %s' % _TypeName(packed_ip))
  if len(packed_ip) != 4:
    raise error('packed IP wrong length for inet_ntoa')
  return '%u.%u.%u.%u' % struct.unpack('4B', packed_ip)

def inet_pton(af, ip):
  """inet_pton(af, ip) -> packed IP address string

  Convert an IP address from string format to a packed string suitable
  for use with low-level network functions.
  """

  if not isinstance(af, (int, long)):
    raise TypeError('an integer is required')
  if not isinstance(ip, basestring):
    raise TypeError('inet_pton() argument 2 must be string, not %s' %
                    _TypeName(ip))
  if af == AF_INET:
    parts = ip.split('.')
    if len(parts) != 4:
      raise error('illegal IP address string passed to inet_pton')
    ret = 0
    bits = 32
    for part in parts:
      if not re.match(r'^(0|[1-9]\d*)$', part) or int(part) > 0xff:
        raise error('illegal IP address string passed to inet_pton')
      bits -= 8
      ret |= ((int(part) & 0xff) << bits)
    return struct.pack('!L', ret)
  elif af == AF_INET6:
    parts = ip.split(':')

    if '.' in parts[-1]:
      ipv4_shorts = struct.unpack('!2H', inet_pton(AF_INET, parts[-1]))
      parts[-1:] = [hex(n)[2:] for n in ipv4_shorts]

    if '' in parts:
      if len(parts) == 1 or len(parts) >= 8:
        raise error('illegal IP address string passed to inet_pton')

      idx = parts.index('')
      count = parts.count('')
      pad = ['0']*(count+(8-len(parts)))

      if count == len(parts) == 3:
        parts = pad
      elif count == 2 and parts[0:2] == ['', '']:
        parts[0:2] = pad
      elif count == 2 and parts[-2:] == ['', '']:
        parts[-2:] = pad
      elif count == 1:
        parts[idx:idx+1] = pad
      else:
        raise error('illegal IP address string passed to inet_pton')
    if (len(parts) != 8 or
        [x for x in parts if not re.match(r'^[0-9A-Fa-f]{1,4}$', x)]):
      raise error('illegal IP address string passed to inet_pton')
    return struct.pack('!8H', *[int(x, 16) for x in parts])
  else:
    raise error(errno.EAFNOSUPPORT, os.strerror(errno.EAFNOSUPPORT))

def inet_ntop(af, packed_ip):
  """inet_ntop(af, packed_ip) -> string formatted IP address

  Convert a packed IP address of the given family to string format.
  """
  if not isinstance(af, (int, long)):
    raise TypeError('an integer is required')
  if not isinstance(packed_ip, basestring):
    raise TypeError('inet_ntop() argument 2 must be string or read-only '
                    'buffer, not %s' % _TypeName(packed_ip))
  if af == AF_INET:
    if len(packed_ip) != 4:
      raise ValueError('invalid length of packed IP address string')
    return '%u.%u.%u.%u' % struct.unpack('4B', packed_ip)
  elif af == AF_INET6:
    if len(packed_ip) != 16:
      raise ValueError('invalid length of packed IP address string')
    parts = [hex(n)[2:] for n in struct.unpack('!8H', packed_ip)]

    if (':'.join(parts[:-2]) in ('0:0:0:0:0:0', '0:0:0:0:0:ffff') and
        ':'.join(parts) not in ('0:0:0:0:0:0:0:0', '0:0:0:0:0:0:0:1')):
      parts[-2:] = [inet_ntop(AF_INET, packed_ip[-4:])]
    off, run = _LongestRun(parts, '0')
    if run >= 2:
      pad = ['']
      if off == 0:
        pad.append('')
      if off + run == len(parts):
        pad.append('')
      parts[off:off+run] = pad
    return ':'.join(parts)
  else:
    raise ValueError('unknown address family %u' % af)


text:
package com.android.internal.view.menu;

import android.annotation.NonNull;
import android.annotation.Nullable;
import android.content.Context;
import android.graphics.Rect;
import android.view.MenuItem;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.HeaderViewListAdapter;
import android.widget.ListAdapter;
import android.widget.PopupWindow;

/**
 * Base class for a menu popup abstraction - i.e., some type of menu, housed in a popup window
 * environment.
 *
 * @hide
 */
public abstract class MenuPopup implements ShowableListMenu, MenuPresenter,
        AdapterView.OnItemClickListener {
    private Rect mEpicenterBounds;

    public abstract void setForceShowIcon(boolean forceShow);

    /**
     * Adds the given menu to the popup, if it is capable of displaying submenus within itself.
     * If menu is the first menu shown, it won't be displayed until show() is called.
     * If the popup was already showing, adding a submenu via this method will cause that new
     * submenu to be shown immediately (that is, if this MenuPopup implementation is capable of
     * showing its own submenus).
     *
     * @param menu
     */
    public abstract void addMenu(MenuBuilder menu);

    public abstract void setGravity(int dropDownGravity);

    public abstract void setAnchorView(View anchor);

    public abstract void setHorizontalOffset(int x);

    public abstract void setVerticalOffset(int y);

    /**
     * Specifies the anchor-relative bounds of the popup's transition
     * epicenter.
     *
     * @param bounds anchor-relative bounds
     */
    public void setEpicenterBounds(Rect bounds) {
        mEpicenterBounds = bounds;
    }

    /**
     * @return anchor-relative bounds of the popup's transition epicenter
     */
    public Rect getEpicenterBounds() {
        return mEpicenterBounds;
    }

    /**
     * Set whether a title entry should be shown in the popup menu (if a title exists for the
     * menu).
     *
     * @param showTitle
     */
    public abstract void setShowTitle(boolean showTitle);

    /**
     * Set a listener to receive a callback when the popup is dismissed.
     *
     * @param listener Listener that will be notified when the popup is dismissed.
     */
    public abstract void setOnDismissListener(PopupWindow.OnDismissListener listener);

    @Override
    public void initForMenu(@NonNull Context context, @Nullable MenuBuilder menu) {
        // Don't need to do anything; we added as a presenter in the constructor.
    }

    @Override
    public MenuView getMenuView(ViewGroup root) {
        throw new UnsupportedOperationException("MenuPopups manage their own views");
    }

    @Override
    public boolean expandItemActionView(MenuBuilder menu, MenuItemImpl item) {
        return false;
    }

    @Override
    public boolean collapseItemActionView(MenuBuilder menu, MenuItemImpl item) {
        return false;
    }

    @Override
    public int getId() {
        return 0;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ListAdapter outerAdapter = (ListAdapter) parent.getAdapter();
        MenuAdapter wrappedAdapter = toMenuAdapter(outerAdapter);

        // Use the position from the outer adapter so that if a header view was added, we don't get
        // an off-by-1 error in position.
        wrappedAdapter.mAdapterMenu.performItemAction((MenuItem) outerAdapter.getItem(position), 0);
    }

    /**
     * Measures the width of the given menu view.
     *
     * @param view The view to measure.
     * @return The width.
     */
    protected static int measureIndividualMenuWidth(ListAdapter adapter, ViewGroup parent,
            Context context, int maxAllowedWidth) {
        // Menus don't tend to be long, so this is more sane than it looks.
        int maxWidth = 0;
        View itemView = null;
        int itemType = 0;

        final int widthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
        final int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
        final int count = adapter.getCount();
        for (int i = 0; i < count; i++) {
            final int positionType = adapter.getItemViewType(i);
            if (positionType != itemType) {
                itemType = positionType;
                itemView = null;
            }

            if (parent == null) {
                parent = new FrameLayout(context);
            }

            itemView = adapter.getView(i, itemView, parent);
            itemView.measure(widthMeasureSpec, heightMeasureSpec);

            final int itemWidth = itemView.getMeasuredWidth();
            if (itemWidth >= maxAllowedWidth) {
                return maxAllowedWidth;
            } else if (itemWidth > maxWidth) {
                maxWidth = itemWidth;
            }
        }

        return maxWidth;
    }

    /**
     * Converts the given ListAdapter originating from a menu, to a MenuAdapter, accounting for
     * the possibility of the parameter adapter actually wrapping the MenuAdapter. (That could
     * happen if a header view was added on the menu.)
     *
     * @param adapter
     * @return
     */
    protected static MenuAdapter toMenuAdapter(ListAdapter adapter) {
        if (adapter instanceof HeaderViewListAdapter) {
            return (MenuAdapter) ((HeaderViewListAdapter) adapter).getWrappedAdapter();
        }
        return (MenuAdapter) adapter;
    }

    /**
     * Returns whether icon spacing needs to be preserved for the given menu, based on whether any
     * of its items contains an icon.
     *
     * NOTE: This should only be used for non-overflow-only menus, because this method does not
     * take into account whether the menu items are being shown as part of the popup or or being
     * shown as actions in the action bar.
     *
     * @param menu
     * @return Whether to preserve icon spacing.
     */
    protected static boolean shouldPreserveIconSpacing(MenuBuilder menu) {
      boolean preserveIconSpacing = false;
      final int count = menu.size();

      for (int i = 0; i < count; i++) {
          MenuItem childItem = menu.getItem(i);
          if (childItem.isVisible() && childItem.getIcon() != null) {
              preserveIconSpacing = true;
              break;
          }
      }

      return preserveIconSpacing;
    }
}


text:
package hr.fer.zemris.jcms.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;

import hr.fer.zemris.jcms.dao.QuestionsDAO;
import hr.fer.zemris.jcms.model.Course;
import hr.fer.zemris.jcms.model.questions.QuestionGroup;

public class QuestionsDAOJPAImpl implements QuestionsDAO {

	@Override
	public QuestionGroup getQuestionGroup(EntityManager em, Long id) {
		return em.find(QuestionGroup.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<QuestionGroup> listQuestionGroupsForCourse(EntityManager em,
			Course course) {
		return (List<QuestionGroup>)em.createNamedQuery("QuestionGroup.byCourse").setParameter("course", course).getResultList();
	}

	@Override
	public void remove(EntityManager em, QuestionGroup questionGroup) {
		em.remove(questionGroup);
	}

	@Override
	public void save(EntityManager em, QuestionGroup questionGroup) {
		em.persist(questionGroup);
	}

}


text:
import axios from 'axios';
import {browserHistory as history} from 'react-router';

const profileData = (profile) => {
  return {
    type: 'GET_PROFILE',
    data: profile,
    destData: profile.Destinations
  }
}

//REDUX---THUNK
//Returns a single profile
export const getProfile = (id) => {
   return (dispatch) => {
    axios.get('api/profile/'+id)
    .then((profile) => {
      dispatch(profileData(profile.data))
    })
  }
}

//------------------------------------------------//
const profileItem = (data) => {
  return {
    type: 'ADD_PROFILE_ITEM',
    payload: data
  }
}

export const addProfileItem = (profile) => {
  return (dispatch) => {
    dispatch(profileItem(profile))
  }
}

//------------------------------------------------//
const user_auth = (data) => ({
	type: "USER_LOGIN",
	data: data,
	profileData: data.Profile,
	destData: data.Profile.Destinations
})

export const userAuth = () => (
  (dispatch) => {
    axios.get('/')
    .then((user) => {
  		dispatch(user_auth(user.data))
    })
		// .then(() => {
		// 	history.push('/')
		// })
  }
);

//------------------------------------------------//
const newProfile = (data) => ({
  type: 'NEW_PROFILE',
  payload: data
  })

export const submitProfile = (data) => {
  return (dispatch) => {
    axios.post('/api/profile', data)
    .then((response) => {
      dispatch(newProfile(response.data))
      console.log(response)
    })
    .then(() => {
      history.push('/profile')
    })
  }
}

const addProfileImage = (data) => {
  return {
    type: 'ADD_PROFILE_IMAGE',
    payload: data.imagePath
  }
}

export const uploadImage = (form) => {
  return (dispatch) => {
    // const config = { headers: { 'Content-Type': 'multipart/form-data' } };
    axios.post("api/profile/upload", form)
    .then((imagePath) => {
        console.log(imagePath)
      dispatch(addProfileImage(imagePath.data))
    })
    .then(() => {
      history.push('/bio')
    })
  }
}


text:
package org.elasticsearch.rest;

import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionRequestBuilder;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.action.admin.cluster.state.ClusterStateRequest;
import org.elasticsearch.action.admin.cluster.stats.ClusterStatsRequest;
import org.elasticsearch.action.admin.indices.close.CloseIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.flush.FlushRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.Requests;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.rest.FakeRestRequest;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.Matchers.is;

public class HeadersAndContextCopyClientTests extends ESTestCase {

    public void testRegisterRelevantHeaders() throws InterruptedException {

        final RestController restController = new RestController(Settings.EMPTY);

        int iterations = randomIntBetween(1, 5);

        Set<String> headers = new HashSet<>();
        ExecutorService executorService = Executors.newFixedThreadPool(iterations);
        for (int i = 0; i < iterations; i++) {
            int headersCount = randomInt(10);
            final Set<String> newHeaders = new HashSet<>();
            for (int j = 0; j < headersCount; j++) {
                String usefulHeader = randomRealisticUnicodeOfLengthBetween(1, 30);
                newHeaders.add(usefulHeader);
            }
            headers.addAll(newHeaders);

            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    restController.registerRelevantHeaders(newHeaders.toArray(new String[newHeaders.size()]));
                }
            });
        }

        executorService.shutdown();
        assertThat(executorService.awaitTermination(1, TimeUnit.SECONDS), equalTo(true));
        String[] relevantHeaders = restController.relevantHeaders().toArray(new String[restController.relevantHeaders().size()]);
        assertThat(relevantHeaders.length, equalTo(headers.size()));

        Arrays.sort(relevantHeaders);
        String[] headersArray = new String[headers.size()];
        headersArray = headers.toArray(headersArray);
        Arrays.sort(headersArray);
        assertThat(relevantHeaders, equalTo(headersArray));
    }

    public void testCopyHeadersRequest() {
        Map<String, String> transportHeaders = randomHeaders(randomIntBetween(0, 10));
        Map<String, String> restHeaders = randomHeaders(randomIntBetween(0, 10));
        Map<String, String> copiedHeaders = randomHeadersFrom(restHeaders);
        Set<String> usefulRestHeaders = new HashSet<>(copiedHeaders.keySet());
        usefulRestHeaders.addAll(randomMap(randomIntBetween(0, 10), "useful-").keySet());
        Map<String, String> restContext = randomContext(randomIntBetween(0, 10));
        Map<String, String> transportContext = onlyOnLeft(randomContext(randomIntBetween(0, 10)), restContext);

        Map<String, String> expectedHeaders = new HashMap<>();
        expectedHeaders.putAll(transportHeaders);
        expectedHeaders.putAll(copiedHeaders);

        Map<String, String> expectedContext = new HashMap<>();
        expectedContext.putAll(transportContext);
        expectedContext.putAll(restContext);

        try (Client client = client(new NoOpClient(getTestName()), new FakeRestRequest(restHeaders, restContext), usefulRestHeaders)) {

            SearchRequest searchRequest = Requests.searchRequest();
            putHeaders(searchRequest, transportHeaders);
            putContext(searchRequest, transportContext);
            assertHeaders(searchRequest, transportHeaders);
            client.search(searchRequest);
            assertHeaders(searchRequest, expectedHeaders);
            assertContext(searchRequest, expectedContext);

            GetRequest getRequest = Requests.getRequest("index");
            putHeaders(getRequest, transportHeaders);
            putContext(getRequest, transportContext);
            assertHeaders(getRequest, transportHeaders);
            client.get(getRequest);
            assertHeaders(getRequest, expectedHeaders);
            assertContext(getRequest, expectedContext);

            IndexRequest indexRequest = Requests.indexRequest();
            putHeaders(indexRequest, transportHeaders);
            putContext(indexRequest, transportContext);
            assertHeaders(indexRequest, transportHeaders);
            client.index(indexRequest);
            assertHeaders(indexRequest, expectedHeaders);
            assertContext(indexRequest, expectedContext);
        }
    }

    public void testCopyHeadersClusterAdminRequest() {
        Map<String, String> transportHeaders = randomHeaders(randomIntBetween(0, 10));
        Map<String, String> restHeaders = randomHeaders(randomIntBetween(0, 10));
        Map<String, String> copiedHeaders = randomHeadersFrom(restHeaders);
        Set<String> usefulRestHeaders = new HashSet<>(copiedHeaders.keySet());
        usefulRestHeaders.addAll(randomMap(randomIntBetween(0, 10), "useful-").keySet());
        Map<String, String> restContext = randomContext(randomIntBetween(0, 10));
        Map<String, String> transportContext = onlyOnLeft(randomContext(randomIntBetween(0, 10)), restContext);

        HashMap<String, String> expectedHeaders = new HashMap<>();
        expectedHeaders.putAll(transportHeaders);
        expectedHeaders.putAll(copiedHeaders);

        Map<String, String> expectedContext = new HashMap<>();
        expectedContext.putAll(transportContext);
        expectedContext.putAll(restContext);

        try (Client client = client(new NoOpClient(getTestName()), new FakeRestRequest(restHeaders, expectedContext), usefulRestHeaders)) {

            ClusterHealthRequest clusterHealthRequest = Requests.clusterHealthRequest();
            putHeaders(clusterHealthRequest, transportHeaders);
            putContext(clusterHealthRequest, transportContext);
            assertHeaders(clusterHealthRequest, transportHeaders);
            client.admin().cluster().health(clusterHealthRequest);
            assertHeaders(clusterHealthRequest, expectedHeaders);
            assertContext(clusterHealthRequest, expectedContext);

            ClusterStateRequest clusterStateRequest = Requests.clusterStateRequest();
            putHeaders(clusterStateRequest, transportHeaders);
            putContext(clusterStateRequest, transportContext);
            assertHeaders(clusterStateRequest, transportHeaders);
            client.admin().cluster().state(clusterStateRequest);
            assertHeaders(clusterStateRequest, expectedHeaders);
            assertContext(clusterStateRequest, expectedContext);

            ClusterStatsRequest clusterStatsRequest = Requests.clusterStatsRequest();
            putHeaders(clusterStatsRequest, transportHeaders);
            putContext(clusterStatsRequest, transportContext);
            assertHeaders(clusterStatsRequest, transportHeaders);
            client.admin().cluster().clusterStats(clusterStatsRequest);
            assertHeaders(clusterStatsRequest, expectedHeaders);
            assertContext(clusterStatsRequest, expectedContext);
        }
    }

    public void testCopyHeadersIndicesAdminRequest() {
        Map<String, String> transportHeaders = randomHeaders(randomIntBetween(0, 10));
        Map<String, String> restHeaders = randomHeaders(randomIntBetween(0, 10));
        Map<String, String> copiedHeaders = randomHeadersFrom(restHeaders);
        Set<String> usefulRestHeaders = new HashSet<>(copiedHeaders.keySet());
        usefulRestHeaders.addAll(randomMap(randomIntBetween(0, 10), "useful-").keySet());
        Map<String, String> restContext = randomContext(randomIntBetween(0, 10));
        Map<String, String> transportContext = onlyOnLeft(randomContext(randomIntBetween(0, 10)), restContext);

        HashMap<String, String> expectedHeaders = new HashMap<>();
        expectedHeaders.putAll(transportHeaders);
        expectedHeaders.putAll(copiedHeaders);

        Map<String, String> expectedContext = new HashMap<>();
        expectedContext.putAll(transportContext);
        expectedContext.putAll(restContext);

        try (Client client = client(new NoOpClient(getTestName()), new FakeRestRequest(restHeaders, restContext), usefulRestHeaders)) {

            CreateIndexRequest createIndexRequest = Requests.createIndexRequest("test");
            putHeaders(createIndexRequest, transportHeaders);
            putContext(createIndexRequest, transportContext);
            assertHeaders(createIndexRequest, transportHeaders);
            client.admin().indices().create(createIndexRequest);
            assertHeaders(createIndexRequest, expectedHeaders);
            assertContext(createIndexRequest, expectedContext);

            CloseIndexRequest closeIndexRequest = Requests.closeIndexRequest("test");
            putHeaders(closeIndexRequest, transportHeaders);
            putContext(closeIndexRequest, transportContext);
            assertHeaders(closeIndexRequest, transportHeaders);
            client.admin().indices().close(closeIndexRequest);
            assertHeaders(closeIndexRequest, expectedHeaders);
            assertContext(closeIndexRequest, expectedContext);

            FlushRequest flushRequest = Requests.flushRequest();
            putHeaders(flushRequest, transportHeaders);
            putContext(flushRequest, transportContext);
            assertHeaders(flushRequest, transportHeaders);
            client.admin().indices().flush(flushRequest);
            assertHeaders(flushRequest, expectedHeaders);
            assertContext(flushRequest, expectedContext);
        }
    }

    public void testCopyHeadersRequestBuilder() {
        Map<String, String> transportHeaders = randomHeaders(randomIntBetween(0, 10));
        Map<String, String> restHeaders = randomHeaders(randomIntBetween(0, 10));
        Map<String, String> copiedHeaders = randomHeadersFrom(restHeaders);
        Set<String> usefulRestHeaders = new HashSet<>(copiedHeaders.keySet());
        usefulRestHeaders.addAll(randomMap(randomIntBetween(0, 10), "useful-").keySet());
        Map<String, String> restContext = randomContext(randomIntBetween(0, 10));
        Map<String, String> transportContext = onlyOnLeft(randomContext(randomIntBetween(0, 10)), restContext);

        HashMap<String, String> expectedHeaders = new HashMap<>();
        expectedHeaders.putAll(transportHeaders);
        expectedHeaders.putAll(copiedHeaders);

        Map<String, String> expectedContext = new HashMap<>();
        expectedContext.putAll(transportContext);
        expectedContext.putAll(restContext);

        try (Client client = client(new NoOpClient(getTestName()), new FakeRestRequest(restHeaders, restContext), usefulRestHeaders)) {

            ActionRequestBuilder requestBuilders[] = new ActionRequestBuilder[]{
                    client.prepareIndex("index", "type"),
                    client.prepareGet("index", "type", "id"),
                    client.prepareBulk(),
                    client.prepareDelete(),
                    client.prepareIndex(),
                    client.prepareClearScroll(),
                    client.prepareMultiGet(),
            };

            for (ActionRequestBuilder requestBuilder : requestBuilders) {
                putHeaders(requestBuilder.request(), transportHeaders);
                putContext(requestBuilder.request(), transportContext);
                assertHeaders(requestBuilder.request(), transportHeaders);
                requestBuilder.get();
                assertHeaders(requestBuilder.request(), expectedHeaders);
                assertContext(requestBuilder.request(), expectedContext);
            }
        }
    }

    public void testCopyHeadersClusterAdminRequestBuilder() {
        Map<String, String> transportHeaders = randomHeaders(randomIntBetween(0, 10));
        Map<String, String> restHeaders = randomHeaders(randomIntBetween(0, 10));
        Map<String, String> copiedHeaders = randomHeadersFrom(restHeaders);
        Set<String> usefulRestHeaders = new HashSet<>(copiedHeaders.keySet());
        usefulRestHeaders.addAll(randomMap(randomIntBetween(0, 10), "useful-").keySet());
        Map<String, String> restContext = randomContext(randomIntBetween(0, 10));
        Map<String, String> transportContext = onlyOnLeft(randomContext(randomIntBetween(0, 10)), restContext);

        HashMap<String, String> expectedHeaders = new HashMap<>();
        expectedHeaders.putAll(transportHeaders);
        expectedHeaders.putAll(copiedHeaders);

        Map<String, String> expectedContext = new HashMap<>();
        expectedContext.putAll(transportContext);
        expectedContext.putAll(restContext);

        try (Client client = client(new NoOpClient(getTestName()), new FakeRestRequest(restHeaders, restContext), usefulRestHeaders)) {

            ActionRequestBuilder requestBuilders[] = new ActionRequestBuilder[]{
                    client.admin().cluster().prepareNodesInfo(),
                    client.admin().cluster().prepareClusterStats(),
                    client.admin().cluster().prepareState(),
                    client.admin().cluster().prepareCreateSnapshot("repo", "name"),
                    client.admin().cluster().prepareHealth(),
                    client.admin().cluster().prepareReroute()
            };

            for (ActionRequestBuilder requestBuilder : requestBuilders) {
                putHeaders(requestBuilder.request(), transportHeaders);
                putContext(requestBuilder.request(), transportContext);
                assertHeaders(requestBuilder.request(), transportHeaders);
                requestBuilder.get();
                assertHeaders(requestBuilder.request(), expectedHeaders);
                assertContext(requestBuilder.request(), expectedContext);
            }
        }
    }

    public void testCopyHeadersIndicesAdminRequestBuilder() {
        Map<String, String> transportHeaders = randomHeaders(randomIntBetween(0, 10));
        Map<String, String> restHeaders = randomHeaders(randomIntBetween(0, 10));
        Map<String, String> copiedHeaders = randomHeadersFrom(restHeaders);
        Set<String> usefulRestHeaders = new HashSet<>(copiedHeaders.keySet());
        usefulRestHeaders.addAll(randomMap(randomIntBetween(0, 10), "useful-").keySet());
        Map<String, String> restContext = randomContext(randomIntBetween(0, 10));
        Map<String, String> transportContext = onlyOnLeft(randomContext(randomIntBetween(0, 10)), restContext);

        HashMap<String, String> expectedHeaders = new HashMap<>();
        expectedHeaders.putAll(transportHeaders);
        expectedHeaders.putAll(copiedHeaders);

        Map<String, String> expectedContext = new HashMap<>();
        expectedContext.putAll(transportContext);
        expectedContext.putAll(restContext);

        try (Client client = client(new NoOpClient(getTestName()), new FakeRestRequest(restHeaders, restContext), usefulRestHeaders)) {

            ActionRequestBuilder requestBuilders[] = new ActionRequestBuilder[]{
                    client.admin().indices().prepareValidateQuery(),
                    client.admin().indices().prepareCreate("test"),
                    client.admin().indices().prepareAliases(),
                    client.admin().indices().prepareAnalyze("text"),
                    client.admin().indices().prepareDeleteWarmer(),
                    client.admin().indices().prepareTypesExists("type"),
                    client.admin().indices().prepareClose()
            };

            for (ActionRequestBuilder requestBuilder : requestBuilders) {
                putHeaders(requestBuilder.request(), transportHeaders);
                putContext(requestBuilder.request(), transportContext);
                assertHeaders(requestBuilder.request(), transportHeaders);
                requestBuilder.get();
                assertHeaders(requestBuilder.request(), expectedHeaders);
                assertContext(requestBuilder.request(), expectedContext);
            }
        }
    }

    private static Map<String, String> randomHeaders(int count) {
        return randomMap(count, "header-");
    }

    private static Map<String, String> randomContext(int count) {
        return randomMap(count, "context-");
    }

    private static Map<String, String> randomMap(int count, String prefix) {
        Map<String, String> headers = new HashMap<>();
        for (int i = 0; i < count; i++) {
            headers.put(prefix + randomInt(30), randomAsciiOfLength(10));
        }
        return headers;
    }

    private static Map<String, String> randomHeadersFrom(Map<String, String> headers) {
        Map<String, String> newHeaders = new HashMap<>();
        if (headers.isEmpty()) {
            return newHeaders;
        }
        int i = randomInt(headers.size() - 1);
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            if (randomInt(i) == 0) {
                newHeaders.put(entry.getKey(), entry.getValue());
            }
        }
        return newHeaders;
    }

    private static Client client(Client noOpClient, RestRequest restRequest, Set<String> usefulRestHeaders) {
        return new BaseRestHandler.HeadersAndContextCopyClient(noOpClient, restRequest, usefulRestHeaders);
    }

    private static void putHeaders(ActionRequest<?> request, Map<String, String> headers) {
        for (Map.Entry<String, String> header : headers.entrySet()) {
            request.putHeader(header.getKey(), header.getValue());
        }
    }

    private static void putContext(ActionRequest<?> request, Map<String, String> context) {
        for (Map.Entry<String, String> header : context.entrySet()) {
            request.putInContext(header.getKey(), header.getValue());
        }
    }

    private static void assertHeaders(ActionRequest<?> request, Map<String, String> headers) {
        if (headers.size() == 0) {
            assertThat(request.getHeaders() == null || request.getHeaders().size() == 0, equalTo(true));
        } else {
            assertThat(request.getHeaders(), notNullValue());
            assertThat(request.getHeaders().size(), equalTo(headers.size()));
            for (String key : request.getHeaders()) {
                assertThat(headers.get(key), equalTo(request.getHeader(key)));
            }
        }
    }

    private static void assertContext(ActionRequest<?> request, Map<String, String> context) {
        if (context.size() == 0) {
            assertThat(request.isContextEmpty(), is(true));
        } else {
            ImmutableOpenMap map = request.getContext();
            assertThat(map, notNullValue());
            assertThat(map.size(), equalTo(context.size()));
            for (Object key : map.keys()) {
                assertThat(context.get(key), equalTo(request.getFromContext(key)));
            }
        }
    }

    private static Map<String, String> onlyOnLeft(Map<String, String> left, Map<String, String> right) {
        Map<String, String> map = new HashMap<>();
        for (Map.Entry<String, String> entry : left.entrySet()) {
            if (!right.containsKey(entry.getKey())) {
                map.put(entry.getKey(), entry.getValue());
            }
        }
        return map;
    }
}


text:
package org.adligo.i.adi.shared;

import org.adligo.i.adi.shared.heavy.HeavyStandardInvokers;
import org.adligo.i.adi.shared.light.CacheReader;
import org.adligo.i.adi.shared.light.CacheRemover;
import org.adligo.i.adi.shared.light.CacheWriter;
import org.adligo.i.adi.shared.light.LightStandardInvokers;
import org.adligo.i.adi.shared.light.MemoryReader;
import org.adligo.i.adi.shared.light.MemoryWriter;
import org.adligo.i.util.shared.Platform;

public class StandardInvokers {
	private static final ProxyInvoker CLOCK =
		   new ProxyInvoker(InvokerNames.CLOCK, SimpleClock.INSTANCE);

	private static final ProxyInvoker CONFIG_PROVIDER =
		new ProxyInvoker(InvokerNames.CONFIGURATION_PROVIDER,
				new BaseConfigProvider());
	private static final ProxyInvoker OUT =
		   new ProxyInvoker(InvokerNames.OUT, SimpleSystemOut.INSTANCE);
	private static final ProxyInvoker ERR =
		   new ProxyInvoker(InvokerNames.ERR, SimpleSystemErr.INSTANCE);

	private static final ProxyInvoker I18N_CONSTANTS_FACTORY =
			new ProxyInvoker(InvokerNames.CONSTANTS_FACTORY, I18nConstantsFactory.INSTANCE);

	/**
	 * can't even be done with a I_Map due to init issues
	 * @param name
	 */
	public static final ProxyInvoker get(String name) {
		if (Platform.getPlatform() == Platform.JSE) {
			ProxyInvoker toRet = HeavyStandardInvokers.get(name);
			if (toRet != null) {
				return toRet;
			}
		} else {
			ProxyInvoker toRet = LightStandardInvokers.get(name);
			if (toRet != null) {
				return toRet;
			}
		}

		if (InvokerNames.CONFIGURATION_PROVIDER.equals(name)) {
			return CONFIG_PROVIDER;
		}
		if (InvokerNames.CLOCK.equals(name)) {
			return CLOCK;
		}
		if (InvokerNames.OUT.equals(name)) {
			return OUT;
		}
		if (InvokerNames.ERR.equals(name)) {
			return ERR;
		}
		if (InvokerNames.CONSTANTS_FACTORY.equals(name)) {
			return I18N_CONSTANTS_FACTORY;
		}
		return null;
	}

	/**
	 * this method should be called to lock
	 * all of the standard invokers
	 */
	public static void lockStandardInvokers() {
		Registry.lockInvoker(InvokerNames.CACHE_READER);
		Registry.lockInvoker(InvokerNames.CACHE_WRITER);
		Registry.lockInvoker(InvokerNames.CACHE_REMOVER);
		Registry.lockInvoker(InvokerNames.MEMORY_READER);
		Registry.lockInvoker(InvokerNames.MEMORY_WRITER);

		Registry.lockInvoker(InvokerNames.CLOCK);
		Registry.lockInvoker(InvokerNames.CONFIGURATION_PROVIDER);
		Registry.lockInvoker(InvokerNames.CONSTANTS_FACTORY);
	}
}


text:
@implementation NSString (CoreExt)

-(BOOL)isBlank {
    // Note that [string length] == 0 can be false when [string isEqualToString:@""] is true, because these are Unicode strings.
    NSString *string = [self stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
    return [string isEqualToString:@""];
}

-(BOOL)isPresent {
    return ![self isBlank];
}

@end


text:
package pub.weber.bym.uicustomviews;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
    }
}


text:
<?php
namespace Bee\MVC\View;

/**
 * Uses a PHP-includable resource (usually a local PHP file) to render the view output. Standard view for web pages.
 *
 * @author Benjamin Hartmann
 * @author Michael Plomer <michael.plomer@iter8.de>
 *
 * @deprecated
 */
class XhtmlView extends TextView {

	const CONTENT_TYPE_XHTML = 'application/xhtml+xml';
	const CONTENT_TYPE_XML = 'application/xml';

	const DEFAULT_ROOT_TAG = 'html';
	const DEFAULT_NAMESPACE = 'http://www.w3.org/1999/xhtml';

	private $rootTag;
	private $defaultNamespace;

	public function __construct() {
		parent::__construct();  // sets default content type to 'text/html'

		if(stristr($_SERVER["HTTP_ACCEPT"], self::CONTENT_TYPE_XHTML)) {
			# if there's a Q value for "application/xhtml+xml" then also
			# retrieve the Q value for "text/html"
			if(preg_match("/application\/xhtml\+xml;q=0(\.[1-9]+)/i", $_SERVER["HTTP_ACCEPT"], $matches)) {
				$xhtml_q = $matches[1];
				if(preg_match("/text\/html;q=0(\.[1-9]+)/i", $_SERVER["HTTP_ACCEPT"], $matches)) {
					$html_q = $matches[1];
					# if the Q value for XHTML is greater than or equal to that
					# for HTML then use the "application/xhtml+xml" mimetype
					if($xhtml_q >= $html_q) {
						$this->setContentType(self::CONTENT_TYPE_XHTML);
					}
				}
				# if there was no Q value, then just use the
				# "application/xhtml+xml" mimetype
			} else {
				$this->setContentType(self::CONTENT_TYPE_XHTML);
   			}
		}

		# special check for the W3C_Validator
		if (stristr($_SERVER["HTTP_USER_AGENT"],"W3C_Validator")) {
		   $this->setContentType(self::CONTENT_TYPE_XHTML);
		}

		$this->rootTag = self::DEFAULT_ROOT_TAG;
		$this->defaultNamespace = self::DEFAULT_NAMESPACE;
	}

	public function getRootTag() {
		return $this->rootTag;
	}

	public function setRootTag($rootTag) {
		$this->rootTag = $rootTag;
	}

	public function getDefaultNamespace() {
		return $this->defaultNamespace;
	}

	public function setDefaultNamespace($defaultNamespace) {
		$this->defaultNamespace = $defaultNamespace;
	}

	protected function renderDoctypePrologue() {
		$mime = $this->getContentType();
		if($mime == self::CONTENT_TYPE_XHTML) {
			$charset = $this->getCharset();
			$prolog_type = "<?xml version='1.0' encoding='$charset' ?>\n<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.1//EN'\n\t'http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd'>\n";
		} else if($mime == self::CONTENT_TYPE_XML) {
			$charset = $this->getCharset();
			$prolog_type = "<?xml version='1.0' encoding='$charset' ?>\n";
		} else {
   			$prolog_type = "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01//EN'\n\t'http://www.w3.org/TR/html4/strict.dtd'>\n";
		}
		echo $prolog_type;
	}

	protected function renderRootElementStart() {
		if($this->getContentType() == self::CONTENT_TYPE_XHTML) {
			// @todo: additional namespaces
			echo "<$this->rootTag xmlns='$this->defaultNamespace'>\n";
		} else {
			echo "<$this->rootTag>\n";
		}
	}

	protected function renderRootElementEnd() {
		echo "\n</$this->rootTag>";
	}

	/**
	 * Render the internal resource given the specified model.
	 * This includes setting the model as request attributes.
	 */
	protected function renderMergedOutputModel() {
		$this->renderDoctypePrologue();
		$this->renderRootElementStart();
		parent::renderMergedOutputModel();
		$this->renderRootElementEnd();
	}
}


text:
# licy.js

[![Build Status]](https://travis-ci.org/mantoni/licy.js)
[![SemVer]](http://semver.org)
[![License]](https://github.com/mantoni/licy.js/blob/master/LICENSE)

Objects with managed lifecycles for Node and the browser.

## Features

- Async creation: Function calls are automatically deferred until constructor
  invokes callback
- All function calls are observable and can be intercepted
- Create hierarchies of instances that get destroyed together

## How does it work?

Licy types can be defined in two ways. Using an object:

```js
var Hello = licy.define({
  constructor: function (name) {
    this.name = name;
  },
  log: function () {
    console.log('Hello ' + this.name);
  }
});
```

Or using a function:

```js
var Hello = licy.define(function (name) {
  return {
    log: function () {
      console.log('Hello ' + name);
    }
  };
});
```

Types that where defined with licy can be newed up like any other JavaScript
type. Both of the examples above can be used like this:

```js
var hello = new Hello('world');
hello.log(); // logs "Hello world"
```

### Async object creation

Any defined type can be changed to be created asynchronously:

```js
var Hello = licy.define(function (name, callback) {
  setTimeout(callback, 500);
  return { /* as above */ };
});

var hello = new Hello('world');
hello.log(); // logs "Hello world" after 500 milliseconds
```

All function calls will be implicitly deferred until the constructor invoked
the callback.

As a consequence, obtaining the return value of a function only works with
callbacks:

```js
var Hello = licy.define(function (name) {
  return {
    get: function () {
      return 'Hello ' + name;
    }
  };
});

var hello = new Hello('world');

console.log(hello.get()); // logs "Hello undefined"
hello.get(function (err, value) {
  console.log(value); // logs "Hello world"
});
```

Note that the callback follows the Node.js `(err, value)` convention.

### Observing and intercepting calls

Each licy instance inherits the [hub.js][] event emitter API and emits an event
for each function call:

```js
hello.on('log', function () {
  // Invoked on hello.log() calls
});
```

[Filters][filter] can be used to intercept calls:

```js
hello.addFilter('log', function (next) {
  // Defer all calls by 500 milliseconds:
  setTimeout(function () {
    next();
  }, 500);
});
```

### Destroying instances

Each licy instance has a `destroy([callback])` implementation which emits a
`"destroy"` event and invokes the defined `destroy` function, if given:

```js
var Hello = licy.define(function (name) {
  return {
    destroy: function () {
      console.log('Bye ' + name);
    }
  };
});

var hello = new Hello('world');

hello.destroy();
```

Calling `licy.destroy()` will destroy all existing licy instances. This can be
used to shut down an application cleanly, e.g. closing a server gracefully.

To bind the lifecycle of one object to another, invoke `a.destroyWith(b)`. Use
`create(definition)` to bind a child object to a parent: `var b = a.create(B)`.

## Install with npm

    npm install licy --save

## Browser support

Use [Browserify][] to create a standalone file. The licy test suite passes on
IE 9, 10, 11, Chrome \*, Filefox \* and PhantomJS.

## API

Licy is a [hub.js][] instance with these additions:

- `Licy`: The `Licy` constructor (`licy instanceof licy.Licy` is `true`)
- `define([definition])`: Defines a new type. The `definition` must be either
  ommitted, of type `function` or an `object`:
    - No `definition`: A plain licy type is returned that creates objects with
      the same API as the parent object.
    - `function`: The function is used as the constructor and is expected to
      return the API as an object.
    - `object`: Defines the API directly. A `constructor` can be defined
      optionally.
  The returned type creates new Licy instances. Each instance is derived from
  Licy itself and also inherits the [hub.js][] API. All created instances are
  destroyed when the defining instance is destroyed.
- `create([definition])`: Creates an instance that will be destroyed with this
  instance. If `definition` is not a type, `define(definition)` is called
  before creating an instance.
- `destroy([callback])`: Emits the `destroy` event on the licy instance and all
  children. If a callback is given, it is invoked after this instance and all
  children are destroyed. If an error occurred, it is passed as the only
  argument to the callback.
- `destroyWith(type)`: Destroy this instance when `type` is destroyed.
- `extend(Super, definition)`: Defines a new type which is derived from the
  `Super` type. Instances of the new type are `instanceof Super`. If a
  constructor is given, or if `definition` is a function, the super constructor
  must be explicitly invoked with `Super.super_.call(this)`. If a method is
  defined that already exists in the super type, it is registered as a
  [filter][].

## Type API

Each type returned by `licy.define()` is a Licy instance with these additions:

- `Type.extend(definition)`: Is a shortcut for `licy.extend(Type, definition)`.

## Events

Each type instance and the root licy object emit these events:

- `define(type, callback)`: When a new child type is defined.
- `create(instance, type, callback)`: When a child instance is created.
- `destroy(callback)`: When the instance is destroyed.

The `prototype` of custom defined types is a licy instance itself. It can be
used to emit and subscribe global type specific events. These events are always
emitted:

- `instance.create(instance, type, callback)`: When a new instance is created.
- `instance.destroy(instance, error, callback)`: When an instance is destroyed.
  If an error occurred during destruction, the Error is passed on as `error`.

## Development

- `npm install` to install the dev dependencies
- `npm test` to lint, run tests on Node and PhantomJS and check code coverage

## License

MIT

[Build Status]: http://img.shields.io/travis/mantoni/licy.js.svg
[SemVer]: http://img.shields.io/:semver-%E2%9C%93-brightgreen.svg
[License]: http://img.shields.io/npm/l/licy.svg
[Browserify]: http://browserify.org
[hub.js]: http://github.com/mantoni/hub.js
[filter]: https://github.com/mantoni/glob-filter.js


text:
<?xml version="1.0" encoding="UTF-8"?>
<b:beans xmlns="http://www.springframework.org/schema/security"
         xmlns:b="http://www.springframework.org/schema/beans"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">

       <!-- 不要过滤图片等静态资源 -->
       <http pattern="/**/*.jpg" security="none"/>
       <http pattern="/**/*.png" security="none"/>
       <http pattern="/**/*.gif" security="none"/>
       <http pattern="/**/*.css" security="none"/>
       <http pattern="/**/*.js" security="none"/>
       <http pattern="/font/**" security="none"/>
       <http pattern="/css/**" security="none"/>
       <http pattern="/js/**" security="none"/>
       <!-- 登录页面和忘记密码页面不过滤  -->
       <http pattern="/accessDenied" security="none"/>
       <http pattern="/sessionTimeout" security="none"/>

       <http auto-config="true" use-expressions="true">
              <form-login login-page="/login" login-processing-url="/checkLogin"
                          authentication-failure-handler-ref="myAuthenticationFailureHandler"
                          authentication-success-handler-ref="myAuthenticationSuccessHandler"/>

             <!--   <intercept-url pattern="/admin/**"  access="hasRole('admin')"/>
                <intercept-url pattern="/fundmanager/**"  access="hasRole('fm')"/>  -->

              <headers><frame-options policy="SAMEORIGIN"/> </headers>
              <access-denied-handler ref="myAccessDeniedHandler"/>

              <session-management session-fixation-protection="migrateSession">
                     <concurrency-control max-sessions="1"
                                          error-if-maximum-exceeded="false" expired-url="/index" session-registry-ref="mySessionRegistry" />
              </session-management>

              <logout invalidate-session="true" logout-url="/logout"  success-handler-ref="myLogoutSuccessHandler" />

              <custom-filter ref="myFilter" before="FILTER_SECURITY_INTERCEPTOR" />
              <csrf disabled="true"/>
              <!--<remember-me user-service-ref="myUserDetailService"/>-->
       </http>

       <!--handler包括登录验证失败,登录验证成功,访问资源权限不够-->
       <b:bean name="myAuthenticationFailureHandler" class="com.portfoliomanager.security.MyAuthenticationFailureHandler">
              <b:property name="defaultFailureUrl" value="/autFailed"/>
       </b:bean>

       <b:bean name="myAuthenticationSuccessHandler" class="com.portfoliomanager.security.MyAuthenticationSuccessHandler">
              <b:property name="defaultTargetUrl" value="/loginSuccess"/>
       </b:bean>

       <b:bean name="myLogoutSuccessHandler" class="com.portfoliomanager.security.MyLogoutSuccessHandler">
              <b:property name="defaultTargetUrl" value="/logoutSuccess" />
       </b:bean>

       <b:bean name="myAccessDeniedHandler" class="com.portfoliomanager.security.MyAccessDeniedHandler">
              <b:property name="errorPage" value="/accessDenied" />
       </b:bean>
       <!--一个自定义的filter,必须包含 authenticationManager,accessDecisionManager,securityMetadataSource三个属性,
              我们的所有控制将在这三个类中实现,解释详见具体配置 -->
       <b:bean id="myFilter"
               class="com.portfoliomanager.security.MyFilterSecurityInterceptor">
              <b:property name="authenticationManager" ref="authenticationManager" />
              <b:property name="accessDecisionManager" ref="myAccessDecisionManager"/>
              <b:property name="securityMetadataSource" ref="securityMetadataSource" />
       </b:bean>
       <!--验证配置,认证管理器,实现用户认证的入口,主要实现UserDetailsService接口即可 -->
       <authentication-manager alias="authenticationManager">
              <authentication-provider ref="myAuthenticationProvider"/>
       </authentication-manager>

       <b:bean id="myAuthenticationProvider"
               class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
              <!--验证用户-->
              <b:property name="userDetailsService" ref="myUserDetailService" />
              <!--显示用户错误信息-->
              <b:property name="hideUserNotFoundExceptions" value="false" />
              <!--md5加密-->
              <b:property name="passwordEncoder" ref="myPasswordEncoder" />
              <!--盐值-->
              <b:property name="saltSource" ref="mySaltSource"/>
       </b:bean>

       <!--在这个类中,你就可以从数据库中读入用户的密码,角色信息,是否锁定,账号是否过期等 -->
       <b:bean id="myUserDetailService" class="com.portfoliomanager.security.MyUserDetailService"/>
       <!--访问决策器,决定某个用户具有的角色,是否有足够的权限去访问某个资源 -->
       <b:bean id="myAccessDecisionManager"
               class="com.portfoliomanager.security.MyAccessDecisionManager" />

       <!--md5加密策略-->
       <b:bean id="myPasswordEncoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder"/>

       <!--配置盐值-->
       <b:bean id="mySaltSource" class="org.springframework.security.authentication.dao.ReflectionSaltSource">
              <b:property name="userPropertyToUse" value="getUsername" />
       </b:bean>

       <!--资源源数据定义,将所有的资源和权限对应关系建立起来,即定义某一资源可以被哪些角色访问 -->
       <b:bean id="securityMetadataSource"
               class="com.portfoliomanager.security.MyInvocationSecurityMetadataSource" />

       <!--session策略-->
       <b:bean id="mySessionRegistry" class="com.portfoliomanager.security.MySessionRegistry"/>

       <!--自定义Security上下文-->
       <b:bean id = "mySecurityContext" class="com.portfoliomanager.security.MySecurityContext">
              <b:property name="mySessionRegistry" ref="mySessionRegistry"/>
              <b:property name="myAuthenticationManager" ref="authenticationManager"/>
       </b:bean>
</b:beans>