text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.camunda.bpm.engine.rest;

import static com.jayway.restassured.RestAssured.given;
import static org.camunda.bpm.engine.authorization.Permissions.DELETE;
import static org.camunda.bpm.engine.authorization.Permissions.UPDATE;
import static org.camunda.bpm.engine.authorization.Resources.USER;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.Response.Status;

import org.camunda.bpm.engine.AuthorizationException;
import org.camunda.bpm.engine.AuthorizationService;
import org.camunda.bpm.engine.IdentityService;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.identity.User;
import org.camunda.bpm.engine.identity.UserQuery;
import org.camunda.bpm.engine.impl.identity.Authentication;
import org.camunda.bpm.engine.rest.dto.identity.UserCredentialsDto;
import org.camunda.bpm.engine.rest.dto.identity.UserDto;
import org.camunda.bpm.engine.rest.dto.identity.UserProfileDto;
import org.camunda.bpm.engine.rest.exception.InvalidRequestException;
import org.camunda.bpm.engine.rest.helper.MockProvider;
import org.camunda.bpm.engine.rest.util.container.TestContainerRule;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;

import com.jayway.restassured.http.ContentType;

/**
 * @author Daniel Meyer
 *
 */
public class UserRestServiceInteractionTest extends AbstractRestServiceTest {

  @ClassRule
  public static TestContainerRule rule = new TestContainerRule();

  protected static final String SERVICE_URL = TEST_RESOURCE_ROOT_PATH + "/user";
  protected static final String USER_URL = SERVICE_URL + "/{id}";
  protected static final String USER_CREATE_URL = SERVICE_URL + "/create";
  protected static final String USER_PROFILE_URL = USER_URL + "/profile";
  protected static final String USER_CREDENTIALS_URL = USER_URL + "/credentials";

  protected IdentityService identityServiceMock;
  protected AuthorizationService authorizationServiceMock;

  @Before
  public void setupUserData() {

    identityServiceMock = mock(IdentityService.class);
    authorizationServiceMock = mock(AuthorizationService.class);

    // mock identity service
    when(processEngine.getIdentityService()).thenReturn(identityServiceMock);
    // authorization service
    when(processEngine.getAuthorizationService()).thenReturn(authorizationServiceMock);

  }

  @Test
  public void testGetSingleUserProfile() {
    User sampleUser = MockProvider.createMockUser();
    UserQuery sampleUserQuery = mock(UserQuery.class);
    when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery);
    when(sampleUserQuery.userId(MockProvider.EXAMPLE_USER_ID)).thenReturn(sampleUserQuery);
    when(sampleUserQuery.singleResult()).thenReturn(sampleUser);

    given()
        .pathParam("id", MockProvider.EXAMPLE_USER_ID)
    .then()
        .statusCode(Status.OK.getStatusCode())
        .body("id", equalTo(MockProvider.EXAMPLE_USER_ID))
        .body("firstName", equalTo(MockProvider.EXAMPLE_USER_FIRST_NAME))
        .body("lastName", equalTo(MockProvider.EXAMPLE_USER_LAST_NAME))
        .body("email", equalTo(MockProvider.EXAMPLE_USER_EMAIL))
    .when()
        .get(USER_PROFILE_URL);
  }

  @Test
  public void testUserRestServiceOptions() {
    String fullAuthorizationUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + UserRestService.PATH;

    given()
      .then()
        .statusCode(Status.OK.getStatusCode())

        .body("links[0].href", equalTo(fullAuthorizationUrl))
        .body("links[0].method", equalTo(HttpMethod.GET))
        .body("links[0].rel", equalTo("list"))

        .body("links[1].href", equalTo(fullAuthorizationUrl+"/count"))
        .body("links[1].method", equalTo(HttpMethod.GET))
        .body("links[1].rel", equalTo("count"))

        .body("links[2].href", equalTo(fullAuthorizationUrl+"/create"))
        .body("links[2].method", equalTo(HttpMethod.POST))
        .body("links[2].rel", equalTo("create"))

    .when()
        .options(SERVICE_URL);

    verify(identityServiceMock, times(1)).getCurrentAuthentication();

  }

  @Test
  public void testUserResourceOptionsUnauthenticated() {
    String fullUserUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + "/user/" + MockProvider.EXAMPLE_USER_ID;

    User sampleUser = MockProvider.createMockUser();
    UserQuery sampleUserQuery = mock(UserQuery.class);
    when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery);
    when(sampleUserQuery.userId(MockProvider.EXAMPLE_USER_ID)).thenReturn(sampleUserQuery);
    when(sampleUserQuery.singleResult()).thenReturn(sampleUser);
    when(identityServiceMock.getCurrentAuthentication()).thenReturn(null);

    given()
        .pathParam("id", MockProvider.EXAMPLE_USER_ID)
    .then()
        .statusCode(Status.OK.getStatusCode())

        .body("links[0].href", equalTo(fullUserUrl+"/profile"))
        .body("links[0].method", equalTo(HttpMethod.GET))
        .body("links[0].rel", equalTo("self"))

        .body("links[1].href", equalTo(fullUserUrl))
        .body("links[1].method", equalTo(HttpMethod.DELETE))
        .body("links[1].rel", equalTo("delete"))

        .body("links[2].href", equalTo(fullUserUrl+"/profile"))
        .body("links[2].method", equalTo(HttpMethod.PUT))
        .body("links[2].rel", equalTo("update"))

    .when()
        .options(USER_URL);

    verify(identityServiceMock, times(2)).getCurrentAuthentication();

  }

  @Test
  public void testUserResourceOptionsUnauthorized() {
    String fullUserUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + "/user/" + MockProvider.EXAMPLE_USER_ID;

    User sampleUser = MockProvider.createMockUser();
    UserQuery sampleUserQuery = mock(UserQuery.class);
    when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery);
    when(sampleUserQuery.userId(MockProvider.EXAMPLE_USER_ID)).thenReturn(sampleUserQuery);
    when(sampleUserQuery.singleResult()).thenReturn(sampleUser);

    Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, null);
    when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication);
    when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, USER, MockProvider.EXAMPLE_USER_ID)).thenReturn(false);
    when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, UPDATE, USER, MockProvider.EXAMPLE_USER_ID)).thenReturn(false);

    given()
        .pathParam("id", MockProvider.EXAMPLE_USER_ID)
    .then()
        .statusCode(Status.OK.getStatusCode())

        .body("links[0].href", equalTo(fullUserUrl+"/profile"))
        .body("links[0].method", equalTo(HttpMethod.GET))
        .body("links[0].rel", equalTo("self"))

        .body("links[1]", nullValue())
        .body("links[2]", nullValue())

    .when()
        .options(USER_URL);

    verify(identityServiceMock, times(2)).getCurrentAuthentication();
    verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, USER, MockProvider.EXAMPLE_USER_ID);
    verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, UPDATE, USER, MockProvider.EXAMPLE_USER_ID);
  }

  @Test
  public void testUserResourceOptionsDeleteAuthorized() {
    String fullUserUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + "/user/" + MockProvider.EXAMPLE_USER_ID;

    User sampleUser = MockProvider.createMockUser();
    UserQuery sampleUserQuery = mock(UserQuery.class);
    when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery);
    when(sampleUserQuery.userId(MockProvider.EXAMPLE_USER_ID)).thenReturn(sampleUserQuery);
    when(sampleUserQuery.singleResult()).thenReturn(sampleUser);

    Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, null);
    when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication);
    when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, USER, MockProvider.EXAMPLE_USER_ID)).thenReturn(true);
    when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, UPDATE, USER, MockProvider.EXAMPLE_USER_ID)).thenReturn(false);

    given()
        .pathParam("id", MockProvider.EXAMPLE_USER_ID)
    .then()
        .statusCode(Status.OK.getStatusCode())

        .body("links[0].href", equalTo(fullUserUrl+"/profile"))
        .body("links[0].method", equalTo(HttpMethod.GET))
        .body("links[0].rel", equalTo("self"))

        .body("links[1].href", equalTo(fullUserUrl))
        .body("links[1].method", equalTo(HttpMethod.DELETE))
        .body("links[1].rel", equalTo("delete"))

        .body("links[2]", nullValue())

    .when()
        .options(USER_URL);

    verify(identityServiceMock, times(2)).getCurrentAuthentication();
    verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, USER, MockProvider.EXAMPLE_USER_ID);
    verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, UPDATE, USER, MockProvider.EXAMPLE_USER_ID);
  }

  @Test
  public void testGetNonExistingUserProfile() {
    UserQuery sampleUserQuery = mock(UserQuery.class);
    when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery);
    when(sampleUserQuery.userId(anyString())).thenReturn(sampleUserQuery);
    when(sampleUserQuery.singleResult()).thenReturn(null);

    given()
        .pathParam("id", "aNonExistingUser")
    .then()
        .statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON)
        .body("type", equalTo(InvalidRequestException.class.getSimpleName()))
        .body("message", equalTo("User with id aNonExistingUser does not exist"))
    .when()
        .get(USER_PROFILE_URL);
  }

  @Test
  public void testDeleteUser() {
    given()
        .pathParam("id", MockProvider.EXAMPLE_USER_ID)
    .then()
        .statusCode(Status.NO_CONTENT.getStatusCode())
    .when()
        .delete(USER_URL);
  }

  @Test
  public void testDeleteNonExistingUser() {
    given()
        .pathParam("id", "non-existing")
    .then()
        .statusCode(Status.NO_CONTENT.getStatusCode())
    .when()
        .delete(USER_URL);
  }

  @Test
  public void testDeleteUserThrowsAuthorizationException() {
    String message = "expected exception";
    doThrow(new AuthorizationException(message)).when(identityServiceMock).deleteUser(MockProvider.EXAMPLE_USER_ID);

    given()
        .pathParam("id", MockProvider.EXAMPLE_USER_ID)
    .then()
      .statusCode(Status.FORBIDDEN.getStatusCode())
      .contentType(ContentType.JSON)
      .body("type", equalTo(AuthorizationException.class.getSimpleName()))
      .body("message", equalTo(message))
    .when()
        .delete(USER_URL);
  }

  @Test
  public void testCreateNewUserWithCredentials() {
    User newUser = MockProvider.createMockUser();
    when(identityServiceMock.newUser(MockProvider.EXAMPLE_USER_ID)).thenReturn(newUser);

    UserDto userDto = UserDto.fromUser(newUser, true);

    given()
        .body(userDto).contentType(ContentType.JSON)
    .expect()
        .statusCode(Status.NO_CONTENT.getStatusCode())
    .when()
        .post(USER_CREATE_URL);

    verify(identityServiceMock).newUser(MockProvider.EXAMPLE_USER_ID);
    verify(newUser).setFirstName(MockProvider.EXAMPLE_USER_FIRST_NAME);
    verify(newUser).setLastName(MockProvider.EXAMPLE_USER_LAST_NAME);
    verify(newUser).setEmail(MockProvider.EXAMPLE_USER_EMAIL);
    verify(newUser).setPassword(MockProvider.EXAMPLE_USER_PASSWORD);
    verify(identityServiceMock).saveUser(newUser);
  }

  @Test
  public void testCreateNewUserWithoutCredentials() {
    User newUser = MockProvider.createMockUser();
    when(identityServiceMock.newUser(MockProvider.EXAMPLE_USER_ID)).thenReturn(newUser);

    UserDto userDto = UserDto.fromUser(newUser, false);

    given()
        .body(userDto).contentType(ContentType.JSON)
    .expect()
        .statusCode(Status.NO_CONTENT.getStatusCode())
    .when()
        .post(USER_CREATE_URL);

    verify(identityServiceMock).newUser(MockProvider.EXAMPLE_USER_ID);
    verify(newUser).setFirstName(MockProvider.EXAMPLE_USER_FIRST_NAME);
    verify(newUser).setLastName(MockProvider.EXAMPLE_USER_LAST_NAME);
    verify(newUser).setEmail(MockProvider.EXAMPLE_USER_EMAIL);
    // no password was set
    verify(newUser, never()).setPassword(any(String.class));

    verify(identityServiceMock).saveUser(newUser);
  }

  @Test
  public void testUserCreateExistingFails() {
    User newUser = MockProvider.createMockUser();
    when(identityServiceMock.newUser(MockProvider.EXAMPLE_USER_ID)).thenReturn(newUser);
    doThrow(new ProcessEngineException("")).when(identityServiceMock).saveUser(newUser);

    UserDto userDto = UserDto.fromUser(newUser, true);

    given()
      .body(userDto).contentType(ContentType.JSON)
    .then()
      .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON)
      .body("type", equalTo(ProcessEngineException.class.getSimpleName()))
    .when()
      .post(USER_CREATE_URL);

    verify(identityServiceMock).newUser(MockProvider.EXAMPLE_USER_ID);
    verify(identityServiceMock).saveUser(newUser);
  }

  @Test
  public void testUserCreateThrowsAuthorizationException() {
    User newUser = MockProvider.createMockUser();
    String message = "exception expected";
    when(identityServiceMock.newUser(MockProvider.EXAMPLE_USER_ID)).thenThrow(new AuthorizationException(message));

    UserDto userDto = UserDto.fromUser(newUser, true);

    given()
      .body(userDto)
      .contentType(ContentType.JSON)
    .then()
      .statusCode(Status.FORBIDDEN.getStatusCode())
      .contentType(ContentType.JSON)
      .body("type", equalTo(AuthorizationException.class.getSimpleName()))
      .body("message", equalTo(message))
    .when()
      .post(USER_CREATE_URL);
  }

  @Test
  public void testSaveNewUserThrowsAuthorizationException() {
    User newUser = MockProvider.createMockUser();
    when(identityServiceMock.newUser(MockProvider.EXAMPLE_USER_ID)).thenReturn(newUser);
    String message = "exception expected";
    doThrow(new AuthorizationException(message)).when(identityServiceMock).saveUser(newUser);

    UserDto userDto = UserDto.fromUser(newUser, true);

    given()
      .body(userDto)
      .contentType(ContentType.JSON)
    .then()
      .statusCode(Status.FORBIDDEN.getStatusCode())
      .contentType(ContentType.JSON)
      .body("type", equalTo(AuthorizationException.class.getSimpleName()))
      .body("message", equalTo(message))
    .when()
      .post(USER_CREATE_URL);
  }

  @Test
  public void testPutCredentials() {
    User initialUser = MockProvider.createMockUser();
    UserQuery sampleUserQuery = mock(UserQuery.class);
    when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery);
    when(sampleUserQuery.userId(MockProvider.EXAMPLE_USER_ID)).thenReturn(sampleUserQuery);
    when(sampleUserQuery.singleResult()).thenReturn(initialUser);

    UserCredentialsDto dto = new UserCredentialsDto();
    dto.setPassword("new-password");

    given()
        .pathParam("id", MockProvider.EXAMPLE_USER_ID)
        .body(dto).contentType(ContentType.JSON)
    .then()
        .statusCode(Status.NO_CONTENT.getStatusCode())
    .when()
        .put(USER_CREDENTIALS_URL);

    // password was updated
    verify(initialUser).setPassword(dto.getPassword());

    // and then saved
    verify(identityServiceMock).saveUser(initialUser);
  }

  @Test
  public void testPutCredentialsThrowsAuthorizationException() {
    User initialUser = MockProvider.createMockUser();
    UserQuery sampleUserQuery = mock(UserQuery.class);
    when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery);
    when(sampleUserQuery.userId(MockProvider.EXAMPLE_USER_ID)).thenReturn(sampleUserQuery);
    when(sampleUserQuery.singleResult()).thenReturn(initialUser);

    String message = "exception expected";
    doThrow(new AuthorizationException(message)).when(identityServiceMock).saveUser(any(User.class));

    UserCredentialsDto dto = new UserCredentialsDto();
    dto.setPassword("new-password");

    given()
        .pathParam("id", MockProvider.EXAMPLE_USER_ID)
        .body(dto).contentType(ContentType.JSON)
    .then()
      .statusCode(Status.FORBIDDEN.getStatusCode())
      .contentType(ContentType.JSON)
      .body("type", equalTo(AuthorizationException.class.getSimpleName()))
      .body("message", equalTo(message))
    .when()
        .put(USER_CREDENTIALS_URL);
  }

  @Test
  public void testChangeCredentials() {
    User initialUser = MockProvider.createMockUser();
    UserQuery sampleUserQuery = mock(UserQuery.class);
    when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery);
    when(sampleUserQuery.userId(MockProvider.EXAMPLE_USER_ID)).thenReturn(sampleUserQuery);
    when(sampleUserQuery.singleResult()).thenReturn(initialUser);

    Authentication authentication = MockProvider.createMockAuthentication();
    when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication);

    when(identityServiceMock.checkPassword(MockProvider.EXAMPLE_USER_ID, MockProvider.EXAMPLE_USER_PASSWORD)).thenReturn(true);

    UserCredentialsDto dto = new UserCredentialsDto();
    dto.setPassword("new-password");
    dto.setAuthenticatedUserPassword(MockProvider.EXAMPLE_USER_PASSWORD);

    given()
        .pathParam("id", MockProvider.EXAMPLE_USER_ID)
        .contentType(ContentType.JSON)
        .body(dto)
    .then()
        .statusCode(Status.NO_CONTENT.getStatusCode())
    .when()
        .put(USER_CREDENTIALS_URL);

    verify(identityServiceMock).getCurrentAuthentication();
    verify(identityServiceMock).checkPassword(MockProvider.EXAMPLE_USER_ID, MockProvider.EXAMPLE_USER_PASSWORD);

    // password was updated
    verify(initialUser).setPassword(dto.getPassword());

    // and then saved
    verify(identityServiceMock).saveUser(initialUser);
  }

  @Test
  public void testChangeCredentialsWithWrongAuthenticatedUserPassword() {
    User initialUser = MockProvider.createMockUser();
    UserQuery sampleUserQuery = mock(UserQuery.class);
    when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery);
    when(sampleUserQuery.userId(MockProvider.EXAMPLE_USER_ID)).thenReturn(sampleUserQuery);
    when(sampleUserQuery.singleResult()).thenReturn(initialUser);

    Authentication authentication = MockProvider.createMockAuthentication();
    when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication);

    when(identityServiceMock.checkPassword(MockProvider.EXAMPLE_USER_ID, MockProvider.EXAMPLE_USER_PASSWORD)).thenReturn(false);

    UserCredentialsDto dto = new UserCredentialsDto();
    dto.setPassword("new-password");
    dto.setAuthenticatedUserPassword(MockProvider.EXAMPLE_USER_PASSWORD);

    given()
        .pathParam("id", MockProvider.EXAMPLE_USER_ID)
        .contentType(ContentType.JSON)
        .body(dto)
    .then()
        .statusCode(Status.BAD_REQUEST.getStatusCode())
        .contentType(ContentType.JSON)
        .body("type", equalTo("InvalidRequestException"))
        .body("message", equalTo("The given authenticated user password is not valid."))
    .when()
        .put(USER_CREDENTIALS_URL);
  }

  @Test
  public void testPutCredentialsNonExistingUserFails() {
    UserQuery sampleUserQuery = mock(UserQuery.class);
    when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery);
    when(sampleUserQuery.userId("aNonExistingUser")).thenReturn(sampleUserQuery);
    when(sampleUserQuery.singleResult()).thenReturn(null);

    UserCredentialsDto dto = new UserCredentialsDto();
    dto.setPassword("new-password");

    given()
        .pathParam("id", "aNonExistingUser")
        .body(dto).contentType(ContentType.JSON)
    .then()
        .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON)
        .body("type", equalTo(InvalidRequestException.class.getSimpleName()))
        .body("message", equalTo("User with id aNonExistingUser does not exist"))
    .when()
        .put(USER_CREDENTIALS_URL);

    // user was not updated
    verify(identityServiceMock, never()).saveUser(any(User.class));
  }

  @Test
  public void testPutProfile() {
    User initialUser = MockProvider.createMockUser();
    User userUpdate = MockProvider.createMockUserUpdate();

    UserQuery sampleUserQuery = mock(UserQuery.class);
    when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery);
    when(sampleUserQuery.userId(MockProvider.EXAMPLE_USER_ID)).thenReturn(sampleUserQuery);
    when(sampleUserQuery.singleResult()).thenReturn(initialUser);

    UserProfileDto updateDto = UserProfileDto.fromUser(userUpdate);

    given()
        .pathParam("id", MockProvider.EXAMPLE_USER_ID)
        .body(updateDto).contentType(ContentType.JSON)
    .then()
        .statusCode(Status.NO_CONTENT.getStatusCode())
    .when()
        .put(USER_PROFILE_URL);

    // password was updated
    verify(initialUser).setEmail(updateDto.getEmail());
    verify(initialUser).setFirstName(updateDto.getFirstName());
    verify(initialUser).setLastName(updateDto.getLastName());

    // and then saved
    verify(identityServiceMock).saveUser(initialUser);
  }

  @Test
  public void testPutProfileNonexistingFails() {
    User userUpdate = MockProvider.createMockUserUpdate();

    UserQuery sampleUserQuery = mock(UserQuery.class);
    when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery);
    when(sampleUserQuery.userId("aNonExistingUser")).thenReturn(sampleUserQuery);
    when(sampleUserQuery.singleResult()).thenReturn(null);

    UserProfileDto updateDto = UserProfileDto.fromUser(userUpdate);

    given()
        .pathParam("id", "aNonExistingUser")
        .body(updateDto).contentType(ContentType.JSON)
    .then()
        .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON)
        .body("type", equalTo(InvalidRequestException.class.getSimpleName()))
        .body("message", equalTo("User with id aNonExistingUser does not exist"))
    .when()
        .put(USER_PROFILE_URL);

    // nothing was saved
    verify(identityServiceMock, never()).saveUser(any(User.class));
  }

  @Test
  public void testPutProfileThrowsAuthorizationException() {
    User initialUser = MockProvider.createMockUser();
    User userUpdate = MockProvider.createMockUserUpdate();

    UserQuery sampleUserQuery = mock(UserQuery.class);
    when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery);
    when(sampleUserQuery.userId(MockProvider.EXAMPLE_USER_ID)).thenReturn(sampleUserQuery);
    when(sampleUserQuery.singleResult()).thenReturn(initialUser);

    String message = "exception expected";
    doThrow(new AuthorizationException(message)).when(identityServiceMock).saveUser(any(User.class));

    UserProfileDto updateDto = UserProfileDto.fromUser(userUpdate);

    given()
        .pathParam("id", MockProvider.EXAMPLE_USER_ID)
        .body(updateDto).contentType(ContentType.JSON)
    .then()
        .statusCode(Status.FORBIDDEN.getStatusCode())
        .contentType(ContentType.JSON)
        .body("type", equalTo(AuthorizationException.class.getSimpleName()))
        .body("message", equalTo(message))
    .when()
        .put(USER_PROFILE_URL);
  }

  @Test
  public void testReadOnlyUserCreateFails() {
    User newUser = MockProvider.createMockUser();
    when(identityServiceMock.isReadOnly()).thenReturn(true);

    given().body(UserDto.fromUser(newUser, true)).contentType(ContentType.JSON)
      .then().expect().statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON)
      .body("type", equalTo(InvalidRequestException.class.getSimpleName()))
      .body("message", equalTo("Identity service implementation is read-only."))
      .when().post(USER_CREATE_URL);

    verify(identityServiceMock, never()).newUser(MockProvider.EXAMPLE_USER_ID);
  }

  @Test
  public void testReadOnlyPutUserProfileFails() {
    User userUdpdate = MockProvider.createMockUser();
    when(identityServiceMock.isReadOnly()).thenReturn(true);

    given()
        .pathParam("id", MockProvider.EXAMPLE_USER_ID)
        .body(UserProfileDto.fromUser(userUdpdate)).contentType(ContentType.JSON)
    .then().expect()
        .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON)
        .body("type", equalTo(InvalidRequestException.class.getSimpleName()))
        .body("message", equalTo("Identity service implementation is read-only."))
    .when().put(USER_PROFILE_URL);

    verify(identityServiceMock, never()).saveUser(userUdpdate);
  }

  @Test
  public void testReadOnlyPutUserCredentialsFails() {
    User userUdpdate = MockProvider.createMockUser();
    when(identityServiceMock.isReadOnly()).thenReturn(true);

    given()
        .pathParam("id", MockProvider.EXAMPLE_USER_ID)
        .body(UserCredentialsDto.fromUser(userUdpdate)).contentType(ContentType.JSON)
    .then().expect()
        .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON)
        .body("type", equalTo(InvalidRequestException.class.getSimpleName()))
        .body("message", equalTo("Identity service implementation is read-only."))
    .when().put(USER_CREDENTIALS_URL);

    verify(identityServiceMock, never()).saveUser(userUdpdate);
  }

  @Test
  public void testReadOnlyUserDeleteFails() {
    when(identityServiceMock.isReadOnly()).thenReturn(true);

    given().pathParam("id", MockProvider.EXAMPLE_USER_ID)
      .then().expect().statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON)
      .body("type", equalTo(InvalidRequestException.class.getSimpleName()))
      .body("message", equalTo("Identity service implementation is read-only."))
      .when().delete(USER_URL);

    verify(identityServiceMock, never()).deleteUser(MockProvider.EXAMPLE_USER_ID);
  }

}


text:
<!--
  Copyright The Ohio State University Research Foundation, The University of Chicago -
Argonne National Laboratory, Emory University, SemanticBits LLC, and Ekagra Software Technologies Ltd.

  Distributed under the OSI-approved BSD 3-Clause License.
  See http://ncip.github.com/cagrid-general/LICENSE.txt for details.
-->
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- properties  -->
        <property name="connection.datasource">java:/@application.context.name@</property>
        <property name="hibernate.show_sql">true</property>
        <property name="dialect">@database.dialect@</property>
        <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JTATransactionFactory</property>
		<property name="transaction.manager_lookup_class">org.hibernate.transaction.JBossTransactionManagerLookup</property>

        <mapping resource="gov/nih/nci/security/authorization/domainobjects/Privilege.hbm.xml"/>
        <mapping resource="gov/nih/nci/security/authorization/domainobjects/Application.hbm.xml"/>
        <mapping resource="gov/nih/nci/security/authorization/domainobjects/FilterClause.hbm.xml"/>
        <mapping resource="gov/nih/nci/security/authorization/domainobjects/Role.hbm.xml"/>
        <mapping resource="gov/nih/nci/security/dao/hibernate/RolePrivilege.hbm.xml"/>
        <mapping resource="gov/nih/nci/security/dao/hibernate/UserGroup.hbm.xml"/>
        <mapping resource="gov/nih/nci/security/dao/hibernate/ProtectionGroupProtectionElement.hbm.xml"/>
        <mapping resource="gov/nih/nci/security/authorization/domainobjects/Group.hbm.xml"/>
        <mapping resource="gov/nih/nci/security/authorization/domainobjects/User.hbm.xml"/>
        <mapping resource="gov/nih/nci/security/authorization/domainobjects/ProtectionGroup.hbm.xml"/>
        <mapping resource="gov/nih/nci/security/authorization/domainobjects/ProtectionElement.hbm.xml"/>
        <mapping resource="gov/nih/nci/security/authorization/domainobjects/UserGroupRoleProtectionGroup.hbm.xml"/>
        <mapping resource="gov/nih/nci/security/authorization/domainobjects/UserProtectionElement.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Google\AdsApi\Common;

/**
 * Provides metadata about an ads API service.
 */
interface AdsServiceDescriptor {

  /**
   * @return string the name of the service
   */
  public function getServiceName();

  /**
   * @return string the fully qualified class name of the service
   */
  public function getServiceClass();

  /**
   * @return string the SOAP namespace of the service
   */
  public function getSoapNamespace();
}


text:
/**
 * tape tests for the bitcoinaddress.js.
 *
 * Check that our library loads and works with all browsers using testling.
 *
 * http://www.catonmat.net/blog/writing-javascript-tests-with-tape/
 */

/* jshint globalstrict:true */
/* globals require, __dirname, window, console */

"use strict";

var test = require("tape");
var $ = require("jquery1-browser");
var bitcoinaddress = require("./bitcoinaddress");

// Load test payload HTML from an external file using brfs complile
// time transformation
// http://stackoverflow.com/a/16951238/315168
var fs = require('fs');
var TEST_HTML = fs.readFileSync(__dirname + '/test-payload.html');

// Dummy BC address used in payload
var TEST_ADDRESS = "xxx";

/**
 * Initialize bitcoinaddress
 */
function init() {

    // Basic initialization
    bitcoinaddress.init({
        selector: ".bitcoin-address",
        template: "bitcoin-address-template",
        jQuery: $
    });
}

function reset() {
    // Clean document from all HTML content
    // (make sure don't clear <script> tags)
    $(document.body).children("div").remove();

    // Load test HTML snippets
    $(document.body).append(TEST_HTML);
}

// Don't execute tests until we have document ready
$(function() {

    test("Create Bitcoin address actions", function(t) {

        reset();

        // Check that the test payload is loaded
        t.equal($("#test-address").size(), 1);
        t.equal($("#bitcoin-address-template").size(), 1);

        // Initialize bitcoinaddress module
        init();

        // Now #test-address should be transformed

        // Check we get 3 actions for handling the address
        var actions = $("#test-address .bitcoin-address-action");
        t.equal(actions.size(), 3);

        // Check address is still displayed correctly
        var addr = $("#test-address .bitcoin-address");
        t.equal(addr.text(), TEST_ADDRESS);

        t.end();
    });

    test("Show QR code", function(t) {

        reset();
        init();

        // Simulate QR action
        var addr = $("#test-address");
        var action = addr.find(".bitcoin-address-action-qr");
        action.click();

        // Let the event sunk in
        setTimeout(function() {
            var qrContainer = addr.find(".bitcoin-address-qr-container");
            var imgs = qrContainer.find("img");
            t.equals(imgs.size(), 1);
            var src = imgs.attr("src");
            t.ok(src, "QR code <img> src was empty");
            t.equals(src.slice(0, 5), "data:");
            t.end();
        }, 2500);

    });

});


text:
namespace MassTransit.Tests.Serialization
{
	using System;
	using System.Diagnostics;
	using System.IO;
	using System.Text;
	using MassTransit.Internal;
	using MassTransit.Serialization;
	using NUnit.Framework;

	public class SerializationSpecificationBase
	{
		private Uri _sourceUri;
		private Uri _responseUri;
		private Uri _faultUri;
		private Uri _destinationUri;
		private int _retryCount;

		protected void TestSerialization<T>(T message)
		{
			byte[] data;
			var serializer = new XmlMessageSerializer();

			_sourceUri = new Uri("loopback://localhost/source");
			_responseUri = new Uri("loopback://localhost/response");
			_faultUri = new Uri("loopback://localhost/fault");
			_destinationUri = new Uri("loopback://localhost/destination");
			_retryCount = 69;

			OutboundMessage.Set(x =>
				{
					x.SetSourceAddress(_sourceUri);
					x.SendResponseTo(_responseUri);
					x.SendFaultTo(_faultUri);
					x.SetDestinationAddress(_destinationUri);
					x.SetRetryCount(_retryCount);
				});

			using (MemoryStream output = new MemoryStream())
			{
				serializer.Serialize(output, message);

				data = output.ToArray();
			}

			Trace.WriteLine(OutboundMessage.Headers.MessageType);

			Trace.WriteLine(Encoding.UTF8.GetString(data));

			using (MemoryStream input = new MemoryStream(data))
			{
				object receivedMessage = serializer.Deserialize(input);

				Assert.AreEqual(message, receivedMessage);
				Assert.AreNotSame(message, receivedMessage);

				Assert.AreEqual(_retryCount, CurrentMessage.Headers.RetryCount);
				Assert.AreEqual(_sourceUri, CurrentMessage.Headers.SourceAddress);
				Assert.AreEqual(_responseUri, CurrentMessage.Headers.ResponseAddress);
				Assert.AreEqual(_faultUri, CurrentMessage.Headers.FaultAddress);
				Assert.AreEqual(_destinationUri, CurrentMessage.Headers.DestinationAddress);
	//			Assert.AreEqual(message.GetType().ToMessageName(), CurrentMessage.Headers.MessageType);

			}
		}
	}
}


text:
package com.bv.eidss;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.bv.eidss.data.EidssDatabase;
import com.bv.eidss.generated.Species_binding;
import com.bv.eidss.model.BaseReference;
import com.bv.eidss.model.BaseReferenceType;
import com.bv.eidss.model.CaseTypeHACode;
import com.bv.eidss.model.Species;
import com.bv.eidss.utils.EidssUtils;

import java.util.List;

public class SpeciesFragment extends EidssBaseBindableFragment
        implements  LoaderManager.LoaderCallbacks<Cursor> {

    private SpeciesActivity mActivity;

    public SpeciesFragment() {
        // Required empty public constructor
    }

    public static SpeciesFragment newInstance() {
        return new SpeciesFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof Activity) {
            mActivity = (SpeciesActivity) context;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View v;
        v = inflater.inflate(R.layout.species_layout, container, false);

        // Custom Binding
        final List<String> mandatoryFields = EidssDatabase.GetMandatoryFields();
        final List<String> invisibleFields = EidssDatabase.GetInvisibleFields();

        final Spinner spinnerSpeciesType = (Spinner)v.findViewById(R.id.idfsSpeciesType);
        if (mActivity.mode == 0) {
            LookupBind(spinnerSpeciesType, mActivity._listSpeciesTypes,
                    new AdapterView.OnItemSelectedListener() {
                        public void onItemSelected(AdapterView<?> parent, View vw, int spnPosition, long id) {
                            mActivity.mSpecies.setSpeciesType(((BaseReference) parent.getSelectedItem()).idfsBaseReference);
                        }
                        public void onNothingSelected(AdapterView<?> parent) {
                            mActivity.mSpecies.setSpeciesType(0);
                        }
                    }, mActivity.mSpecies.getSpeciesType(), true, true, false);
        } else {
            LookupBind(R.id.idfsSpeciesType, v, mActivity.mSpecies.getSpeciesType(),
                    BaseReferenceType.rftSpeciesList,
                    (mActivity.mode == 1 ? CaseTypeHACode.LIVESTOCK : CaseTypeHACode.AVIAN),
                    new AdapterView.OnItemSelectedListener() {
                        public void onItemSelected(AdapterView<?> parent, View vw, int spnPosition, long id) {
                            mActivity.mSpecies.setSpeciesType(((BaseReference) parent.getSelectedItem()).idfsBaseReference);
                        }

                        public void onNothingSelected(AdapterView<?> parent) {
                            mActivity.mSpecies.setSpeciesType(0);
                        }
                    }, true, Species.eidss_SpeciesType, mandatoryFields, invisibleFields);
        }

        if (mActivity.mode != 0) {// 0 - assession, 1 - livestock, 2 - avian
            //FF
            RefreshFFSummary();

            // Clinical Signs
            View.OnClickListener cl = new View.OnClickListener() {
                public void onClick(View v) {
                    Intent intent = new Intent(mActivity, FFActivity.class);
                    Resources res = getResources();
                    intent.putExtra("idSpeciesType", mActivity.mSpecies.getSpeciesType());
                    intent.putExtra("ffmodel", mActivity.mSpecies.FFPresenterCs);
                    intent.putExtra("caption", getResources().getString((mActivity.mode == 1
                        ? R.string.EpidemiologicalAndClinicalInvestigation
                        : R.string.ClinicalSigns)));
                    startActivityForResult(intent, res.getInteger(R.integer.FF_ACTIVITY));
                }
            };

            final TextView FFSummaryText = (TextView) v.findViewById(R.id.ffSummaryText);
            final TextView FFSummaryTextCaption = (TextView) v.findViewById(R.id.ffSummaryTextCaption);
            final ImageView FFSummaryIcon = (ImageView) v.findViewById(R.id.ffSummaryIcon);

            FFSummaryIcon.setOnClickListener(cl);
            FFSummaryText.setOnClickListener(cl);
            FFSummaryTextCaption.setOnClickListener(cl);
            FFSummaryTextCaption.setText(getResources().getString((mActivity.mode == 1
                    ? R.string.EpidemiologicalAndClinicalInvestigation
                    : R.string.ClinicalSigns)));

            FFSummaryText.setText(mActivity.mSpecies.FFPresenterCs.GetActivityParameterSummary());

            FFSummaryText.setSelected(true);
            FFSummaryText.setEllipsize(TextUtils.TruncateAt.MARQUEE);
            FFSummaryText.setSingleLine(true);

            Species_binding.Bind(this, v, mActivity.mSpecies, mandatoryFields, invisibleFields, EidssUtils.getCurrentLanguage(), 0);
        } else {// mActivity.mode = 0 - assession

            Species_binding.Bind(this, v, mActivity.mSpecies, mandatoryFields, invisibleFields, EidssUtils.getCurrentLanguage(), 0);

            View parent = (View)v.findViewById(R.id.datStartOfSignsDate).getParent().getParent();
            if (parent != null)
                parent.setVisibility(View.GONE);
            parent = (View)v.findViewById(R.id.intDeadAnimalQty).getParent();
            if (parent != null)
                parent.setVisibility(View.GONE);
            parent = (View)v.findViewById(R.id.intSickAnimalQty).getParent();
            if (parent != null)
                parent.setVisibility(View.GONE);
            v.findViewById(R.id.FFDetailsButton).setVisibility(View.GONE);
            v.findViewById(R.id.ffSummaryText).setVisibility(View.GONE);
            v.findViewById(R.id.ffSummaryTextCaption).setVisibility(View.GONE);
            v.findViewById(R.id.ffSummaryIcon).setVisibility(View.GONE);
        }

        // 0 - assession, 1 - livestock, 2 - avian
        if (mActivity.mode != 1)
            EidssUtils.setInvisible(v.findViewById(R.id.strNote));
        if (mActivity.mode != 2)
            EidssUtils.setInvisible(v.findViewById(R.id.intAverageAge));
        // End of Custom Binding

        // hide soft keyboard
        mActivity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        return v;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == getResources().getInteger(R.integer.FF_ACTIVITY)) {
            if (resultCode == Activity.RESULT_OK) {
                mActivity.mSpecies.FFPresenterCs = intent.getParcelableExtra("ffmodel");
                ((TextView) mActivity.findViewById(R.id.ffSummaryText)).setText(mActivity.mSpecies.FFPresenterCs.GetActivityParameterSummary());
            }
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.case_toolbar, menu);
    }

    /* Called whenever we call invalidateOptionsMenu() */
    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        menu.findItem(R.id.Save).setVisible(false);
        menu.findItem(R.id.Remove).setVisible(false);
        menu.findItem(R.id.Refresh).setVisible(false);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case android.R.id.home:
                mActivity.Home();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return Species_binding.onCreateLoader(id, EidssUtils.getCurrentLanguage(), mActivity.mSpecies, mActivity);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        Species_binding.onLoadFinished(loader.getId(), data, mActivity.mSpecies);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        Species_binding.onLoaderReset(loader.getId());
    }

    public void RefreshFFSummary(){
        EidssDatabase db = new EidssDatabase(mActivity);
        mActivity.mSpecies.FFPresenterCs.LoadTemplate(db, mActivity.mSpecies.getSpeciesType());
        db.close();
    }
}


text:
.background_image {
  background: url('../img/bg.png') no-repeat center center fixed;
  /*background: url('../img/bg.jpg') no-repeat center center fixed;*/
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  -o-background-size: cover;
}
#background_lightgray {
  background-color: #eeeeee;
}
#background_lightgray img {
  border: 7px solid #ffe100;
}
body {
  font-size: 20px;
  color: #333333;
}
p {
  line-height: 1.5;
  margin: 30px 0;
}
.text-muted {
  color: #000000;
}
.text-primary {
  color: #ffe100;
}
.heading {
  color: #127504;
}
.subheading {
  color: #e6cb00;
}
p.large {
  font-size: 16px;
  color: #000000;
}
a,
a:hover,
a:focus,
a:active,
a.active {
  outline: none;
}
a {
  color: #2b76e2;
  text-transform: none;
  text-decoration: none;
}
a:hover,
a:focus,
a:active,
a.active {
  color: #1a5ec0;
}
h1,
h2,
h3,
h4,
h5,
h6 {
  font-size: 25px;
}
.img-centered {
  margin: 0 auto;
}
.bg-light-gray {
  background-color: #eeeeee;
}
.bg-darkest-gray {
  background-color: #222222;
}
.btn-primary {
  color: white;
  background-color: #2b76e2;
  border-color: #2b76e2;
  font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
  text-transform: uppercase;
  font-weight: 700;
}
.btn-primary:hover,
.btn-primary:focus,
.btn-primary:active,
.btn-primary.active,
.open .dropdown-toggle.btn-primary {
  color: white;
  background-color: #1a5ec0;
  border-color: #195ab7;
}
.btn-primary:active,
.btn-primary.active,
.open .dropdown-toggle.btn-primary {
  background-image: none;
}
.btn-primary.disabled,
.btn-primary[disabled],
fieldset[disabled] .btn-primary,
.btn-primary.disabled:hover,
.btn-primary[disabled]:hover,
fieldset[disabled] .btn-primary:hover,
.btn-primary.disabled:focus,
.btn-primary[disabled]:focus,
fieldset[disabled] .btn-primary:focus,
.btn-primary.disabled:active,
.btn-primary[disabled]:active,
fieldset[disabled] .btn-primary:active,
.btn-primary.disabled.active,
.btn-primary[disabled].active,
fieldset[disabled] .btn-primary.active {
  background-color: #2b76e2;
  border-color: #2b76e2;
}
.btn-primary .badge {
  color: #2b76e2;
  background-color: white;
}
.btn-xl {
  color: white;
  background-color: #2b76e2;
  border-color: #2b76e2;
  font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
  text-transform: uppercase;
  font-weight: 700;
  border-radius: 3px;
  font-size: 18px;
  padding: 20px 40px;
}
.btn-xl:hover,
.btn-xl:focus,
.btn-xl:active,
.btn-xl.active,
.open .dropdown-toggle.btn-xl {
  color: white;
  background-color: #1a5ec0;
  border-color: #195ab7;
}
.btn-xl:active,
.btn-xl.active,
.open .dropdown-toggle.btn-xl {
  background-image: none;
}
.btn-xl.disabled,
.btn-xl[disabled],
fieldset[disabled] .btn-xl,
.btn-xl.disabled:hover,
.btn-xl[disabled]:hover,
fieldset[disabled] .btn-xl:hover,
.btn-xl.disabled:focus,
.btn-xl[disabled]:focus,
fieldset[disabled] .btn-xl:focus,
.btn-xl.disabled:active,
.btn-xl[disabled]:active,
fieldset[disabled] .btn-xl:active,
.btn-xl.disabled.active,
.btn-xl[disabled].active,
fieldset[disabled] .btn-xl.active {
  background-color: #2b76e2;
  border-color: #2b76e2;
}
.btn-xl .badge {
  color: #2b76e2;
  background-color: white;
}
.navbar-custom {
  font-size: 25px;

  border-color: transparent;
}
.navbar-custom .navbar-brand {
  color: #2b76e2;
  font-size: 30px;
  font-family: "Kaushan Script", "Helvetica Neue", Helvetica, Arial, cursive;
}
.navbar-custom .navbar-brand:hover,
.navbar-custom .navbar-brand:focus,
.navbar-custom .navbar-brand:active,
.navbar-custom .navbar-brand.active {
  color: #1a5ec0;
}
.navbar-custom .navbar-collapse {
  border-color: rgba(255, 255, 255, 0.02);
}
.navbar-custom .navbar-toggle {
  background-color: #2b76e2;
  border-color: #2b76e2;
  font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
  text-transform: uppercase;
  color: white;
  font-size: 18px;
}
.navbar-custom .navbar-toggle:hover,
.navbar-custom .navbar-toggle:focus {
  background-color: #2b76e2;
}
.navbar-custom .nav li a {
  font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
  text-transform: uppercase;
  font-weight: 400;
  letter-spacing: 1px;
  color: #2b76e2;
}
.navbar-custom .nav li a:hover,
.navbar-custom .nav li a:focus {
  color: #2b76e2;
  outline: none;
}
.navbar-custom .navbar-nav > .active > a {
  border-radius: 0;
  color: white;
  background-color: #2b76e2;
}
.navbar-custom .navbar-nav > .active > a:hover,
.navbar-custom .navbar-nav > .active > a:focus {
  color: white;
  background-color: #1a5ec0;
}
@media (min-width: 768px) {
  .navbar-custom {
    background-color: transparent;
    color: white;
    padding: 25px 0;
    -webkit-transition: padding 0.3s;
    -moz-transition: padding 0.3s;
    transition: padding 0.3s;
    border: none;
  }
  .navbar-custom .navbar-brand {
    color: #2b76e2;
    font-size: 2em;
    -webkit-transition: all 0.3s;
    -moz-transition: all 0.3s;
    transition: all 0.3s;
  }
  .navbar-custom .nav li a {
    -webkit-transition: all 0.3s;
    -moz-transition: all 0.3s;
    transition: all 0.3s;
  }
  .navbar-custom .navbar-nav > .active > a {
    border-radius: 3px;
  }
}
@media (min-width: 768px) {
  .navbar-custom.affix {
    background-color: #222222;
    color: white;
    padding: 10px 0;
  }
  .navbar-custom.affix .navbar-brand {
    color: #2b76e2;
    font-size: 1.5em;
  }
  .navbar-custom.affix .nav li a {
    color: white;
    -webkit-transition: all 0.3s;
    -moz-transition: all 0.3s;
    transition: all 0.3s;
  }
}
header {
  background-image: url('../img/header-bg.jpg');
  background-repeat: no-repeat;
  background-attachment: scroll;
  background-position: center center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  -o-background-size: cover;
  text-align: center;
  color: white;
}

header .intro-text {
  padding-top: 100px;
  padding-bottom: 50px;
}
header .intro-text .intro-lead-in {
  font-family: "Droid Serif", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-style: italic;
  font-size: 22px;
  line-height: 22px;
  margin-bottom: 130px;
}
header .intro-text .intro-heading {
  font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
  text-transform: uppercase;
  font-weight: 700;
  font-size: 50px;
  line-height: 50px;
  margin-bottom: 25px;
}
@media (min-width: 768px) {
  header .intro-text {
    padding-top: 300px;
    padding-bottom: 200px;
  }
  header .intro-text .intro-lead-in {
    font-family: "Roboto Slab", "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-style: italic;
    font-size: 40px;
    line-height: 40px;
    margin-bottom: 130px;
  }
  header .intro-text .intro-heading {
    font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
    text-transform: uppercase;
    font-weight: 700;
    font-size: 75px;
    line-height: 75px;
    margin-bottom: 50px;
  }
}
section {
  padding: 100px 0;
}
section h2.section-heading {
  font-size: 55px;
  margin-top: 0;
  margin-bottom: 15px;
}
section h3.section-subheading {
  font-size: 1.3em;
  text-transform: none;
  font-style: italic;
  font-weight: 400;
  margin-bottom: 75px;
}
@media (min-width: 768px) {
  section {
    padding: 100px 0;
  }
}
#media .portfolio-item {
  margin: 0 0 18px;
  right: 0;
}
#media .portfolio-item .portfolio-link {
  display: block;
  position: relative;
  max-width: 400px;
  margin: 0 auto;
}
#media .portfolio-item .portfolio-link .portfolio-hover {
  background: rgba(43, 118, 226, 0.8);
  position: absolute;
  width: 100%;
  height: 100%;
  opacity: 0;
  transition: all ease 0.5s;
  -webkit-transition: all ease 0.5s;
  -moz-transition: all ease 0.5s;
}
#media .portfolio-item .portfolio-link .portfolio-hover:hover {
  opacity: 1;
}
#media .portfolio-item .portfolio-link .portfolio-hover .portfolio-hover-content {
  position: absolute;
  width: 100%;
  height: 20px;
  font-size: 20px;
  text-align: center;
  top: 50%;
  margin-top: -12px;
  color: white;
}
#media .portfolio-item .portfolio-link .portfolio-hover .portfolio-hover-content i {
  margin-top: -12px;
}
#media .portfolio-item .portfolio-link .portfolio-hover .portfolio-hover-content h3,
#media .portfolio-item .portfolio-link .portfolio-hover .portfolio-hover-content h4 {
  margin: 0;
}
#media .portfolio-item .portfolio-caption {
  max-width: 400px;
  margin: 0 auto;
  background-color: white;
  text-align: center;
  padding: 25px;
}
#media .portfolio-item .portfolio-caption h4 {
  text-transform: none;
  margin: 0;
}
#media .portfolio-item .portfolio-caption p {
  font-family: "Droid Serif", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-style: italic;
  font-size: 16px;
  margin: 0;
}
#media * {
  z-index: 2;
}
@media (min-width: 767px) {
  #media .portfolio-item {
    margin: 0 0 30px;
  }
}
.italic {
  font-style: italic;
}
.timeline {
  list-style: none;
  padding: 0;
  position: relative;
}
.timeline:before {
  top: 0;
  bottom: 0;
  position: absolute;
  content: "";
  width: 2px;
  background-color: #f1f1f1;
  left: 40px;
  margin-left: -1.5px;
}
.timeline > li {
  margin-bottom: 50px;
  position: relative;
  min-height: 50px;
}
.timeline > li:before,
.timeline > li:after {
  content: " ";
  display: table;
}
.timeline > li:after {
  clear: both;
}
.timeline > li .timeline-panel {
  width: 100%;
  float: right;
  padding: 0 20px 0 100px;
  position: relative;
  text-align: left;
}
.timeline > li .timeline-panel:before {
  border-left-width: 0;
  border-right-width: 15px;
  left: -15px;
  right: auto;
}
.timeline > li .timeline-panel:after {
  border-left-width: 0;
  border-right-width: 14px;
  left: -14px;
  right: auto;
}
.timeline > li .timeline-image {
  background-color: white;
  left: 0;
  margin-left: 0;
  width: 80px;
  height: 80px;
  position: absolute;
  z-index: 100;
  color: black;
  border-radius: 100%;
  border: 8px solid #ffe100;
  text-align: center;
}
.timeline > li .timeline-image h4 {
  font-size: 14px;
  margin-top: 12px;
  line-height: 14px;
}
.timeline > li.timeline-inverted > .timeline-panel {
  float: right;
  text-align: left;
  padding: 0 20px 0 100px;
}
.timeline > li.timeline-inverted > .timeline-panel:before {
  border-left-width: 0;
  border-right-width: 15px;
  left: -15px;
  right: auto;
}
.timeline > li.timeline-inverted > .timeline-panel:after {
  border-left-width: 0;
  border-right-width: 14px;
  left: -14px;
  right: auto;
}
.timeline > li:last-child {
  margin-bottom: 0;
}
.timeline .timeline-heading h4 {
  margin-top: 0;
  color: inherit;
}
.timeline .timeline-heading h4.subheading {
  text-transform: none;
}
.timeline .timeline-body > p,
.timeline .timeline-body > ul {
  margin-bottom: 0;
}
@media (min-width: 768px) {
  .timeline:before {
    left: 50%;
  }
  .timeline > li {
    margin-bottom: 100px;
    min-height: 100px;
  }
  .timeline > li .timeline-panel {
    width: 41%;
    float: left;
    padding: 0 20px 20px 30px;
    text-align: right;
  }
  .timeline > li .timeline-image {
    width: 100px;
    height: 100px;
    left: 50%;
    margin-left: -50px;
  }
  .timeline > li .timeline-image h4 {
    font-size: 20px;
    margin-top: 16px;
    line-height: 18px;
  }
  .timeline > li.timeline-inverted > .timeline-panel {
    float: right;
    text-align: left;
    padding: 0 30px 20px 20px;
  }
}
@media (min-width: 992px) {
  .timeline > li {
    min-height: 150px;
  }
  .timeline > li .timeline-panel {
    padding: 0 20px 20px;
  }
  .timeline > li .timeline-image {
    width: 150px;
    height: 150px;
    margin-left: -75px;
  }
  .timeline > li .timeline-image h4 {
    font-size: 24px;
    margin-top: 30px;
    line-height: 26px;
  }
  .timeline > li.timeline-inverted > .timeline-panel {
    padding: 0 20px 20px;
  }
}
@media (min-width: 1200px) {
  .timeline > li {
    min-height: 170px;
  }
  .timeline > li .timeline-panel {
    padding: 0 20px 20px 100px;
  }
  .timeline > li .timeline-image {
    width: 170px;
    height: 170px;
    margin-left: -85px;
  }
  .timeline > li .timeline-image h4 {
    margin-top: 40px;
  }
  .timeline > li.timeline-inverted > .timeline-panel {
    padding: 0 100px 20px 20px;
  }
}
.me-member {
  text-align: center;
  margin-bottom: 50px;
  margin-right: 50px;
}
.me-member img {
  margin: 0 auto;
  border: 70px solid #ffe100;
}
.me-member h4 {
  margin-top: 25px;
  margin-bottom: 0;
  text-transform: none;
}
.me-member p {
  margin-top: 0;
}
aside.clients img {
  margin: 50px auto;
}
section#contact {
  background-color: #222222;
  background-image: url('../img/map-image.png');
  background-position: center;
  background-repeat: no-repeat;
}
section#contact .section-heading {
  color: white;
}
section#contact .form-group {
  margin-bottom: 25px;
}
section#contact .form-group input,
section#contact .form-group textarea {
  padding: 20px;
}
section#contact .form-group input.form-control {
  height: auto;
}
section#contact .form-group textarea.form-control {
  height: 236px;
}
section#contact .form-control:focus {
  border-color: #2b76e2;
  box-shadow: none;
}
section#contact ::-webkit-input-placeholder {
  font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
  text-transform: uppercase;
  font-weight: 700;
  color: #eeeeee;
}
section#contact :-moz-placeholder {
  /* Firefox 18- */
  font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
  text-transform: uppercase;
  font-weight: 700;
  color: #eeeeee;
}
section#contact ::-moz-placeholder {
  /* Firefox 19+ */
  font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
  text-transform: uppercase;
  font-weight: 700;
  color: #eeeeee;
}
section#contact :-ms-input-placeholder {
  font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
  text-transform: uppercase;
  font-weight: 700;
  color: #eeeeee;
}
section#contact .text-danger {
  color: #1dbf06;
}
footer {
  padding: 25px 0;
  text-align: center;
}
footer span.copyright {
  line-height: 40px;
  font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
  text-transform: uppercase;
  text-transform: none;
}
ul.social-buttons {
  margin-bottom: 0;
}
ul.social-buttons li a {
  display: block;
  background-color: #222222;
  height: 40px;
  width: 40px;
  border-radius: 100%;
  font-size: 20px;
  line-height: 40px;
  color: white;
  outline: none;
  -webkit-transition: all 0.3s;
  -moz-transition: all 0.3s;
  transition: all 0.3s;
}
ul.social-buttons li a:hover,
ul.social-buttons li a:focus,
ul.social-buttons li a:active {
  background-color: #2b76e2;
}
.btn:focus,
.btn:active,
.btn.active,
.btn:active:focus {
  outline: none;
}
::-moz-selection {
  text-shadow: none;
  background: #ffe100;
}
::selection {
  text-shadow: none;
  background: #ffe100;
}
img::selection {
  background: transparent;
}
img::-moz-selection {
  background: transparent;
}
body {
  webkit-tap-highlight-color: #ffe100;
}
.featherlight-image {
  max-width: 100%;
}


text:
import type { Document } from './bson';
import { MongoRuntimeError, MongoTransactionError } from './error';
import type { CommandOperationOptions } from './operations/command';
import { ReadConcern, ReadConcernLike } from './read_concern';
import type { ReadPreferenceLike } from './read_preference';
import { ReadPreference } from './read_preference';
import type { Server } from './sdam/server';
import { WriteConcern } from './write_concern';

/** @internal */
export const TxnState = Object.freeze({
  NO_TRANSACTION: 'NO_TRANSACTION',
  STARTING_TRANSACTION: 'STARTING_TRANSACTION',
  TRANSACTION_IN_PROGRESS: 'TRANSACTION_IN_PROGRESS',
  TRANSACTION_COMMITTED: 'TRANSACTION_COMMITTED',
  TRANSACTION_COMMITTED_EMPTY: 'TRANSACTION_COMMITTED_EMPTY',
  TRANSACTION_ABORTED: 'TRANSACTION_ABORTED'
} as const);

/** @internal */
export type TxnState = typeof TxnState[keyof typeof TxnState];

const stateMachine: { [state in TxnState]: TxnState[] } = {
  [TxnState.NO_TRANSACTION]: [TxnState.NO_TRANSACTION, TxnState.STARTING_TRANSACTION],
  [TxnState.STARTING_TRANSACTION]: [
    TxnState.TRANSACTION_IN_PROGRESS,
    TxnState.TRANSACTION_COMMITTED,
    TxnState.TRANSACTION_COMMITTED_EMPTY,
    TxnState.TRANSACTION_ABORTED
  ],
  [TxnState.TRANSACTION_IN_PROGRESS]: [
    TxnState.TRANSACTION_IN_PROGRESS,
    TxnState.TRANSACTION_COMMITTED,
    TxnState.TRANSACTION_ABORTED
  ],
  [TxnState.TRANSACTION_COMMITTED]: [
    TxnState.TRANSACTION_COMMITTED,
    TxnState.TRANSACTION_COMMITTED_EMPTY,
    TxnState.STARTING_TRANSACTION,
    TxnState.NO_TRANSACTION
  ],
  [TxnState.TRANSACTION_ABORTED]: [TxnState.STARTING_TRANSACTION, TxnState.NO_TRANSACTION],
  [TxnState.TRANSACTION_COMMITTED_EMPTY]: [
    TxnState.TRANSACTION_COMMITTED_EMPTY,
    TxnState.NO_TRANSACTION
  ]
};

const ACTIVE_STATES: Set<TxnState> = new Set([
  TxnState.STARTING_TRANSACTION,
  TxnState.TRANSACTION_IN_PROGRESS
]);

const COMMITTED_STATES: Set<TxnState> = new Set([
  TxnState.TRANSACTION_COMMITTED,
  TxnState.TRANSACTION_COMMITTED_EMPTY,
  TxnState.TRANSACTION_ABORTED
]);

/**
 * Configuration options for a transaction.
 * @public
 */
export interface TransactionOptions extends CommandOperationOptions {
  // TODO(NODE-3344): These options use the proper class forms of these settings, it should accept the basic enum values too
  /** A default read concern for commands in this transaction */
  readConcern?: ReadConcernLike;
  /** A default writeConcern for commands in this transaction */
  writeConcern?: WriteConcern;
  /** A default read preference for commands in this transaction */
  readPreference?: ReadPreferenceLike;
  /** Specifies the maximum amount of time to allow a commit action on a transaction to run in milliseconds */
  maxCommitTimeMS?: number;
}

/**
 * @public
 * A class maintaining state related to a server transaction. Internal Only
 */
export class Transaction {
  /** @internal */
  state: TxnState;
  options: TransactionOptions;
  /** @internal */
  _pinnedServer?: Server;
  /** @internal */
  _recoveryToken?: Document;

  /** Create a transaction @internal */
  constructor(options?: TransactionOptions) {
    options = options ?? {};
    this.state = TxnState.NO_TRANSACTION;
    this.options = {};

    const writeConcern = WriteConcern.fromOptions(options);
    if (writeConcern) {
      if (writeConcern.w === 0) {
        throw new MongoTransactionError('Transactions do not support unacknowledged write concern');
      }

      this.options.writeConcern = writeConcern;
    }

    if (options.readConcern) {
      this.options.readConcern = ReadConcern.fromOptions(options);
    }

    if (options.readPreference) {
      this.options.readPreference = ReadPreference.fromOptions(options);
    }

    if (options.maxCommitTimeMS) {
      this.options.maxTimeMS = options.maxCommitTimeMS;
    }

    // TODO: This isn't technically necessary
    this._pinnedServer = undefined;
    this._recoveryToken = undefined;
  }

  /** @internal */
  get server(): Server | undefined {
    return this._pinnedServer;
  }

  get recoveryToken(): Document | undefined {
    return this._recoveryToken;
  }

  get isPinned(): boolean {
    return !!this.server;
  }

  /** @returns Whether the transaction has started */
  get isStarting(): boolean {
    return this.state === TxnState.STARTING_TRANSACTION;
  }

  /**
   * @returns Whether this session is presently in a transaction
   */
  get isActive(): boolean {
    return ACTIVE_STATES.has(this.state);
  }

  get isCommitted(): boolean {
    return COMMITTED_STATES.has(this.state);
  }
  /**
   * Transition the transaction in the state machine
   * @internal
   * @param nextState - The new state to transition to
   */
  transition(nextState: TxnState): void {
    const nextStates = stateMachine[this.state];
    if (nextStates && nextStates.includes(nextState)) {
      this.state = nextState;
      if (
        this.state === TxnState.NO_TRANSACTION ||
        this.state === TxnState.STARTING_TRANSACTION ||
        this.state === TxnState.TRANSACTION_ABORTED
      ) {
        this.unpinServer();
      }
      return;
    }

    throw new MongoRuntimeError(
      `Attempted illegal state transition from [${this.state}] to [${nextState}]`
    );
  }

  /** @internal */
  pinServer(server: Server): void {
    if (this.isActive) {
      this._pinnedServer = server;
    }
  }

  /** @internal */
  unpinServer(): void {
    this._pinnedServer = undefined;
  }
}

export function isTransactionCommand(command: Document): boolean {
  return !!(command.commitTransaction || command.abortTransaction);
}


text:
'use strict';

const chai = require('chai');
chai.use(require('chai-as-promised'));
const expect = chai.expect;
const TestUtil = require('../../../../TestUtil');
const fs = require('fs');
const RC = require('../../../RC');
const {SimpleCredentials} = require('./SimpleCredentials');
const {IllegalStateError} = require('../../../../../lib');

describe('CustomCredentialsTest', function () {
    let cluster;
    let member;
    const testFactory = new TestUtil.TestFactory();

    before(async function () {
        TestUtil.markEnterprise(this);

        cluster = await testFactory.createClusterForParallelTests(null,
            fs.readFileSync(__dirname + '/hazelcast_custom_credentials.xml', 'utf8'));
        member = await RC.startMember(cluster.id);
    });

    after(async function () {
        await testFactory.shutdownAll();
    });

    afterEach(async function () {
        await testFactory.shutdownAllClients();
    });

    it('should connect with valid custom credentials', async function () {
        const client = await testFactory.newHazelcastClientForParallelTests({
            clusterName: cluster.id,
            customCredentials: new SimpleCredentials('dummy-username', 'dummy-password')
        }, member);
        expect(client.getLifecycleService().isRunning()).to.be.true;
    });

    it('should not connect with invalid custom credentials', async function () {
        await expect(testFactory.newHazelcastClientForParallelTests({
            clusterName: cluster.id,
            customCredentials: new SimpleCredentials('dummy-username', 'not-a-dummy-password'),
            connectionStrategy: {
                connectionRetry: {
                    clusterConnectTimeoutMillis: 1000
                }
            }
        }, member)).to.be.rejectedWith(IllegalStateError);
    });
});


text:
.class final Landroid/speech/tts/SynthesisPlaybackQueueItem$ListEntry;
.super Ljava/lang/Object;
.source "SynthesisPlaybackQueueItem.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/speech/tts/SynthesisPlaybackQueueItem;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x18
    name = "ListEntry"
.end annotation

# instance fields
.field final mBytes:[B

# direct methods
.method constructor <init>([B)V
    .locals 0
    .parameter "bytes"

    .prologue
    .line 243
    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    .line 244
    iput-object p1, p0, Landroid/speech/tts/SynthesisPlaybackQueueItem$ListEntry;->mBytes:[B

    .line 245
    return-void
.end method


text:
% FUNCTION ne_openstatsfile: open file as stats file
function varargout = ne_openstatsfile(varargin)
% ne_openstatsfile  - open a file as a statistical object
%
% FORMAT:       [obj = ] ne_openstatsfile(src, evt, filespec)
%
% Input fields:
%
%       src         handle of UI object issuing the call (0 for GUI)
%       evt         event data (currently unused)
%       filespec    either filename or object reference (optional)
%
% Output fields:
%
%       obj         object reference (e.g. for filenames)

% Version:  v0.9c
% Build:    13101810
% Date:     Aug-22 2011, 3:00 PM EST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://neuroelf.net/

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

% global variable
global ne_gcfg;

% preset output
if nargout > 0
    varargout = cell(1, nargout);
end

% not while in a callback
if ne_gcfg.c.incb
    return;
end
ne_gcfg.c.incb = true;

% get handles
ch = ne_gcfg.h;

% current status of pointer
mfp = ch.MainFig.Pointer;
ch.MainFig.Pointer = 'watch';

% filename given and valid
if nargin > 2 && ...
    ischar(varargin{3}) && ...
   ~isempty(varargin{3}) && ...
    exist(varargin{3}, 'file') > 0 && ...
   ~isempty(regexpi(varargin{3}(:)', '\.(hdr|head)$'))
    hname = varargin{3}(:)';

% otherwise request
else
    [hname, hpath] = uigetfile( ...
        {'*.hdr;*.nii', 'Analyze files (*.hdr, *.nii)'; ...
         '*.nii.gz', 'Compressed Analyze files (*.nii.gz)'; ...
         '*.head', 'AFNI HEAD files (*.head)'}, ...
         'Please select a statistical file to load...', ...
         'MultiSelect', 'on');
    if isequal(hname, 0) || ...
        isequal(hpath, 0) || ...
        isempty(hname)
        ch.MainFig.Pointer = mfp;
        ne_gcfg.c.incb = false;
        return;
    end
    if isempty(hpath)
        hpath = pwd;
    elseif any(hpath(end) == '\/')
        hpath(end) = [];
    end
    hpath = strrep(hpath, filesep, '/');
    if ischar(hname)
        hname = {hname};
    end
    for fc = numel(hname):-1:1
        hname{fc} = [hpath '/' hname{fc}];
        if exist(hname{fc}, 'file') ~= 2
            hname(fc) = [];
        end
    end
    if isempty(hname)
        ch.MainFig.Pointer = mfp;
        ne_gcfg.c.incb = false;
        return;
    end
end

% load file
try
    if numel(hname) == 1
        hobj = bless(xff(hname{1}));
        if ~isxff(hobj, {'hdr', 'head'})
            clearxffobjects({hobj});
            error( ...
                'neuroelf:BadFileSelected', ...
                'Invalid file selected.' ...
            );
        end
    else
        hobj = xff(hname);
        if numel(hobj) == 1
            hobj = bless(hobj);
            if ~isxff(hobj, {'hdr', 'head'})
                clearxffobjects({hobj});
                error( ...
                    'neuroelf:BadFileSelected', ...
                    'Invalid file selected.' ...
                );
            end
        else
            clearxffobjects(hobj);
            error( ...
                'neuroelf:BadFileSelected', ...
                'Invalid file selected.' ...
            );
        end
    end
catch ne_eo;
    ch.MainFig.Pointer = mfp;
    ne_gcfg.c.incb = false;
    rethrow(ne_eo);
end

% set stats object status
hobj.RunTimeVars.StatsObject = true;

% request missing information (distribution type, DF)
ra = inputdlg({'Stats type (t, F, r, %):', 'Degrees of freedom:'}, ...
    'NeuroElf - user input', 1, {'  t', '  20'});
if ~iscell(ra) || ...
    numel(ra) ~= 2 || ...
   ~ischar(ra{1}) || ...
   ~ischar(ra{2}) || ...
    isempty(ra{1}) || ...
    isempty(ra{2})
    ch.MainFig.Pointer = mfp;
    clearxffobjects({hobj});
    ne_gcfg.c.incb = false;
    return;
end
ra{1} = lower(ddeblank(ra{1}));
if numel(ra{1}) ~= 1 || ...
   ~any('ftr%' == ra{1})
    ch.MainFig.Pointer = mfp;
    clearxffobjects({hobj});
    ne_gcfg.c.incb = false;
    return;
end
ra{2} = ddeblank(ra{2});
try
    ra{2} = eval(['[' ra{2} ']']);
catch ne_eo;
    ne_gcfg.c.lasterr = ne_eo;
    ra{2} = [234, 1];
end

% set map status
rtv = hobj.RunTimeVars;
for mc = 1:numel(rtv.Map)
    rtv.Map(mc).DF1 = ra{2}(1);
    if numel(ra{2}) > 1
        rtv.Map(mc).DF2 = ra{2}(2);
    else
        rtv.Map(mc).DF2 = 1;
    end
    switch(ra{1})
        case {'f'}
            rtv.Map(mc).Type = 4;
        case {'r'}
            rtv.Map(mc).Type = 2;
            rtv.Map(mc).LowerThreshold = 0.1;
            rtv.Map(mc).UpperThreshold = 0.5;
        case {'t'}
            rtv.Map(mc).Type = 1;
        case {'%'}
            rtv.Map(mc).Type = 15;
    end
end
hobj.RunTimeVars = rtv;

% open in NeuroElf
ch.MainFig.Pointer = mfp;
ne_gcfg.c.incb = false;
ne_openfile(0, 0, hobj, true);


text:
Boiler plate for a react redux web app, bootstrap classes available.

## install

git clone this repository, then build with:
```
> $ npm install
```

If you want to run with webpack-dev-server simply run this command:

```
> $ npm run dev
```

Open the web browser to `http://localhost:8080/`

For building static files, run:

```
> $ npm run build
```

## overview

This is a simple react-redux app containing some of the boilerplate needed for a larger-scale application.

Public contains the index.html file, which has no added css (it is possible to do all css inline with React) and no extra html elements except for a ```<title>``` tag, a link to the bundle.js (which will be created when you build with the webpack command), and a div for the React code to be rendered into (```<div id="app"></div>```).

The project also uses ES2015/ES6/ES7 features, through various babel libraries. ES** is simply added features to the core javascript language. [For more information see here.](http://www.2ality.com/2015/11/tc39-process.html)

## React

The React part consists of the files found in the "src/components" folder.

[React docs can be found here.](https://facebook.github.io/react/docs/getting-started.html)

React specifies "view" logic for the app (in this case the login form, the title and the numbers).

The entry point for the app is index.jsx, which specifies how the whole app renders.
## Redux

The Redux part consists of the files found in the "src/redux" folder.

[Redux docs can be found here.](http://redux.js.org/)

Redux specifies "state" logic for the app (what data is stored in the app). This is a useful abstraction because rather than worrying about a bunch of seperate interconnecting states of objects, all required state is stored in the "store" (which can be easily viewed with the Redux debug tools chrome extension).

## Notes

Tests still to be written. Test suite runs, but haven't added any.


text:
from setuptools import setup

setup(
    name='islplot',
    description='Python module to render isl integer sets and maps',
    version='0.1',
    author='Tobias Grosser',
    long_description=open('README.rst').read(),
    packages=['islplot']
)


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.harmazing</groupId>
	<artifactId>ob-elk</artifactId>
	<version>1.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>ob-elk</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>1.7</maven.compiler.source>
		<maven.compiler.target>1.7</maven.compiler.target>
	</properties>

	<repositories>
		<repository>
			<id>dev-nexus</id>
			<url>http://ob.yihecloud.com:88/nexus/content/groups/public</url>
			<snapshots>
				<enabled>true</enabled>
				<updatePolicy>always</updatePolicy>
			</snapshots>
		</repository>
	</repositories>
	<pluginRepositories>
		<pluginRepository>
			<id>dev-nexus</id>
			<url>http://ob.yihecloud.com:88/nexus/content/groups/public/</url>
			<snapshots>
				<enabled>true</enabled>
				<updatePolicy>always</updatePolicy>
			</snapshots>
			<releases>
				<updatePolicy>never</updatePolicy>
			</releases>
		</pluginRepository>
	</pluginRepositories>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.harmazing</groupId>
			<artifactId>ob-framework</artifactId>
			<version>1.0.1-SNAPSHOT</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.elasticsearch</groupId>
			<artifactId>elasticsearch</artifactId>
			<version>2.0.0</version>
		</dependency>

		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.16</version>
		</dependency>

		<dependency>
			<groupId>com.github.chewiebug</groupId>
		    <artifactId>gcviewer</artifactId>
		    <version>1.35-SNAPSHOT</version>
		</dependency>
	</dependencies>
	<build>
		<resources>
			<resource>
				<directory>src/main/java</directory>
				<includes>
					<include>**/*.xml</include>
					<include>**/*.properties</include>
				</includes>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
				<includes>
					<include>**/*</include>
				</includes>
			</resource>
		</resources>
	</build>

	<distributionManagement>
		<repository>
			<id>nexus-releases</id>
			<name>Nexus Release Repository</name>
			<url>http://ob.yihecloud.com:88/nexus/content/repositories/releases/</url>
		</repository>
		<snapshotRepository>
			<id>nexus-snapshots</id>
			<name>nexus snapshot repository</name>
			<url>http://ob.yihecloud.com:88/nexus/content/repositories/snapshots/</url>
		</snapshotRepository>
	</distributionManagement>
</project>


text:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserActivity extends Model
{
    protected $table = 'user_activity';
    protected $fillable = ['user_id', 'activity_id','confirm'];
}


text:
package diamond;

import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Bottom extends Klass implements Left, Right {
	public void method() {
		super.method();
		Left.super.method();
		Right.super.method();
	}

	final public static void main(String[] args) {
		Bottom b = new Bottom();
		b.method();
	}
}


text:
% IfaceMixin.m
%
% Mark J. Olah (mjo@cs.unm.edu)
% 08/2014
%
% copyright Mark J. Olah and The Regents of the University of New Mexico (2014).
%            This code is free for non-commercial use and modification, provided
%            this copyright notice remains unmodified and attached to the code
%
% A mixin class that is to be inherited from for classes that conform to the Mex_Iface matlab<--->C++ Class interface

classdef IfaceMixin < handle
    properties (Access = protected)
        % ifaceHandle - Function Handle to the Matlab class which is the interface
        ifaceHandle;
        % objectHandle - Numeric scalar uint64 that represents a C++ Handle object that itself holds the persistant C++ object we are associated with
        objectHandle=uint64(0);
    end

    methods (Access=public)
        %% Destructor
        function delete(obj)
            obj.closeIface();
        end
    end

    methods (Access=protected)
        function obj=IfaceMixin(ifaceHandle)
            % Inputs:
            %  ifaceHandle - A function handle to the *_Iface mex function that implements the C++ side of the interface
            obj.ifaceHandle=ifaceHandle;
        end

        function success=openIface(obj, varargin)
            % Make a new C++ object and save the numeric handle to the allocated object
            %
            % Inputs:
            %  varargin - These are the inputs the iface @new command expects.  They are passed directly though
            % Ouput:
            %  success - True if we were able to make a peristant C++ object and are now ready for calling methods.
            if obj.objectHandle
                error([class(obj) ':call'],'objectHandle already exists and is non 0. Cannot create new ifaceobject until current object is closed.');
            end
            obj.objectHandle = obj.ifaceHandle('@new', varargin{:});
            success= obj.objectHandle>0;
        end

        function closeIface(obj)
            % Close the iface and release the objectHandle and free the memory on the C++ side
            if obj.objectHandle
                obj.call('@delete');
                obj.objectHandle=uint64(0);
            end
        end

        function varargout=call(obj, cmdstr, varargin)
            % This is the entry point to call a method of the underlying C++ class.  The Matlab side of the wrapped class
            % should internally call this protected method to call member functions of the C++ class.
            %
            % Inputs:
            %  cmdstr - This is charactor array giving the name of the method to call
            %  varargin - The rest of the arguments the method expects.  These are passed directly in.
            % Output:
            %  varargout - Whatever arguments the method is supposed to return.  These are passed back directly
            if ~obj.objectHandle && ~obj.openIface()
                error([class(obj) ':call'],'objectHandle not valid and could not be created.');
            end
            [varargout{1:nargout}]=obj.ifaceHandle(cmdstr,obj.objectHandle, varargin{:});
        end
    end %Protected methods

    methods (Access=protected, Static=true)
        function varargout=callstatic(ifaceHandle, cmdstr, varargin)
            % This is the entry point to call a static method of the underlying C++ class.  The Matlab side of the wrapped class
            % should internally call this protected method to call static member functions of the C++ class.  Because these are
            % static methods there is no need to have an active intantiation of the C++ class in objectHandle.
            %
            % The user must provide the ifaceHandle directly, since we won't have an instantiated matlab object from which to get ifaceHandle
            %
            % Inputs:
            %  ifaceHandle - This is the function pointer to the mex *_Iface function that provides the C++ side of the interface
            %  cmdstr - This is charactor array giving the name of the method to call
            %  varargin - The rest of the arguments the method expects.  These are passed directly in.
            % Output:
            %  varargout - Whatever arguments the method is supposed to return.  These are passed back directly
            [varargout{1:nargout}]=ifaceHandle('@static',cmdstr, varargin{:});
        end
    end % Protected static methods
end


text:
import json

import httplib2
import google.auth
import google_auth_httplib2
import google.oauth2.service_account

from airflow.exceptions import AirflowException
from airflow.hooks.base_hook import BaseHook
from airflow.utils.log.logging_mixin import LoggingMixin

_DEFAULT_SCOPES = ('https://www.googleapis.com/auth/cloud-platform',)

class GoogleCloudBaseHook(BaseHook, LoggingMixin):
    """
    A base hook for Google cloud-related hooks. Google cloud has a shared REST
    API client that is built in the same way no matter which service you use.
    This class helps construct and authorize the credentials needed to then
    call apiclient.discovery.build() to actually discover and build a client
    for a Google cloud service.

    The class also contains some miscellaneous helper functions.

    All hook derived from this base hook use the 'Google Cloud Platform' connection
    type. Two ways of authentication are supported:

    Default credentials: Only the 'Project Id' is required. You'll need to
    have set up default credentials, such as by the
    ``GOOGLE_APPLICATION_DEFAULT`` environment variable or from the metadata
    server on Google Compute Engine.

    JSON key file: Specify 'Project Id', 'Key Path' and 'Scope'.

    Legacy P12 key files are not supported.
    """

    def __init__(self, gcp_conn_id='google_cloud_default', delegate_to=None):
        """
        :param gcp_conn_id: The connection ID to use when fetching connection info.
        :type gcp_conn_id: str
        :param delegate_to: The account to impersonate, if any.
            For this to work, the service account making the request must have
            domain-wide delegation enabled.
        :type delegate_to: str
        """
        self.gcp_conn_id = gcp_conn_id
        self.delegate_to = delegate_to
        self.extras = self.get_connection(self.gcp_conn_id).extra_dejson

    def _get_credentials(self):
        """
        Returns the Credentials object for Google API
        """
        key_path = self._get_field('key_path', False)
        keyfile_dict = self._get_field('keyfile_dict', False)
        scope = self._get_field('scope', None)
        if scope:
            scopes = [s.strip() for s in scope.split(',')]
        else:
            scopes = _DEFAULT_SCOPES

        if not key_path and not keyfile_dict:
            self.log.info('Getting connection using `google.auth.default()` '
                          'since no key file is defined for hook.')
            credentials, _ = google.auth.default(scopes=scopes)
        elif key_path:
            # Get credentials from a JSON file.
            if key_path.endswith('.json'):
                self.log.debug('Getting connection using JSON key file %s' % key_path)
                credentials = (
                    google.oauth2.service_account.Credentials.from_service_account_file(
                        key_path, scopes=scopes)
                )
            elif key_path.endswith('.p12'):
                raise AirflowException('Legacy P12 key file are not supported, '
                                       'use a JSON key file.')
            else:
                raise AirflowException('Unrecognised extension for key file.')
        else:
            # Get credentials from JSON data provided in the UI.
            try:
                keyfile_dict = json.loads(keyfile_dict)

                # Depending on how the JSON was formatted, it may contain
                # escaped newlines. Convert those to actual newlines.
                keyfile_dict['private_key'] = keyfile_dict['private_key'].replace(
                    '\\n', '\n')

                credentials = (
                    google.oauth2.service_account.Credentials.from_service_account_info(
                        keyfile_dict, scopes=scopes)
                )
            except json.decoder.JSONDecodeError:
                raise AirflowException('Invalid key JSON.')

        return credentials.with_subject(self.delegate_to) \
            if self.delegate_to else credentials

    def _get_access_token(self):
        """
        Returns a valid access token from Google API Credentials
        """
        return self._get_credentials().token

    def _authorize(self):
        """
        Returns an authorized HTTP object to be used to build a Google cloud
        service hook connection.
        """
        credentials = self._get_credentials()
        http = httplib2.Http()
        authed_http = google_auth_httplib2.AuthorizedHttp(
            credentials, http=http)
        return authed_http

    def _get_field(self, f, default=None):
        """
        Fetches a field from extras, and returns it. This is some Airflow
        magic. The google_cloud_platform hook type adds custom UI elements
        to the hook page, which allow admins to specify service_account,
        key_path, etc. They get formatted as shown below.
        """
        long_f = 'extra__google_cloud_platform__{}'.format(f)
        if long_f in self.extras:
            return self.extras[long_f]
        else:
            return default

    @property
    def project_id(self):
        return self._get_field('project')


text:
DetectedGate::DetectedGate()
{
}

DetectedGate::~DetectedGate()
{
}

void DetectedGate::InitializeFromTwoPosts(RotatedRect post1, RotatedRect post2)
{
	DetectedPost = E_DetectedPost_BOTH;

	LeftPost = (post1.center.x < post2.center.x) ? post1 : post2;
	RightPost = (post1.center.x > post2.center.x) ? post1 : post2;
	Center.x = (RightPost.center.x + LeftPost.center.x) / 2;
	Center.y = (RightPost.center.y + LeftPost.center.y) / 2;
}

void DetectedGate::InitializeFromOnePost(RotatedRect post, E_DetectedPost detectedPost)
{
	DetectedPost = detectedPost;

	if (DetectedPost == E_DetectedPost_LEFT)
	{
		LeftPost = post;
	}
	else
	{
		RightPost = post;
	}
}

void DetectedGate::SetNotDetected()
{
	DetectedPost = E_DetectedPost_NONE;
}


text:
/**
 * api endpoint for posts
 * @author adrienjoly, whyd
 **/

var snip = require("../../snip.js");
var mongodb = require("../../models/mongodb.js");
var postModel = require("../../models/post.js");
var userModel = require("../../models/user.js");
var notifModel = require("../../models/notif.js");
var followModel = require("../../models/follow.js");
var commentModel = require("../../models/comment.js");
var analytics = require("../../models/analytics.js");
var lastFm = require("./lastFm.js").lastFm;

var sequencedParameters = {_1: "pId", _2: "action"}; //[null, "pId", "action"];

function fetchSubscribedUsers(uidList, uid, cb) {
	followModel.fetch({uId:uid, tId:{$in:uidList}}, null, function(results) {
		var uidSet = {};
		for (var i in results)
			uidSet[results[i].tId] = results[i];
		cb(uidSet);
	});
}

var publicActions = {
	lovers: function (p, callback) {
		postModel.fetchPostById(p.pId, function (post) {
			var lovers = [];
			if (post && post.lov)
				fetchSubscribedUsers(post.lov, p.uId, function(subscrUidSet) {
					for (var i in post.lov)
						lovers.push({
							id: /*"/u/"+*/post.lov[i],
							name: (mongodb.usernames[post.lov[i]] || {}).name,
							subscribed: !!subscrUidSet[post.lov[i]]
						});
					console.log("lovers", lovers)
					userModel.fetchUserBios(lovers, function() {
						callback(lovers);
					});
				});
			else
				callback(lovers);
		});
	},

	reposts: function (p, callback) {
		postModel.fetchPosts({"repost.pId": p.pId}, null, null, function (results) {
			var reposts = [];
			if (results) {
				var repostUids = [];
				for (var i in results)
					repostUids.push(results[i].uId);
				fetchSubscribedUsers(repostUids, p.uId, function(subscrUidSet) {
					for (var i in results)
						reposts.push({
							id: /*"/u/"+*/results[i].uId,
							name: (mongodb.usernames[results[i].uId] || {}).name,
							subscribed: !!subscrUidSet[results[i].uId]
						});
					userModel.fetchUserBios(reposts, function() {
						callback(reposts);
					});
				});
			}
			else
				callback(reposts);
		});
	}
};

exports.actions = {

	sendToUsers: notifModel.sendTrackToUsers,

	addComment: commentModel.insert,

	deleteComment: commentModel.delete,

	insert: function (p, callback) {

		var q = {
			uId: p.uId,
			uNm: p.uNm,
			text: p.text || "",
			pl: undefined, // to be parsed/populated before calling actualInsert()
			// fields that will be ignored by rePost():
			name: p.name,
			eId: p.eId
		};

		if (p.ctx)
			q.ctx = p.ctx;

		function tryJsonParse(p) {
			try {
				return JSON.parse(p);
			}
			catch(e) {
				return null;
			}
		}

		function actualInsert() {
			if (p.pId)
				postModel.rePost(p.pId, q, callback);
			else {
				if (p._id) // edit mode
					q._id = p._id;

				if (p.img && p.img != "null")
					q.img = p.img;

				if (p.src) // source webpage of the content: {id,name} provided by bookmarklet
					q.src = typeof p.src == "object" ? p.src : tryJsonParse(p.src);
				else if (p["src[id]"] && p["src[name]"])
					q.src = {
						id: p["src[id]"],
						name: p["src[name]"]
					}
				if (!q.src || !q.src.id)
					delete q.src;

				postModel.savePost(q, callback);
			}
		}

		// process playlist
		try {
			q.pl = typeof p.pl == "object" ? p.pl : JSON.parse(p.pl);
		}
		catch(e) {
			q.pl = {
				id: p["pl[id]"],
				name: p["pl[name]"],
				collabId: p["pl[collabId]"] || undefined
			};
		}
		if (q.pl.collabId)
			delete q.pl.id;
		else if (q.pl.id == "create") {
			userModel.createPlaylist(p.uId, q.pl.name, function(playlist) {
				if (playlist) {
					q.pl.id = playlist.id;
					console.log("playlist was created", q.pl);
				}
				actualInsert();
			});
			return; // avoid inserting twice
		}
		else {
			q.pl.id = parseInt(q.pl.id);
			if (isNaN(q.pl.id))
				delete q.pl; //q.pl = null;
		}

		actualInsert();
	},
	delete: function (p, callback) {
		postModel.deletePost(p._id, function (result) {
			callback((result || {}).pop ? result.pop() : {});
		}, p.uId);
	},
	toggleLovePost: function(p, callback) {
		postModel.isPostLovedByUid(p.pId, p.uId, function(loved, post) {
			if (!post)
				callback({loved:false, lovers:0}); // to prevent crash when trying to love a repost
			else if (loved)
				postModel.unlovePost(p.pId, p.uId, function () {
					callback({loved:false, lovers:(post.lov || [1]).length - 1});
				});
			else
				postModel.lovePost(p.pId, p.uId, function () {
					callback({loved:true, lovers:(post.lov || []).length + 1, post:post});
				});
		});
	},
	incrPlayCounter: function(p, cb) {
		// TODO: prevent a user from sending many calls in a row
		if (!p.uId)
			return cb && cb({error:"not logged in"});
		// erroneous call made by an old iOS version
		if (p.pId == "(null)") {
			console.log("warning: (null) pId");
			return cb && cb({error:"invalid pId"});
		}
		p.logData = p.logData || {};
		function callbackAndLogPlay(post){
			cb && cb({result: post});
			if (!post || !post.name)
				return;
			analytics.addPlay({
				eId: post.eId,
				pId: ""+post._id,
				uId: p.uId,
				own: p.uId == post.uId,
				err: p.logData.err,
				fbk: p.logData.fbk,
			});
			if (p.duration > 0)
				post.duration = p.duration;
			if (!p.logData.err)
				lastFm.updateNowPlaying2(post, (mongodb.usernames[p.uId].lastFm || {}).sk, function(res){
					//console.log("-> last fm response", res);
				});
		}
		if (p.logData.err)
			postModel.fetchPostById(p.pId, callbackAndLogPlay);
		else
			postModel.incrPlayCounter(p.pId, callbackAndLogPlay);
	},
	scrobble: function(p, cb) {
		if (!p.uId)
			return cb && cb({error:"not logged in"});
		postModel.fetchPostById(p.pId, function(r) {
			if (!r)
				return cb && cb({error:"missing track"});
			var lastFmSessionKey = (mongodb.usernames[p.uId].lastFm || {}).sk;
			lastFm.scrobble2(r && r.name, lastFmSessionKey, p.uId == r.uId, p.timestamp, function(res){
				//console.log("-> last fm response", res);
				cb && cb(res);
			});
		});
	}
};

exports.handleRequest = function(request, reqParams, response) {
	request.logToConsole("api.post.handleRequest", reqParams);

	function resultHandler(res, args) {
		if (!res || res.error)
			console.log(/*reqParams,*/ "api.post." + reqParams.action, " RESULT =>", res);
		response.render(res, null, args || {'content-type': 'application/json'});
	}

	var user = request.getUser() || {}; //checkLogin(response);
	reqParams.uId = user.id;
	reqParams.uNm = user.name;

	if (reqParams.action && publicActions[reqParams.action])
		return publicActions[reqParams.action](reqParams, resultHandler);

	// make sure a registered user is logged, or return an error page
	if (!user || !user.id) return response.badRequest();

	if (reqParams.action && exports.actions[reqParams.action])
		exports.actions[reqParams.action](reqParams, resultHandler);
	else
		response.badRequest();
};

exports.controller = function(request, getParams, response) {
	//request.logToConsole("api.post", getParams);
	var params = snip.translateFields(getParams || {}, sequencedParameters);

	//if (request.method.toLowerCase() === 'post')
	for(var i in request.body)
		params[i] = request.body[i];

	exports.handleRequest(request, params, response);
}


text:
'use strict'

const jst = require('jst')

exports.name = 'jst'
exports.inputFormats = ['jst', 'html', 'text']
exports.outputFormat = 'html'

exports.compile = function (str, opts) {
  jst.configure(opts)
  return jst.compile(str)
}

exports.render = function (str, opts, locals) {
  locals = arguments.length <= 2 ? opts : locals
  opts = opts && typeof opts === 'object' ? opts : {}
  locals = locals && typeof locals === 'object' ? locals : {}

  jst.configure(opts)
  return jst.render(str, locals)
}


text:
package org.wso2.am.integration.test.utils.bean;

/**
 * Basic request for subscribe to API
 * action=addAPISubscription&name=apiName&version=1.0.0&provider=provider&tier=Gold&applicationName=DefaultApplication
 *
 */
public class SubscriptionRequest extends AbstractRequest {

    private String name;
    private String provider;
    private String version = "1.0.0";
    private String applicationName = "DefaultApplication";
    private String tier = "Gold";

    /**
     * Constructor using default values
     *
     * @param apiName  - Name of the API
     * @param provider - Provider of the API
     */
    public SubscriptionRequest(String apiName, String provider) {
        this.name = apiName;
        this.provider = provider;
    }

    /**
     * constructor with more configurable params
     *
     * @param apiName    - Name of the API
     * @param apiVersion - Version of the API
     * @param provider   - API provider
     * @param appName    - Application name
     * @param tier       - Tire type
     */
    public SubscriptionRequest(String apiName, String apiVersion, String provider,
                               String appName, String tier) {
        this.name = apiName;
        this.version = apiVersion;
        this.provider = provider;
        this.applicationName = appName;
        this.tier = tier;
    }

    @Override
    public void setAction() {
        setAction("addAPISubscription");
    }

    @Override
    public void init() {
        addParameter("name", name);
        addParameter("provider", provider);
        addParameter("version", version);
        addParameter("applicationName", applicationName);
        addParameter("tier", tier);
    }

    public String getName() {
        return name;
    }

    public String getProvider() {
        return provider;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getApplicationName() {
        return applicationName;
    }

    public void setApplicationName(String applicationName) {
        this.applicationName = applicationName;
    }

    public String getTier() {
        return tier;
    }

    public void setTier(String tier) {
        this.tier = tier;
    }
}