text:
package com.devicehive;

import com.devicehive.auth.HiveAuthentication;
import com.devicehive.auth.HivePrincipal;
import com.devicehive.base.AbstractResourceTest;
import com.devicehive.base.RequestDispatcherProxy;
import com.devicehive.base.fixture.DeviceFixture;
import com.devicehive.configuration.Constants;
import com.devicehive.dao.NetworkDao;
import com.devicehive.model.DeviceCommand;
import com.devicehive.model.DeviceNotification;
import com.devicehive.model.JsonStringWrapper;
import com.devicehive.model.enums.UserRole;
import com.devicehive.model.enums.UserStatus;
import com.devicehive.model.rpc.CommandSearchRequest;
import com.devicehive.model.rpc.CommandSearchResponse;
import com.devicehive.model.rpc.ListNetworkRequest;
import com.devicehive.model.rpc.ListNetworkResponse;
import com.devicehive.model.rpc.NotificationInsertRequest;
import com.devicehive.model.rpc.NotificationInsertResponse;
import com.devicehive.model.rpc.NotificationSearchRequest;
import com.devicehive.model.rpc.NotificationSearchResponse;
import com.devicehive.model.updates.DeviceCommandUpdate;
import com.devicehive.model.updates.DeviceUpdate;
import com.devicehive.service.DeviceCommandService;
import com.devicehive.service.DeviceNotificationService;
import com.devicehive.service.DeviceService;
import com.devicehive.service.DeviceTypeService;
import com.devicehive.service.NetworkService;
import com.devicehive.service.UserService;
import com.devicehive.service.configuration.ConfigurationService;
import com.devicehive.service.time.TimestampService;
import com.devicehive.shim.api.Action;
import com.devicehive.shim.api.Request;
import com.devicehive.shim.api.Response;
import com.devicehive.shim.api.server.RequestHandler;
import com.devicehive.vo.ApiInfoVO;
import com.devicehive.vo.ClusterConfigVO;
import com.devicehive.vo.DeviceTypeVO;
import com.devicehive.vo.DeviceVO;
import com.devicehive.vo.NetworkVO;
import com.devicehive.vo.UserVO;
import org.apache.commons.lang3.RandomStringUtils;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.core.context.SecurityContextHolder;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static com.devicehive.model.enums.SortOrder.ASC;
import static java.util.Collections.emptyMap;
import static java.util.UUID.randomUUID;
import static javax.ws.rs.core.Response.Status.OK;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@Ignore //TODO: FIX missed Kafka class
public class FrontendSmokeTest extends AbstractResourceTest {

    private static final String DEFAULT_STATUS = "default_status";

    @Autowired
    private Environment env;

    @Autowired
    private NetworkService networkService;

    @Autowired
    private DeviceTypeService deviceTypeService;

    @Autowired
    private UserService userService;

    @Autowired
    private ConfigurationService configurationService;

    @Autowired
    private DeviceCommandService deviceCommandService;

    @Autowired
    private DeviceNotificationService notificationService;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private RequestDispatcherProxy requestDispatcherProxy;

    @Autowired
    private TimestampService timestampService;

    @Autowired
    private NetworkDao networkDao;

    @Mock
    private RequestHandler requestHandler;

    private ArgumentCaptor<Request> argument = ArgumentCaptor.forClass(Request.class);

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        requestDispatcherProxy.setRequestHandler(requestHandler);
    }

    @After
    public void tearDown() {
        Mockito.reset(requestHandler);
    }

    @Test
    public void should_return_API_info() throws Exception {
        ApiInfoVO apiInfo = performRequest("info", "GET", emptyMap(), emptyMap(), null, OK, ApiInfoVO.class);
        assertThat(apiInfo.getServerTimestamp(), notNullValue());
        assertThat(apiInfo.getRestServerUrl(), nullValue());
        assertThat(apiInfo.getWebSocketServerUrl(), is(wsBaseUri() + "/websocket"));
    }

    @Test
    public void should_return_cluster_config() throws Exception {
        ClusterConfigVO clusterConfig = performRequest("info/config/cluster", "GET", emptyMap(), emptyMap(), null, OK, ClusterConfigVO.class);
        assertThat(clusterConfig, notNullValue());
        assertThat(clusterConfig.getBootstrapServers(), is(env.getProperty(Constants.BOOTSTRAP_SERVERS)));
        assertThat(clusterConfig.getZookeeperConnect(), is(env.getProperty(Constants.ZOOKEEPER_CONNECT)));
    }

    @Test
    public void should_save_configuration_property_and_return_by_name() throws Exception {
        String key = RandomStringUtils.randomAlphabetic(10);
        String val = RandomStringUtils.randomAlphabetic(10);
        configurationService.save(key, val);

        String savedVal = configurationService.get(key);
        assertThat(savedVal, equalTo(val));
    }

    @Test
    public void should_update_config_property() throws Exception {
        String key = RandomStringUtils.randomAlphabetic(10);
        String val = RandomStringUtils.randomAlphabetic(10);
        configurationService.save(key, val);

        String savedVal = configurationService.get(key);
        assertThat(savedVal, equalTo(val));

        String newVal = RandomStringUtils.randomAlphabetic(10);
        configurationService.save(key, newVal);

        savedVal = configurationService.get(key);
        assertThat(savedVal, equalTo(newVal));
    }

    @Test
    public void should_delete_config_property() throws Exception {
        String key = RandomStringUtils.randomAlphabetic(10);
        String val = RandomStringUtils.randomAlphabetic(10);
        configurationService.save(key, val);

        String savedVal = configurationService.get(key);
        assertThat(savedVal, equalTo(val));

        configurationService.delete(key);

        savedVal = configurationService.get(key);
        assertThat(savedVal, Matchers.nullValue());
    }

    @Test
    public void should_find_commands_by_device_id() throws Exception {
        final List<String> deviceIds = IntStream.range(0, 5)
                .mapToObj(i -> UUID.randomUUID().toString())
                .collect(Collectors.toList());
        final Date timestampSt = timestampService.getDate();
        final Date timestampEnd = timestampService.getDate();
        final String parameters = "{\"param1\":\"value1\",\"param2\":\"value2\"}";

        final Set<String> idsForSearch = new HashSet<>(Arrays.asList(
                deviceIds.get(0),
                deviceIds.get(2),
                deviceIds.get(3)));

        final Map<String, DeviceCommand> commandMap = idsForSearch.stream()
                .collect(Collectors.toMap(Function.identity(), deviceId -> {
                    DeviceCommand command = new DeviceCommand();
                    command.setId(System.nanoTime());
                    command.setDeviceId(deviceId);
                    command.setCommand(RandomStringUtils.randomAlphabetic(10));
                    command.setTimestamp(timestampService.getDate());
                    command.setParameters(new JsonStringWrapper(parameters));
                    command.setStatus(DEFAULT_STATUS);
                    return command;
                }));

        when(requestHandler.handle(any(Request.class))).then(invocation -> {
            Request request = invocation.getArgument(0, Request.class);
            Set<String> foundDeviceIds = request.getBody().cast(CommandSearchRequest.class).getDeviceIds();
            CommandSearchResponse response = new CommandSearchResponse();
            response.setCommands(foundDeviceIds.stream().map(commandMap::get).collect(Collectors.toList()));
            return Response.newBuilder()
                    .withBody(response)
                    .buildSuccess();
        });

        deviceCommandService.find(idsForSearch, Collections.emptySet(), timestampSt, timestampEnd, DEFAULT_STATUS, null, null, null, null)
                .thenAccept(commands -> {
                    assertEquals(3, commands.size());
                    assertEquals(new HashSet<>(commandMap.values()), new HashSet<>(commands));
                })
                .get(15, TimeUnit.SECONDS);

        verify(requestHandler, times(1)).handle(argument.capture());
    }

    @Test
    public void should_update_command() throws Exception {
        final DeviceCommand deviceCommand = new DeviceCommand();
        deviceCommand.setId(System.nanoTime());
        deviceCommand.setDeviceId(UUID.randomUUID().toString());
        deviceCommand.setCommand("command");
        deviceCommand.setParameters(new JsonStringWrapper("{'test':'test'}"));
        deviceCommand.setStatus(DEFAULT_STATUS);

        final DeviceCommandUpdate commandUpdate = new DeviceCommandUpdate();
        commandUpdate.setStatus("OK");

        when(requestHandler.handle(any(Request.class))).then(invocation -> Response.newBuilder()
                .buildSuccess());

        deviceCommandService.update(deviceCommand, commandUpdate).
                thenAccept(Assert::assertNull).get(15, TimeUnit.SECONDS);

        verify(requestHandler, times(2)).handle(argument.capture());
    }

    @Test
    public void should_insert_notification() throws Exception {
        final DeviceVO deviceVO = new DeviceVO();
        deviceVO.setId(System.nanoTime());
        deviceVO.setDeviceId(UUID.randomUUID().toString());

        final DeviceNotification deviceNotification = new DeviceNotification();
        deviceNotification.setId(System.nanoTime());
        deviceNotification.setTimestamp(new Date());
        deviceNotification.setNotification(RandomStringUtils.randomAlphabetic(10));
        deviceNotification.setDeviceId(deviceVO.getDeviceId());

        when(requestHandler.handle(any(Request.class))).thenReturn(Response.newBuilder()
                .withBody(new NotificationInsertResponse(deviceNotification))
                .buildSuccess());

        notificationService.insert(deviceNotification, deviceVO)
                .thenAccept(notification -> assertEquals(deviceNotification, notification))
                .exceptionally(ex -> {
                    fail(ex.toString());
                    return null;
                }).get(15, TimeUnit.SECONDS);

        verify(requestHandler, times(1)).handle(argument.capture());

        NotificationInsertRequest request = argument.getValue().getBody().cast(NotificationInsertRequest.class);
        assertEquals(Action.NOTIFICATION_INSERT_REQUEST, request.getAction());
        assertEquals(deviceNotification, request.getDeviceNotification());
    }

    @Test
    public void should_find_notification() throws Exception {
        final String deviceId = UUID.randomUUID().toString();
        final long id = System.currentTimeMillis();
        final String notification = "Expected notification";
        final Date timestamp = new Date();
        final String parameters = "{\"param1\":\"value1\",\"param2\":\"value2\"}";

        final DeviceNotification deviceNotification = new DeviceNotification();
        deviceNotification.setId(id);
        deviceNotification.setDeviceId(deviceId);
        deviceNotification.setNotification(notification);
        deviceNotification.setTimestamp(timestamp);
        deviceNotification.setParameters(new JsonStringWrapper(parameters));

        // return response for any request
        when(requestHandler.handle(any(Request.class))).thenReturn(Response.newBuilder()
                .withBody(new NotificationSearchResponse(Collections.singletonList(deviceNotification)))
                .buildSuccess());

        // call service method
        notificationService.findOne(id, deviceId)
                .thenAccept(opt -> {
                    assertTrue(opt.isPresent());
                    assertEquals(deviceId, opt.get().getDeviceId());
                    assertEquals(timestamp, opt.get().getTimestamp());
                    assertEquals(parameters, opt.get().getParameters().getJsonString());
                    assertEquals(notification, opt.get().getNotification());
                    assertEquals(Long.valueOf(id), opt.get().getId());
                })
                .exceptionally(ex -> {
                    fail(ex.toString());
                    return null;
                }).get(15, TimeUnit.SECONDS);

        verify(requestHandler, times(1)).handle(argument.capture());
        assertEquals(Action.NOTIFICATION_SEARCH_REQUEST, argument.getValue().getBody().getAction());

        NotificationSearchRequest request = argument.getValue().getBody().cast(NotificationSearchRequest.class);
        assertEquals(id, request.getId().longValue());
        assertEquals(deviceId, request.getDeviceId());
        assertNull(request.getStatus());
        assertNull(request.getNames());
        assertNull(request.getTimestampStart());
        assertNull(request.getTimestampEnd());
        assertNull(request.getTimestampEnd());
    }

    @Test
    public void should_save_and_find_devices_by_user() throws UnknownHostException {
        final DeviceVO device = DeviceFixture.createDeviceVO();
        final DeviceUpdate deviceUpdate = DeviceFixture.createDevice(device.getDeviceId());

        final DeviceVO device1 = DeviceFixture.createDeviceVO();
        final DeviceUpdate deviceUpdate1 = DeviceFixture.createDevice(device1.getDeviceId());

        UserVO user = new UserVO();
        user.setLogin(RandomStringUtils.randomAlphabetic(10));
        user.setRole(UserRole.CLIENT);
        user.setAllDeviceTypesAvailable(false);
        user = userService.createUser(user, VALID_PASSWORD);

        UserVO user1 = new UserVO();
        user1.setLogin(RandomStringUtils.randomAlphabetic(10));
        user1.setRole(UserRole.CLIENT);
        user1.setAllDeviceTypesAvailable(false);
        user1 = userService.createUser(user1, VALID_PASSWORD);

        final NetworkVO network = new NetworkVO();
        network.setName("" + randomUUID());
        NetworkVO created = networkService.create(network);
        assertThat(created.getId(), notNullValue());
        userService.assignNetwork(user.getId(), network.getId());
        deviceUpdate.setNetworkId(network.getId());

        final NetworkVO network1 = new NetworkVO();
        network1.setName("" + randomUUID());
        NetworkVO created1 = networkService.create(network1);
        assertThat(created1.getId(), notNullValue());
        userService.assignNetwork(user1.getId(), network1.getId());
        deviceUpdate1.setNetworkId(network1.getId());

        final DeviceTypeVO deviceType = new DeviceTypeVO();
        deviceType.setName("" + randomUUID());
        DeviceTypeVO createdType = deviceTypeService.create(deviceType);
        assertThat(createdType.getId(), notNullValue());
        userService.assignDeviceType(user.getId(), deviceType.getId());
        deviceUpdate.setDeviceTypeId(deviceType.getId());

        final DeviceTypeVO deviceType1 = new DeviceTypeVO();
        deviceType1.setName("" + randomUUID());
        DeviceTypeVO createdType1 = deviceTypeService.create(deviceType1);
        assertThat(createdType1.getId(), notNullValue());
        userService.assignDeviceType(user1.getId(), deviceType1.getId());
        deviceUpdate1.setDeviceTypeId(deviceType1.getId());

        final HivePrincipal principal = new HivePrincipal(user);
        final HiveAuthentication authentication = new HiveAuthentication(principal);
        authentication.setDetails(new HiveAuthentication.HiveAuthDetails(InetAddress.getByName("localhost"), "origin", "bearer"));

        deviceService.deviceSave(device.getDeviceId(), deviceUpdate);
        deviceService.deviceSave(device1.getDeviceId(), deviceUpdate1);

        final List<DeviceVO> devices = deviceService.findByIdWithPermissionsCheck(
                Arrays.asList(device.getDeviceId(), device1.getDeviceId()), principal);
        assertNotNull(devices);
        assertEquals(1, devices.size());
        assertEquals(devices.get(0).getDeviceId(), device.getDeviceId());
    }

    @Test
    public void should_save_and_find_by_device_id() throws UnknownHostException {
        final DeviceVO device = DeviceFixture.createDeviceVO();
        final DeviceUpdate deviceUpdate = DeviceFixture.createDevice(device.getDeviceId());

        final DeviceVO device1 = DeviceFixture.createDeviceVO();
        final DeviceUpdate deviceUpdate1 = DeviceFixture.createDevice(device1.getDeviceId());

        UserVO user = new UserVO();
        user.setLogin(RandomStringUtils.randomAlphabetic(10));
        user.setRole(UserRole.CLIENT);
        user.setAllDeviceTypesAvailable(false);
        user = userService.createUser(user, VALID_PASSWORD);

        UserVO user1 = new UserVO();
        user1.setLogin(RandomStringUtils.randomAlphabetic(10));
        user1.setRole(UserRole.CLIENT);
        user1.setAllDeviceTypesAvailable(false);
        user1 = userService.createUser(user1, VALID_PASSWORD);

        final NetworkVO network = new NetworkVO();
        network.setName("" + randomUUID());
        NetworkVO created = networkService.create(network);
        assertThat(created.getId(), notNullValue());
        userService.assignNetwork(user.getId(), network.getId());
        deviceUpdate.setNetworkId(network.getId());

        final NetworkVO network1 = new NetworkVO();
        network1.setName("" + randomUUID());
        NetworkVO created1 = networkService.create(network1);
        assertThat(created1.getId(), notNullValue());
        userService.assignNetwork(user1.getId(), network1.getId());
        deviceUpdate1.setNetworkId(network1.getId());

        final DeviceTypeVO deviceType = new DeviceTypeVO();
        deviceType.setName("" + randomUUID());
        DeviceTypeVO createdType = deviceTypeService.create(deviceType);
        assertThat(createdType.getId(), notNullValue());
        userService.assignDeviceType(user.getId(), deviceType.getId());
        deviceUpdate.setDeviceTypeId(deviceType.getId());

        final DeviceTypeVO deviceType1 = new DeviceTypeVO();
        deviceType1.setName("" + randomUUID());
        DeviceTypeVO createdType1 = deviceTypeService.create(deviceType1);
        assertThat(createdType1.getId(), notNullValue());
        userService.assignDeviceType(user1.getId(), deviceType1.getId());
        deviceUpdate1.setDeviceTypeId(deviceType1.getId());

        deviceService.deviceSave(device.getDeviceId(), deviceUpdate);
        deviceService.deviceSave(device1.getDeviceId(), deviceUpdate1);

        HivePrincipal principal = new HivePrincipal();
        Set<Long> allowedDeviceTypes = new HashSet<>();
        allowedDeviceTypes.add(deviceType.getId());
        principal.setDeviceTypeIds(allowedDeviceTypes);
        final HiveAuthentication authentication = new HiveAuthentication(principal);
        authentication.setDetails(new HiveAuthentication.HiveAuthDetails(InetAddress.getByName("localhost"), "origin", "bearer"));

        final List<DeviceVO> devices = deviceService.findByIdWithPermissionsCheck(
                Arrays.asList(device.getDeviceId(), device1.getDeviceId()), principal);
        assertNotNull(devices);
        assertEquals(1, devices.size());
        assertEquals(devices.get(0).getDeviceId(), device.getDeviceId());
    }

    @Test
    public void should_update_device_data() throws Exception {
        final DeviceVO device = DeviceFixture.createDeviceVO();
        final DeviceUpdate deviceUpdate = DeviceFixture.createDevice(device.getDeviceId());
        deviceUpdate.setData(new JsonStringWrapper("{'data': 'data'}"));

        UserVO user = new UserVO();
        user.setLogin(RandomStringUtils.randomAlphabetic(10));
        user.setRole(UserRole.ADMIN);
        user.setAllDeviceTypesAvailable(false);
        user = userService.createUser(user, VALID_PASSWORD);

        final NetworkVO network = new NetworkVO();
        network.setName("" + randomUUID());
        NetworkVO created = networkService.create(network);
        assertThat(created.getId(), notNullValue());
        userService.assignNetwork(user.getId(), network.getId());
        deviceUpdate.setNetworkId(network.getId());

        final DeviceTypeVO deviceType = new DeviceTypeVO();
        deviceType.setName("" + randomUUID());
        DeviceTypeVO createdType = deviceTypeService.create(deviceType);
        assertThat(createdType.getId(), notNullValue());
        userService.assignDeviceType(user.getId(), deviceType.getId());
        deviceUpdate.setDeviceTypeId(deviceType.getId());

        deviceService.deviceSave(device.getDeviceId(), deviceUpdate);

        final HivePrincipal principal = new HivePrincipal(user);
        SecurityContextHolder.getContext().setAuthentication(new HiveAuthentication(principal));
        deviceUpdate.setData(null);

        deviceService.deviceSaveAndNotify(device.getDeviceId(), deviceUpdate, principal);

        DeviceVO deviceVO = deviceService.findById(device.getDeviceId());

        assertNull(deviceVO.getData());
    }

    @Test
    public void should_delete_device() {
        final DeviceVO device = DeviceFixture.createDeviceVO();
        final DeviceUpdate deviceUpdate = DeviceFixture.createDevice(device.getDeviceId());

        final NetworkVO network = new NetworkVO();
        network.setName("" + randomUUID());
        NetworkVO created = networkService.create(network);
        deviceUpdate.setNetworkId(created.getId());

        final DeviceTypeVO deviceType = new DeviceTypeVO();
        deviceType.setName("" + randomUUID());
        DeviceTypeVO createdType = deviceTypeService.create(deviceType);
        deviceUpdate.setDeviceTypeId(createdType.getId());

        deviceService.deviceSave(device.getDeviceId(), deviceUpdate);
        DeviceVO existingDevice = deviceService.findByIdWithPermissionsCheck(device.getDeviceId(), null);
        assertNotNull(existingDevice);

        deviceService.deleteDevice(device.getDeviceId());
        existingDevice = deviceService.findByIdWithPermissionsCheck(device.getDeviceId(), null);
        assertNull(existingDevice);
    }

    @Test
    public void should_return_list_of_networks() throws Exception {
        String namePrefix = RandomStringUtils.randomAlphabetic(10);
        for (int i = 0; i < 10; i++) {
            NetworkVO network = new NetworkVO();
            network.setName(namePrefix + randomUUID());
            network.setDescription("network description_" + randomUUID());
            NetworkVO created = networkService.create(network);
            assertThat(created.getId(), notNullValue());
        }
        when(requestHandler.handle(any(Request.class))).thenAnswer(invocation -> {
            Request request = invocation.getArgument(0, Request.class);
            ListNetworkRequest req = request.getBody().cast(ListNetworkRequest.class);
            final List<NetworkVO> networks =
                    networkDao.list(req.getName(), req.getNamePattern(),
                            req.getSortField(), req.isSortOrderAsc(),
                            req.getTake(), req.getSkip(), req.getPrincipal());

            return Response.newBuilder()
                    .withBody(new ListNetworkResponse(networks))
                    .buildSuccess();
        });
        networkService.list(null, namePrefix + "%", null, ASC.name(), 10, 0, null)
                .thenAccept(networks -> assertThat(networks, hasSize(10))).get(5, TimeUnit.SECONDS);

        verify(requestHandler, times(1)).handle(argument.capture());
    }

    @Test
    public void should_delete_network() throws Exception {
        UserVO user = new UserVO();
        user.setLogin(RandomStringUtils.randomAlphabetic(10));
        user.setRole(UserRole.ADMIN);
        user = userService.createUser(user, VALID_PASSWORD);

        String namePrefix = RandomStringUtils.randomAlphabetic(10);
        NetworkVO network = new NetworkVO();
        network.setName(namePrefix + randomUUID());
        network.setDescription("network description_" + randomUUID());

        NetworkVO created = networkService.create(network);
        assertThat(created.getId(), notNullValue());
        userService.assignNetwork(user.getId(), network.getId());

        final HivePrincipal principal = new HivePrincipal(user);
        SecurityContextHolder.getContext().setAuthentication(new HiveAuthentication(principal));

        boolean deleted = networkService.delete(created.getId(), true);
        assertTrue(deleted);

        created = networkDao.find(created.getId());
        assertThat(created, Matchers.nullValue());
    }

    @Test
    public void should_create_user() throws Exception {
        UserVO user = new UserVO();
        user.setLogin(RandomStringUtils.randomAlphabetic(10));
        user.setStatus(UserStatus.ACTIVE);
        user.setRole(UserRole.CLIENT);
        user = userService.createUser(user, VALID_PASSWORD);
        assertThat(user, notNullValue());
        assertThat(user.getId(), notNullValue());
        assertThat(user.getLogin(), notNullValue());
        assertThat(user.getPasswordHash(), notNullValue());
        assertThat(user.getPasswordSalt(), notNullValue());
        assertThat(user.getStatus(), equalTo(UserStatus.ACTIVE));
        assertThat(user.getLoginAttempts(), equalTo(0));
    }

    @Test
    public void should_authenticate_user_successfully() throws Exception {
        UserVO user = new UserVO();
        user.setLogin(RandomStringUtils.randomAlphabetic(10));
        user.setStatus(UserStatus.ACTIVE);
        user.setRole(UserRole.CLIENT);
        user = userService.createUser(user, VALID_PASSWORD);
        assertThat(user, notNullValue());
        assertThat(user.getId(), notNullValue());
        assertThat(user.getLogin(), notNullValue());
        assertThat(user.getPasswordHash(), notNullValue());
        assertThat(user.getPasswordSalt(), notNullValue());
        assertThat(user.getStatus(), equalTo(UserStatus.ACTIVE));

        UserVO authenticated = userService.authenticate(user.getLogin(), VALID_PASSWORD);
        assertThat(authenticated, notNullValue());
        assertThat(authenticated.getLoginAttempts(), equalTo(0));
        assertThat(authenticated.getLastLogin(), notNullValue());
    }

    @Test
    public void should_return_user_by_id() throws Exception {
        UserVO user = new UserVO();
        user.setLogin(RandomStringUtils.randomAlphabetic(10));
        user.setStatus(UserStatus.ACTIVE);
        user.setRole(UserRole.CLIENT);
        user = userService.createUser(user, VALID_PASSWORD);
        assertThat(user, notNullValue());
        assertThat(user.getId(), notNullValue());

        user = userService.findById(user.getId());
        assertThat(user, notNullValue());
        assertThat(user.getId(), notNullValue());
        assertThat(user.getLogin(), notNullValue());
        assertThat(user.getPasswordHash(), notNullValue());
        assertThat(user.getPasswordSalt(), notNullValue());
        assertThat(user.getStatus(), equalTo(UserStatus.ACTIVE));
    }

    @Test
    public void should_delete_user() throws Exception {
        UserVO user = new UserVO();
        user.setLogin(RandomStringUtils.randomAlphabetic(10));
        user.setStatus(UserStatus.ACTIVE);
        user.setRole(UserRole.CLIENT);
        user = userService.createUser(user, VALID_PASSWORD);
        assertThat(user, notNullValue());
        assertThat(user.getId(), notNullValue());

        assertTrue(userService.deleteUser(user.getId()));

        user = userService.findById(user.getId());
        assertThat(user, Matchers.nullValue());
    }

}


text:
require 'spec_helper'

describe Admin::BaseHelper do
  describe :twitter_available? do
    context "when blog has twitter configured" do
      let!(:blog) { create(:blog, twitter_consumer_key: "12345", twitter_consumer_secret: "67890" ) }

      context "when user has twitter configured" do
        let!(:user) { create(:user, twitter_oauth_token: "1234", twitter_oauth_token_secret: "67890" ) }
        it { expect(helper.twitter_available?(blog, user)).to be_true }
      end

      context "when user hasn't twitter configured" do
        let!(:user) { create(:user, twitter_oauth_token: nil) }
        it { expect(helper.twitter_available?(blog, user)).to be_false }
      end
    end

    context "when blog hasn't twitter configured" do
      let!(:blog) { create(:blog, twitter_consumer_key: nil) }

      context "when user has twitter configured" do
        let!(:user) { create(:user, twitter_oauth_token: "1234", twitter_oauth_token_secret: "67890" ) }
        it { expect(helper.twitter_available?(blog, user)).to be_false }
      end

      context "when user hasn't twitter configured" do
        let!(:user) { create(:user, twitter_oauth_token: nil) }
        it { expect(helper.twitter_available?(blog, user)).to be_false }
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
/*global require, module, exports */
var
// Module
    _ = require('lodash'),
    ocl = require('../util/ocl'),
    command = require('../console/command'),
    scenehelper = require('../phys/scenehelper'),
// Local
    ids = [];

require('../common/level');

exports.spawn = function (obj, id) {
    if (!obj.pos) {
        console.warn("Skipping map object without position.");
        return;
    }
    if (obj.mesh) {
        obj.mesh.position.copy(obj.pos);
        obj.mesh.__dirtyPosition = true;
        scenehelper.add(obj.mesh, id);
        ids.push(id);
    }
};

exports.spawnFromDesc = function (desc, id) {
    ocl.load(desc, function (obj) {
        exports.spawn(obj, id);
    });
};

exports.load = function (str) {
    ocl.load(str, function (objList) {
        objList.forEach(exports.spawn);
        console.log("Level loaded");
    });
};

exports.init = _.noop;
exports.initDom = _.noop;
exports.render = _.noop;

exports.update = function (dt, data) {
    _(data.packets).where({type: 'spawnObj'}).forEach(function (pck) {
        exports.spawnFromDesc(pck.string, pck.eid);
    });

    _(data.packets).where({type: 'spawnMany'}).pluck('list').flatten().forEach(function (pck) {
        if (obj.str) {
            exports.spawnFromDesc(obj.str, obj.id);
        }
    });
};


text:
import { expect } from 'chai';
import { action, ReduxApp } from 'src';

// tslint:disable:no-unused-expression

describe(nameof(action), () => {

    it("decorated method dispatches an action", () => {

        class App {

            public value = 0;

            @action
            public increment() {
                this.value = this.value + 1;
            }
        }

        var dispatched = false;

        const app = new ReduxApp(new App());
        app.store.subscribe(() => dispatched = true);

        app.root.increment();
        expect(dispatched).to.be.true;

        app.dispose();
    });

    it("non-decorated method does not dispatch an action", () => {

        class App {
            public value = 0;

            public increment() {
                this.value = this.value + 1;
            }
        }

        var dispatched = false;

        const app = new ReduxApp(new App());
        app.store.subscribe(() => dispatched = true);

        app.root.increment();
        expect(dispatched).to.be.false;

        app.dispose();
    });

});


text:
function Invoke-GitHubRestMethod {
<#
    .SYNOPSIS
    A module specific wrapper for Invoke-ResetMethod

    .DESCRIPTION
    A module specific wrapper for Invoke-ResetMethod

    .PARAMETER Method
    METHOD: GET, POST, PUT, DELETE

    .PARAMETER URI
    Service URI

    .PARAMETER Body
    Payload for the request, if applicable

    .PARAMETER InFile
    The File to upload

    .PARAMETER OutFile
    Path to downloaded file

    .PARAMETER ContentType
    The content type of the file to upload

    .PARAMETER Headers
    Optional Headers to send. This will override the default set provided

    .INPUTS
    System.String

    .OUTPUTS
    System.Management.Automation.PSObject

    .EXAMPLE
    Invoke-GitHubRestMethod -Method POST -URI /api/release/1

#>
[CmdletBinding(DefaultParameterSetName="Standard")][OutputType('System.Management.Automation.PSObject')]

    Param (

        [Parameter(Mandatory=$true, Position=0)]
        [ValidateSet("HEAD","GET","POST","PUT","DELETE", "PATCH")]
        [String]$Method,

        [Parameter(Mandatory=$true, Position=1)]
        [ValidateNotNullOrEmpty()]
        [String]$URI,

        [Parameter(Mandatory=$false, Position=2, ParameterSetName="WithBody")]
        [ValidateNotNullOrEmpty()]
        [String]$Body,

        [Parameter(Mandatory=$false, Position=3, ParameterSetName="InFile")]
        [ValidateNotNullOrEmpty()]
        [String]$InFile,

        [Parameter(Mandatory=$false, Position=4, ParameterSetName="InFile")]
        [ValidateNotNullOrEmpty()]
        [String]$ContentType,

        [Parameter(Mandatory=$false, Position=5, ParameterSetName="OutFile")]
        [ValidateNotNullOrEmpty()]
        [String]$OutFile,

        [Parameter(Mandatory=$false, Position=6)]
        [ValidateNotNullOrEmpty()]
        [System.Collections.IDictionary]$Headers

    )

    # --- Build full URI
    $BaseURI = "https://api.github.com"
    $FullURI = "$($BaseUri)$($URI)"

    # --- Grab the sessionstate variable & test throw if it is null
    $SessionInfo = Get-GitHubSessionInformation -Verbose:$VerbosePreference

    # --- If the headers parameter is not passed use the deafult
    if (!$PSBoundParameters.ContainsKey("Headers")) {

        $Headers = @{

            "Accept" = "application/vnd.github.v3+json"
            "Authorization" = "Basic $($SessionInfo.Authorization)"
        }

    }

    try {

        $Params = @{

            Method = $Method
            Headers = $Headers
            Uri = $FullURI

        }

        if ($PSBoundParameters.ContainsKey("Body")) {

            $Params.Add("Body", $Body)

        }

        if ($PSBoundParameters.ContainsKey("OutFile")) {

            $Params.Add("OutFile", $OutFile)

        }

        if ($PSBoundParameters.ContainsKey("InFile")) {

            $UploadURI = "https://uploads.github.com"
            $Params.Uri = "$($UploadURI)$($URI)"
            $Params.Add("InFile", $InFile)
            $Params.Add("ContentType", $ContentType)

        }

        $Response = Invoke-RestMethod @Params -Verbose:$VerbosePreference

    }
    catch [System.Net.WebException]{

        $PSCallStack = Get-PSCallStack
        throw "$($PSCallStack[1].Command) $($_)"

    }
    catch [Exception] {

        throw $_.Exception.Message

    }
    finally {

        if ($PSVersionTable.PSEdition -eq "Desktop") {

            $ServicePoint = [System.Net.ServicePointManager]::FindServicePoint($FullURI)
            $ServicePoint.CloseConnectionGroup("") | Out-Null

        }

    }

    Write-Output $Response

}


text:
package com.dremio.exec.planner.sql;

import static org.junit.Assert.assertEquals;

import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.dialect.CalciteSqlDialect;
import org.apache.calcite.sql.parser.SqlParserPos;
import org.junit.Test;

import com.dremio.common.exceptions.UserException;
import com.dremio.exec.planner.physical.PlannerSettings;

public class TestSQLConverter {

  private void validateFormattedIs(String sql, SqlParserPos pos, String expected) {
    String formatted = SqlConverter.formatSQLParsingError(sql, pos);
    assertEquals(expected, formatted);
  }

  @Test
  public void testErrorFormating() {
    String sql = "Select * from Foo\nwhere tadadidada;\n";
    validateFormattedIs(sql, new SqlParserPos(1, 2),
        "Select * from Foo\n"
      + " ^\n"
      + "where tadadidada;\n");
    validateFormattedIs(sql, new SqlParserPos(2, 2),
        "Select * from Foo\n"
      + "where tadadidada;\n"
      + " ^\n" );
    validateFormattedIs(sql, new SqlParserPos(1, 10),
        "Select * from Foo\n"
      + "         ^\n"
      + "where tadadidada;\n");
    validateFormattedIs(sql, new SqlParserPos(-11, -10), sql);
    validateFormattedIs(sql, new SqlParserPos(0, 10), sql);
    validateFormattedIs(sql, new SqlParserPos(100, 10), sql);
  }

  @Test(expected = UserException.class)
  public void testFailMultipleQueries() {
    ParserConfig config = new ParserConfig(ParserConfig.QUOTING, 100, PlannerSettings.FULL_NESTED_SCHEMA_SUPPORT.getDefault().getBoolVal());
    SqlConverter.parseSingleStatementImpl("select * from t1; select * from t2", config, false);
  }

  @Test
  public void testPassSemicolon() {
    ParserConfig config = new ParserConfig(ParserConfig.QUOTING, 100, PlannerSettings.FULL_NESTED_SCHEMA_SUPPORT.getDefault().getBoolVal());
    SqlNode node = SqlConverter.parseSingleStatementImpl("select * from t1;", config, false);
    assertEquals("SELECT *\n" +
      "FROM \"t1\"", node.toSqlString(CalciteSqlDialect.DEFAULT).getSql());
  }
}


text:
package com.twu.biblioteca.controller;

import com.twu.biblioteca.entity.Customer;
import com.twu.biblioteca.entityDao.CustomerDao;

import java.util.List;

/**
 * Created by marry on 8/1/15.
 */
public class CustomerController{
    CustomerDao customerDao = new CustomerDao();

    public Customer checkLogin(String libNumber,String password){
        List<Customer> customers = customerDao.getCustomers();
        for (Customer customer : customers) {
            if(libNumber.equals(customer.getLibraryNumber()) && password.equals(customer.getPassword())){
                return customer;
            }
        }
        return null;
    }
}


text:
#include "tests/PathOpsTestCommon.h"
#include "tests/Test.h"

static const double roughlyTests[][2] = {
    {5.0402503619650929e-005, 4.3178054475078825e-005}
};

static const size_t roughlyTestsCount = SK_ARRAY_COUNT(roughlyTests);

DEF_TEST(PathOpsRoughly, reporter) {
    for (size_t index = 0; index < roughlyTestsCount; ++index) {
        bool equal = RoughlyEqualUlps(roughlyTests[index][0], roughlyTests[index][1]);
        REPORTER_ASSERT(reporter, equal);
    }
}


text:
[![Build Status](https://github.com/stripe/stripe-php/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/stripe/stripe-php/actions?query=branch%3Amaster)
[![Latest Stable Version](https://poser.pugx.org/stripe/stripe-php/v/stable.svg)](https://packagist.org/packages/stripe/stripe-php)
[![Total Downloads](https://poser.pugx.org/stripe/stripe-php/downloads.svg)](https://packagist.org/packages/stripe/stripe-php)
[![License](https://poser.pugx.org/stripe/stripe-php/license.svg)](https://packagist.org/packages/stripe/stripe-php)
[![Code Coverage](https://coveralls.io/repos/stripe/stripe-php/badge.svg?branch=master)](https://coveralls.io/r/stripe/stripe-php?branch=master)

The Stripe PHP library provides convenient access to the Stripe API from
applications written in the PHP language. It includes a pre-defined set of
classes for API resources that initialize themselves dynamically from API
responses which makes it compatible with a wide range of versions of the Stripe
API.

## Requirements

PHP 5.6.0 and later.

## Composer

You can install the bindings via [Composer](http://getcomposer.org/). Run the following command:

```bash
composer require stripe/stripe-php
```

To use the bindings, use Composer's [autoload](https://getcomposer.org/doc/01-basic-usage.md#autoloading):

```php
require_once('vendor/autoload.php');
```

## Manual Installation

If you do not wish to use Composer, you can download the [latest release](https://github.com/stripe/stripe-php/releases). Then, to use the bindings, include the `init.php` file.

```php
require_once('/path/to/stripe-php/init.php');
```

## Dependencies

The bindings require the following extensions in order to work properly:

-   [`curl`](https://secure.php.net/manual/en/book.curl.php), although you can use your own non-cURL client if you prefer
-   [`json`](https://secure.php.net/manual/en/book.json.php)
-   [`mbstring`](https://secure.php.net/manual/en/book.mbstring.php) (Multibyte String)

If you use Composer, these dependencies should be handled automatically. If you install manually, you'll want to make sure that these extensions are available.

## Getting Started

Simple usage looks like:

```php
$stripe = new \Stripe\StripeClient('sk_test_BQokikJOvBiI2HlWgH4olfQ2');
$customer = $stripe->customers->create([
    'description' => 'example customer',
    'email' => 'email@example.com',
    'payment_method' => 'pm_card_visa',
]);
echo $customer;
```

### Client/service patterns vs legacy patterns

You can continue to use the legacy integration patterns used prior to version [7.33.0](https://github.com/stripe/stripe-php/blob/master/CHANGELOG.md#7330---2020-05-14). Review the [migration guide](https://github.com/stripe/stripe-php/wiki/Migration-to-StripeClient-and-services-in-7.33.0) for the backwards-compatible client/services pattern changes.

## Documentation

See the [PHP API docs](https://stripe.com/docs/api/?lang=php#intro).

See [video demonstrations][youtube-playlist] covering how to use the library.

## Legacy Version Support

### PHP 5.4 & 5.5

If you are using PHP 5.4 or 5.5, you should consider upgrading your environment as those versions have been past end of life since September 2015 and July 2016 respectively.
Otherwise, you can still use Stripe by downloading stripe-php v6.43.1 ([zip](https://github.com/stripe/stripe-php/archive/v6.43.1.zip), [tar.gz](https://github.com/stripe/stripe-php/archive/6.43.1.tar.gz)) from our [releases page](https://github.com/stripe/stripe-php/releases). This version will work but might not support recent features we added since the version was released and upgrading PHP is the best course of action.

### PHP 5.3

If you are using PHP 5.3, you should upgrade your environment as this version has been past end of life since August 2014.
Otherwise, you can download v5.9.2 ([zip](https://github.com/stripe/stripe-php/archive/v5.9.2.zip), [tar.gz](https://github.com/stripe/stripe-php/archive/v5.9.2.tar.gz)) from our [releases page](https://github.com/stripe/stripe-php/releases). This version will continue to work with new versions of the Stripe API for all common uses.

## Custom Request Timeouts

> **Note**
> We do not recommend decreasing the timeout for non-read-only calls (e.g. charge creation), since even if you locally timeout, the request on Stripe's side can still complete. If you are decreasing timeouts on these calls, make sure to use [idempotency tokens](https://stripe.com/docs/api/?lang=php#idempotent_requests) to avoid executing the same transaction twice as a result of timeout retry logic.

To modify request timeouts (connect or total, in seconds) you'll need to tell the API client to use a CurlClient other than its default. You'll set the timeouts in that CurlClient.

```php
// set up your tweaked Curl client
$curl = new \Stripe\HttpClient\CurlClient();
$curl->setTimeout(10); // default is \Stripe\HttpClient\CurlClient::DEFAULT_TIMEOUT
$curl->setConnectTimeout(5); // default is \Stripe\HttpClient\CurlClient::DEFAULT_CONNECT_TIMEOUT

echo $curl->getTimeout(); // 10
echo $curl->getConnectTimeout(); // 5

// tell Stripe to use the tweaked client
\Stripe\ApiRequestor::setHttpClient($curl);

// use the Stripe API client as you normally would
```

## Custom cURL Options (e.g. proxies)

Need to set a proxy for your requests? Pass in the requisite `CURLOPT_*` array to the CurlClient constructor, using the same syntax as `curl_stopt_array()`. This will set the default cURL options for each HTTP request made by the SDK, though many more common options (e.g. timeouts; see above on how to set those) will be overridden by the client even if set here.

```php
// set up your tweaked Curl client
$curl = new \Stripe\HttpClient\CurlClient([CURLOPT_PROXY => 'proxy.local:80']);
// tell Stripe to use the tweaked client
\Stripe\ApiRequestor::setHttpClient($curl);
```

Alternately, a callable can be passed to the CurlClient constructor that returns the above array based on request inputs. See `testDefaultOptions()` in `tests/CurlClientTest.php` for an example of this behavior. Note that the callable is called at the beginning of every API request, before the request is sent.

### Configuring a Logger

The library does minimal logging, but it can be configured
with a [`PSR-3` compatible logger][psr3] so that messages
end up there instead of `error_log`:

```php
\Stripe\Stripe::setLogger($logger);
```

### Accessing response data

You can access the data from the last API response on any object via `getLastResponse()`.

```php
$customer = $stripe->customers->create([
    'description' => 'example customer',
]);
echo $customer->getLastResponse()->headers['Request-Id'];
```

### SSL / TLS compatibility issues

Stripe's API now requires that [all connections use TLS 1.2](https://stripe.com/blog/upgrading-tls). Some systems (most notably some older CentOS and RHEL versions) are capable of using TLS 1.2 but will use TLS 1.0 or 1.1 by default. In this case, you'd get an `invalid_request_error` with the following error message: "Stripe no longer supports API requests made with TLS 1.0. Please initiate HTTPS connections with TLS 1.2 or later. You can learn more about this at [https://stripe.com/blog/upgrading-tls](https://stripe.com/blog/upgrading-tls).".

The recommended course of action is to [upgrade your cURL and OpenSSL packages](https://support.stripe.com/questions/how-do-i-upgrade-my-stripe-integration-from-tls-1-0-to-tls-1-2#php) so that TLS 1.2 is used by default, but if that is not possible, you might be able to solve the issue by setting the `CURLOPT_SSLVERSION` option to either `CURL_SSLVERSION_TLSv1` or `CURL_SSLVERSION_TLSv1_2`:

```php
$curl = new \Stripe\HttpClient\CurlClient([CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1]);
\Stripe\ApiRequestor::setHttpClient($curl);
```

### Per-request Configuration

For apps that need to use multiple keys during the lifetime of a process, like
one that uses [Stripe Connect][connect], it's also possible to set a
per-request key and/or account:

```php
$customers = $stripe->customers->all([],[
    'api_key' => 'sk_test_...',
    'stripe_account' => 'acct_...'
]);

$stripe->customers->retrieve('cus_123456789', [], [
    'api_key' => 'sk_test_...',
    'stripe_account' => 'acct_...'
]);
```

### Configuring CA Bundles

By default, the library will use its own internal bundle of known CA
certificates, but it's possible to configure your own:

```php
\Stripe\Stripe::setCABundlePath("path/to/ca/bundle");
```

### Configuring Automatic Retries

The library can be configured to automatically retry requests that fail due to
an intermittent network problem:

```php
\Stripe\Stripe::setMaxNetworkRetries(2);
```

[Idempotency keys][idempotency-keys] are added to requests to guarantee that
retries are safe.

### Request latency telemetry

By default, the library sends request latency telemetry to Stripe. These
numbers help Stripe improve the overall latency of its API for all users.

You can disable this behavior if you prefer:

```php
\Stripe\Stripe::setEnableTelemetry(false);
```

### Beta SDKs

Stripe has features in the beta phase that can be accessed via the beta version of this package.
We would love for you to try these and share feedback with us before these features reach the stable phase.
Use the `composer require` command with an exact version specified to install the beta version of the stripe-php pacakge.

```bash
composer require stripe/stripe-php:v9.2.0-beta.1
```

> **Note**
> There can be breaking changes between beta versions. Therefore we recommend pinning the package version to a specific beta version in your composer.json file. This way you can install the same version each time without breaking changes unless you are intentionally looking for the latest beta version.

We highly recommend keeping an eye on when the beta feature you are interested in goes from beta to stable so that you can move from using a beta version of the SDK to the stable version.

If your beta feature requires a `Stripe-Version` header to be sent, use the `apiVersion` property of `config` object to set it:

```php
Stripe::setApiVersion(Stripe::getApiVersion() . '; feature_beta=v3');
```

## Support

New features and bug fixes are released on the latest major version of the Stripe PHP library. If you are on an older major version, we recommend that you upgrade to the latest in order to use the new features and bug fixes including those for security vulnerabilities. Older major versions of the package will continue to be available for use, but will not be receiving any updates.

## Development

Get [Composer][composer]. For example, on Mac OS:

```bash
brew install composer
```

Install dependencies:

```bash
composer install
```

The test suite depends on [stripe-mock], so make sure to fetch and run it from a
background terminal ([stripe-mock's README][stripe-mock] also contains
instructions for installing via Homebrew and other methods):

```bash
go get -u github.com/stripe/stripe-mock
stripe-mock
```

Install dependencies as mentioned above (which will resolve [PHPUnit](http://packagist.org/packages/phpunit/phpunit)), then you can run the test suite:

```bash
./vendor/bin/phpunit
```

Or to run an individual test file:

```bash
./vendor/bin/phpunit tests/Stripe/UtilTest.php
```

Update bundled CA certificates from the [Mozilla cURL release][curl]:

```bash
./update_certs.php
```

The library uses [PHP CS Fixer][php-cs-fixer] for code formatting. Code must be formatted before PRs are submitted, otherwise CI will fail. Run the formatter with:

```bash
./vendor/bin/php-cs-fixer fix -v .
```

## Attention plugin developers

Are you writing a plugin that integrates Stripe and embeds our library? Then please use the `setAppInfo` function to identify your plugin. For example:

```php
\Stripe\Stripe::setAppInfo("MyAwesomePlugin", "1.2.34", "https://myawesomeplugin.info");
```

The method should be called once, before any request is sent to the API. The second and third parameters are optional.

### SSL / TLS configuration option

See the "SSL / TLS compatibility issues" paragraph above for full context. If you want to ensure that your plugin can be used on all systems, you should add a configuration option to let your users choose between different values for `CURLOPT_SSLVERSION`: none (default), `CURL_SSLVERSION_TLSv1` and `CURL_SSLVERSION_TLSv1_2`.

[composer]: https://getcomposer.org/
[connect]: https://stripe.com/connect
[curl]: http://curl.haxx.se/docs/caextract.html
[idempotency-keys]: https://stripe.com/docs/api/?lang=php#idempotent_requests
[php-cs-fixer]: https://github.com/FriendsOfPHP/PHP-CS-Fixer
[psr3]: http://www.php-fig.org/psr/psr-3/
[stripe-mock]: https://github.com/stripe/stripe-mock
[youtube-playlist]: https://www.youtube.com/playlist?list=PLy1nL-pvL2M6cUbiHrfMkXxZ9j9SGBxFE


text:
<!doctype html>

pq

    <form method="post" action="/record">

        Item:
        <input type="text" name="item">

        <input type="submit" value="Record">

    </form>

    <button id="btn1" type="button">Analysis</button>
    <canvas id="timeline" width="1200" height="300" style="border:1px solid blue;">[No canvas support]</canvas>


text:
from six.moves import (SimpleHTTPServer, BaseHTTPServer)
from threading import Thread
from six.moves import socketserver
import socket
import traceback
from decimal import Decimal
import base64
import cgi
import json
import codecs
import uuid
import io

class FloSrvException(Exception): pass

class FlorinCoinSrv(object):
    '''Acts as a JSONRPC server, simulating a Florincoin wallet/node
    '''

    PORT = 19929
    CURRENT_BAL = Decimal('10.0')
    Blocks = { }

    class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler):
        def __init__(self, request, client_addr, server):
            SimpleHTTPServer.SimpleHTTPRequestHandler.__init__(self, request, client_addr, server)
            self.server = server

        def log_message(self, format, *args):
            pass

        def _handle_req(self):
            text = self.rfile.read(int(self.headers['Content-Length'])).decode('utf-8')
            req = json.loads(text)

            funcname = 'handle_' + req['method']
            req_handler = getattr(self, 'handle_' + req['method'])
            return req_handler(*req['params'])

        def handle_getaccountaddress(self, params):
            return 'addr'

        def handle_getblockhash(self, blocknum):
            for bhash, block in FlorinCoinSrv.Blocks.items():
                if block['height'] == blocknum:
                    return block['hash']
            return None

        def handle_decoderawtransaction(self, txraw):
            return json.loads(txraw)

        def handle_getrawtransaction(self, txid):
            tx_bytes = io.BytesIO(codecs.encode(json.dumps(self.server.Transactions[txid]), 'utf-8'))
            encoded = base64.b64encode(tx_bytes.getvalue())
            return json.dumps(self.server.Transactions[txid])

        def handle_getblock(self, blockhash):
            return FlorinCoinSrv.Blocks[blockhash]

        def handle_getbalance(self):
            return str(FlorinCoinSrv.CURRENT_BAL)

        def handle_sendtoaddress(self, addr, amount, comment, comment_to, tx_comment):
            if len(tx_comment) > 528:
                raise FloSrvException('tx-comment too long: {}'.format(len(tx_comment)))
            txid = str(hash(uuid.uuid1()))
            tx = { 'addr': addr, 'amount': amount, 'comment': comment, 'comment-to': comment_to,
                   'tx-comment': tx_comment,
                  }
            other_txids = list(str(uuid.uuid1()) for i in range(7))
            blocknum = len(FlorinCoinSrv.Blocks)
            blockhash = str(uuid.uuid1())
            block = {  'size': 0,
                      'tx': [txid] + other_txids, 'height': blocknum, 'hash': blockhash,
                    }
            FlorinCoinSrv.Blocks[blockhash] = block
            self.server.Transactions[txid] = tx
            filler_tx = { 'addr': 'filler', 'amount': 3.33, 'comment': 'filler', 'comment-to': 'filler',
                   'tx-comment': 'filler',
                  }
            for txid_ in other_txids:
                self.server.Transactions[txid_] = filler_tx

            return txid

        def handle_getblockcount(self):
            return len(FlorinCoinSrv.Blocks)

        def do_POST(self):
            try:
                result = self._handle_req()
                success = True
                response = {'result': result, }
            except (TypeError, KeyError, AttributeError, IndexError, FloSrvException) as e:
                success = False
                response = {'result': None, 'errors': str(e), }
            self.send_response(200 if success else 500)
            self.end_headers()
            self.wfile.write(codecs.encode(json.dumps(response), ('utf-8')))

        def do_GET(self):
            self.send_response(500)
            self.end_headers()

    class AnHTTPServer(BaseHTTPServer.HTTPServer):
        def __init__(self, *args, **kw):
            BaseHTTPServer.HTTPServer.__init__(self, *args, **kw)
            self.allow_reuse_address = True
            self.Transactions = {}

    def __init__(self):
        self.httpd = FlorinCoinSrv.AnHTTPServer(("", FlorinCoinSrv.PORT), FlorinCoinSrv.Handler)
        self.httpd_thread = Thread(target=self.httpd.serve_forever, group=None)
        self.httpd_thread.start()

    def __del__(self):
        self.httpd.shutdown()
        self.httpd.server_close()
        del self.httpd
        self.httpd_thread.join()
        del self.httpd_thread

    @property
    def url(self):
        return u'http://localhost:{}'.format(FlorinCoinSrv.PORT)

    @property
    def username(self):
        return 'user'

    @property
    def passwd(self):
        return 'pass'


text:
using System;
using AzureVmFarmer.Objects;
using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;
using Microsoft.WindowsAzure;

namespace AzureVmFarmer.Core.Messengers.Impl
{
	public class Messenger : IMessenger
	{
		public void QueueCreateMessage(VirtualMachine virtualMachine)
		{
			QueueMessage("Create", virtualMachine);
		}

		public void QueueDeleteMessage(VirtualMachine virtualMachine)
		{
			QueueMessage("Delete", virtualMachine);
		}

		private static void QueueMessage(string messageType, VirtualMachine virtualMachine)
		{
			if (VirtualMachine.IsValid(virtualMachine) == false)
			{
				throw new ArgumentException("Invalid virtual machine.", "virtualMachine");
			}

			var connectionString = CloudConfigurationManager.GetSetting("ServiceBus.ConnectionString");
			var queueName = CloudConfigurationManager.GetSetting("QueueName");

			var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

			if (!namespaceManager.QueueExists(queueName))
			{
				var queue = new QueueDescription(queueName)
				{
					DefaultMessageTimeToLive = new TimeSpan(7, 0, 0, 0)
				};

				namespaceManager.CreateQueue(queue);
			}

			var message = PrepareMessage(messageType, virtualMachine);

			var client = QueueClient.CreateFromConnectionString(connectionString, queueName);

			client.Send(message);
		}

		private static BrokeredMessage PrepareMessage(string messageType, VirtualMachine virtualMachine)
		{
			var message = new BrokeredMessage();
			message.SetMessageType(messageType);
			message.SetObject(virtualMachine);

			return message;
		}
	}
}


text:
/**
 * Created by cassidy on 2/9/18.
 */

var mack = [];
mack.push('Mack');
mack.push('the', 'Knife');

console.log(mack.join(" "));
console.log(mack);
console.log(mack.pop());
console.log(mack);

var todoList = [];
function rememberTo(task) {
    todoList.push(task);
}
function whatIsNext() {
    return todoList.shift();
}
function urgentlyRememberTo(task) {
    todoList.unshift(task);
}

rememberTo('study Javascript');
whatIsNext('make dinner');
urgentlyRememberTo('breath');
console.log(todoList);

console.log([1,2,3,2,1].indexOf(2));
console.log([1,2,3,2,1].lastIndexOf(2));

console.log([0,1,2,3,4].slice(2,4));
console.log([0,1,2,3,4].slice(2));

function argumentCounter() {
    console.log("You gave me", arguments.length, "arguments.");
}
argumentCounter("Straw man", "Tautology", "Ad hominem");

console.log(Math.floor(Math.random() * 10));


text:
<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

    <android.support.v7.widget.GridLayout android:id="@+id/demo_container"
                                          xmlns:app="http://schemas.android.com/apk/res-auto"
                                          android:layout_width="match_parent"
                                          android:layout_height="wrap_content"
                                          android:clickable="false"
                                          android:padding="16dp"
                                          app:columnCount="2"
                                          app:useDefaultMargins="true">

        <EditText
            android:id="@+id/demo_name"
            android:layout_width="match_parent"
            android:layout_height="@dimen/row_height"
            android:hint="@string/demo_name"
            android:singleLine="true"
            app:layout_column="0"
            app:layout_columnSpan="2"
            app:layout_row="0"/>

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/demo_number_of_participants"
            app:layout_column="0"
            app:layout_row="1"/>

        <EditText
            android:id="@+id/demo_participants"
            android:layout_width="@dimen/form_width"
            android:layout_height="@dimen/row_height"
            android:hint="@string/demo_participants_hint"
            android:inputType="number"
            android:singleLine="true"
            app:layout_column="1"
            app:layout_gravity="right"
            app:layout_row="1"/>

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="@dimen/row_height"
            android:text="@string/demo_date"
            app:layout_column="0"
            app:layout_row="2"/>

        <TextView
            android:id="@+id/demo_date"
            android:layout_width="@dimen/form_width"
            android:layout_height="@dimen/row_height"
            android:background="?selectableItemBackgroundBorderless"
            android:gravity="left|center_vertical"
            android:singleLine="true"
            android:text="@string/demo_pick_date"
            app:layout_column="1"
            app:layout_gravity="right"
            app:layout_row="2"/>

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/demo_type"
            app:layout_column="0"
            app:layout_row="3"/>

        <Spinner
            android:id="@+id/demo_spinner"
            android:layout_width="@dimen/form_width"
            android:layout_height="@dimen/row_height"
            android:spinnerMode="dropdown"
            app:layout_column="1"
            app:layout_gravity="right"
            app:layout_row="3"/>

        <TextView
            android:id="@+id/textView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/demo_email"
            app:layout_column="0"
            app:layout_row="4"/>

        <EditText
            android:id="@+id/demo_email"
            android:layout_width="@dimen/form_width"
            android:layout_height="@dimen/row_height"
            android:hint="@string/demo_email_hint"
            android:inputType="textEmailAddress"
            android:singleLine="true"
            app:layout_column="1"
            app:layout_gravity="right"
            app:layout_row="4"/>

        <TextView
            android:id="@+id/textView5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/demo_address"
            app:layout_column="0"
            app:layout_row="5"/>

        <EditText
            android:id="@+id/demo_address1"
            android:layout_width="@dimen/form_width"
            android:layout_height="@dimen/row_height"
            android:hint="@string/demo_address"
            android:inputType="textPostalAddress"
            android:singleLine="true"
            app:layout_column="1"
            app:layout_gravity="right"
            app:layout_row="5"/>

        <EditText
            android:id="@+id/demo_address2"
            android:layout_width="@dimen/form_width"
            android:layout_height="@dimen/row_height"
            android:hint="@string/demo_address"
            android:inputType="textPostalAddress"
            android:singleLine="true"
            app:layout_column="1"
            app:layout_gravity="right"
            app:layout_row="6"/>

        <Button
            android:id="@+id/demo_ok"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@android:string/ok"
            app:layout_column="0"
            app:layout_columnSpan="2"
            app:layout_gravity="bottom"
            app:layout_row="7"/>
    </android.support.v7.widget.GridLayout>
</ScrollView>


text:
package es.urjc.code.practica.offers;

import java.util.List;

import org.hibernate.criterion.Order;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;

public interface OfferRepository extends JpaRepository<Offer, Long> {

    Offer findById(Long id);

    Offer findByName(String name);

	//Page<Offer> findAll(Pageable page);

}


text:
DELIMITER /
--
-- Copyright 2005-2014 The Kuali Foundation
--
-- Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
--
-- 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.
--

-- KULRICE-5360 add KIM entity fields
alter table KRIM_ENTITY_NM_T add column TITLE_NM VARCHAR(20)
/
alter table KRIM_ENTITY_NM_T add column NOTE_MSG VARCHAR(1024)
/
alter table KRIM_ENTITY_NM_T add column NM_CHNG_DT DATETIME
/

alter table KRIM_ENTITY_ADDR_T add column ATTN_LINE VARCHAR(45)
/
alter table KRIM_ENTITY_ADDR_T add column ADDR_FMT VARCHAR(256)
/
alter table KRIM_ENTITY_ADDR_T add column MOD_DT DATETIME
/
alter table KRIM_ENTITY_ADDR_T add column VALID_DT DATETIME
/
alter table KRIM_ENTITY_ADDR_T add column VALID_IND VARCHAR(1)
/
alter table KRIM_ENTITY_ADDR_T add column NOTE_MSG VARCHAR(1024)
/

alter table KRIM_ENTITY_BIO_T add column NOTE_MSG VARCHAR(1024)
/
alter table KRIM_ENTITY_BIO_T add column GNDR_CHG_CD VARCHAR(20)
/

alter table KRIM_PND_NM_MT add column TITLE_NM VARCHAR(20)
/
alter table KRIM_PND_NM_MT add column NOTE_MSG VARCHAR(1024)
/
alter table KRIM_PND_NM_MT add column NM_CHNG_DT DATETIME
/

alter table KRIM_PND_ADDR_MT add column ATTN_LINE VARCHAR(45)
/
alter table KRIM_PND_ADDR_MT add column ADDR_FMT VARCHAR(256)
/
alter table KRIM_PND_ADDR_MT add column MOD_DT DATETIME
/
alter table KRIM_PND_ADDR_MT add column VALID_DT DATETIME
/
alter table KRIM_PND_ADDR_MT add column VALID_IND VARCHAR(1)
/
alter table KRIM_PND_ADDR_MT add column NOTE_MSG VARCHAR(1024)
/
DELIMITER ;


text:
zipkin-infrastructure
=====================

All components needed to run Zipkin in Docker containers (Cassandra, Collector, Query, Web, and FB-Scribe)
We build a Zipkin base container installing scala and zipkin.
From this docker image, we derive the specific zipkin parts to combine a zipkin infrastructure.
Directorey fb-scribe will generate a facebook [scribe](https://github.com/facebookarchive/scribe) service
ready to communicat with zipkin collector. The same functionallity can be obtained by using a [Scala Akka Tracing](https://github.com/levkhomich/akka-tracing) mechanism.

![Zipkin infrascructure overview](zipkin-architecture-overview.jpg)

### Zipkin Port Structure
The ports and how to relate them is described in file [Ports.md](Ports.md).

#### AWS security group
As cassandra uses many ports a possible AWS security group is described by [DATASTAX](http://www.datastax.com/documentation/cassandra/2.0/cassandra/install/installAMISecurityGroup.html).

#### Building containers

Building the scribe container takes between 10 and 15 minutes on a 2GHz CPU depending on the memory available.
The resulting image is about 800MB. We had to start an AMI of type `t2` to not run out of memory.
#### Usage
Two scripts build and deploy zipkin containers. To build them freshly just call [`./build.sh `](build.sh)` -f` and to pull them from registry call `./build.sh -r`.
To deploy and run zipkin container on one host call [`./deploy.sh`](deploy.sh)` -r` and to cleanup old containers call `./deploy.sh -c`.
######TODO
 * Check for container link between web and query?
 * Configure linking between fb-scribe (or akka) and collector (`COLLECTOR_PORT`) running on different docker hosts.

#### Notes

Docker-Zipkin starts the services in their own container: zipkin-cassandra,
zipkin-collector, zipkin-query, zipkin-web and only link required dependencies
together.

The started Zipkin instance would be backed by a single node Cassandra. By
default, the collector port is not mapped to public. You will need to link
containers that you wish to trace with zipkin-collector or you may change the
respective line in deploy.sh to map the port.

All images with the exception of zipkin-cassandra are sharing a base image:
[base](https://github.com/elemica/zipkin-infrastructure/tree/master/base). zipkin-base and zipkin-cassandra are built on ubuntu:12.04.

Once the containers are running you can connect to the collector on
port 9410 via akka-tracing or other libraries that support Zipkin tracing. <https://github.com/levkhomich/akka-tracing>

#### Dockerfile
We try to place as many installation commands into Docker files, to ease the build process:
 * Each build step is frozen as an intermediate container
 * Errors during build don`t require rerunning it completely
 * Testing new install instructions start from a partly build process and thus run faster

#### Directory structure

 * [base](https://github.com/elemica/zipkin-infrastructure/tree/master/base) docker container with scala and zipkin installed
 * [cassandra](https://github.com/elemica/zipkin-infrastructure/tree/master/cassandra) docker container with cassandra installed
 * [collector](https://github.com/elemica/zipkin-infrastructure/tree/master/collector) docker container with zipkin collector installed
 * [query](https://github.com/elemica/zipkin-infrastructure/tree/master/query) docker container with zipkin query installed
 * [web](https://github.com/elemica/zipkin-infrastructure/tree/master/web) docker container with zipkin web
 * [script](https://github.com/elemica/zipkin-infrastructure/tree/master/script) contains utilites to manage (build, push, pull, start, deploy ) the zipkin container.

#### Source
This repo is cloned from [https://github.com/lispmeister/docker-zipkin.git](https://github.com/lispmeister/docker-zipkin.git)
Zipkin base installation is describe in the [twitter zipkin repo](https://github.com/twitter/zipkin/blob/master/doc/install.md) and further configuration in detail in [Zipkin, from Twitter](http://twitter.github.io/zipkin/install.html).
#### Authors

Michael Klöckner <mkl@im7.de>

Markus Fix <lispmeister@gmail.com>


text:
using System;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using JabbR.Models.Mapping;

namespace JabbR.Models
{
    public class JabbrContext : DbContext
    {
        public JabbrContext()
            : base("Jabbr")
        {
            ((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized += OnObjectContextObjectMaterialized;
        }

        private void OnObjectContextObjectMaterialized(object sender, ObjectMaterializedEventArgs e)
        {
            var entityChatUser = e.Entity as ChatUser;
            if (entityChatUser != null)
            {
                entityChatUser.LastActivity = DateTime.SpecifyKind(entityChatUser.LastActivity, DateTimeKind.Utc);
            }
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new ChatClientMap());

            modelBuilder.Configurations.Add(new ChatMessageMap());

            modelBuilder.Configurations.Add(new ChatRoomMap());

            modelBuilder.Configurations.Add(new ChatUserMap());

            modelBuilder.Configurations.Add(new AttachmentMap());

            modelBuilder.Configurations.Add(new NotificationMap());

            base.OnModelCreating(modelBuilder);
        }

        public DbSet<ChatClient> Clients { get; set; }
        public DbSet<ChatMessage> Messages { get; set; }
        public DbSet<ChatRoom> Rooms { get; set; }
        public DbSet<ChatUser> Users { get; set; }
        public DbSet<ChatUserIdentity> Identities { get; set; }
        public DbSet<Attachment> Attachments { get; set; }
        public DbSet<Notification> Notifications { get; set; }
        public DbSet<Settings> Settings { get; set; }
    }
}


text:
package controllers.group

import models.dao.application.applicationDao
import models.dao.group.{groupDao, permissionGroupDao, userGroupDao}
import models.dao.permission.permissionDao
import models.dao.user.userDao
import models.entity.group.{Group, PermissionGroup, UserGroup}
import play.api.Play.current
import play.api.data.Form
import play.api.data.Forms._
import play.api.db.slick.Config.driver.simple._
import play.api.db.slick._
import play.api.i18n.Messages
import play.api.mvc.{Action, Controller}
import views.html.group._

import scala.collection.mutable.ListBuffer

object GroupManagement extends Controller {

  def  allApplicationsList = DB.withSession { implicit request =>
    applicationDao.dao.applications.list
  }

  /**
   * Form that handle "finding group"
   */
  val searchGroupForm = Form(
    mapping(
      "name" -> default(optional(text), None),
      "refNale" -> default(optional(text), None),
      "applicationID" -> default(optional(number), None)
    )(SearchGroupForm.apply)(SearchGroupForm.unapply)
  )

  /**
   * The form that handle the creation and the update of a group
   */
  val groupForm = Form(
    mapping(
      "id" -> default(optional(number), None),
      "name" -> nonEmptyText,
      "refName" -> nonEmptyText,
      "creationDate" -> default(sqlDate, null),
      "updateDate" -> default(sqlDate, new java.sql.Date(new java.util.Date().getTime)),
      "updatingUser" -> default(text, "user"),
      "description" -> default(optional(text), None),
      "applicationId" -> number
    )(Group.apply)(Group.unapply)
  )

  /**
   * Show the index page of groups management
   */
  def groupIndex = Action { implicit request =>
    Ok(groupManagementView(searchGroupForm, None, allApplicationsList))
  }

  /**
   * Show the group view
   * @param id The id used to retrieve the group informations
   * @return The view page filled with the informations.
   */
  def showGroup(id: Int) = DBAction { implicit request =>
    val group = groupDao.findById(id).first
    val permissions = permissionGroupDao.findPermissions(id).list
    val users = userGroupDao.findUsers(id).list
    val allPermissions = permissionDao.dao.permissions.list
    Ok(groupView(group, Some(permissions), Some(users), Some(allPermissions),None))
  }

  /**
   * Show the group form view.
   * If the id isDefined ,it is an update :
   * - The form is filled with the informations retrieved with the id
   *
   * If the id is not defined, it is a creation :
   * - The form is initialised as an empty form.
   * @param id The id of the group to update , None if creation
   * @return The form view with the form initialized.
   */
  def showGroupForm(id: Option[Int]) = DBAction { implicit request =>
    if (id.isDefined) {
      val group = groupDao.findById(id.get).first
      val filledGroupForm = groupForm.fill(group)
      Ok(groupFormView(filledGroupForm, allApplicationsList)(Messages("groupUpdate")))
    }
    else {
      Ok(groupFormView(groupForm, allApplicationsList)(Messages("groupCreation")))
    }
  }

  /**
   * Find a group according tho the searchFrom informations
   * @return The index page with the list of the found groups.
   */
  def findGroup = DBAction { implicit request =>
    searchGroupForm.bindFromRequest.fold(
      formWithErrors => {
        BadRequest(groupManagementView(formWithErrors, None, allApplicationsList))
      },
      validForm => {
        val groupsList = groupDao.findBySearchForm(validForm).list
        Ok(groupManagementView(searchGroupForm.fill(validForm), Some(groupsList), allApplicationsList))
      }
    )
  }

  /**
   * Create a group using the groupForm.
   *
   * If the validation of the form fails, a message is sent to the user
   * If the name or ref name of the group already exists, a message is sent to the user.
   *
   * @return The group view filled with the new group
   */
  def createGroup = DBAction { implicit request =>
    groupForm.bindFromRequest.fold(
      formWithErrors => {
        BadRequest(groupFormView(formWithErrors, allApplicationsList)(Messages("groupCreation")))
      },
      validForm => {
        val groupExists = !groupDao.findByNameOrRefName(validForm.name, validForm.refName).list.isEmpty
        if (groupExists) {
          BadRequest(groupFormView(groupForm.fill(validForm).withGlobalError(Messages("groupExists")), allApplicationsList)(Messages("groupCreation")))
        }
        else {
          val group = Group(validForm.id, validForm.name, validForm.refName, new java.sql.Date(new java.util.Date().getTime), validForm.updateDate, validForm.updatingUser, validForm.description, validForm.applicationId)
          groupDao.dao.groups += group
          Redirect(routes.GroupManagement.showGroup(groupDao.findByRefName(validForm.refName).first.id.get))
        }
      }
    )
  }

  /**
   * Update the infos of a group.
   * If the name or the ref name is changed, and the one of the new ones is already in use, a message is sent to the user.
   * @return The group view filled with the updated user
   */
  def updateGroup = DBAction { implicit request =>
    groupForm.bindFromRequest.fold(
      formWithErrors => {
        BadRequest(groupFormView(formWithErrors, allApplicationsList)(Messages("groupUpdate")))
      },
      validForm => {
        val groupExists = groupDao.findByNameOrRefName(validForm.name, validForm.refName).list
        if (!groupExists.isEmpty && groupExists(0).id != validForm.id) {
          BadRequest(groupFormView(groupForm.fill(validForm).withGlobalError(Messages("groupExists")), allApplicationsList)(Messages("groupUpdate")))
        }
        else {
          groupDao.findById(validForm.id.get)
            .map(g => (g.name, g.refName, g.descritpion, g.updatingUser, g.updateDate, g.applicationId))
            .update((validForm.name, validForm.refName, validForm.description.orNull, validForm.updatingUser, validForm.updateDate, validForm.applicationId))
          Redirect(routes.GroupManagement.showGroup(validForm.id.get))
        }
      }
    )
  }

  /**
   * Delete a selected group
   * If the group contains user or permission ,
   * a message is sent to the user to remove them from the group before deletion
   * @param id The id of the group to delete
   * @return The group index page
   */
  def deleteGroup(id: Int) = DBAction { implicit request =>
    val permissionGroupListIsEmpty = permissionGroupDao.findPermissions(id).list.isEmpty
    val userGroupListIsEmpty = userGroupDao.findUsers(id).list.isEmpty
    if (!permissionGroupListIsEmpty || !userGroupListIsEmpty) {
      val group = groupDao.findById(id).first
      val permissions = permissionGroupDao.findPermissions(id).list
      val users = userGroupDao.findUsers(id).list
      val listeMessage = {
        var messages = ListBuffer[String]()
        if(!permissionGroupListIsEmpty) messages += Messages("groupStillContainsPermissions")
        if (!userGroupListIsEmpty) messages += Messages("groupStillContainsUsers")
        messages.toList
      }
      val allPermissions = permissionDao.dao.permissions.list
      BadRequest(groupView(group, Some(permissions), Some(users), Some(allPermissions),Some(listeMessage)))
    }
    else {
      groupDao.findById(id).mutate(_.delete)
      Redirect(routes.GroupManagement.groupIndex())
    }
  }

  /**
   * Add a permission to a group
   * @param groupId The id of the group
   * @param permissionId The id of the permission we want to add
   * @return The group view with updated data
   */
  def addPermissionToGroup(groupId: Int, permissionId: Int) = DBAction { implicit request =>
    permissionGroupDao.dao.permissionsGroups += PermissionGroup(None, permissionId, groupId, new java.sql.Date(new java.util.Date().getTime))
    Redirect(routes.GroupManagement.showGroup(groupId))
  }

  /**
   * Add a user to a group by using his userName or last and firstName
   * @param groupId The id of the group
   * @param userLastName The lastName of the user
   * @param userFirstName The firstName of the user
   * @param userUserName The userName of the user
   * @return The group view with data updated.
   */
  def addUserToGroup(groupId: Int, userLastName: Option[String], userFirstName: Option[String], userUserName: Option[String]) = DBAction { implicit request =>
    val user = {
      if (userUserName.isDefined && !userUserName.isEmpty) Some(userDao.findByUserName(userUserName.get).first)
      else if (userLastName.isDefined && !userLastName.isEmpty && userFirstName.isDefined && !userFirstName.isEmpty) Some(userDao.findByUserLastAndFirstName(userLastName.get, userFirstName.get).first)
      else None
    }
    if (user.isDefined) {
      userGroupDao.dao.usersgroups += UserGroup(None, user.get.id.get, groupId, new java.sql.Date(new java.util.Date().getTime))
    }
    Redirect(routes.GroupManagement.showGroup(groupId))
  }

  /**
   * Remove a permission from a group
   * @param groupId The id of the group
   * @param permissionId The id of the permission we want to remove
   * @return The group view with updated data
   */
  def removePermissionFromGroup(groupId: Int, permissionId: Int) = DBAction { implicit request =>
    permissionGroupDao.findByPermissionAndGroupIds(permissionId, groupId).mutate(_.delete)
    Redirect(routes.GroupManagement.showGroup(groupId))
  }

  /**
   * Remove a user from a group
   * @param groupId The id of the group
   * @param userId The id of the user we want to remove from the group
   * @return The group view with updated data.
   */
  def removeUserFromGroup(groupId: Int, userId: Int) = DBAction { implicit request =>
    userGroupDao.findByUserAndGroupIds(userId, groupId).mutate(_.delete)
    Redirect(routes.GroupManagement.showGroup(groupId))
  }
}


text:
package card;
/**
 * @author Jack Kasbeer
 * Assignment #3
 * Tests the methods of Deck
 */

public class DeckTester{
    public static void main(String[] args){
        Deck d = new Deck();
        System.out.println(d);
        System.out.println(d.getNumberOfCards());
    }
}


text:
<?php namespace Rancherize\Push\CreateModeFactory;

use Pimple\Container;
use Rancherize\Configuration\Configuration;
use Rancherize\Push\CreateMode\CreateMode;

/**
 * Class ContainerCreateModeFactory
 * @package Rancherize\Push\CreateModeFactory
 */
class ContainerCreateModeFactory implements CreateModeFactory  {

	protected $prefix = 'push.create.mode.';

	/**
	 * @var Container
	 */
	private $container;

	/**
	 * @var string
	 */
	private $defaultMode;
	/**
	 * @var CreateModeParser
	 */
	private $createModeParser;

	/**
	 * ContainerCreateModeFactory constructor.
	 * @param Container $container
	 * @param CreateModeParser $createModeParser
	 */
	public function __construct( Container $container, CreateModeParser $createModeParser ) {
		$this->container = $container;
		$this->createModeParser = $createModeParser;
	}

	/**
	 * @param Configuration $configuration
	 * @return mixed
	 */
	public function make( Configuration $configuration ) {
		$mode = $this->createModeParser->getCreateMode($configuration, $this->defaultMode);

		return $this->container[$mode];
	}

	/**
	 * Register a createMode.
	 * If no Mode is registered yet it will be used as the default mode
	 *
	 * @param $modeName
	 * @param CreateMode $createMode
	 */
	public function register( $modeName, CreateMode $createMode ) {
		if( empty($this->defaultMode) )
			$this->defaultMode = $modeName;

		$this->container[$modeName] = function() use ($createMode) {
			return $createMode;
		};
	}

	/**
	 * @param string $defaultMode
	 */
	public function setDefaultMode( string $defaultMode ) {
		$this->defaultMode = $defaultMode;
	}
}


text:
Command: else

Used in conjunction with the *if command, *else is used when prior *if or *elseif checks fail.

Example Usage

*create gender "male"
*create garment "pants"

*if gender = "male"
	*set garment "pants"
	*goto clothing
*if gender = "female"
	*set garment "dress"
	*goto clothing
*else
	*set garment "barrel"
	*goto clothing

*label clothing
Since you're a ${gender}, you pick the ${garment} to wear.

*finish

Looking for a little more detail? Try the wiki page


text:
import warnings

import requests
from requests.exceptions import RequestException

from inapppy.errors import InAppPyValidationError

# https://developer.apple.com/library/content/releasenotes/General/ValidateAppStoreReceipt/Chapters/ValidateRemotely.html
# `Table 2-1  Status codes`
api_result_ok = 0
api_result_errors = {
    21000: InAppPyValidationError("Bad json"),
    21002: InAppPyValidationError("Bad data"),
    21003: InAppPyValidationError("Receipt authentication"),
    21004: InAppPyValidationError("Shared secret mismatch"),
    21005: InAppPyValidationError("Server is unavailable"),
    21006: InAppPyValidationError("Subscription has expired"),
    # two following errors can use auto_retry_wrong_env_request.
    21007: InAppPyValidationError("Sandbox receipt was sent to the production env"),
    21008: InAppPyValidationError("Production receipt was sent to the sandbox env"),
    21009: InAppPyValidationError("Internal data access error"),
    21010: InAppPyValidationError("The user account cannot be found or has been deleted"),
}

class AppStoreValidator:
    def __init__(
        self,
        bundle_id: str = "",
        sandbox: bool = False,
        auto_retry_wrong_env_request: bool = False,
        http_timeout: int = None,
    ):
        """Constructor for AppStoreValidator

        :param bundle_id: apple bundle id (no longer required).
        :param sandbox: sandbox mode ?
        :param auto_retry_wrong_env_request: auto retry on wrong env ?
        """
        if bundle_id:
            warnings.warn(
                "bundle_id will be removed in version 3, since it's not used here.",
                PendingDeprecationWarning,
            )

        self.bundle_id = bundle_id
        self.sandbox = sandbox
        self.http_timeout = http_timeout
        self.auto_retry_wrong_env_request = auto_retry_wrong_env_request

        self._change_url_by_sandbox()

    def _change_url_by_sandbox(self):
        self.url = (
            "https://sandbox.itunes.apple.com/verifyReceipt"
            if self.sandbox
            else "https://buy.itunes.apple.com/verifyReceipt"
        )

    def _prepare_receipt(self, receipt: str, shared_secret: str, exclude_old_transactions: bool) -> dict:
        receipt_json = {"receipt-data": receipt}

        if shared_secret:
            receipt_json["password"] = shared_secret

        if exclude_old_transactions:
            receipt_json["exclude-old-transactions"] = True

        return receipt_json

    def post_json(self, request_json: dict) -> dict:
        self._change_url_by_sandbox()

        try:
            return requests.post(self.url, json=request_json, timeout=self.http_timeout).json()
        except (ValueError, RequestException):
            raise InAppPyValidationError("HTTP error")

    def validate(
        self,
        receipt: str,
        shared_secret: str = None,
        exclude_old_transactions: bool = False,
    ) -> dict:
        """Validates receipt against apple services.

        :param receipt: receipt
        :param shared_secret: optional shared secret.
        :param exclude_old_transactions: optional to include only the latest renewal transaction
        :return: validation result or exception.
        """
        receipt_json = self._prepare_receipt(receipt, shared_secret, exclude_old_transactions)

        api_response = self.post_json(receipt_json)
        status = api_response.get("status", "unknown")

        # Check retry case.
        if self.auto_retry_wrong_env_request and status in [21007, 21008]:
            # switch environment
            self.sandbox = not self.sandbox

            api_response = self.post_json(receipt_json)
            status = api_response["status"]

        if status != api_result_ok:
            error = api_result_errors.get(status, InAppPyValidationError("Unknown API status"))
            error.raw_response = api_response

            raise error

        return api_response


text:
package org.apache.ignite.internal.processors.cache.transactions;

import java.util.concurrent.TimeUnit;
import org.apache.ignite.internal.processors.cache.GridCacheContext;
import org.apache.ignite.internal.util.typedef.internal.U;

/**
 *
 */
public abstract class IgniteTxLocalStateAdapter implements IgniteTxLocalState {
    /**
     * @param cacheCtx Cache context.
     * @param tx Transaction.
     * @param commit {@code False} if transaction rolled back.
     */
    protected final void onTxEnd(GridCacheContext cacheCtx, IgniteInternalTx tx, boolean commit) {
        if (cacheCtx.statisticsEnabled()) {
            long durationNanos = TimeUnit.MILLISECONDS.toNanos(U.currentTimeMillis() - tx.startTime());

            if (commit)
                cacheCtx.cache().metrics0().onTxCommit(durationNanos);
            else
                cacheCtx.cache().metrics0().onTxRollback(durationNanos);
        }
    }
}


text:
require "open3"
require "tempfile"

module TypeScript
  VERSION = '0.1.2'

  class Error < StandardError
  end

  class << self
    def typescript_path
      ENV['TYPESCRIPT_SOURCE_PATH']
    end

    def node_compile(*args)
      if typescript_path
        cmd = [typescript_path] + args
      else
        cmd = ['tsc'] + args
      end
      cmd = cmd.join(' ')
      stdin, stdout, stderr, wait_thr = Open3.popen3(cmd)
      stdin.close
      [stdout.read, stderr.read, wait_thr]
    end

    def flatten_options(options)
      args = []
      if options[:output]
        args << '--out' << options[:output]
      end

      if options[:output_dir]
        args << '--outDir' << options[:output_dir]
      end

      if options[:source_map]
        args << '--sourceMap'
      end

      if options[:module]
        args << '--module' << options[:module]
      end

      if options[:target]
        args << '--target' << options[:target]
      end

      return args
    end

    # Compiles a TypeScript file to JavaScript.
    #
    # @param [String] filepath the path to the TypeScript file
    # @param [Hash] options the options for the execution
    # @option options [String] :output the output path
    # @option options [Boolean] :output_dir the directory to output files to
    # @option options [Boolean] :source_map create the source map or not
    # @option options [String] :module module type to compile for (commonjs or amd)
    # @option options [String] :target the target to compile toward: ES3 (default) or ES5
    def compile_file(filepath, options={})
      options = options.clone
      if options[:output]
        output_filename = options[:output]
      elsif options[:output_dir]
        filename = File.basename(filepath).gsub(/[.]ts$/, '.js')
        output_filename = File.join(options[:output_dir], filename)
      else
        output_filename = filepath.gsub(/[.]ts$/, '.js')
      end

      args = [filepath] + flatten_options(options)
      stdout, stderr, wait_thr = node_compile(*args)

      if wait_thr.nil?
        success = stdout.empty? and stderr.empty?
      else
        success = wait_thr.value == 0
      end

      if success
        result = {
          :js => output_filename,
          :stdout => stdout,
        }
        if options[:source_map]
          result[:source_map] = output_filename + '.map'
        end
        return result
      else
        raise TypeScript::Error, ( stderr.empty? ? stdout : stderr )
      end
    end

  end
end


text:
<?php

defined('IN_IA') or exit('Access Denied');
$dos = array('verifycode', 'image');
$do = in_array($do, $dos) ? $do : 'verifycode';

$_W['uniacid'] = intval($_GPC['uniacid']);
if($do == 'verifycode') {
	load()->func('communication');
		$username = trim($_GPC['username']);
	$response = ihttp_get("https://mp.weixin.qq.com/cgi-bin/verifycode?username={$username}&r=" . TIMESTAMP);
	if(!is_error($response)) {
		isetcookie('code_cookie', $response['headers']['Set-Cookie']);
		header('Content-type: image/jpg');
		echo $response['content'];
		exit();
	}
} elseif($do == 'image') {
	load()->func('communication');
		$image = trim($_GPC['attach']);
	if(empty($image)) {
		exit();
	}
	$content = ihttp_request($image, '', array('CURLOPT_REFERER' => 'http://www.qq.com'));
	header('Content-Type:image/jpg');
	echo $content['content'];
	exit();
}


text:
"""Parse all text files, assumed to contain numbers, and print summary info."""

# ***** BEGIN LICENSE BLOCK *****
#
# Copyright (c) 2007-2012, Python File Format Interface
# 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 the Python File Format Interface
#      project 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# ***** END LICENSE BLOCK *****

from __future__ import print_function

import argparse
import os
import sys

from summary import confint

parser = argparse.ArgumentParser(
    description='Summary statistics about population mean from sample data.')
parser.add_argument(
    '--robust', dest='robust', default=False, action='store_true',
    help='use median and iqr instead of mean and standard deviation',
    )
parser.add_argument(
    'folder', type=str, action='store',
    help='the folder to process files from',
    )

args = parser.parse_args()

total = {}
folder = sys.argv[1]
for root, dirs, files in os.walk(folder):
    for name in files:
        if not name.endswith(".txt"):
            continue
        print("parsing {0}".format(name))
        total[name] = []
        with open(os.path.join(root, name), "rb") as txtfile:
            for row in txtfile:
                row = row.strip()
                total[name].append(float(row))

def summary(outfile):
    for name, vec in sorted(total.items()):
        low, up = confint(vec, robust=args.robust)
        print("{0:10}: [{1:10.4f}, {2:10.4f}]".format(name, low, up), file=outfile)

summary(sys.stdout)


text:
%%%%%%%%%%%%%%%%%%%%%
%
% Author: Wachter Johannes, Stefan Laesser
% Date: 17.01.2014
% File: template/attributes.tex
%
% Document Attributes

% general
\newcommand{\myauthor}{Michael Zangerle, BSc}
\newcommand{\myshortauthor}{Zangerle}
\newcommand{\mytitle}{Implementierung eines Verfahrens zur automatisierten Verkehrsmittelerkennung auf Basis von Entscheidungsbäumen}
\newcommand{\myworktitle}{Transportation Mode Detection}
\newcommand{\myshorttitle}{Transportation Mode Detection}

%pdf metadata
\newcommand{\mysubject}{Transportation Mode Detection}
\newcommand{\mykeywords}{Transportation Mode Detection}

% additional informations
\newcommand{\myuniversity}{Fachhochschule Vorarlberg\\University of Applied Sciences}
\newcommand{\mydepartment}{Master Informatik}
\newcommand{\mystudentnumber}{1310249004}
\newcommand{\mysupervisor}{Prof. (FH) Dipl.-Inform. Thomas Feilhauer}
\newcommand{\myhometown}{Dornbirn}
\newcommand{\mysubmissionday}{29.}
\newcommand{\mysubmissionmonth}{Juli}
\newcommand{\mysubmissionyear}{2015}
\newcommand{\mysubmissiontown}{\myhometown}

% blocking notice information
\newcommand{\mycompany}{Name der Firma}
\newcommand{\myblockinguntil}{dd.mm.yyyy}

% gaining academic degree with this thesis
% Master of Science in Engineering, MSc
% Bachelor of Science in Engineering, BSc
\newcommand{\mygainacademicdegree}{Master of Science in Engineering, MSc}

% e.g. Bachelorarbeit or Masterarbeit
\newcommand{\mykindofthesis}{Masterthesis}

% set default commands
\title{\mytitle}
\author{\myauthor}
\date{\today{}, \mysubmissiontown}