text:
""" The 'View' menu """

# Standard library imports.
import logging

# Enthought library imports.
from pyface.action.api import Group, MenuManager
from traits.api import Any, Bool, Instance, List, Str, Unicode
from traits.api import on_trait_change

# Local imports.
from perspective_menu_manager import PerspectiveMenuManager
from show_view_action import ShowViewAction
from toggle_view_visibility_action import ToggleViewVisibilityAction

# Logging.
logger = logging.getLogger(__name__)

class ViewMenuManager(MenuManager):
    """ The 'View' menu.

    By default, this menu is displayed on the main menu bar.

    """

    #### 'ActionManager' interface ############################################

    # All of the groups in the manager.
    groups = List(Group)

    # The manager's unique identifier (if it has one).
    id = Str('View')

    #### 'MenuManager' interface ##############################################

    # The menu manager's name (if the manager is a sub-menu, this is what its
    # label will be).
    name = Unicode('&View')

    #### 'ViewMenuManager' interface ##########################################

    # Should the perspective menu be shown?
    show_perspective_menu = Bool(True)

    # The workbench window that the menu is part of.
    window = Instance('pyface.workbench.api.WorkbenchWindow')

    #### 'Private' interface ##################################################

    # The group containing the view hide/show actions.
    _view_group = Any

    ###########################################################################
    # 'ActionManager' interface.
    ###########################################################################

    def _groups_default(self):
        """ Trait initializer. """

        groups = []

        # Add a group containing the perspective menu (if requested).
        if self.show_perspective_menu and len(self.window.perspectives) > 0:
            groups.append(Group(PerspectiveMenuManager(window=self.window)))

        # Add a group containing a 'toggler' for all visible views.
        self._view_group = self._create_view_group(self.window)
        groups.append(self._view_group)

        # Add a group containing an 'Other...' item that will launch a dialog
        # to allow the user to choose a view to show.
        groups.append(self._create_other_group(self.window))

        return groups

    ###########################################################################
    # 'ViewMenuManager' interface.
    ###########################################################################

    @on_trait_change(
        'window.active_perspective,window.active_part,'
        'window.views,window.views_items'
    )
    def refresh(self):
        """ Refreshes the checked state of the actions in the menu. """

        logger.debug('refreshing view menu')

        if self._view_group is not None:
            self._clear_group(self._view_group)
            self._initialize_view_group(self.window, self._view_group)
            self.changed = True

        return

    ###########################################################################
    # Private interface.
    ###########################################################################

    def _clear_group(self, group):
        """ Remove all items in a group. """

        # fixme: Fix this API in PyFace so there is only one call!
        group.destroy()
        group.clear()

        return

    def _create_other_group(self, window):
        """ Creates a group containing the 'Other...' action. """

        group = Group()
        group.append(ShowViewAction(name='Other...', window=window))

        return group

    def _create_view_group(self, window):
        """ Creates a group containing the view 'togglers'. """

        group = Group()
        self._initialize_view_group(window, group)

        return group

    def _initialize_view_group(self, window, group):
        """ Initializes a group containing the view 'togglers'. """

        views = window.views[:]
        views.sort(None, lambda view: view.name)

        for view in views:
            # fixme: It seems a little smelly to be reaching in to the window
            # layout here. Should the 'contains_view' method be part of the
            # window interface?
            if window.layout.contains_view(view):
                group.append(
                    ToggleViewVisibilityAction(view=view, window=window)
                )

        return

#### EOF ######################################################################


text:
package org.apache.pulsar.client.impl.conf;

import java.io.Serializable;
import java.util.regex.Pattern;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class TopicConsumerConfigurationData implements Serializable {
    private static final long serialVersionUID = 1L;

    private TopicNameMatcher topicNameMatcher;
    private int priorityLevel;

    public static TopicConsumerConfigurationData ofTopicsPattern(@NonNull Pattern topicsPattern, int priorityLevel) {
        return of(new TopicNameMatcher.TopicsPattern(topicsPattern), priorityLevel);
    }

    public static TopicConsumerConfigurationData ofTopicsPattern(@NonNull Pattern topicsPattern,
                                                                 ConsumerConfigurationData<?> conf) {
        return ofTopicsPattern(topicsPattern, conf.getPriorityLevel());
    }

    public static TopicConsumerConfigurationData ofTopicName(@NonNull String topicName, int priorityLevel) {
        return of(new TopicNameMatcher.TopicName(topicName), priorityLevel);
    }

    public static TopicConsumerConfigurationData ofTopicName(@NonNull String topicName,
                                                             ConsumerConfigurationData<?> conf) {
        return ofTopicName(topicName, conf.getPriorityLevel());
    }

    static TopicConsumerConfigurationData of(@NonNull TopicNameMatcher topicNameMatcher, int priorityLevel) {
        return new TopicConsumerConfigurationData(topicNameMatcher, priorityLevel);
    }

    public interface TopicNameMatcher extends Serializable {
        boolean matches(String topicName);

        @RequiredArgsConstructor
        class TopicsPattern implements TopicNameMatcher {
            @NonNull
            private final Pattern topicsPattern;

            @Override
            public boolean matches(String topicName) {
                return topicsPattern.matcher(topicName).matches();
            }
        }

        @RequiredArgsConstructor
        class TopicName implements TopicNameMatcher {
            @NonNull
            private final String topicName;

            @Override
            public boolean matches(String topicName) {
                return this.topicName.equals(topicName);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include <algorithm>
#include <ctime>
#include <numeric>
#include <vector>

#include "rc_rpc_plugin/commands/mobile/get_interior_vehicle_data_consent_request.h"
#include "rc_rpc_plugin/rc_helpers.h"
#include "rc_rpc_plugin/rc_module_constants.h"
#include "rc_rpc_plugin/rc_rpc_types.h"
#include "smart_objects/enum_schema_item.h"

namespace rc_rpc_plugin {
namespace app_mngr = application_manager;
namespace commands {

SDL_CREATE_LOG_VARIABLE("Commands")

GetInteriorVehicleDataConsentRequest::GetInteriorVehicleDataConsentRequest(
    const application_manager::commands::MessageSharedPtr& message,
    const RCCommandParams& params)
    : RCCommandRequest(message, params) {}

void GetInteriorVehicleDataConsentRequest::Execute() {
  SDL_LOG_AUTO_TRACE();

  auto& msg_params = (*message_)[app_mngr::strings::msg_params];

  const bool module_ids_exists =
      msg_params.keyExists(message_params::kModuleIds);
  if (!module_ids_exists) {
    SendResponse(false,
                 mobile_apis::Result::INVALID_DATA,
                 "ModuleIds collection is absent in request message");
    return;
  }

  if (msg_params[message_params::kModuleIds].empty()) {
    SDL_LOG_DEBUG(
        "ModuleIds collection is empty. Will be add default "
        "module_id from capabilities");

    const auto module_id =
        rc_capabilities_manager_.GetDefaultModuleIdFromCapabilities(
            ModuleType());

    msg_params[message_params::kModuleIds][0] = module_id;
  }

  const std::string module_type = ModuleType();
  for (const auto module_id :
       *(msg_params[message_params::kModuleIds].asArray())) {
    const ModuleUid module(module_type, module_id.asString());
    if (!rc_capabilities_manager_.CheckIfModuleExistsInCapabilities(module)) {
      SDL_LOG_WARN("Accessing not supported module: " << module_type << " "
                                                      << module_id.asString());
      SetResourceState(module_type, ResourceState::FREE);
      SendResponse(false,
                   mobile_apis::Result::UNSUPPORTED_RESOURCE,
                   "Accessing not supported module data");
      return;
    }
  }

  smart_objects::SmartObject response_params;
  if (GetCalculatedVehicleDataConsent(response_params)) {
    SDL_LOG_DEBUG(
        "No need to send request to HMI. Sending cached consents to mobile");
    SendResponse(true, mobile_apis::Result::SUCCESS, nullptr, &response_params);
    return;
  }

  (*message_)[application_manager::strings::msg_params]
             [application_manager::strings::app_id] = connection_key();

  hmi_request_consents_ =
      smart_objects::SmartObject(response_params[message_params::kAllowed]);

  SDL_LOG_DEBUG(
      "Filtering out module ids with successfully calculated consent");

  smart_objects::SmartObject hmi_msg_params(msg_params);
  auto module_ids_for_consent =
      hmi_msg_params[message_params::kModuleIds].asArray();
  module_ids_for_consent->clear();

  auto module_ids = msg_params[message_params::kModuleIds].asArray();
  for (uint32_t i = 0; i < module_ids->size(); ++i) {
    // Only add modules whose consent is unknown(needs to be sent to the hmi)
    bool is_consent_undefined =
        (*hmi_request_consents_.asArray())[i].getType() ==
        smart_objects::SmartType::SmartType_Null;
    if (is_consent_undefined) {
      module_ids_for_consent->push_back((*module_ids)[i]);
    }
  }

  SDL_LOG_DEBUG(
      "Forwarding request to HMI with moduleIds for modules with "
      "unknown consent");
  SendHMIRequest(hmi_apis::FunctionID::RC_GetInteriorVehicleDataConsent,
                 (&hmi_msg_params),
                 true);
}

void GetInteriorVehicleDataConsentRequest::on_event(
    const app_mngr::event_engine::Event& event) {
  SDL_LOG_AUTO_TRACE();

  if (event.id() != hmi_apis::FunctionID::RC_GetInteriorVehicleDataConsent) {
    SDL_LOG_ERROR("Received wrong event. FunctionID: " << event.id());
    return;
  }

  auto temp_response = event.smart_object();

  auto result_code =
      GetMobileResultCode(static_cast<hmi_apis::Common_Result::eType>(
          temp_response[app_mngr::strings::params][app_mngr::hmi_response::code]
              .asUInt()));

  const bool success_result =
      helpers::Compare<mobile_apis::Result::eType, helpers::EQ, helpers::ONE>(
          result_code,
          mobile_apis::Result::SUCCESS,
          mobile_apis::Result::WARNINGS);

  if (!success_result) {
    std::string info;
    GetInfo(temp_response, info);
    SendResponse(false, result_code, info.c_str(), nullptr);
    return;
  }

  if (!temp_response[app_mngr::strings::msg_params].keyExists(
          message_params::kAllowed) ||
      temp_response[app_mngr::strings::msg_params][message_params::kAllowed]
          .empty()) {
    std::string info_out =
        "Collection of consents is absent in HMI response or empty";
    SDL_LOG_ERROR(info_out);
    SendResponse(false, mobile_apis::Result::GENERIC_ERROR, info_out.c_str());
    return;
  }

  uint32_t number_of_expected_response_consents = std::accumulate(
      hmi_request_consents_.asArray()->begin(),
      hmi_request_consents_.asArray()->end(),
      uint32_t(0),
      [](uint32_t num_consents, smart_objects::SmartObject& consent) {
        // Only module ids with valid location consents were sent to the hmi
        bool is_consent_undefined =
            consent.getType() == smart_objects::SmartType::SmartType_Null;
        return (is_consent_undefined) ? num_consents + 1 : num_consents;
      });

  const auto response_consents =
      temp_response[app_mngr::strings::msg_params][message_params::kAllowed]
          .asArray();

  if (number_of_expected_response_consents != response_consents->size()) {
    std::string info_out =
        "HMI response has incorrect number of consents expected: " +
        std::to_string(number_of_expected_response_consents) +
        ", actual: " + std::to_string(response_consents->size());
    SDL_LOG_ERROR(info_out);
    SendResponse(false, mobile_apis::Result::GENERIC_ERROR, info_out.c_str());
    return;
  }

  SDL_LOG_DEBUG("Adding back filtered out module ids for response to mobile");
  uint32_t response_consents_counter = 0;
  for (auto& consent : *(hmi_request_consents_.asArray())) {
    // Only modify consent for moduleIds allowed by location constraints
    bool is_consent_undefined =
        consent.getType() == smart_objects::SmartType::SmartType_Null;
    if (is_consent_undefined) {
      consent = (*response_consents)[response_consents_counter];
      ++response_consents_counter;
    }
  }

  temp_response[app_mngr::strings::msg_params][message_params::kAllowed] =
      hmi_request_consents_;

  const auto hmi_response = temp_response;
  std::string response_info;
  const bool result_of_saving = SaveModuleIdConsents(
      response_info, hmi_response[app_mngr::strings::msg_params]);

  if (!result_of_saving) {
    SDL_LOG_DEBUG("Consent saving failed");
    SendResponse(
        false, mobile_apis::Result::GENERIC_ERROR, response_info.c_str());
    return;
  }

  smart_objects::SmartObject response_params =
      hmi_response[app_mngr::strings::msg_params];
  std::string info;
  GetInfo(hmi_response, info);
  SendResponse(success_result, result_code, info.c_str(), &response_params);
}

std::string GetInteriorVehicleDataConsentRequest::ModuleType() const {
  mobile_apis::ModuleType::eType module_type =
      static_cast<mobile_apis::ModuleType::eType>(
          (*message_)[app_mngr::strings::msg_params]
                     [message_params::kModuleType]
                         .asUInt());

  const char* str;
  const bool ok = smart_objects::EnumConversionHelper<
      mobile_apis::ModuleType::eType>::EnumToCString(module_type, &str);
  return ok ? str : "unknown";
}

std::string GetInteriorVehicleDataConsentRequest::ModuleId() const {
  return std::string();
}

GetInteriorVehicleDataConsentRequest::~GetInteriorVehicleDataConsentRequest() {}

bool GetInteriorVehicleDataConsentRequest::IsUserLocationValid(
    const ModuleUid& module_uid) const {
  SDL_LOG_AUTO_TRACE();

  if (!rc_capabilities_manager_.IsSeatLocationCapabilityProvided()) {
    return true;
  }
  const auto app_ptr = application_manager_.application(connection_key());
  const auto extension = RCHelpers::GetRCExtension(*app_ptr);
  const auto module_service_area =
      rc_capabilities_manager_.GetModuleServiceArea(module_uid);
  const auto user_location = extension->GetUserLocation();
  const auto driver =
      rc_capabilities_manager_.GetDriverLocationFromSeatLocationCapability();
  const bool is_driver = (user_location == driver);
  if (is_driver || user_location.IntersectionExists(module_service_area)) {
    return true;
  }
  return false;
}

rc_rpc_types::ModuleConsent
GetInteriorVehicleDataConsentRequest::GetModuleConsentByAccessMode(
    const ModuleUid& module_uid,
    const hmi_apis::Common_RCAccessMode::eType access_mode) const {
  SDL_LOG_AUTO_TRACE();

  auto get_auto_allow_consent = [](const ModuleUid& module_uid) {
    return rc_rpc_types::ModuleConsent::CONSENTED;
  };

  auto get_auto_deny_consent = [this](const ModuleUid& module_uid) {
    auto app = application_manager_.application(connection_key());
    const uint32_t app_id = app->app_id();
    const bool is_resource_available =
        (resource_allocation_manager_.AcquireResource(
             module_uid.first, module_uid.second, app_id) ==
         AcquireResult::ALLOWED);
    return (is_resource_available) ? rc_rpc_types::ModuleConsent::CONSENTED
                                   : rc_rpc_types::ModuleConsent::NOT_CONSENTED;
  };

  auto get_ask_driver_consent = [this](const ModuleUid& module_uid) {
    auto app = application_manager_.application(connection_key());
    const std::string policy_app_id = app->policy_app_id();
    const std::string mac_address = app->mac_address();

    auto consent = rc_consent_manager_.GetModuleConsent(
        policy_app_id, mac_address, module_uid);

    if (rc_rpc_types::ModuleConsent::NOT_EXISTS == consent) {
      auto acquire_result = resource_allocation_manager_.AcquireResource(
          module_uid.first, module_uid.second, app->app_id());
      const bool is_resource_available =
          (acquire_result == AcquireResult::ALLOWED);
      const bool is_resource_rejected =
          (acquire_result == AcquireResult::REJECTED);

      if (!is_resource_available && !is_resource_rejected) {
        return rc_rpc_types::ModuleConsent::NOT_EXISTS;
      }

      return (is_resource_available)
                 ? rc_rpc_types::ModuleConsent::CONSENTED
                 : rc_rpc_types::ModuleConsent::NOT_CONSENTED;
    }

    const bool is_consent_allowed =
        (rc_rpc_types::ModuleConsent::CONSENTED == consent);
    return (is_consent_allowed) ? rc_rpc_types::ModuleConsent::CONSENTED
                                : rc_rpc_types::ModuleConsent::NOT_CONSENTED;
  };

  switch (access_mode) {
    case hmi_apis::Common_RCAccessMode::AUTO_ALLOW: {
      SDL_LOG_DEBUG("Calculating consent for module("
                    << module_uid.first << ", " << module_uid.second
                    << ") in accessMode: AUTO_ALLOW");
      return get_auto_allow_consent(module_uid);
    }
    case hmi_apis::Common_RCAccessMode::AUTO_DENY: {
      SDL_LOG_DEBUG("Calculating consent for module("
                    << module_uid.first << ", " << module_uid.second
                    << ") in accessMode: AUTO_DENY");
      return get_auto_deny_consent(module_uid);
    }
    case hmi_apis::Common_RCAccessMode::ASK_DRIVER: {
      SDL_LOG_DEBUG("Calculating consent for module("
                    << module_uid.first << ", " << module_uid.second
                    << ") in accessMode: ASK_DRIVER");
      return get_ask_driver_consent(module_uid);
    }
    default: {
      SDL_LOG_DEBUG("Unknown accessMode specified. Denying consent for module("
                    << module_uid.first << ", " << module_uid.second << ")");
      return rc_rpc_types::ModuleConsent::NOT_CONSENTED;
    }
  }
}

bool GetInteriorVehicleDataConsentRequest::GetCalculatedVehicleDataConsent(
    smart_objects::SmartObject& out_response) const {
  SDL_LOG_AUTO_TRACE();

  out_response =
      smart_objects::SmartObject(smart_objects::SmartType::SmartType_Map);
  out_response[message_params::kAllowed] =
      smart_objects::SmartObject(smart_objects::SmartType::SmartType_Array);

  auto modules_consent_array = out_response[message_params::kAllowed].asArray();
  const auto module_ids =
      (*message_)[app_mngr::strings::msg_params][message_params::kModuleIds]
          .asArray();
  const std::string module_type = ModuleType();
  bool can_handle_internally = true;

  auto get_disallowed_multiple_access_consent =
      [this](const ModuleUid& module_uid) {
        auto app = application_manager_.application(connection_key());
        const uint32_t app_id = app->app_id();
        const bool is_resource_available =
            (resource_allocation_manager_.AcquireResource(
                 module_uid.first, module_uid.second, app_id) ==
             AcquireResult::ALLOWED);
        return (is_resource_available)
                   ? rc_rpc_types::ModuleConsent::CONSENTED
                   : rc_rpc_types::ModuleConsent::NOT_CONSENTED;
      };

  for (const auto module_id : *(module_ids)) {
    const ModuleUid module_uid(module_type, module_id.asString());
    // Check if the user_location is covered by the module's serviceArea
    if (!IsUserLocationValid(module_uid)) {
      SDL_LOG_DEBUG("User is outside the serviceArea for module("
                    << module_uid.first << ", " << module_uid.second
                    << "). Denying consent");
      modules_consent_array->push_back(smart_objects::SmartObject(false));
      continue;
    }

    rc_rpc_types::ModuleConsent module_consent;

    const bool is_multiple_access_allowed =
        rc_capabilities_manager_.IsMultipleAccessAllowed(module_uid);
    if (!is_multiple_access_allowed) {
      SDL_LOG_DEBUG("multipleAccess disallowed for module("
                    << module_uid.first << ", " << module_uid.second << ")");
      module_consent = get_disallowed_multiple_access_consent(module_uid);
      modules_consent_array->push_back(smart_objects::SmartObject(
          module_consent == rc_rpc_types::ModuleConsent::CONSENTED));
      continue;
    }

    const auto access_mode = resource_allocation_manager_.GetAccessMode();

    module_consent = GetModuleConsentByAccessMode(module_uid, access_mode);
    if (module_consent == rc_rpc_types::ModuleConsent::NOT_EXISTS) {
      SDL_LOG_DEBUG("Unable to calculate consent for module("
                    << module_uid.first << ", " << module_uid.second
                    << "), should send moduleId to HMI for consent");
      modules_consent_array->push_back(smart_objects::SmartObject());
      can_handle_internally = false;
      continue;
    }
    modules_consent_array->push_back(smart_objects::SmartObject(
        module_consent == rc_rpc_types::ModuleConsent::CONSENTED));
  }
  return can_handle_internally;
}

bool GetInteriorVehicleDataConsentRequest::SaveModuleIdConsents(
    std::string& info_out, const smart_objects::SmartObject& msg_params) {
  SDL_LOG_AUTO_TRACE();

  const auto& allowed = msg_params[message_params::kAllowed];
  const auto& moduleIds =
      (*message_)[app_mngr::strings::msg_params][message_params::kModuleIds];

  if (allowed.length() != moduleIds.length()) {
    info_out =
        "The received module_id collection from mobile and received consent "
        "collection from HMI are not equal by size.";
    SDL_LOG_ERROR(info_out);
    return false;
  }
  std::string module_type = ModuleType();
  auto module_ids = RCHelpers::RetrieveModuleIds(moduleIds);
  auto module_allowed = RCHelpers::RetrieveModuleConsents(allowed);

  auto module_consents =
      RCHelpers::FillModuleConsents(module_type, module_ids, module_allowed);

  auto application = application_manager_.application(connection_key());
  if (!application) {
    SDL_LOG_ERROR("Application with connection key:" << connection_key()
                                                     << " isn't registered");
    return false;
  }
  std::string policy_app_id = application->policy_app_id();
  const auto mac_address = application->mac_address();
  rc_consent_manager_.SaveModuleConsents(
      policy_app_id, mac_address, module_consents);
  return true;
}

}  // namespace commands
}  // namespace rc_rpc_plugin


text:
package org.continuity.wessbas.managers;

import static org.assertj.core.api.Assertions.assertThat;

import org.continuity.api.entities.config.TaskDescription;
import org.continuity.api.entities.exchange.ArtifactExchangeModel;
import org.continuity.idpa.annotation.ApplicationAnnotation;
import org.continuity.idpa.annotation.DirectListInput;
import org.continuity.idpa.application.Application;
import org.continuity.idpa.application.HttpEndpoint;
import org.continuity.idpa.application.HttpParameter;
import org.continuity.idpa.application.HttpParameterType;
import org.continuity.idpa.visitor.FindBy;
import org.continuity.wessbas.entities.WessbasBundle;
import org.continuity.wessbas.transform.annotation.AnnotationFromWessbasExtractor;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class UrlPartParametersTest {

	private static final String SESSION_LOG = "123;\"fooRequest\":1:42:/foo/{bar}:8080:localhost:HTTP/1.1:GET:abc=123&URL_PART_bar=hi:<no-encoding>;\"fooRequest\":43:50:/foo/{bar}:8080:localhost:HTTP/1.1:GET:URL_PART_bar=hello:<no-encoding>";

	private RestTemplate restMock;

	private WessbasPipelineManager manager;

	@SuppressWarnings("unchecked")
	@Before
	public void setup() {
		restMock = Mockito.mock(RestTemplate.class);
		Mockito.when(restMock.getForObject(Mockito.anyString(), Mockito.any())).thenReturn(SESSION_LOG);
		Mockito.when(restMock.exchange(Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(Class.class))).thenReturn(ResponseEntity.ok(SESSION_LOG));

		manager = new WessbasPipelineManager(restMock);
	}

	@Test
	public void testTransformationFromSessionLog() {
		TaskDescription task = new TaskDescription();
		ArtifactExchangeModel  source = new ArtifactExchangeModel();
		source.getSessionLinks().setExtendedLink("");
		task.setSource(source);
		WessbasBundle bundle = manager.runPipeline(task, 60000000000L);

		AnnotationFromWessbasExtractor extractor = new AnnotationFromWessbasExtractor(bundle.getWorkloadModel());
		Application systemModel = extractor.extractSystemModel();
		ApplicationAnnotation annotation = extractor.extractInitialAnnotation();

		assertThat(systemModel.getEndpoints()).extracting(interf -> (HttpEndpoint) interf).extracting(HttpEndpoint::getPath).containsExactly("/foo/{bar}");

		assertThat(systemModel.getEndpoints()).extracting(interf -> (HttpEndpoint) interf).flatExtracting(HttpEndpoint::getParameters).extracting(HttpParameter::getName)
				.containsExactlyInAnyOrder("bar", "abc");

		assertThat(systemModel.getEndpoints()).extracting(interf -> (HttpEndpoint) interf).flatExtracting(HttpEndpoint::getParameters).extracting(HttpParameter::getParameterType)
		.containsExactlyInAnyOrder(HttpParameterType.URL_PART, HttpParameterType.REQ_PARAM);

		DirectListInput input = FindBy.findById("Input_fooRequest_bar_URL_PART", DirectListInput.class).in(annotation).getFound();

		assertThat(input.getData()).containsExactlyInAnyOrder("hi", "hello");
	}

}


text:
#if HAVE_CONFIG_H
# include "config.h"
#endif

#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#ifdef WIN32
#include <fcntl.h>
#endif

#include "base64.h"

#include "io.h"

/* The number of bytes read in each iteration, we do one line at a time: */
#define CHUNK_SIZE 54

/* The *maximum* size of an encoded chunk: */
#define ENCODED_SIZE BASE64_ENCODE_LENGTH(CHUNK_SIZE)

/*
 * Reads bytes from standard input and writes base64-encoded
 * on standard output.
 */
int
main(int argc UNUSED, char **argv UNUSED)
{
  struct base64_encode_ctx b64_ctx;

  /* Init the context: */
  base64_encode_init(&b64_ctx);

#ifdef WIN32
  _setmode(0, O_BINARY);
#endif

  for (;;)
    {
      /* "buffer" will hold the bytes from disk: */
      uint8_t buffer[CHUNK_SIZE];
      /* "result" is the result vector: */
      uint8_t result[ENCODED_SIZE + BASE64_ENCODE_FINAL_LENGTH + 1];
      unsigned nbytes; /* Number of bytes read from stdin */
      int encoded_bytes; /* total number of bytes encoded per iteration */
      nbytes = fread(buffer,1,CHUNK_SIZE,stdin);

      /* We overwrite result with more data */
      encoded_bytes = base64_encode_update(&b64_ctx, result, nbytes, buffer);

      if (nbytes < CHUNK_SIZE)
	{
	  if (ferror(stdin))
	    {
	      werror ("Error reading file: %s\n", strerror(errno));
	      return EXIT_FAILURE;
	    }
	  encoded_bytes += base64_encode_final(&b64_ctx,result + encoded_bytes);

	  result[encoded_bytes++] = '\n';
	  if (!write_string (stdout, encoded_bytes, result)
	      || fflush (stdout) != 0)
	    {
	      werror ("Error writing file: %s\n", strerror(errno));
	      return EXIT_FAILURE;
	    }
	  return EXIT_SUCCESS;
	}

      /* The result vector is written */
      result[encoded_bytes++] = '\n';
      if (!write_string (stdout, encoded_bytes, result))
	{
	  werror ("Error writing file: %s\n", strerror(errno));
	  return EXIT_FAILURE;
	}
    }
}


text:
import hashlib
from twisted.internet import reactor
from autobahn.websocket import WebSocketServerFactory, \
                               WebSocketServerProtocol, \
                               listenWS

class FrameBasedHashServerProtocol(WebSocketServerProtocol):
   """
   Frame-based WebSockets server that computes a running SHA-256 for message
   data received. It will respond after every frame received with the digest
   computed up to that point. It can receive messages of unlimited number
   of frames. Digest is reset upon new message.
   """

   def onMessageBegin(self, opcode):
      WebSocketServerProtocol.onMessageBegin(self, opcode)
      self.sha256 = hashlib.sha256()

   def onMessageFrame(self, payload, reserved):
      l = 0
      for data in payload:
         l += len(data)
         self.sha256.update(data)
      digest = self.sha256.hexdigest()
      print "Received frame with payload length %7d, compute digest: %s" % (l, digest)
      self.sendMessage(digest)

   def onMessageEnd(self):
      self.sha256 = None

if __name__ == '__main__':

   factory = WebSocketServerFactory("ws://localhost:9000")
   factory.protocol = FrameBasedHashServerProtocol

   enableCompression = True
   if enableCompression:
      from autobahn.compress import PerMessageDeflateOffer, \
                                    PerMessageDeflateOfferAccept
      ## Function to accept offers from the client ..
      def accept(offers):
         for offer in offers:
            if isinstance(offer, PerMessageDeflateOffer):
               return PerMessageDeflateOfferAccept(offer)

      factory.setProtocolOptions(perMessageCompressionAccept = accept)

   listenWS(factory)
   reactor.run()


text:
EasyBlog.module("dashboard/editor", function($){

var module = this;

EasyBlog.Controller(
	"Dashboard.Editor",
	{
		defaultOptions: {

			editorId: "write_content"
		}
	},
	function(self) { return {

		init: function() {

			EasyBlog.dashboard.registerPlugin("editor", self);
		},

		insert: function(html) {

			window.jInsertEditorText(html, self.options.editorId);
		},

		content: function(html) {

			// TODO: Port eblog.editor to this new controller

			if (html!==undefined) {

				window.eblog.editor.setContent(html);
			}

			return window.eblog.editor.getContent();
		}
	}}
);

module.resolve();

});


text:
import styled from "styled-components";
import PropTypes from "prop-types";
import { radius, colors, shadow } from "constants/theme";

const Panel = styled.div`
  border-radius: ${radius};
  background-color: ${colors.white};
  box-shadow: ${shadow};
`;

Panel.propTypes = {
  children: PropTypes.node.isRequired
};

export const CenteredPanel = styled(Panel)`
  padding: 2em 2.5em;
  display: flex;
  flex: 1 1 100%;
  flex-direction: column;
  align-items: center;
  justify-content: center;
`;

export default Panel;


text:
package net.evermemo.dbmigrate;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.MessageFormat;

public class MySQLClientScriptRunner implements ScriptRunner {

	@Override
	public void runScript(File scriptFile, DatabaseInfo dbInfo)
			throws Exception {

		String command = "mysql -c -u{0} -p{1} -h{2} -P{3} -D{4}";
		command = MessageFormat.format(command, dbInfo.user, dbInfo.password,
				dbInfo.host, dbInfo.port, dbInfo.database);

		ProcessBuilder processBuilder = new ProcessBuilder();
		processBuilder.command(command.split(" "));
		processBuilder.redirectErrorStream(true);

		Process process = processBuilder.start();

		String script = this.getFileContent(scriptFile);
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
		bw.write(script);
		bw.close();

		int returnCode = process.waitFor();
		if (returnCode != 0) {
			BufferedReader resultReader = new BufferedReader(new InputStreamReader(
					process.getInputStream()));
			StringBuilder message = new StringBuilder();
			String resultLine = resultReader.readLine();
			while (resultLine != null) {
				message.append(resultLine);
				message.append("\n");
				resultLine = resultReader.readLine();
			}
			resultReader.close();
			throw new ScriptRunnerException(message.toString());
		}
	}

	private String getFileContent(File file) throws Exception {
		StringBuilder builder = new StringBuilder();

		BufferedReader br = new BufferedReader(new FileReader(file));
		String line = br.readLine();
		while (line != null) {
			builder.append(line);
			builder.append("\n");
			line = br.readLine();
		}
		br.close();

		return builder.toString();
	}

}


text:
'''
Class used for passing events from analysis script to multiapp_plot
objects.
'''
class PlotEvent:
	tag = 'PlotEvent'

	# All of these members are optional - typically, only one or maybe
	# two will be set to non-None.
	vma = None            # class vm_mapping
	page_event = None     # class PageEvent
	rss_event = None      # class RssEvent
	cp_event = None       # class CheckpointEvent
	perf_sample = None    # class perf_sample
	datapoint = None      # arbitrary (understood by a particular datafn)

	def __init__(self, vma=None, page_event=None, rss_event=None,
			cp_event=None, perf_sample = None, datapoint=None):
		tag = "{}.__init__".format(self.tag)

		self.vma = vma
		self.page_event = page_event
		self.rss_event = rss_event
		self.cp_event = cp_event
		self.perf_sample = perf_sample
		self.datapoint = datapoint

		return

if __name__ == '__main__':
	print_error_exit("not an executable module")


text:
/*
 * Author: tdanford
 * Date: Aug 12, 2008
 */
/**
 *
 */
package edu.psu.compbio.seqcode.gse.viz.metagenes;

import java.awt.*;

import edu.psu.compbio.seqcode.gse.viz.paintable.*;

/**
 * Wraps a Profile object, and paints it in a window region in the simplest possible way
 * (connected lines between points).
 *
 * @author tdanford
 *
 */
public class ProfilePaintable extends AbstractPaintable implements ProfileListener {

	private PaintableScale scale;
	private BinningParameters params;
	private Profile profile;
	private Color col=Color.blue;
	private String style="Line";
	private boolean useNormalized=true;

	private int[] xs, ys;

	public ProfilePaintable(PaintableScale sc, Profile p) {
		scale = sc;
		profile = p;
		profile.addProfileListener(this);
		params = profile.getBinningParameters();
		xs = new int[params.getNumBins()];
		ys = new int[params.getNumBins()];
	}

	public void profileChanged(ProfileEvent p) {
		dispatchChangedEvent();
	}

	public Color getColor(){return col;}
	public void setColor(Color c){col=c;}
	public void setStyle(String s){style=s;}
	public void normalized(boolean n){useNormalized=n;}

	public void paintItem(Graphics g, int x1, int y1, int x2, int y2) {
		int w = x2-x1, h = y2-y1;
		Graphics2D g2 = (Graphics2D)g;
		Stroke oldStroke = g2.getStroke();
		g2.setStroke(new BasicStroke((float)2.5));

		int binPix = w / (params.getNumBins()+1);

		// Make sure that the profile doesn't change out from underneath us...
		synchronized(profile) {
			if(profile.min()<scale.getMin())
				scale.setScale(profile.min(), scale.getMax());
			if(profile.max()>scale.getMax())
				scale.setScale(scale.getMin(), profile.max());

			for(int i = 0; i < params.getNumBins(); i++) {
				int x = x1 + (i+1)*binPix;
				double yf= scale.fractionalOffset(profile.value(i));
				int y = y2 - (int)Math.round(yf * (double)h);
				xs[i] = x; ys[i] = y;
			}

			//g2.setColor(Color.white);
			//g2.fillRect(x1, y1, w, h);
			g2.setColor(col);

			if(style.equals("Histo")){
				//Histogram style
				for(int i = 0; i < xs.length; i++) {
					g2.fillRect(xs[i],ys[i], binPix, h-ys[i]);
				}
			}else{
				//Line Graph style
				for(int i = 1; i < xs.length; i++) {
					g2.drawLine(xs[i-1], ys[i-1], xs[i], ys[i]);
				}
				int rad = 2;
				int diam = rad*2;
				for(int i = 0; i < xs.length; i++) {
					g2.setColor(Color.white);
					g2.fillOval(xs[i]-rad, ys[i]-rad, diam, diam);
					g2.setColor(col);
					g2.drawOval(xs[i]-rad, ys[i]-rad, diam, diam);
				}
			}
		}
		g2.setStroke(oldStroke);
	}

}


text:
package main

import (
	"crypto/md5"
	"errors"
	"fmt"
	"io"
	"log"
	"os"
	"path/filepath"
	"sync"

	"github.com/boltdb/bolt"
	ui "github.com/gosuri/uiprogress"
)

// A result is the product of reading and summing a file using MD5.
type result struct {
	path string
	sum  []byte
	err  error
}

// walkFiles starts a goroutine to walk the directory tree at root and send the
// path of each regular file on the string channel.  It sends the result of the
// walk on the error channel.  If done is closed, walkFiles abandons its work.
func walkFiles(done <-chan struct{}, root string) (<-chan string, <-chan error) {
	paths := make(chan string)
	errc := make(chan error, 1)
	go func() { // HL
		// Close the paths channel after Walk returns.
		defer close(paths) // HL
		// No select needed for this send, since errc is buffered.
		errc <- filepath.Walk(root, func(path string, info os.FileInfo, err error) error { // HL
			if err != nil {
				log.Println("eoor")
				return err
			}
			if !info.Mode().IsRegular() {
				return nil
			}

			select {
			case paths <- path: // HL
			case <-done: // HL
				return errors.New("walk canceled")
			}
			return nil
		})
	}()
	return paths, errc
}

// digester reads path names from paths and sends digests of the corresponding
// files on c until either paths or done is closed.
func digester(done <-chan struct{}, paths <-chan string, c chan<- result) {
	for path := range paths { // HLpaths
		res := result{path: path}
		f, err := os.Open(path)
		if err != nil {
			res.err = err
		} else {
			h := md5.New()
			if _, err := io.Copy(h, f); err != nil {
				res.err = err
			}
			res.sum = h.Sum(nil)
		}
		select {
		case c <- res:
		case <-done:
			return

		}

	}
}

// MD5All reads all the files in the file tree rooted at root and returns a map
// from file path to the MD5 sum of the file's contents.  If the directory walk
// fails or any read operation fails, MD5All returns an error.  In that case,
// MD5All does not wait for inflight read operations to complete.
func MD5All(root string, dbName string, bucketName string, stats *Statistics, bar *ui.Bar) error {

	db, err := bolt.Open(dbname, 0600, nil)
	if err != nil {
		return err
	}
	defer func() {
		if err := db.Close(); err != nil {
			fmt.Println(err)
		}
	}()

	// MD5All closes the done channel when it returns; it may do so before
	// receiving all the values from c and errc.
	done := make(chan struct{})
	defer close(done)

	paths, errc := walkFiles(done, root)

	// Start a fixed number of goroutines to read and digest files.
	c := make(chan result) // HLc
	var wg sync.WaitGroup

	wg.Add(digesterNr)
	log.Printf("launching %d digester", digesterNr)
	for i := 0; i < digesterNr; i++ {
		go func() {
			digester(done, paths, c) // HLc
			wg.Done()
		}()
	}
	go func() {
		wg.Wait()
		close(c) // HLc
	}()
	// End of pipeline. OMIT
	err = db.Batch(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte(bucketName))
		e := b.Bucket([]byte("errors"))
		if b == nil {
			return fmt.Errorf("gettings bucket")
		}
		for r := range c { // HLrange
			bar.Incr()
			stats.Files++
			if r.err != nil {
				stats.Errors++
				if err = e.Put([]byte(r.path), []byte(r.err.Error())); err != nil {
					log.Println(err)
				}
			} else {
				if err = b.Put([]byte(r.path), r.sum[:]); err != nil {
					log.Println(err)
				}

			}

		}
		return nil
	})
	if err != nil {
		return err
	}
	if err := <-errc; err != nil {
		log.Println(err)
		return err
	}
	return nil
}


text:
import template from './newGroup.html';
import controller from './newGroup.controller';
import './newGroup.styl';

let newGroupComponent = {
  restrict: 'E',
  bindings: {},
  template,
  controller,
  controllerAs: 'vm'
};

export default newGroupComponent;


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/np__user_profile_edit_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/np__transparent_background"
        android:gravity="center_horizontal"
        android:orientation="vertical" >

        <RelativeLayout
            android:id="@+id/np__user_profile_edit_action_bar_container"
            android:layout_width="match_parent"
            android:layout_height="@dimen/np__dummy_action_bar_default_height"
            android:background="@color/np__white"
            android:gravity="center_vertical" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center_vertical"
                android:orientation="horizontal" >

                <ImageButton
                    android:id="@+id/np__user_profile_edit_back_button"
                    style="@style/NP__.Widget.ImageButton"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:background="@null"
                    android:src="@drawable/np__ic_navigate_back" />

                <View
                    android:layout_width="1dp"
                    android:layout_height="@dimen/np__user_profile_edit_action_bar_vertical_separator"
                    android:layout_marginEnd="@dimen/np__user_profile_edit_action_bar_vertical_separator_margin"
                    android:layout_marginRight="@dimen/np__user_profile_edit_action_bar_vertical_separator_margin"
                    android:background="@color/np__grey_light" />

                <TextView
                    android:id="@+id/np__user_profile_edit_action_bar_title"
                    style="@style/NP__.Credentials.Title.Text"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/np__application_name" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:orientation="horizontal" >

                <ImageButton
                    android:id="@+id/np__user_profile_edit_done_button"
                    style="@style/NP__.Widget.ImageButton"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:background="@null"
                    android:src="@drawable/np__ic_check_mark" />
            </LinearLayout>
        </RelativeLayout>

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center_horizontal"
                android:orientation="vertical"
                android:padding="@dimen/np__fragment_default_padding" >

                <com.nextpeer.android.open.ui.NPCircularImageView
                    android:id="@+id/np__user_profile_edit_picture"
                    android:layout_width="@dimen/np__user_profile_picture_radius"
                    android:layout_height="@dimen/np__user_profile_picture_radius"
                    android:layout_marginTop="@dimen/np__user_profile_picture_top_margin"
                    android:clickable="true"
                    android:src="@drawable/np__ic_add_player_profile_picture"
                    app:np__image_border="true"
                    app:np__image_borderColor="@color/np__white"
                    app:np__image_borderWidth="@dimen/np__user_profile_picture_border_line_size"
                    app:np__image_shadow="true" />

                <TextView
                    android:id="@+id/np__user_profile_edit_description"
                    style="@style/NP__.Profile.Edit.Description"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="@dimen/np__user_profile_edit_title_text_margin_bottom"
                    android:layout_marginTop="@dimen/np__user_profile_edit_title_text_margin_top"
                    android:gravity="center_horizontal"
                    android:text="@string/np__application_name" />

                <EditText
                    android:id="@+id/np__user_profile_edit_username"
                    style="@style/NP__.Profile.Edit.Text"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/np__user_profile_edit_text_height"
                    android:layout_margin="@dimen/np__user_profile_edit_text_margin"
                    android:focusable="false"
                    android:maxLength="@integer/np__user_profile_edit_name_max_length" />

                <EditText
                    android:id="@+id/np__user_profile_edit_motto"
                    style="@style/NP__.Profile.Edit.Text"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/np__user_profile_edit_text_height"
                    android:layout_margin="@dimen/np__user_profile_edit_text_margin"
                    android:focusable="false"
                    android:maxLength="@integer/np__user_profile_edit_motto_max_length" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal" >

                    <AutoCompleteTextView
                        android:id="@+id/np__user_profile_edit_country"
                        style="@style/NP__.Profile.SearchView"
                        android:layout_width="0dp"
                        android:layout_height="@dimen/np__user_profile_edit_text_height"
                        android:layout_margin="@dimen/np__user_profile_edit_text_margin"
                        android:layout_weight="1"
                        android:focusable="false"
                        android:hint="@string/np__application_name" />

                    <AutoCompleteTextView
                        android:id="@+id/np__user_profile_edit_city"
                        style="@style/NP__.Profile.SearchView"
                        android:layout_width="0dp"
                        android:layout_height="@dimen/np__user_profile_edit_text_height"
                        android:layout_margin="@dimen/np__user_profile_edit_text_margin"
                        android:layout_weight="1"
                        android:focusable="false"
                        android:hint="@string/np__application_name"
                        android:maxLength="@integer/np__user_profile_edit_city_max_length" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal" >

                    <Spinner
                        android:id="@+id/np__user_profile_edit_gender"
                        style="@style/NP__.Profile.Spinner"
                        android:layout_width="0dp"
                        android:layout_height="@dimen/np__user_profile_edit_text_height"
                        android:layout_margin="@dimen/np__user_profile_edit_text_margin"
                        android:layout_weight="1"
                        android:focusable="false"
                        android:hint="@string/np__application_name" />

                    <Button
                        android:id="@+id/np__user_profile_edit_birthday"
                        style="@style/NP__.Profile.Edit.Button"
                        android:layout_width="0dp"
                        android:layout_height="@dimen/np__user_profile_edit_text_height"
                        android:layout_margin="@dimen/np__user_profile_edit_text_margin"
                        android:layout_weight="1"
                        android:focusable="false"
                        android:hint="@string/np__application_name" />
                </LinearLayout>

                <!--
                This is placeholder view which holds nothing. The reason being the fact that on some Android versions the soft keyboard
                doesn't update the view size correctly and prevents the user to scroll while editing.
                See https://code.google.com/p/android/issues/detail?id=57382
                -->

                <LinearLayout
                    android:id="@+id/np__user_profile_bottom_placeholder"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/np__scrollable_keyboard_height"
                    android:orientation="vertical" >
                </LinearLayout>
            </LinearLayout>
        </ScrollView>
    </LinearLayout>

</LinearLayout>


text:
module B where

import A

data B = B deriving Show

instance Class1 B


text:
This guide documents the Onyx build process. For example usage of this building process, look at `.github/workflows/main.yml`.

Note that steps 0, 1 and 2 can be skipped if you have already done them before.

## Step 0: Set up the build environment

First, you'll need to download the [minimal sysroot](https://storage.googleapis.com/onyx-stuffs/minimal-sysroot.tar.zst).
This allows you to have the toolchain build against a sane libc.
Be sure to export `SYSROOT=$PWD/sysroot` and `ONYX_ARCH=x86_64` (right now, only x86_64 is supported).

## Step 1: Get the toolchains

If you so desire, you can find prebuilts for Linux and macOS in the project's github action artifacts,
under `build-toolchain-${os}` or `build-toolchain-llvm-${os}`. Note that macOS LLVM builds are broken.

You can find two scripts, `build_gcc.sh` and `build_llvm.sh`, under `toolchains/scripts`. These build a
GCC and LLVM toolchain for Onyx, respectively. Use these and install the toolchains to a known location.
Note: $GCC_TOOLCHAIN/bin needs to be on the system's $PATH. LLVM has no such requirement.

## Step 2: Set up the kernel config

The kernel build requires a valid `kernel.config` under kernel/. You can look at pre-existing examples
(.example and .minimal) and lay the kernel out yourself; kernel.config.example is a fine choice.

After this point, it's required that SYSROOT, ONYX_ARCH are set and that, if using LLVM, CLANG_PATH points to the
installation path of the LLVM toolchain.

## Step 3: Set up the build

This step only needs to be done once. Run `./scripts/setup_build.sh`.

## Step 4: Build

Do `make -j <nproc> iso` where nproc is the number of threads you want the build to use.

`RUN_CLANG_TIDY=0` might be a useful flag to pass, as it stops the kernel build from running clang-tidy on files.

If everything went well, you will have a Onyx.iso under the base directory!


text:
require_relative 'api'
require 'json'
@tag = "hikasa youko"
@limit = "1"
@site = "sei.neesan.org"
def scrap(site,tag,limit,api_key)
  @site = site
  scrapper = TumblrScrapper.new(@site, api_key)
  scraps = scrapper.posts(type="photo", id="", @tag=tag, @limit=limit, fiter="text")
  usable_scraps = JSON.parse(scraps)
  #posts is an array
  posts = usable_scraps["response"]["posts"]
  print posts.count.to_s + " results.\n"

  #find all the urls
  (0..posts.count-1).each do |count|
    if posts[count]["link_url"]
      print posts[count]["link_url"] + "\n"
    else
      #largest dimensions, multi photo post
      (0..posts[count]["photos"].count-1).each do | pcount |
        print posts[count]["photos"][pcount]["alt_sizes"][0]["url"] + "\n"
      end
    end
  end
end


text:
package com.amazonaws.services.connect.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeContactRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The identifier of the Amazon Connect instance. You can find the instanceId in the ARN of the instance.
     *

     */
    private String instanceId;
    /**
     *

     * The identifier of the contact.
     *

     */
    private String contactId;

    /**
     *

     * The identifier of the Amazon Connect instance. You can find the instanceId in the ARN of the instance.
     *

     *
     * @param instanceId
     *        The identifier of the Amazon Connect instance. You can find the instanceId in the ARN of the instance.
     */

    public void setInstanceId(String instanceId) {
        this.instanceId = instanceId;
    }

    /**
     *

     * The identifier of the Amazon Connect instance. You can find the instanceId in the ARN of the instance.
     *

     *
     * @return The identifier of the Amazon Connect instance. You can find the instanceId in the ARN of the instance.
     */

    public String getInstanceId() {
        return this.instanceId;
    }

    /**
     *

     * The identifier of the Amazon Connect instance. You can find the instanceId in the ARN of the instance.
     *

     *
     * @param instanceId
     *        The identifier of the Amazon Connect instance. You can find the instanceId in the ARN of the instance.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeContactRequest withInstanceId(String instanceId) {
        setInstanceId(instanceId);
        return this;
    }

    /**
     *

     * The identifier of the contact.
     *

     *
     * @param contactId
     *        The identifier of the contact.
     */

    public void setContactId(String contactId) {
        this.contactId = contactId;
    }

    /**
     *

     * The identifier of the contact.
     *

     *
     * @return The identifier of the contact.
     */

    public String getContactId() {
        return this.contactId;
    }

    /**
     *

     * The identifier of the contact.
     *

     *
     * @param contactId
     *        The identifier of the contact.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeContactRequest withContactId(String contactId) {
        setContactId(contactId);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getInstanceId() != null)
            sb.append("InstanceId: ").append(getInstanceId()).append(",");
        if (getContactId() != null)
            sb.append("ContactId: ").append(getContactId());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DescribeContactRequest == false)
            return false;
        DescribeContactRequest other = (DescribeContactRequest) obj;
        if (other.getInstanceId() == null ^ this.getInstanceId() == null)
            return false;
        if (other.getInstanceId() != null && other.getInstanceId().equals(this.getInstanceId()) == false)
            return false;
        if (other.getContactId() == null ^ this.getContactId() == null)
            return false;
        if (other.getContactId() != null && other.getContactId().equals(this.getContactId()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getInstanceId() == null) ? 0 : getInstanceId().hashCode());
        hashCode = prime * hashCode + ((getContactId() == null) ? 0 : getContactId().hashCode());
        return hashCode;
    }

    @Override
    public DescribeContactRequest clone() {
        return (DescribeContactRequest) super.clone();
    }

}


text:
var fs = require('fs');
require('babel/register');
require('./scripts/server');
fs.closeSync(fs.openSync('./tmp/reload', 'w'));


text:
using System;
using UnityEngine;

public class ToLua_DG_Tweening_Tween
{

	public DG.Tweening.Tween SetAutoKill()	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween SetAutoKill(bool arg1)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween SetId(object arg1)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween SetTarget(object arg1)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween SetLoops(int arg1)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween SetLoops(int arg1, DG.Tweening.LoopType arg2)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween SetEase(DG.Tweening.Ease arg1)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween SetEase(DG.Tweening.Ease arg1, float arg2)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween SetEase(DG.Tweening.Ease arg1, float arg2, float arg3)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween SetEase(UnityEngine.AnimationCurve arg1)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween SetEase(DG.Tweening.EaseFunction arg1)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween SetRecyclable()	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween SetRecyclable(bool arg1)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween SetUpdate(bool arg1)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween SetUpdate(DG.Tweening.UpdateType arg1)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween SetUpdate(DG.Tweening.UpdateType arg1, bool arg2)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween OnStart(DG.Tweening.TweenCallback arg1)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween OnPlay(DG.Tweening.TweenCallback arg1)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween OnPause(DG.Tweening.TweenCallback arg1)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween OnRewind(DG.Tweening.TweenCallback arg1)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween OnUpdate(DG.Tweening.TweenCallback arg1)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween OnStepComplete(DG.Tweening.TweenCallback arg1)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween OnComplete(DG.Tweening.TweenCallback arg1)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween OnKill(DG.Tweening.TweenCallback arg1)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween OnWaypointChange(DG.Tweening.TweenCallback<int> arg1)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween SetAs(DG.Tweening.Tween arg1)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween SetAs(DG.Tweening.TweenParams arg1)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween SetDelay(float arg1)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween SetRelative()	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween SetRelative(bool arg1)	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween SetSpeedBased()	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween SetSpeedBased(bool arg1)	{ return default(DG.Tweening.Tween); }
	public void Complete()	{}
	public void Complete(bool arg1)	{}
	public void Flip()	{}
	public void ForceInit()	{}
	public void Goto(float arg1, bool arg2)	{}
	public void Kill(bool arg1)	{}
	public DG.Tweening.Tween Pause()	{ return default(DG.Tweening.Tween); }
	public DG.Tweening.Tween Play()	{ return default(DG.Tweening.Tween); }
	public void PlayBackwards()	{}
	public void PlayForward()	{}
	public void Restart(bool arg1)	{}
	public void Rewind(bool arg1)	{}
	public void SmoothRewind()	{}
	public void TogglePause()	{}
	public void GotoWaypoint(int arg1, bool arg2)	{}
	public UnityEngine.YieldInstruction WaitForCompletion()	{ return default(UnityEngine.YieldInstruction); }
	public UnityEngine.YieldInstruction WaitForRewind()	{ return default(UnityEngine.YieldInstruction); }
	public UnityEngine.YieldInstruction WaitForKill()	{ return default(UnityEngine.YieldInstruction); }
	public UnityEngine.YieldInstruction WaitForElapsedLoops(int arg1)	{ return default(UnityEngine.YieldInstruction); }
	public UnityEngine.YieldInstruction WaitForPosition(float arg1)	{ return default(UnityEngine.YieldInstruction); }
	public UnityEngine.Coroutine WaitForStart()	{ return default(UnityEngine.Coroutine); }
	public int CompletedLoops()	{ return default(int); }
	public float Delay()	{ return default(float); }
	public float Duration(bool arg1)	{ return default(float); }
	public float Elapsed(bool arg1)	{ return default(float); }
	public float ElapsedPercentage(bool arg1)	{ return default(float); }
	public float ElapsedDirectionalPercentage()	{ return default(float); }
	public bool IsActive()	{ return default(bool); }
	public bool IsBackwards()	{ return default(bool); }
	public bool IsComplete()	{ return default(bool); }
	public bool IsInitialized()	{ return default(bool); }
	public bool IsPlaying()	{ return default(bool); }
	public int Loops()	{ return default(int); }
	public UnityEngine.Vector3 PathGetPoint(float arg1)	{ return default(UnityEngine.Vector3); }
	public UnityEngine.Vector3[] PathGetDrawPoints(int arg1)	{ return default(UnityEngine.Vector3[]); }
	public float PathLength()	{ return default(float); }
}


text:
(function () {
    'use strict';

    angular
        .module('app')
        .controller('ResourcesController', ResourcesController)
        .controller('ResourcesEditController', ResourcesEditController)
        .controller('ResourcesDeleteController', ResourcesDeleteController);
        //.controller('RowEditCtrl', RowEditCtrl)
        //.service('RowResourceEditor', RowResourceEditor)
	ResourcesController.$inject = ['$rootScope','$state','$cookieStore','$timeout','$scope','$log','$http','UserService', '$location', 'FlashService','$routeParams'];
	function ResourcesController($rootScope,$state,$cookieStore,$timeout,$scope,$log,$http,UserService, $location,FlashService,$routeParams) {

        var vm = this;
        $rootScope.shownav=true;
        $rootScope.rootAccess =  $cookieStore.get("rootAccess");
        $rootScope.pmAccess =  $cookieStore.get("pmAccess");
        var jsonstring="";
        vm.saveresource = saveresource;
        //vm.getSkilldata = getSkilldata;
        $scope.resmodel = [];
$rootScope.ressettings = $scope.ressettings = {
  scrollableHeight: '200px',
    scrollable: true,
  enableSearch: true,
  displayProp:'skill_name',
  idProp:'id',
  externalIdProp:'id',
  closeOnBlur:true
};
$scope.data = {
                          repeatSelect: null,
                          statusSelect: null,
                          managerSelect: null,

                         };
        var rowIndexTemp = 0;
        // $timeout(function () {
        UserService.getHeirarchies()
                         .then(function (response) {
                          $rootScope.availableHeirarchyOptions = response.data;
                         $scope.data.availableHeirarchyOptions= $rootScope.availableHeirarchyOptions;
                         });
                       // },3000);
        // $timeout(function () {
        UserService.getSkills()
                         .then(function (response) {
                          $rootScope.availableSkillOptions = response.data;
                          $scope.data.availableSkillOptions = $rootScope.availableSkillOptions;
                          var skillArray = {};
                          for(var i = 0; i < response.data.length; i++) {
                          var obj = response.data[i];
                          skillArray[obj.id] = obj.skill_name;
                          }
                          $scope.resdata = response.data;
                         });
                       // },3000);
    //$scope.clickResourceHandler = RowResourceEditor.editRow;
		$scope.eventDetails = eventDetails;
        $scope.message = 'Look! I am a Resource page.';

       /* function getSkilldata(){
          return "are";
        }*/

    $scope.ShowHide = function () {
                //If DIV is visible it will be hidden and vice versa.
                $scope.IsVisible = $scope.IsVisible ? false : true;
            }

     function saveresource() {
            vm.dataLoading = true;
            vm.resource.resmodel=$scope.resmodel;
            UserService.saveResource(vm.resource)
                .then(function (response) {
                    if (response.data.success) {
                        FlashService.Success('Save successful', true);
                        vm.dataLoading = false;
                        // UserService.getResources()
                          // .then(function (response) {
                            $state.go("resources", {}, {reload: true});
                           // });
                    } else {
                      if(response.data.error.employee_id){
                        FlashService.Error('Employee ID ' +response.data.error.employee_id[0]);
                      }
                      if(response.data.error.heirarchy_name){
                        FlashService.Error('Heirarchy Name ' +response.data.error.heirarchy_name[0]);
                      }
                        vm.dataLoading = false;
                    }
                });
        }

    function eventDetails(event){
       $scope.selected = event;
       $scope.query = event;

    }

    $scope.example13model = [];
$scope.example13settings = {
	scrollableHeight: '200px',
    scrollable: true,
	enableSearch: true,

};
$scope.$scope = $scope;
vm.gridOptions = {
   enableColumnResizing: true,
   enableCellEdit: false,
    columnDefs: [
    { field: 'id',name: 'E/D',  cellTemplate:'
<button type="button" class="btn btn-xs btn-primary" ></button>&nbsp<button type="button" class="btn btn-xs danger-class"  ></button>
', width: 70 },
    { name: 'employee_name', width: 260 },
      { name: 'employee_id' , width: 130},
      { name: 'role' , width: 180},
      // { name: 'heirarchy_id' , width: 140},
      { name: 'skill', enableColumnResizing: true },
      //{ name: 'skill_id' },
    ]

  };
  $scope.removeaccount = function(id) {
      };
  //vm.gridOptions.columnDefs[6].visible = false;
  UserService.getResources()
     .then(function (response) {
      vm.gridOptions.data = response.data;
     });
    }

ResourcesEditController.$inject = ['$scope','$state','$rootScope','$log','$http','UserService', '$location', 'FlashService','$timeout','$routeParams'];
function ResourcesEditController($scope,$state,$rootScope,$log,$http,UserService, $location,FlashService,$timeout,$routeParams) {
  var vm=this;
   vm.saveresource = saveresource;
  var splits=$location.url().toString().split("/");
  console.log(splits);
  UserService.getResource(splits[splits.length - 1])
                  .then(function (response) {
                      if (response.data) {
                        vm.resource = response.data;
                        $scope.resmodel=vm.resource.skill_id;
                        // $scope.resmodel=vm.resource.resmodel;
                        //$scope.sermodel=vm.account.sermodel=
                       // vm.account.start_date=$scope.minEndDate;
             // //vm.account.end_date=$scope.maxEndDate;
             // vm.account.anticipated_value = vm.account.anticipated_value.concat(" ").concat(vm.account.anticipated_value_currency);
                      }
                  });

                  function saveresource() {
            vm.dataLoading = true;
            vm.resource.resmodel=$scope.resmodel;

for(var i = 0; i < $rootScope.availableHeirarchyOptions.length; i++)
{
  if($rootScope.availableHeirarchyOptions[i].id == vm.resource.heirarchy_id)
  {
    vm.resource.role= $rootScope.availableHeirarchyOptions[i].role_name;
  }
}

            vm.resource.id=splits[splits.length - 1];
            UserService.editResource(vm.resource)
                .then(function (response) {
                    if (response.data.success) {
                        FlashService.Success('Save successful', true);
                        vm.dataLoading = false;
                        // UserService.getResources()
                          // .then(function (response) {
                            $state.go("resources", {}, {reload: true});
                           // });
                    } else {
                      if(response.data.error.employee_id){
                        FlashService.Error('Employee ID ' +response.data.error.employee_id[0]);
                      }
                      if(response.data.error.heirarchy_name){
                        FlashService.Error('Heirarchy Name  ' +response.data.error.heirarchy_name[0]);
                      }
                        vm.dataLoading = false;
                    }
                });
        }

  }

ResourcesDeleteController.$inject = ['$rootScope','$scope','$state','$log','$http','UserService', '$location', 'FlashService', 'RowEditor', '$timeout','$routeParams'];
function ResourcesDeleteController($rootScope,$scope,$state,$log,$http,UserService, $location,FlashService,RowEditor,$timeout,$routeParams) {
  var vm=this;
   vm.deleteresource = deleteresource;
   $scope.deltext="";
  var splits=$location.url().toString().split("/");
  UserService.deleteDependency({"type":"resource","data":splits[splits.length - 1]})
                  .then(function (response) {
                    if(response.data){
                      $scope.deltext="The data you are trying to delete has a dependency and will be deleted if you proceed";
                    }
                  });
  function deleteresource() {
          vm.dataLoading = true;
              UserService.deleteResource(splits[splits.length - 1])
                  .then(function (response) {
                    console.log(response.status);
                      if (response.status==204) {
                          FlashService.Success('Delete successful', true);
                          vm.dataLoading = false;
                          $state.go("resources", {}, {reload: true});
                          // UserService.getAccounts()
                          //   .then(function (response) {
                          //      vm.gridOptions.data = response.data;
                          //    });
                      } else {
                          FlashService.Error(response.message);
                          vm.dataLoading = false;
                      }
                      // $state.go("account");
                  });

          }
  }

})();


text:
// xrLC.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "math.h"
#include "build.h"
#include "../xrLC_Light/xrLC_GlobalData.h"

//#pragma comment(linker,"/STACK:0x800000,0x400000")
//#pragma comment(linker,"/HEAP:0x70000000,0x10000000")

CBuild* pBuild = NULL;
u32 version = 0;

extern void logThread();
extern volatile BOOL bClose;

static const char* h_str = "The following keys are supported / required:\n"
                           "-? or -h	== this help\n"
                           "-o			== modify build options\n"
                           "-nosun		== disable sun-lighting\n"
                           "-f<NAME>	== compile level in GameData\\Levels\\<NAME>\\\n"
                           "\n"
                           "NOTE: The last key is required for any functionality\n";

void Help() { MessageBox(0, h_str, "Command line options", MB_OK | MB_ICONINFORMATION); }

typedef int __cdecl xrOptions(b_params* params, u32 version, bool bRunBuild);

void Startup(LPSTR lpCmdLine) {

    create_global_data();
    char cmd[512], name[256];
    BOOL bModifyOptions = FALSE;

    xr_strcpy(cmd, lpCmdLine);
    strlwr(cmd);
    if (strstr(cmd, "-?") || strstr(cmd, "-h")) {
        Help();
        return;
    }
    if (strstr(cmd, "-f") == 0) {
        Help();
        return;
    }
    if (strstr(cmd, "-o"))
        bModifyOptions = TRUE;
    if (strstr(cmd, "-gi"))
        g_build_options.b_radiosity = TRUE;
    if (strstr(cmd, "-noise"))
        g_build_options.b_noise = TRUE;
    if (strstr(cmd, "-net"))
        g_build_options.b_net_light = TRUE;
    VERIFY(lc_global_data());
    lc_global_data()->b_nosun_set(!!strstr(cmd, "-nosun"));
    // if (strstr(cmd,"-nosun"))							b_nosun			=
    // TRUE;

    // Give a LOG-thread a chance to startup
    //_set_sbh_threshold(1920);
    InitCommonControls();
	std::thread log_thread(logThread);
    Sleep(150);

    // Faster FPU
    SetPriorityClass(GetCurrentProcess(), NORMAL_PRIORITY_CLASS);

    /*
    u32	dwMin			= 1800*(1024*1024);
    u32	dwMax			= 1900*(1024*1024);
    if (0==SetProcessWorkingSetSize(GetCurrentProcess(),dwMin,dwMax))
    {
            clMsg("*** Failed to expand working set");
    };
    */

    // Load project
    name[0] = 0;
    sscanf(strstr(cmd, "-f") + 2, "%s", name);

    extern HWND logWindow;
    string256 temp;
    xr_sprintf(temp, "%s - Levels Compiler", name);
    SetWindowText(logWindow, temp);

    string_path prjName;
    FS.update_path(prjName, "$game_levels$",
                   strconcat(sizeof(prjName), prjName, name, "\\build.prj"));
    string256 phaseName;
    Phase(strconcat(sizeof(phaseName), phaseName, "Reading project [", name, "]..."));

    string256 inf;
    IReader* F = FS.r_open(prjName);
    if (NULL == F) {
        xr_sprintf(inf, "Build failed!\nCan't find level: '%s'", name);
        clMsg(inf);
        MessageBox(logWindow, inf, "Error!", MB_OK | MB_ICONERROR);
        return;
    }

    // Version
    F->r_chunk(EB_Version, &version);
    clMsg("version: %d", version);
    R_ASSERT(XRCL_CURRENT_VERSION == version);

    // Header
    b_params Params;
    F->r_chunk(EB_Parameters, &Params);

    // Show options if needed
    if (bModifyOptions) {
        Phase("Project options...");
        HMODULE L = LoadLibrary("xrLC_Options.dll");
        void* P = GetProcAddress(L, "_frmScenePropertiesRun");
        R_ASSERT(P);
        xrOptions* O = (xrOptions*)P;
        int R = O(&Params, version, false);
        FreeLibrary(L);
        if (R == 2) {
            ExitProcess(0);
        }
    }

    // Conversion
    Phase("Converting data structures...");
    pBuild = xr_new<CBuild>();
    pBuild->Load(Params, *F);
    FS.r_close(F);

    // Call for builder
    string_path lfn;
    CTimer dwStartupTime;
    dwStartupTime.Start();
    FS.update_path(lfn, _game_levels_, name);
    pBuild->Run(lfn);
    xr_delete(pBuild);

    // Show statistic
    extern std::string make_time(u32 sec);
    u32 dwEndTime = dwStartupTime.GetElapsed_ms();
    xr_sprintf(inf, "Time elapsed: %s", make_time(dwEndTime / 1000).c_str());
    clMsg("Build succesful!\n%s", inf);

    if (!strstr(cmd, "-silent"))
        MessageBox(logWindow, inf, "Congratulation!", MB_OK | MB_ICONINFORMATION);

    // Close log
    bClose = TRUE;
    Sleep(500);
}

int APIENTRY WinMain(HINSTANCE hInst, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
    // Initialize debugging
    Debug._initialize();
    Core._initialize("xrLC");

    if (strstr(Core.Params, "-nosmg"))
        g_using_smooth_groups = false;

    Startup(lpCmdLine);
    Core._destroy();

    return 0;
}


text:
package me.erp.domain.service.verified.user;

import me.erp.domain.model.verified.VerifiedType;
import me.erp.domain.model.verified.user.IUserVerifiedRepository;
import me.erp.domain.model.verified.user.UserVerified;
import me.erp.domain.service.NoFoundException;
import me.erp.infrastructure.persistence.hibernate.generic.Pagination;
import me.erp.interfaces.verified.web.user.command.CreateUserCommand;
import me.erp.interfaces.verified.web.user.command.ListCommand;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by ivan_ on 2015/4/10.
 */
@Service("userVerifiedService")
@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
public class UserVerifiedService implements IUserVerifiedService {

    @Autowired
    private IUserVerifiedRepository<UserVerified, String> userVerifiedRepository;

    @Override
    public UserVerified findById(String id) {
        UserVerified userVerified = userVerifiedRepository.getById(id);
        if (null == userVerified) {
            throw new NoFoundException("没有发现该帐号");
        }
        return userVerified;
    }

    @Override
    public Pagination<UserVerified> pagination(ListCommand command) {

        command.setPageSize(10);

        List<Criterion> criterionList = new ArrayList<Criterion>();

        Criterion[] restrictions = null;
        int size = criterionList.size();
        if (size> 0) {
            restrictions = new Criterion[size];
            criterionList.toArray(restrictions);
        }

        Order[] orders = {Order.desc("createdDate")};
        return userVerifiedRepository.pagination(command.getPage(), command.getPageSize(), restrictions, orders);
    }

    @Override
    public void create(CreateUserCommand command) {

        Boolean sex;
        if ("0".equals(command.getSex())) {
            sex = false;
        } else {
            sex = true;
        }

        UserVerified user = new UserVerified();
        user.setUsername(command.getUsername());
        user.setRealName(command.getRealName());
        user.setPassword(command.getPassword());
        user.setEmail(command.getEmail());
        user.setSex(sex);
        user.setTelephone(command.getTelephone());
        user.setIdCard(command.getIdCard());
        user.setOrganization(command.getOrganization());
        user.setType(VerifiedType.USER_VERIFIED);
        user.setCreatedDate(new Date());

        userVerifiedRepository.save(user);
    }

    @Override
    public void delete(String id) {
        UserVerified userVerified = this.findById(id);
        userVerifiedRepository.delete(userVerified);
    }
}


text:
require 'random_word'

class LeetPassword

  # note: nowadays it's typical for passwords to be required to
  #       contain at least 1 symbol, 2 uppercase characters and 2 numerals
  #
  def self.generate(max_len=nil, subs: {i: '1', o: '0', e: '3'},
                    symlist: ['@'], upcase: 2, symchar: 1, debug: false,
                    verbose: true)

    max_len += symchar if max_len

    if max_len and max_len <= 6 then
      raise "max length must be greater than 6 characters"
    end

    rawnoun = RandomWord.nouns.next
    hint1 = rawnoun.clone
    noun = rawnoun.gsub(/_/,'')
    if max_len then
      until noun.length >= 6 and noun.length <= max_len
        rawnoun = RandomWord.nouns.next
        hint1 = rawnoun.clone
        noun = rawnoun.gsub(/_/,'')
      end
    end

    subs.each{|k,v| noun.gsub!(k.to_s,v)}

    if noun.length > 7 then

      n = upcase / 2
      r = upcase - n
      noun.sub!(/[a-z]{#{n}}/) {|x| x.upcase}
      noun.sub!(/[a-z]{#{r}}/) {|x| x.upcase}

      noun +=  symlist.sample
      puts 'returning a noun' if debug
      puts 'hint: ' + hint1 if verbose
      return [noun, :noun, hint1]
    end

    rawadj = RandomWord.adjs.next
    hint2 = rawadj.clone
    adj = rawadj.gsub(/_/,'')

    if max_len then
      until adj.length >= 6 and adj.length <= max_len
        rawadj = RandomWord.adjs.next
        hint2 = rawadj.clone
        adj = rawadj.gsub(/_/,'')
      end
    end

    subs.each{|k,v| adj.gsub!(k.to_s,v)}

    if adj.length > 7 then
      n = upcase / 2
      r = upcase - n
      adj.sub!(/[a-z]{#{n}}/) {|x| x.upcase}
      adj.sub!(/[a-z]{#{r}}/) {|x| x.upcase}
      adj +=  symlist.sample
      puts 'returning an adjective' if debug
      puts 'hint: ' + hint2 if verbose
      return [adj, :adj, hint2]
    end

    hint = hint1 + ' ' + hint2

    if max_len then

      words = [noun, adj]

      n = upcase / 2
      r = upcase - n
      words[0].sub!(/.{#{n}}/) {|x| x.upcase}
      words[-1].sub!(/.{#{r}}/) {|x| x.upcase}
      words.insert 1, symlist.sample(symchar)

      if (words.join).length <= max_len then
        puts 'returning a maxlen word' if debug
        puts 'hint: ' + hint if verbose
        return [words.join, :maxlen, hint]
      else
        LeetPassword.generate(max_len, verbose: verbose)
      end

    else

      words = [noun, adj]
      n = upcase / 2
      r = upcase - n

      words[0].sub!(/.{#{n}}/) {|x| x.upcase}
      words[-1].sub!(/.{#{r}}/) {|x| x.upcase}
      words.insert 1, symlist.sample(symchar)
      puts 'words: ' + words.inspect if debug
      puts 'returning a variable length' if debug
      puts 'hint: ' + hint if verbose
      return [words.join, :varlen, hint]

    end

  end

  # This method makes it easier to remember the password since it consists of
  # the following:
  #
  #   * 2 words
  #   * each word is capitalized
  #   * the letters i, e, o are replaced with the numbers 1, 3, and
  #     0 respectively
  #   * the words are separated by the @ symbol
  #   * a password never longer than 12 characters
  #
  def self.easygen()
    pwd, type, hint = self.generate(12, verbose: false) until type == :maxlen
    puts 'hint: ' + hint
    return pwd
  end
end

if __FILE__ == $0 then
  RandomWord.generate
end


text:
from flask import render_template
from . import main

@main.app_errorhandler(404)
def page_not_found(e):
    return "Not Found", 404

@main.app_errorhandler(500)
def internal_server_error(e):
    return "Error", 500


text:
namespace llvm {

/// This class represents the llvm.coro.subfn.addr instruction.
class LLVM_LIBRARY_VISIBILITY CoroSubFnInst : public IntrinsicInst {
  enum { FrameArg, IndexArg };

public:
  enum ResumeKind {
    RestartTrigger = -1,
    ResumeIndex,
    DestroyIndex,
    CleanupIndex,
    IndexLast,
    IndexFirst = RestartTrigger
  };

  Value *getFrame() const { return getArgOperand(FrameArg); }
  ResumeKind getIndex() const {
    int64_t Index = getRawIndex()->getValue().getSExtValue();
    assert(Index >= IndexFirst && Index < IndexLast &&
           "unexpected CoroSubFnInst index argument");
    return static_cast<ResumeKind>(Index);
  }

  ConstantInt *getRawIndex() const {
    return cast<ConstantInt>(getArgOperand(IndexArg));
  }

  // Methods to support type inquiry through isa, cast, and dyn_cast:
  static bool classof(const IntrinsicInst *I) {
    return I->getIntrinsicID() == Intrinsic::coro_subfn_addr;
  }
  static bool classof(const Value *V) {
    return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
  }
};

/// This represents the llvm.coro.alloc instruction.
class LLVM_LIBRARY_VISIBILITY CoroAllocInst : public IntrinsicInst {
public:
  // Methods to support type inquiry through isa, cast, and dyn_cast:
  static bool classof(const IntrinsicInst *I) {
    return I->getIntrinsicID() == Intrinsic::coro_alloc;
  }
  static bool classof(const Value *V) {
    return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
  }
};

/// This represents a common base class for llvm.coro.id instructions.
class LLVM_LIBRARY_VISIBILITY AnyCoroIdInst : public IntrinsicInst {
public:
  CoroAllocInst *getCoroAlloc() {
    for (User *U : users())
      if (auto *CA = dyn_cast<CoroAllocInst>(U))
        return CA;
    return nullptr;
  }

  IntrinsicInst *getCoroBegin() {
    for (User *U : users())
      if (auto *II = dyn_cast<IntrinsicInst>(U))
        if (II->getIntrinsicID() == Intrinsic::coro_begin)
          return II;
    llvm_unreachable("no coro.begin associated with coro.id");
  }

  // Methods to support type inquiry through isa, cast, and dyn_cast:
  static bool classof(const IntrinsicInst *I) {
    auto ID = I->getIntrinsicID();
    return ID == Intrinsic::coro_id ||
           ID == Intrinsic::coro_id_retcon ||
           ID == Intrinsic::coro_id_retcon_once;
  }

  static bool classof(const Value *V) {
    return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
  }
};

/// This represents the llvm.coro.id instruction.
class LLVM_LIBRARY_VISIBILITY CoroIdInst : public AnyCoroIdInst {
  enum { AlignArg, PromiseArg, CoroutineArg, InfoArg };

public:
  AllocaInst *getPromise() const {
    Value *Arg = getArgOperand(PromiseArg);
    return isa<ConstantPointerNull>(Arg)
               ? nullptr
               : cast<AllocaInst>(Arg->stripPointerCasts());
  }

  void clearPromise() {
    Value *Arg = getArgOperand(PromiseArg);
    setArgOperand(PromiseArg,
                  ConstantPointerNull::get(Type::getInt8PtrTy(getContext())));
    if (isa<AllocaInst>(Arg))
      return;
    assert((isa<BitCastInst>(Arg) || isa<GetElementPtrInst>(Arg)) &&
           "unexpected instruction designating the promise");
    // TODO: Add a check that any remaining users of Inst are after coro.begin
    // or add code to move the users after coro.begin.
    auto *Inst = cast<Instruction>(Arg);
    if (Inst->use_empty()) {
      Inst->eraseFromParent();
      return;
    }
    Inst->moveBefore(getCoroBegin()->getNextNode());
  }

  // Info argument of coro.id is
  //   fresh out of the frontend: null ;
  //   outlined                 : {Init, Return, Susp1, Susp2, ...} ;
  //   postsplit                : [resume, destroy, cleanup] ;
  //
  // If parts of the coroutine were outlined to protect against undesirable
  // code motion, these functions will be stored in a struct literal referred to
  // by the Info parameter. Note: this is only needed before coroutine is split.
  //
  // After coroutine is split, resume functions are stored in an array
  // referred to by this parameter.

  struct Info {
    ConstantStruct *OutlinedParts = nullptr;
    ConstantArray *Resumers = nullptr;

    bool hasOutlinedParts() const { return OutlinedParts != nullptr; }
    bool isPostSplit() const { return Resumers != nullptr; }
    bool isPreSplit() const { return !isPostSplit(); }
  };
  Info getInfo() const {
    Info Result;
    auto *GV = dyn_cast<GlobalVariable>(getRawInfo());
    if (!GV)
      return Result;

    assert(GV->isConstant() && GV->hasDefinitiveInitializer());
    Constant *Initializer = GV->getInitializer();
    if ((Result.OutlinedParts = dyn_cast<ConstantStruct>(Initializer)))
      return Result;

    Result.Resumers = cast<ConstantArray>(Initializer);
    return Result;
  }
  Constant *getRawInfo() const {
    return cast<Constant>(getArgOperand(InfoArg)->stripPointerCasts());
  }

  void setInfo(Constant *C) { setArgOperand(InfoArg, C); }

  Function *getCoroutine() const {
    return cast<Function>(getArgOperand(CoroutineArg)->stripPointerCasts());
  }
  void setCoroutineSelf() {
    assert(isa<ConstantPointerNull>(getArgOperand(CoroutineArg)) &&
           "Coroutine argument is already assigned");
    auto *const Int8PtrTy = Type::getInt8PtrTy(getContext());
    setArgOperand(CoroutineArg,
                  ConstantExpr::getBitCast(getFunction(), Int8PtrTy));
  }

  // Methods to support type inquiry through isa, cast, and dyn_cast:
  static bool classof(const IntrinsicInst *I) {
    return I->getIntrinsicID() == Intrinsic::coro_id;
  }
  static bool classof(const Value *V) {
    return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
  }
};

/// This represents either the llvm.coro.id.retcon or
/// llvm.coro.id.retcon.once instruction.
class LLVM_LIBRARY_VISIBILITY AnyCoroIdRetconInst : public AnyCoroIdInst {
  enum { SizeArg, AlignArg, StorageArg, PrototypeArg, AllocArg, DeallocArg };

public:
  void checkWellFormed() const;

  uint64_t getStorageSize() const {
    return cast<ConstantInt>(getArgOperand(SizeArg))->getZExtValue();
  }

  uint64_t getStorageAlignment() const {
    return cast<ConstantInt>(getArgOperand(AlignArg))->getZExtValue();
  }

  Value *getStorage() const {
    return getArgOperand(StorageArg);
  }

  /// Return the prototype for the continuation function.  The type,
  /// attributes, and calling convention of the continuation function(s)
  /// are taken from this declaration.
  Function *getPrototype() const {
    return cast<Function>(getArgOperand(PrototypeArg)->stripPointerCasts());
  }

  /// Return the function to use for allocating memory.
  Function *getAllocFunction() const {
    return cast<Function>(getArgOperand(AllocArg)->stripPointerCasts());
  }

  /// Return the function to use for deallocating memory.
  Function *getDeallocFunction() const {
    return cast<Function>(getArgOperand(DeallocArg)->stripPointerCasts());
  }

  // Methods to support type inquiry through isa, cast, and dyn_cast:
  static bool classof(const IntrinsicInst *I) {
    auto ID = I->getIntrinsicID();
    return ID == Intrinsic::coro_id_retcon
        || ID == Intrinsic::coro_id_retcon_once;
  }
  static bool classof(const Value *V) {
    return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
  }
};

/// This represents the llvm.coro.id.retcon instruction.
class LLVM_LIBRARY_VISIBILITY CoroIdRetconInst
    : public AnyCoroIdRetconInst {
public:
  // Methods to support type inquiry through isa, cast, and dyn_cast:
  static bool classof(const IntrinsicInst *I) {
    return I->getIntrinsicID() == Intrinsic::coro_id_retcon;
  }
  static bool classof(const Value *V) {
    return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
  }
};

/// This represents the llvm.coro.id.retcon.once instruction.
class LLVM_LIBRARY_VISIBILITY CoroIdRetconOnceInst
    : public AnyCoroIdRetconInst {
public:
  // Methods to support type inquiry through isa, cast, and dyn_cast:
  static bool classof(const IntrinsicInst *I) {
    return I->getIntrinsicID() == Intrinsic::coro_id_retcon_once;
  }
  static bool classof(const Value *V) {
    return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
  }
};

/// This represents the llvm.coro.frame instruction.
class LLVM_LIBRARY_VISIBILITY CoroFrameInst : public IntrinsicInst {
public:
  // Methods to support type inquiry through isa, cast, and dyn_cast:
  static bool classof(const IntrinsicInst *I) {
    return I->getIntrinsicID() == Intrinsic::coro_frame;
  }
  static bool classof(const Value *V) {
    return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
  }
};

/// This represents the llvm.coro.free instruction.
class LLVM_LIBRARY_VISIBILITY CoroFreeInst : public IntrinsicInst {
  enum { IdArg, FrameArg };

public:
  Value *getFrame() const { return getArgOperand(FrameArg); }

  // Methods to support type inquiry through isa, cast, and dyn_cast:
  static bool classof(const IntrinsicInst *I) {
    return I->getIntrinsicID() == Intrinsic::coro_free;
  }
  static bool classof(const Value *V) {
    return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
  }
};

/// This class represents the llvm.coro.begin instruction.
class LLVM_LIBRARY_VISIBILITY CoroBeginInst : public IntrinsicInst {
  enum { IdArg, MemArg };

public:
  AnyCoroIdInst *getId() const {
    return cast<AnyCoroIdInst>(getArgOperand(IdArg));
  }

  Value *getMem() const { return getArgOperand(MemArg); }

  // Methods for support type inquiry through isa, cast, and dyn_cast:
  static bool classof(const IntrinsicInst *I) {
    return I->getIntrinsicID() == Intrinsic::coro_begin;
  }
  static bool classof(const Value *V) {
    return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
  }
};

/// This represents the llvm.coro.save instruction.
class LLVM_LIBRARY_VISIBILITY CoroSaveInst : public IntrinsicInst {
public:
  // Methods to support type inquiry through isa, cast, and dyn_cast:
  static bool classof(const IntrinsicInst *I) {
    return I->getIntrinsicID() == Intrinsic::coro_save;
  }
  static bool classof(const Value *V) {
    return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
  }
};

/// This represents the llvm.coro.promise instruction.
class LLVM_LIBRARY_VISIBILITY CoroPromiseInst : public IntrinsicInst {
  enum { FrameArg, AlignArg, FromArg };

public:
  bool isFromPromise() const {
    return cast<Constant>(getArgOperand(FromArg))->isOneValue();
  }
  unsigned getAlignment() const {
    return cast<ConstantInt>(getArgOperand(AlignArg))->getZExtValue();
  }

  // Methods to support type inquiry through isa, cast, and dyn_cast:
  static bool classof(const IntrinsicInst *I) {
    return I->getIntrinsicID() == Intrinsic::coro_promise;
  }
  static bool classof(const Value *V) {
    return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
  }
};

class LLVM_LIBRARY_VISIBILITY AnyCoroSuspendInst : public IntrinsicInst {
public:
  CoroSaveInst *getCoroSave() const;

  // Methods to support type inquiry through isa, cast, and dyn_cast:
  static bool classof(const IntrinsicInst *I) {
    return I->getIntrinsicID() == Intrinsic::coro_suspend ||
           I->getIntrinsicID() == Intrinsic::coro_suspend_retcon;
  }
  static bool classof(const Value *V) {
    return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
  }
};

/// This represents the llvm.coro.suspend instruction.
class LLVM_LIBRARY_VISIBILITY CoroSuspendInst : public AnyCoroSuspendInst {
  enum { SaveArg, FinalArg };

public:
  CoroSaveInst *getCoroSave() const {
    Value *Arg = getArgOperand(SaveArg);
    if (auto *SI = dyn_cast<CoroSaveInst>(Arg))
      return SI;
    assert(isa<ConstantTokenNone>(Arg));
    return nullptr;
  }

  bool isFinal() const {
    return cast<Constant>(getArgOperand(FinalArg))->isOneValue();
  }

  // Methods to support type inquiry through isa, cast, and dyn_cast:
  static bool classof(const IntrinsicInst *I) {
    return I->getIntrinsicID() == Intrinsic::coro_suspend;
  }
  static bool classof(const Value *V) {
    return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
  }
};

inline CoroSaveInst *AnyCoroSuspendInst::getCoroSave() const {
  if (auto Suspend = dyn_cast<CoroSuspendInst>(this))
    return Suspend->getCoroSave();
  return nullptr;
}

/// This represents the llvm.coro.suspend.retcon instruction.
class LLVM_LIBRARY_VISIBILITY CoroSuspendRetconInst : public AnyCoroSuspendInst {
public:
  op_iterator value_begin() { return arg_begin(); }
  const_op_iterator value_begin() const { return arg_begin(); }

  op_iterator value_end() { return arg_end(); }
  const_op_iterator value_end() const { return arg_end(); }

  iterator_range<op_iterator> value_operands() {
    return make_range(value_begin(), value_end());
  }
  iterator_range<const_op_iterator> value_operands() const {
    return make_range(value_begin(), value_end());
  }

  // Methods to support type inquiry through isa, cast, and dyn_cast:
  static bool classof(const IntrinsicInst *I) {
    return I->getIntrinsicID() == Intrinsic::coro_suspend_retcon;
  }
  static bool classof(const Value *V) {
    return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
  }
};

/// This represents the llvm.coro.size instruction.
class LLVM_LIBRARY_VISIBILITY CoroSizeInst : public IntrinsicInst {
public:
  // Methods to support type inquiry through isa, cast, and dyn_cast:
  static bool classof(const IntrinsicInst *I) {
    return I->getIntrinsicID() == Intrinsic::coro_size;
  }
  static bool classof(const Value *V) {
    return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
  }
};

/// This represents the llvm.coro.end instruction.
class LLVM_LIBRARY_VISIBILITY CoroEndInst : public IntrinsicInst {
  enum { FrameArg, UnwindArg };

public:
  bool isFallthrough() const { return !isUnwind(); }
  bool isUnwind() const {
    return cast<Constant>(getArgOperand(UnwindArg))->isOneValue();
  }

  // Methods to support type inquiry through isa, cast, and dyn_cast:
  static bool classof(const IntrinsicInst *I) {
    return I->getIntrinsicID() == Intrinsic::coro_end;
  }
  static bool classof(const Value *V) {
    return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
  }
};

/// This represents the llvm.coro.alloca.alloc instruction.
class LLVM_LIBRARY_VISIBILITY CoroAllocaAllocInst : public IntrinsicInst {
  enum { SizeArg, AlignArg };
public:
  Value *getSize() const {
    return getArgOperand(SizeArg);
  }
  unsigned getAlignment() const {
    return cast<ConstantInt>(getArgOperand(AlignArg))->getZExtValue();
  }

  // Methods to support type inquiry through isa, cast, and dyn_cast:
  static bool classof(const IntrinsicInst *I) {
    return I->getIntrinsicID() == Intrinsic::coro_alloca_alloc;
  }
  static bool classof(const Value *V) {
    return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
  }
};

/// This represents the llvm.coro.alloca.get instruction.
class LLVM_LIBRARY_VISIBILITY CoroAllocaGetInst : public IntrinsicInst {
  enum { AllocArg };
public:
  CoroAllocaAllocInst *getAlloc() const {
    return cast<CoroAllocaAllocInst>(getArgOperand(AllocArg));
  }

  // Methods to support type inquiry through isa, cast, and dyn_cast:
  static bool classof(const IntrinsicInst *I) {
    return I->getIntrinsicID() == Intrinsic::coro_alloca_get;
  }
  static bool classof(const Value *V) {
    return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
  }
};

/// This represents the llvm.coro.alloca.free instruction.
class LLVM_LIBRARY_VISIBILITY CoroAllocaFreeInst : public IntrinsicInst {
  enum { AllocArg };
public:
  CoroAllocaAllocInst *getAlloc() const {
    return cast<CoroAllocaAllocInst>(getArgOperand(AllocArg));
  }

  // Methods to support type inquiry through isa, cast, and dyn_cast:
  static bool classof(const IntrinsicInst *I) {
    return I->getIntrinsicID() == Intrinsic::coro_alloca_free;
  }
  static bool classof(const Value *V) {
    return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
  }
};

} // End namespace llvm.

#endif