text:
namespace content {

WorkerService* WorkerService::GetInstance() {
  return SharedWorkerServiceImpl::GetInstance();
}

namespace {

class ScopedWorkerDependencyChecker {
 public:
  explicit ScopedWorkerDependencyChecker(SharedWorkerServiceImpl* service)
      : service_(service) {}
  ScopedWorkerDependencyChecker(SharedWorkerServiceImpl* service,
                                base::Closure done_closure)
      : service_(service), done_closure_(done_closure) {}
  ~ScopedWorkerDependencyChecker() {
    service_->CheckWorkerDependency();
    if (!done_closure_.is_null())
      done_closure_.Run();
  }

 private:
  SharedWorkerServiceImpl* service_;
  base::Closure done_closure_;
  DISALLOW_COPY_AND_ASSIGN(ScopedWorkerDependencyChecker);
};

void UpdateWorkerDependencyOnUI(const std::vector<int>& added_ids,
                                const std::vector<int>& removed_ids) {
  for (int id : added_ids) {
    RenderProcessHostImpl* render_process_host_impl =
        static_cast<RenderProcessHostImpl*>(RenderProcessHost::FromID(id));
    if (!render_process_host_impl)
      continue;
    render_process_host_impl->IncrementWorkerRefCount();
  }
  for (int id : removed_ids) {
    RenderProcessHostImpl* render_process_host_impl =
        static_cast<RenderProcessHostImpl*>(RenderProcessHost::FromID(id));
    if (!render_process_host_impl)
      continue;
    render_process_host_impl->DecrementWorkerRefCount();
  }
}

void UpdateWorkerDependency(const std::vector<int>& added_ids,
                            const std::vector<int>& removed_ids) {
  BrowserThread::PostTask(
      BrowserThread::UI,
      FROM_HERE,
      base::Bind(&UpdateWorkerDependencyOnUI, added_ids, removed_ids));
}

void DecrementWorkerRefCount(int process_id) {
  if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
    BrowserThread::PostTask(BrowserThread::UI,
                            FROM_HERE,
                            base::Bind(&DecrementWorkerRefCount, process_id));
    return;
  }
  RenderProcessHostImpl* render_process_host_impl =
      static_cast<RenderProcessHostImpl*>(
          RenderProcessHost::FromID(process_id));
  if (render_process_host_impl)
    render_process_host_impl->DecrementWorkerRefCount();
}

bool TryIncrementWorkerRefCount(int worker_process_id) {
  RenderProcessHostImpl* render_process = static_cast<RenderProcessHostImpl*>(
      RenderProcessHost::FromID(worker_process_id));
  if (!render_process || render_process->FastShutdownStarted())
    return false;
  render_process->IncrementWorkerRefCount();
  return true;
}

}  // namespace

class SharedWorkerServiceImpl::SharedWorkerPendingInstance {
 public:
  struct SharedWorkerPendingRequest {
    SharedWorkerPendingRequest(SharedWorkerMessageFilter* filter,
                               int route_id,
                               unsigned long long document_id,
                               int render_process_id,
                               int render_frame_route_id)
        : filter(filter),
          route_id(route_id),
          document_id(document_id),
          render_process_id(render_process_id),
          render_frame_route_id(render_frame_route_id) {}
    SharedWorkerMessageFilter* const filter;
    const int route_id;
    const unsigned long long document_id;
    const int render_process_id;
    const int render_frame_route_id;
  };

  using SharedWorkerPendingRequests =
      std::vector<std::unique_ptr<SharedWorkerPendingRequest>>;

  explicit SharedWorkerPendingInstance(
      std::unique_ptr<SharedWorkerInstance> instance)
      : instance_(std::move(instance)) {}

  ~SharedWorkerPendingInstance() {}

  SharedWorkerInstance* instance() { return instance_.get(); }
  SharedWorkerInstance* release_instance() { return instance_.release(); }
  SharedWorkerPendingRequests* requests() { return &requests_; }

  SharedWorkerMessageFilter* FindFilter(int process_id) {
    for (const auto& request : requests_) {
      if (request->render_process_id == process_id)
        return request->filter;
    }
    return nullptr;
  }

  void AddRequest(std::unique_ptr<SharedWorkerPendingRequest> request_info) {
    requests_.push_back(std::move(request_info));
  }

  void RemoveRequest(int process_id) {
    auto to_remove = std::remove_if(
        requests_.begin(), requests_.end(),
        [process_id](const std::unique_ptr<SharedWorkerPendingRequest>& r) {
          return r->render_process_id == process_id;
        });
    requests_.erase(to_remove, requests_.end());
  }

  void RegisterToSharedWorkerHost(SharedWorkerHost* host) {
    for (const auto& request : requests_) {
      host->AddFilter(request->filter, request->route_id);
      host->worker_document_set()->Add(request->filter,
                                       request->document_id,
                                       request->render_process_id,
                                       request->render_frame_route_id);
    }
  }

  void SendWorkerCreatedMessages() {
    for (const auto& request : requests_)
      request->filter->Send(new ViewMsg_WorkerCreated(request->route_id));
  }

 private:
  std::unique_ptr<SharedWorkerInstance> instance_;
  SharedWorkerPendingRequests requests_;
  DISALLOW_COPY_AND_ASSIGN(SharedWorkerPendingInstance);
};

class SharedWorkerServiceImpl::SharedWorkerReserver
    : public base::RefCountedThreadSafe<SharedWorkerReserver> {
 public:
  SharedWorkerReserver(int pending_instance_id,
                       int worker_process_id,
                       int worker_route_id,
                       bool is_new_worker,
                       const SharedWorkerInstance& instance)
      : worker_process_id_(worker_process_id),
        worker_route_id_(worker_route_id),
        is_new_worker_(is_new_worker),
        instance_(instance) {}

  void TryReserve(const base::Callback<void(bool)>& success_cb,
                  const base::Closure& failure_cb,
                  bool (*try_increment_worker_ref_count)(int)) {
    DCHECK_CURRENTLY_ON(BrowserThread::UI);
    if (!try_increment_worker_ref_count(worker_process_id_)) {
      BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, failure_cb);
      return;
    }
    bool pause_on_start = false;
    if (is_new_worker_) {
      pause_on_start =
          SharedWorkerDevToolsManager::GetInstance()->WorkerCreated(
              worker_process_id_, worker_route_id_, instance_);
    }
    BrowserThread::PostTask(
        BrowserThread::IO, FROM_HERE, base::Bind(success_cb, pause_on_start));
  }

 private:
  friend class base::RefCountedThreadSafe<SharedWorkerReserver>;
  ~SharedWorkerReserver() {}

  const int worker_process_id_;
  const int worker_route_id_;
  const bool is_new_worker_;
  const SharedWorkerInstance instance_;
};

// static
bool (*SharedWorkerServiceImpl::s_try_increment_worker_ref_count_)(int) =
    TryIncrementWorkerRefCount;

SharedWorkerServiceImpl* SharedWorkerServiceImpl::GetInstance() {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  return base::Singleton<SharedWorkerServiceImpl>::get();
}

SharedWorkerServiceImpl::SharedWorkerServiceImpl()
    : update_worker_dependency_(UpdateWorkerDependency),
      next_pending_instance_id_(0) {
}

SharedWorkerServiceImpl::~SharedWorkerServiceImpl() {}

void SharedWorkerServiceImpl::ResetForTesting() {
  last_worker_depended_renderers_.clear();
  worker_hosts_.clear();
  observers_.Clear();
  update_worker_dependency_ = UpdateWorkerDependency;
  s_try_increment_worker_ref_count_ = TryIncrementWorkerRefCount;
}

bool SharedWorkerServiceImpl::TerminateWorker(int process_id, int route_id) {
  SharedWorkerHost* host = FindSharedWorkerHost(process_id, route_id);
  if (!host || !host->instance())
    return false;
  host->TerminateWorker();
  return true;
}

std::vector<WorkerService::WorkerInfo> SharedWorkerServiceImpl::GetWorkers() {
  std::vector<WorkerService::WorkerInfo> results;
  for (const auto& iter : worker_hosts_) {
    SharedWorkerHost* host = iter.second.get();
    const SharedWorkerInstance* instance = host->instance();
    if (instance) {
      WorkerService::WorkerInfo info;
      info.url = instance->url();
      info.name = instance->name();
      info.route_id = host->worker_route_id();
      info.process_id = host->process_id();
      info.handle = host->container_render_filter()->PeerHandle();
      results.push_back(info);
    }
  }
  return results;
}

void SharedWorkerServiceImpl::AddObserver(WorkerServiceObserver* observer) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  observers_.AddObserver(observer);
}

void SharedWorkerServiceImpl::RemoveObserver(WorkerServiceObserver* observer) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  observers_.RemoveObserver(observer);
}

blink::WebWorkerCreationError SharedWorkerServiceImpl::CreateWorker(
    const ViewHostMsg_CreateWorker_Params& params,
    int route_id,
    SharedWorkerMessageFilter* filter,
    ResourceContext* resource_context,
    const WorkerStoragePartitionId& partition_id) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  std::unique_ptr<SharedWorkerInstance> instance(new SharedWorkerInstance(
      params.url, params.name, params.content_security_policy,
      params.security_policy_type, params.creation_address_space,
      resource_context, partition_id, params.creation_context_type));
  std::unique_ptr<SharedWorkerPendingInstance::SharedWorkerPendingRequest>
      request(new SharedWorkerPendingInstance::SharedWorkerPendingRequest(
          filter, route_id, params.document_id, filter->render_process_id(),
          params.render_frame_route_id));
  if (SharedWorkerPendingInstance* pending = FindPendingInstance(*instance)) {
    if (params.url != pending->instance()->url())
      return blink::WebWorkerCreationErrorURLMismatch;
    pending->AddRequest(std::move(request));
    if (params.creation_context_type !=
        pending->instance()->creation_context_type())
      return blink::WebWorkerCreationErrorSecureContextMismatch;
    return blink::WebWorkerCreationErrorNone;
  }

  std::unique_ptr<SharedWorkerPendingInstance> pending_instance(
      new SharedWorkerPendingInstance(std::move(instance)));
  pending_instance->AddRequest(std::move(request));
  return ReserveRenderProcessToCreateWorker(std::move(pending_instance));
}

void SharedWorkerServiceImpl::ForwardToWorker(
    const IPC::Message& message,
    SharedWorkerMessageFilter* filter) {
  for (WorkerHostMap::const_iterator iter = worker_hosts_.begin();
       iter != worker_hosts_.end();
       ++iter) {
    if (iter->second->FilterMessage(message, filter))
      return;
  }
}

void SharedWorkerServiceImpl::DocumentDetached(
    unsigned long long document_id,
    SharedWorkerMessageFilter* filter) {
  ScopedWorkerDependencyChecker checker(this);
  for (WorkerHostMap::const_iterator iter = worker_hosts_.begin();
       iter != worker_hosts_.end();
       ++iter) {
    iter->second->DocumentDetached(filter, document_id);
  }
}

void SharedWorkerServiceImpl::WorkerContextClosed(
    int worker_route_id,
    SharedWorkerMessageFilter* filter) {
  ScopedWorkerDependencyChecker checker(this);
  if (SharedWorkerHost* host =
          FindSharedWorkerHost(filter->render_process_id(), worker_route_id))
    host->WorkerContextClosed();
}

void SharedWorkerServiceImpl::WorkerContextDestroyed(
    int worker_route_id,
    SharedWorkerMessageFilter* filter) {
  ScopedWorkerDependencyChecker checker(this);
  ProcessRouteIdPair key(filter->render_process_id(), worker_route_id);
  if (!ContainsKey(worker_hosts_, key))
    return;
  std::unique_ptr<SharedWorkerHost> host(worker_hosts_[key].release());
  worker_hosts_.erase(key);
  host->WorkerContextDestroyed();
}

void SharedWorkerServiceImpl::WorkerReadyForInspection(
    int worker_route_id,
    SharedWorkerMessageFilter* filter) {
  if (SharedWorkerHost* host =
          FindSharedWorkerHost(filter->render_process_id(), worker_route_id))
    host->WorkerReadyForInspection();
}

void SharedWorkerServiceImpl::WorkerScriptLoaded(
    int worker_route_id,
    SharedWorkerMessageFilter* filter) {
  if (SharedWorkerHost* host =
          FindSharedWorkerHost(filter->render_process_id(), worker_route_id))
    host->WorkerScriptLoaded();
}

void SharedWorkerServiceImpl::WorkerScriptLoadFailed(
    int worker_route_id,
    SharedWorkerMessageFilter* filter) {
  ScopedWorkerDependencyChecker checker(this);
  ProcessRouteIdPair key(filter->render_process_id(), worker_route_id);
  if (!ContainsKey(worker_hosts_, key))
    return;
  std::unique_ptr<SharedWorkerHost> host(worker_hosts_[key].release());
  worker_hosts_.erase(key);
  host->WorkerScriptLoadFailed();
}

void SharedWorkerServiceImpl::WorkerConnected(
    int message_port_id,
    int worker_route_id,
    SharedWorkerMessageFilter* filter) {
  if (SharedWorkerHost* host =
          FindSharedWorkerHost(filter->render_process_id(), worker_route_id))
    host->WorkerConnected(message_port_id);
}

void SharedWorkerServiceImpl::AllowFileSystem(
    int worker_route_id,
    const GURL& url,
    IPC::Message* reply_msg,
    SharedWorkerMessageFilter* filter) {
  if (SharedWorkerHost* host =
          FindSharedWorkerHost(filter->render_process_id(), worker_route_id)) {
    host->AllowFileSystem(url, base::WrapUnique(reply_msg));
  } else {
    filter->Send(reply_msg);
    return;
  }
}

void SharedWorkerServiceImpl::AllowIndexedDB(
    int worker_route_id,
    const GURL& url,
    const base::string16& name,
    bool* result,
    SharedWorkerMessageFilter* filter) {
  if (SharedWorkerHost* host =
          FindSharedWorkerHost(filter->render_process_id(), worker_route_id))
    host->AllowIndexedDB(url, name, result);
  else
    *result = false;
}

void SharedWorkerServiceImpl::OnSharedWorkerMessageFilterClosing(
    SharedWorkerMessageFilter* filter) {
  ScopedWorkerDependencyChecker checker(this);
  std::vector<ProcessRouteIdPair> remove_list;
  for (const auto& it : worker_hosts_) {
    it.second->FilterShutdown(filter);
    if (it.first.first == filter->render_process_id())
      remove_list.push_back(it.first);
  }
  for (const ProcessRouteIdPair& to_remove : remove_list)
    worker_hosts_.erase(to_remove);

  std::vector<int> remove_pending_instance_list;
  for (const auto& it : pending_instances_) {
    it.second->RemoveRequest(filter->render_process_id());
    if (it.second->requests()->empty())
      remove_pending_instance_list.push_back(it.first);
  }
  for (int to_remove : remove_pending_instance_list)
    pending_instances_.erase(to_remove);
}

void SharedWorkerServiceImpl::NotifyWorkerDestroyed(int worker_process_id,
                                                    int worker_route_id) {
  FOR_EACH_OBSERVER(WorkerServiceObserver,
                    observers_,
                    WorkerDestroyed(worker_process_id, worker_route_id));
}

// TODO(alokp): Remove after collecting crash data.
// Temporary checks to verify that all shared workers are terminated.
// It is suspected that shared workers prevent render process hosts
// from shutting down: crbug.com/608049
void SharedWorkerServiceImpl::CheckAllWorkersTerminated() {
  std::set<int> dependent_renderers = GetRenderersWithWorkerDependency();
  CHECK_EQ(0u, dependent_renderers.size());
}

blink::WebWorkerCreationError
SharedWorkerServiceImpl::ReserveRenderProcessToCreateWorker(
    std::unique_ptr<SharedWorkerPendingInstance> pending_instance) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  DCHECK(!FindPendingInstance(*pending_instance->instance()));
  if (!pending_instance->requests()->size())
    return blink::WebWorkerCreationErrorNone;

  int worker_process_id = -1;
  int worker_route_id = MSG_ROUTING_NONE;
  bool is_new_worker = true;
  blink::WebWorkerCreationError creation_error =
      blink::WebWorkerCreationErrorNone;
  SharedWorkerHost* host = FindSharedWorkerHost(*pending_instance->instance());
  if (host) {
    if (pending_instance->instance()->url() != host->instance()->url())
      return blink::WebWorkerCreationErrorURLMismatch;
    if (pending_instance->instance()->creation_context_type() !=
        host->instance()->creation_context_type()) {
      creation_error = blink::WebWorkerCreationErrorSecureContextMismatch;
    }
    worker_process_id = host->process_id();
    worker_route_id = host->worker_route_id();
    is_new_worker = false;
  } else {
    SharedWorkerMessageFilter* first_filter =
        (*pending_instance->requests()->begin())->filter;
    worker_process_id = first_filter->render_process_id();
    worker_route_id = first_filter->GetNextRoutingID();
  }

  const int pending_instance_id = next_pending_instance_id_++;
  scoped_refptr<SharedWorkerReserver> reserver(
      new SharedWorkerReserver(pending_instance_id,
                               worker_process_id,
                               worker_route_id,
                               is_new_worker,
                               *pending_instance->instance()));
  BrowserThread::PostTask(
      BrowserThread::UI,
      FROM_HERE,
      base::Bind(
          &SharedWorkerReserver::TryReserve,
          reserver,
          base::Bind(&SharedWorkerServiceImpl::RenderProcessReservedCallback,
                     base::Unretained(this),
                     pending_instance_id,
                     worker_process_id,
                     worker_route_id,
                     is_new_worker),
          base::Bind(
              &SharedWorkerServiceImpl::RenderProcessReserveFailedCallback,
              base::Unretained(this),
              pending_instance_id,
              worker_process_id,
              worker_route_id,
              is_new_worker),
          s_try_increment_worker_ref_count_));
  pending_instances_[pending_instance_id] = std::move(pending_instance);
  return creation_error;
}

void SharedWorkerServiceImpl::RenderProcessReservedCallback(
    int pending_instance_id,
    int worker_process_id,
    int worker_route_id,
    bool is_new_worker,
    bool pause_on_start) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  // To offset the TryIncrementWorkerRefCount called for the reservation,
  // calls DecrementWorkerRefCount after CheckWorkerDependency in
  // ScopeWorkerDependencyChecker's destructor.
  ScopedWorkerDependencyChecker checker(
      this, base::Bind(&DecrementWorkerRefCount, worker_process_id));

  if (!ContainsKey(pending_instances_, pending_instance_id))
    return;
  std::unique_ptr<SharedWorkerPendingInstance> pending_instance(
      pending_instances_[pending_instance_id].release());
  pending_instances_.erase(pending_instance_id);

  if (!is_new_worker) {
    SharedWorkerHost* host =
        FindSharedWorkerHost(worker_process_id, worker_route_id);
    if (!host) {
      // Retry reserving a renderer process if the existed Shared Worker was
      // destroyed on IO thread while reserving the renderer process on UI
      // thread.
      ReserveRenderProcessToCreateWorker(std::move(pending_instance));
      return;
    }
    pending_instance->RegisterToSharedWorkerHost(host);
    pending_instance->SendWorkerCreatedMessages();
    return;
  }

  SharedWorkerMessageFilter* filter =
      pending_instance->FindFilter(worker_process_id);
  if (!filter) {
    pending_instance->RemoveRequest(worker_process_id);
    // Retry reserving a renderer process if the requested renderer process was
    // destroyed on IO thread while reserving the renderer process on UI thread.
    ReserveRenderProcessToCreateWorker(std::move(pending_instance));
    return;
  }

  std::unique_ptr<SharedWorkerHost> host(new SharedWorkerHost(
      pending_instance->release_instance(), filter, worker_route_id));
  pending_instance->RegisterToSharedWorkerHost(host.get());
  const GURL url = host->instance()->url();
  const base::string16 name = host->instance()->name();
  host->Start(pause_on_start);
  ProcessRouteIdPair key(worker_process_id, worker_route_id);
  worker_hosts_[key] = std::move(host);
  FOR_EACH_OBSERVER(
      WorkerServiceObserver,
      observers_,
      WorkerCreated(url, name, worker_process_id, worker_route_id));
}

void SharedWorkerServiceImpl::RenderProcessReserveFailedCallback(
    int pending_instance_id,
    int worker_process_id,
    int worker_route_id,
    bool is_new_worker) {
  worker_hosts_.erase(std::make_pair(worker_process_id, worker_route_id));
  if (!ContainsKey(pending_instances_, pending_instance_id))
    return;
  std::unique_ptr<SharedWorkerPendingInstance> pending_instance(
      pending_instances_[pending_instance_id].release());
  pending_instances_.erase(pending_instance_id);
  pending_instance->RemoveRequest(worker_process_id);
  // Retry reserving a renderer process.
  ReserveRenderProcessToCreateWorker(std::move(pending_instance));
}

SharedWorkerHost* SharedWorkerServiceImpl::FindSharedWorkerHost(
    int render_process_id,
    int worker_route_id) {
  ProcessRouteIdPair key = std::make_pair(render_process_id, worker_route_id);
  if (!ContainsKey(worker_hosts_, key))
    return nullptr;
  return worker_hosts_[key].get();
}

SharedWorkerHost* SharedWorkerServiceImpl::FindSharedWorkerHost(
    const SharedWorkerInstance& instance) {
  for (const auto& iter : worker_hosts_) {
    SharedWorkerHost* host = iter.second.get();
    if (host->IsAvailable() && host->instance()->Matches(instance))
      return host;
  }
  return nullptr;
}

SharedWorkerServiceImpl::SharedWorkerPendingInstance*
SharedWorkerServiceImpl::FindPendingInstance(
    const SharedWorkerInstance& instance) {
  for (const auto& iter : pending_instances_) {
    if (iter.second->instance()->Matches(instance))
      return iter.second.get();
  }
  return nullptr;
}

const std::set<int>
SharedWorkerServiceImpl::GetRenderersWithWorkerDependency() {
  std::set<int> dependent_renderers;
  for (WorkerHostMap::iterator host_iter = worker_hosts_.begin();
       host_iter != worker_hosts_.end();
       ++host_iter) {
    const int process_id = host_iter->first.first;
    if (dependent_renderers.count(process_id))
      continue;
    if (host_iter->second->instance() &&
        host_iter->second->worker_document_set()->ContainsExternalRenderer(
            process_id)) {
      dependent_renderers.insert(process_id);
    }
  }
  return dependent_renderers;
}

void SharedWorkerServiceImpl::CheckWorkerDependency() {
  const std::set<int> current_worker_depended_renderers =
      GetRenderersWithWorkerDependency();
  std::vector<int> added_items = base::STLSetDifference<std::vector<int> >(
      current_worker_depended_renderers, last_worker_depended_renderers_);
  std::vector<int> removed_items = base::STLSetDifference<std::vector<int> >(
      last_worker_depended_renderers_, current_worker_depended_renderers);
  if (!added_items.empty() || !removed_items.empty()) {
    last_worker_depended_renderers_ = current_worker_depended_renderers;
    update_worker_dependency_(added_items, removed_items);
  }
}

void SharedWorkerServiceImpl::ChangeUpdateWorkerDependencyFuncForTesting(
    UpdateWorkerDependencyFunc new_func) {
  update_worker_dependency_ = new_func;
}

void SharedWorkerServiceImpl::ChangeTryIncrementWorkerRefCountFuncForTesting(
    bool (*new_func)(int)) {
  s_try_increment_worker_ref_count_ = new_func;
}

}  // namespace content


text:
package com.swfarm.biz.chain.bo.ywapi;

import java.io.Serializable;
import java.util.Date;
import java.util.Iterator;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.swfarm.biz.chain.bo.Currency;
import com.swfarm.biz.chain.bo.CustomerOrder;
import com.swfarm.biz.chain.bo.CustomerOrderItem;
import com.swfarm.biz.chain.srv.ChainService;
import com.swfarm.biz.ebay.bo.CountryMap;
import com.swfarm.biz.oa.bo.Country;
import com.swfarm.biz.oa.srv.SysConfigService;
import com.swfarm.biz.product.bo.Category;
import com.swfarm.biz.product.bo.StockKeepingUnit;
import com.swfarm.biz.warehouse.bo.AllocationProductVoucher;
import com.swfarm.biz.warehouse.bo.AllocationProductVoucherItem;
import com.swfarm.biz.warehouse.dto.AllocationProductVoucherDTO;
import com.swfarm.biz.warehouse.dto.AllocationProductVoucherItemDTO;
import com.swfarm.biz.warehouse.srv.WarehouseService;
import com.swfarm.pub.framework.Env;
import com.swfarm.pub.utils.DateUtils;
import com.swfarm.pub.utils.NumberUtils;
import com.swfarm.pub.utils.SpringUtils;

public class ExpressTypeXmlBuilder implements Serializable {

	Logger logger = Logger.getLogger(ExpressTypeXmlBuilder.class);

	private String epcode;

	private String userId;

	private String channel;

	private String packageType;

	private String userOrderNumber;

	private String sendDate;

	private String receiverName;

	private String receiverPhone;

	private String receiverMobile;

	private String receiverEmail;

	private String receiverCompany;

	private String receiverCountry;

	private String receiverPostcode;

	private String receiverState;

	private String receiverCity;

	private String receiverAddress1;

	private String receiverAddress2;

	private String memo;

	private String quantity;

	private String goodsNameId;

	private String goodsNameNameCh;

	private String goodsNameNameEn;

	private String goodsNameWeight;

	private String goodsNameWeightInKg;

	private String goodsNameDeclaredValue;

	private String goodsNameDeclaredCurrency;

	private String moreGoodsName;

	public ExpressTypeXmlBuilder() {
	}

	public String getEpcode() {
		return epcode;
	}

	public void setEpcode(String epcode) {
		this.epcode = epcode;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getChannel() {
		return channel;
	}

	public void setChannel(String channel) {
		this.channel = channel;
	}

	public String getPackageType() {
		return packageType;
	}

	public void setPackageType(String packageType) {
		this.packageType = packageType;
	}

	public String getUserOrderNumber() {
		return userOrderNumber;
	}

	public void setUserOrderNumber(String userOrderNumber) {
		this.userOrderNumber = userOrderNumber;
	}

	public String getSendDate() {
		return sendDate;
	}

	public void setSendDate(String sendDate) {
		this.sendDate = sendDate;
	}

	public String getReceiverName() {
		return receiverName;
	}

	public void setReceiverName(String receiverName) {
		this.receiverName = receiverName;
	}

	public String getReceiverPhone() {
		return receiverPhone;
	}

	public void setReceiverPhone(String receiverPhone) {
		this.receiverPhone = receiverPhone;
	}

	public String getReceiverMobile() {
		return receiverMobile;
	}

	public void setReceiverMobile(String receiverMobile) {
		this.receiverMobile = receiverMobile;
	}

	public String getReceiverEmail() {
		return receiverEmail;
	}

	public void setReceiverEmail(String receiverEmail) {
		this.receiverEmail = receiverEmail;
	}

	public String getReceiverCompany() {
		return receiverCompany;
	}

	public void setReceiverCompany(String receiverCompany) {
		this.receiverCompany = receiverCompany;
	}

	public String getReceiverCountry() {
		return receiverCountry;
	}

	public void setReceiverCountry(String receiverCountry) {
		this.receiverCountry = receiverCountry;
	}

	public String getReceiverPostcode() {
		return receiverPostcode;
	}

	public void setReceiverPostcode(String receiverPostcode) {
		this.receiverPostcode = receiverPostcode;
	}

	public String getReceiverState() {
		return receiverState;
	}

	public void setReceiverState(String receiverState) {
		this.receiverState = receiverState;
	}

	public String getReceiverCity() {
		return receiverCity;
	}

	public void setReceiverCity(String receiverCity) {
		this.receiverCity = receiverCity;
	}

	public String getReceiverAddress1() {
		return receiverAddress1;
	}

	public void setReceiverAddress1(String receiverAddress1) {
		this.receiverAddress1 = receiverAddress1;
	}

	public String getReceiverAddress2() {
		return receiverAddress2;
	}

	public void setReceiverAddress2(String receiverAddress2) {
		this.receiverAddress2 = receiverAddress2;
	}

	public String getMemo() {
		return memo;
	}

	public void setMemo(String memo) {
		this.memo = memo;
	}

	public String getQuantity() {
		return quantity;
	}

	public void setQuantity(String quantity) {
		this.quantity = quantity;
	}

	public String getGoodsNameId() {
		return goodsNameId;
	}

	public void setGoodsNameId(String goodsNameId) {
		this.goodsNameId = goodsNameId;
	}

	public String getGoodsNameNameCh() {
		return goodsNameNameCh;
	}

	public void setGoodsNameNameCh(String goodsNameNameCh) {
		this.goodsNameNameCh = goodsNameNameCh;
	}

	public String getGoodsNameNameEn() {
		return goodsNameNameEn;
	}

	public void setGoodsNameNameEn(String goodsNameNameEn) {
		this.goodsNameNameEn = goodsNameNameEn;
	}

	public String getGoodsNameWeight() {
		return goodsNameWeight;
	}

	public void setGoodsNameWeight(String goodsNameWeight) {
		this.goodsNameWeight = goodsNameWeight;
	}

	public String getGoodsNameWeightInKg() {
		return goodsNameWeightInKg;
	}

	public void setGoodsNameWeightInKg(String goodsNameWeightInKg) {
		this.goodsNameWeightInKg = goodsNameWeightInKg;
	}

	public String getGoodsNameDeclaredValue() {
		return goodsNameDeclaredValue;
	}

	public void setGoodsNameDeclaredValue(String goodsNameDeclaredValue) {
		this.goodsNameDeclaredValue = goodsNameDeclaredValue;
	}

	public String getGoodsNameDeclaredCurrency() {
		return goodsNameDeclaredCurrency;
	}

	public void setGoodsNameDeclaredCurrency(String goodsNameDeclaredCurrency) {
		this.goodsNameDeclaredCurrency = goodsNameDeclaredCurrency;
	}

	public String getMoreGoodsName() {
		return moreGoodsName;
	}

	public void setMoreGoodsName(String moreGoodsName) {
		this.moreGoodsName = moreGoodsName;
	}

	public ExpressTypeXmlBuilder(String expressChannel, CustomerOrder co) {
		this.channel = expressChannel;
		this.userOrderNumber = co.getCustomerOrderNo();
		this.sendDate = DateUtils.dateToString(co.getOrderTime(), "yyyy-MM-dd") + "T"
				+ DateUtils.dateToString(co.getOrderTime(), "HH:mm:ss");
		this.receiverName = co.getBuyerFullname();
		if (StringUtils.isNotEmpty(co.getBuyerPhoneNumber())) {
			this.receiverPhone = getYwPhoneNumber(co.getBuyerPhoneNumber());
		}
		if (StringUtils.isNotEmpty(co.getBuyerMobile())) {
			this.receiverMobile = getYwPhoneNumber(co.getBuyerMobile());
		}
		this.receiverEmail = co.getBuyerEmail();
		this.receiverCountry = this.getYwCountryName(co.getBuyerCountry());
		this.receiverPostcode = co.getBuyerZip();
		this.receiverState = co.getBuyerState();
		this.receiverCity = co.getBuyerCity();
		if (StringUtils.isEmpty(this.receiverState)) {
			this.receiverState = this.receiverCity;
		}
		if (StringUtils.isEmpty(this.receiverCity)) {
			this.receiverCity = this.receiverState;
		}
		this.receiverAddress1 = filterIllegalCharacters(co.getBuyerAddress1());
		this.receiverAddress2 = filterIllegalCharacters(co.getBuyerAddress2());
		CustomerOrderItem ci = (CustomerOrderItem) co.getCustomerOrderItemList().iterator().next();
		this.quantity = new Integer(ci.getQuantity().intValue()).toString();
		this.memo = co.getSaleChannelOrderId();
		StockKeepingUnit stockKeepingUnit = ci.getStockKeepingUnit();
		if ("altnux".equalsIgnoreCase(Env.COMPANY_CODE))
			this.goodsNameNameCh = filterIllegalCharacters(stockKeepingUnit.getDeclareCnName());
		else
			this.goodsNameNameCh = filterIllegalCharacters(stockKeepingUnit.getName());

		if (ci.getStockKeepingUnit() != null
				&& CollectionUtils.isNotEmpty(ci.getStockKeepingUnit().getRelateCategories())) {
			Category relateCategory = (Category) ci.getStockKeepingUnit().getRelateCategories().iterator().next();
			goodsNameNameEn = filterIllegalCharacters(relateCategory.getName());
		}

		if (StringUtils.isEmpty(this.goodsNameNameEn)) {
			this.goodsNameNameEn = stockKeepingUnit.getDeclareEnName();
		}

		Double weight = 0d;
		Double price = 0d;
		for (Iterator iter = co.getCustomerOrderItemList().iterator(); iter.hasNext();) {
			CustomerOrderItem coItem = (CustomerOrderItem) iter.next();
			StockKeepingUnit sku = coItem.getStockKeepingUnit();
			weight += sku.getWeight() * coItem.getQuantity();
			price += coItem.getPrice() * coItem.getQuantity();
		}

		if (weight == 0d) {
			weight = 10d;
		}
		int intWeight = (int) weight.doubleValue();
		this.goodsNameWeight = "" + intWeight;
		this.goodsNameWeightInKg = "" + intWeight / 1000.0;

		if (price == 0d || price > 15d) {
			price = 15d;
		}

		String currency = ci.getCurrency();

		String ywCurrencyCode = this.getCurrencyCode(currency);
		this.goodsNameDeclaredCurrency = ywCurrencyCode;

		String[] supportedCurrencyCodes = new String[] { "USD", "EUR", "GBP", "RMB" };
		Double declareValue = null;
		if (!ArrayUtils.contains(supportedCurrencyCodes, currency)) {
			declareValue = NumberUtils.round(this.getConvertedAmount(price, currency), 2);
		} else {
			declareValue = NumberUtils.round(price, 2);
		}

		this.goodsNameDeclaredValue = declareValue.toString();

		this.moreGoodsName = this.goodsNameNameEn + " " + this.quantity;
	}

	public ExpressTypeXmlBuilder(String expressChannel, AllocationProductVoucher apv, Boolean isUsingAliasApvNo) {
		this.channel = expressChannel;
		if (isUsingAliasApvNo == true) {
			this.userOrderNumber = apv.generateAliasApvNo();
			apv.setAliasApvNo(this.userOrderNumber);
			WarehouseService warehouseService = (WarehouseService) SpringUtils.getBean("warehouseService");
			warehouseService.saveAllocationProductVoucher(apv);
		} else {
			this.userOrderNumber = apv.getAllocationProductVoucherNo();
		}
		this.sendDate = DateUtils.dateToString(apv.getGenerateTime(), "yyyy-MM-dd") + "T"
				+ DateUtils.dateToString(apv.getGenerateTime(), "HH:mm:ss");
		this.receiverName = apv.getBuyerFullname();
		if (StringUtils.isNotEmpty(apv.getBuyerPhoneNumber())) {
			this.receiverPhone = getYwPhoneNumber(apv.getBuyerPhoneNumber());
		}
		logger.warn("receiverPhone[" + receiverPhone + "]");
		if (StringUtils.isNotEmpty(apv.getBuyerMobile())) {
			this.receiverMobile = getYwPhoneNumber(apv.getBuyerMobile());
		}
		logger.warn("receiverMobile[" + receiverMobile + "]");
		if (StringUtils.isNotEmpty(apv.getBuyerEmail())) {
			this.receiverEmail = apv.getBuyerEmail();
			logger.warn("receiverEmail[" + receiverEmail + "]");
		}
		this.receiverCountry = this.getYwCountryName(apv.getBuyerCountry());
		logger.warn("receiverCountry[" + receiverCountry + "]");
		this.receiverPostcode = apv.getBuyerZip();
		logger.warn("receiverPostcode[" + receiverPostcode + "]");
		this.receiverState = apv.getBuyerState();
		this.receiverCity = apv.getBuyerCity();
		if (StringUtils.isEmpty(this.receiverState)) {
			this.receiverState = this.receiverCity;
		}
		if (StringUtils.isEmpty(this.receiverCity)) {
			this.receiverCity = this.receiverState;
		}
		logger.warn("receiverState[" + receiverState + "]");
		logger.warn("receiverCity[" + receiverCity + "]");
		this.receiverAddress1 = filterIllegalCharacters(apv.getBuyerAddress1());
		logger.warn("receiverAddress1[" + receiverAddress1 + "]");
		if (StringUtils.isNotEmpty(apv.getBuyerAddress2())) {
			this.receiverAddress2 = filterIllegalCharacters(apv.getBuyerAddress2());
			logger.warn("receiverAddress2[" + receiverAddress2 + "]");
		}
		AllocationProductVoucherItem apvi = (AllocationProductVoucherItem) apv.getAllocationProductVoucherItemList()
				.iterator().next();
		this.quantity = new Integer(apvi.getQuantity().intValue()).toString();
		logger.warn("quantity[" + quantity + "]");
		this.memo = apv.getCustomerOrder().getSaleChannelOrderId();
		logger.warn("memo[" + memo + "]");
		StockKeepingUnit stockKeepingUnit = apvi.getStockKeepingUnit();
		if ("altnux".equalsIgnoreCase(Env.COMPANY_CODE))
			this.goodsNameNameCh = filterIllegalCharacters(stockKeepingUnit.getDeclareCnName());
		else
			this.goodsNameNameCh = filterIllegalCharacters(stockKeepingUnit.getDeclareCnName());
		logger.warn("goodsNameNameCh[" + goodsNameNameCh + "]");

		if (apvi.getStockKeepingUnit() != null
				&& CollectionUtils.isNotEmpty(apvi.getStockKeepingUnit().getRelateCategories())) {
			Category relateCategory = (Category) apvi.getStockKeepingUnit().getRelateCategories().iterator().next();
			goodsNameNameEn = filterIllegalCharacters(relateCategory.getName());
		}

		if (StringUtils.isEmpty(this.goodsNameNameEn)) {
			this.goodsNameNameEn = stockKeepingUnit.getDeclareEnName();
		}
		logger.warn("goodsNameNameEn[" + goodsNameNameEn + "]");

		Double weight = 0d;
		Double price = 0d;
		for (Iterator iter = apv.getAllocationProductVoucherItems().iterator(); iter.hasNext();) {
			AllocationProductVoucherItem apvItem = (AllocationProductVoucherItem) iter.next();
			StockKeepingUnit sku = apvItem.getStockKeepingUnit();
			weight += sku.getWeight() * apvItem.getQuantity();
			price += apvi.getCustomerOrderItem().getPrice() * apvi.getQuantity();
		}

		if (weight == 0d) {
			weight = 10d;
		}
		int intWeight = (int) weight.doubleValue();
		this.goodsNameWeight = "" + intWeight;
		this.goodsNameWeightInKg = "" + intWeight / 1000.0;
		logger.warn("goodsNameWeight[" + goodsNameWeight + "]");
		logger.warn("goodsNameWeightInKg[" + goodsNameWeightInKg + "]");
		if (price == 0d || price > 15d) {
			price = 15d;
		}
		// accecity公司yub物流方式
		if (("燕邮宝挂号".equalsIgnoreCase(expressChannel) || "RYUB".equalsIgnoreCase(expressChannel))
				&& "Australia".equalsIgnoreCase(apv.getBuyerCountry())) {
			String currency = "AUD"; // 只推送AUD货币
			this.goodsNameDeclaredCurrency = this.getCurrencyCode(currency);
			Double declareValue = NumberUtils.round(price, 2);
			this.goodsNameDeclaredValue = declareValue.toString();
			logger.warn("currency[" + currency + "] price [" + price + "] goodsNameDeclaredCurrency ["
					+ goodsNameDeclaredCurrency + "] declareValue [" + declareValue + "]");
		} else {
			String currency = apvi.getCustomerOrderItem().getCurrency();
			String ywCurrencyCode = "1"; // 只推送USD货币
			this.goodsNameDeclaredCurrency = ywCurrencyCode;
			Double declareValue = NumberUtils.round(this.getConvertedAmount(price, currency), 2);
			this.goodsNameDeclaredValue = declareValue.toString();
			logger.warn("currency[" + currency + "] price [" + price + "] goodsNameDeclaredCurrency ["
					+ goodsNameDeclaredCurrency + "] declareValue [" + declareValue + "]");
		}
		this.moreGoodsName = this.goodsNameNameEn + " " + this.quantity;
		logger.warn("moreGoodsName[" + moreGoodsName + "]");
	}

	public ExpressTypeXmlBuilder(String expressChannel, AllocationProductVoucherDTO apvDTO, Boolean isUsingAliasApvNo) {
		this.channel = expressChannel;
		if (isUsingAliasApvNo == true) {
			this.userOrderNumber = apvDTO.getAliasApvNo();
		} else {
			this.userOrderNumber = apvDTO.getApvNo();
		}
		this.sendDate = DateUtils.dateToString(apvDTO.getGenerateTime(), "yyyy-MM-dd") + "T"
				+ DateUtils.dateToString(apvDTO.getGenerateTime(), "HH:mm:ss");
		this.receiverName = apvDTO.getBuyerFullname();
		if (StringUtils.isNotEmpty(apvDTO.getBuyerPhoneNumber())) {
			this.receiverPhone = getYwPhoneNumber(apvDTO.getBuyerPhoneNumber());
		}
		logger.warn("receiverPhone[" + receiverPhone + "]");
		if (StringUtils.isNotEmpty(apvDTO.getBuyerMobile())) {
			this.receiverMobile = getYwPhoneNumber(apvDTO.getBuyerMobile());
		}
		logger.warn("receiverMobile[" + receiverMobile + "]");
		if (StringUtils.isNotEmpty(apvDTO.getBuyerEmail())) {
			this.receiverEmail = apvDTO.getBuyerEmail();
			logger.warn("receiverEmail[" + receiverEmail + "]");
		}
		this.receiverCountry = this.getYwCountryName(apvDTO.getBuyerCountry());
		logger.warn("receiverCountry[" + receiverCountry + "]");
		this.receiverPostcode = apvDTO.getBuyerZip();
		logger.warn("receiverPostcode[" + receiverPostcode + "]");
		this.receiverState = apvDTO.getBuyerState();
		this.receiverCity = apvDTO.getBuyerCity();
		if (StringUtils.isEmpty(this.receiverState)) {
			this.receiverState = this.receiverCity;
		}
		if (StringUtils.isEmpty(this.receiverCity)) {
			this.receiverCity = this.receiverState;
		}
		logger.warn("receiverState[" + receiverState + "]");
		logger.warn("receiverCity[" + receiverCity + "]");
		this.receiverAddress1 = filterIllegalCharacters(apvDTO.getBuyerAddress1());
		logger.warn("receiverAddress1[" + receiverAddress1 + "]");
		if (StringUtils.isNotEmpty(apvDTO.getBuyerAddress2())) {
			this.receiverAddress2 = filterIllegalCharacters(apvDTO.getBuyerAddress2());
			logger.warn("receiverAddress2[" + receiverAddress2 + "]");
		}
		AllocationProductVoucherItemDTO firstApviDTO = (AllocationProductVoucherItemDTO) apvDTO
				.getAllocationProductVoucherItemDTOs().iterator().next();
		this.quantity = new Integer(firstApviDTO.getQuantity().intValue()).toString();
		logger.warn("quantity[" + quantity + "]");
		this.memo = apvDTO.getSaleChannelOrderId();
		logger.warn("memo[" + memo + "]");
		this.goodsNameNameCh = filterIllegalCharacters(firstApviDTO.getDeclareCnName());
		if (StringUtils.isEmpty(this.goodsNameNameCh)
				&& StringUtils.isNotEmpty(firstApviDTO.getCategoryDisplayName())) {
			goodsNameNameEn = filterIllegalCharacters(firstApviDTO.getCategoryDisplayName());

		}
		logger.warn("goodsNameNameCh[" + goodsNameNameCh + "]");

		this.goodsNameNameEn = firstApviDTO.getDeclareEnName();
		if (StringUtils.isEmpty(this.goodsNameNameEn) && StringUtils.isNotEmpty(firstApviDTO.getCategoryName())) {
			goodsNameNameEn = filterIllegalCharacters(firstApviDTO.getCategoryName());
		}
		logger.warn("goodsNameNameEn[" + goodsNameNameEn + "]");

		Double weight = 0d;
		Double price = 0d;
		for (Iterator iter = apvDTO.getAllocationProductVoucherItemDTOs().iterator(); iter.hasNext();) {
			AllocationProductVoucherItemDTO apviDTO = (AllocationProductVoucherItemDTO) iter.next();
			weight += apviDTO.getSkuWeight() * apviDTO.getQuantity();
			price += apviDTO.getPrice() * apviDTO.getQuantity();
		}

		if (weight == 0d) {
			weight = 10d;
		}
		int intWeight = (int) weight.doubleValue();
		this.goodsNameWeight = "" + intWeight;
		this.goodsNameWeightInKg = "" + intWeight / 1000.0;
		logger.warn("goodsNameWeight[" + goodsNameWeight + "]");
		logger.warn("goodsNameWeightInKg[" + goodsNameWeightInKg + "]");
		if (price == 0d || price > 15d) {
			price = 15d;
		}
		// accecity公司yub物流方式
		if (("燕邮宝挂号".equalsIgnoreCase(expressChannel) || "RYUB".equalsIgnoreCase(expressChannel))
				&& "Australia".equalsIgnoreCase(apvDTO.getBuyerCountry())) {
			String currency = "AUD"; // 只推送AUD货币
			this.goodsNameDeclaredCurrency = this.getCurrencyCode(currency);
			Double declareValue = NumberUtils.round(price, 2);
			this.goodsNameDeclaredValue = declareValue.toString();
			logger.warn("currency[" + currency + "] price [" + price + "] goodsNameDeclaredCurrency ["
					+ goodsNameDeclaredCurrency + "] declareValue [" + declareValue + "]");
		} else {
			String currency = firstApviDTO.getCurrency();
			String ywCurrencyCode = "1"; // 只推送USD货币
			this.goodsNameDeclaredCurrency = ywCurrencyCode;
			Double declareValue = NumberUtils.round(this.getConvertedAmount(price, currency), 2);
			this.goodsNameDeclaredValue = declareValue.toString();
			logger.warn("currency[" + currency + "] price [" + price + "] goodsNameDeclaredCurrency ["
					+ goodsNameDeclaredCurrency + "] declareValue [" + declareValue + "]");
		}
		this.moreGoodsName = this.goodsNameNameEn + " " + this.quantity;
		logger.warn("moreGoodsName[" + moreGoodsName + "]");
	}

	public String build() {
		StringBuffer urlBuffer = new StringBuffer();
		urlBuffer.append("<ExpressType>");
		if (StringUtils.isNotEmpty(this.getEpcode())) {
			urlBuffer.append("<Epcode>" + this.getEpcode() + "</Epcode>");
		} else {
			urlBuffer.append("<Epcode></Epcode>");
		}
		urlBuffer.append("<Userid>" + this.getUserId() + "</Userid>");
		urlBuffer.append("<Channel>" + this.getChannel() + "</Channel>");
		if (StringUtils.isNotEmpty(this.getPackageType())) {
			urlBuffer.append("<Package>" + this.getPackageType() + "</Package>");
		} else {
			urlBuffer.append("<Package></Package>");
		}
		urlBuffer.append("<UserOrderNumber>" + this.getUserOrderNumber() + "</UserOrderNumber>");
		urlBuffer.append("<SendDate>" + this.getSendDate() + "</SendDate>");
		urlBuffer.append("<Receiver>");
		urlBuffer.append("<Userid>" + this.getUserId() + "</Userid>");
		urlBuffer.append("<Name>" + this.getReceiverName() + "</Name>");

		if (StringUtils.isEmpty(this.receiverPhone) || StringUtils.isEmpty(this.receiverMobile)) {
			if (StringUtils.isNotEmpty(this.receiverPhone)) {
				this.receiverMobile = this.receiverPhone;
			} else if (StringUtils.isNotEmpty(this.receiverMobile)) {
				this.receiverPhone = this.receiverMobile;
			}
		}

		urlBuffer.append("<Phone>" + this.getReceiverPhone() + "</Phone>");
		urlBuffer.append("<Mobile>" + this.getReceiverMobile() + "</Mobile>");
		urlBuffer.append("<Email>" + this.getReceiverEmail() + "</Email>");
		urlBuffer.append("<Company></Company>");
		urlBuffer.append("<Country>" + this.getReceiverCountry() + "</Country>");
		urlBuffer.append("<Postcode>" + this.getReceiverPostcode() + "</Postcode>");
		urlBuffer.append("<State>" + this.getReceiverState() + "</State>");
		urlBuffer.append("<City>" + this.getReceiverCity() + "</City>");
		urlBuffer.append("<Address1>" + this.getReceiverAddress1() + "</Address1>");
		urlBuffer.append("<Address2>" + this.getReceiverAddress2() + "</Address2>");
		urlBuffer.append("</Receiver>");
		urlBuffer.append("<Memo>" + this.getMemo() + "</Memo>");
		urlBuffer.append("<Quantity>" + this.getQuantity() + "</Quantity>");
		urlBuffer.append("<GoodsName>");
		urlBuffer.append("<Id>" + this.getGoodsNameId() + "</Id>");
		urlBuffer.append("<Userid>" + this.getUserId() + "</Userid>");
		urlBuffer.append("<NameCh>" + this.getGoodsNameNameCh() + "</NameCh>");
		urlBuffer.append("<NameEn>" + this.getGoodsNameNameEn() + "</NameEn>");
		urlBuffer.append("<Weight>" + this.getGoodsNameWeight() + "</Weight>");
		urlBuffer.append("<DeclaredValue>" + this.getGoodsNameDeclaredValue() + "</DeclaredValue>");
		urlBuffer.append("<DeclaredCurrency>" + this.getGoodsNameDeclaredCurrency() + "</DeclaredCurrency>");
		urlBuffer.append("<MoreGoodsName>" + this.getMoreGoodsName() + "</MoreGoodsName>");
		urlBuffer.append("</GoodsName>");
		urlBuffer.append("</ExpressType>");
		return urlBuffer.toString();
	}

	public String getYwCountryName(String countryName) {
		String mappingCountry = CountryMap.getMappingCountry(countryName);
		if ("Russian".equalsIgnoreCase(mappingCountry)) {
			return "俄罗斯";
		} else if ("Brazil".equalsIgnoreCase(mappingCountry)) {
			return "巴西";
		} else if ("Canada".equalsIgnoreCase(mappingCountry)) {
			return "加拿大";
		} else if ("Australia".equalsIgnoreCase(mappingCountry)) {
			return "澳大利亚";
		} else {
			SysConfigService sysConfigService = (SysConfigService) SpringUtils.getBean("sysConfigService");
			Country country = sysConfigService.findCountryByName(mappingCountry);
			if (country != null) {
				return country.getChineseName();
			}
		}
		return mappingCountry;
	}

	public String getYwPhoneNumber(String phoneNumber) {
		StringBuffer sb = new StringBuffer();
		char[] charArr = phoneNumber.toCharArray();
		for (int i = 0; i < charArr.length; i++) {
			char c = charArr[i];
			if (i == 0) {
				if (c == '+') {
					sb.append("00");
				}
			} else {
				if (c != ' ') {
					sb.append(c);
				}
			}
		}
		logger.warn("yw phone number [" + phoneNumber + "]");
		return sb.toString();
	}

	public String getCurrencyCode(String currency) {
		if ("USD".equalsIgnoreCase(currency)) {
			return "1";
		} else if ("EUR".equalsIgnoreCase(currency)) {
			return "2";
		} else if ("GBP".equalsIgnoreCase(currency)) {
			return "3";
		} else if ("RMB".equalsIgnoreCase(currency)) {
			return "4";
		} else if ("AUD".equalsIgnoreCase(currency)) {
			return "5";
		}
		return "1";
	}

	public Double getConvertedAmount(Double amount, String currency) {
		ChainService chainService = (ChainService) SpringUtils.getBean("chainService");
		Currency originCurrency = chainService.findCurrencyByCode(currency);
		Double buyingRate = originCurrency.getBuyingRate();
		if (buyingRate == null) {
			buyingRate = originCurrency.getConversionPrice();
		}
		if (buyingRate == null) {
			buyingRate = originCurrency.getCashBuyingRate();
		}
		Currency usdCurrency = chainService.findCurrencyByCode("USD");
		Double convertedAmount = amount * buyingRate / usdCurrency.getBuyingRate();
		return convertedAmount;
	}

	private String filterIllegalCharacters(String originName) {
		if (StringUtils.isNotEmpty(originName)) {
			String[] illegalCharacters = new String[] { "&" };
			for (int i = 0; i < illegalCharacters.length; i++) {
				String illegalCharacter = illegalCharacters[i];
				originName = originName.replaceAll(illegalCharacter, " ");
			}
		}
		return originName;
	}

	public static void main(String[] args) {
		System.out.println(DateUtils.dateToString(new Date(), "yyyy-MM-dd"));
		System.out.println(DateUtils.dateToString(new Date(), "HH:mm:ss"));
	}
}

redpajama_set_name: RedPajamaGithub


text:
Meet The Ripples International Founders
Our Promise, Vision, Mission And Goals
Join our Causes
Frequently Asked Questions (FAQ) – Ripples International
160 Girls
Watch The 160 Girls Video Here
"I Take A Stand Against Domestic Violence!"
Taking A Stand Against Domestic And Election Violence In Kenya
Making domestic violence in Kenya a thing of the past is our prime responsibility right now.
In two days time, John Burke Baidoo and Douglas Kinyua will be making it their only responsibility as they begin the Zero Violence254 walk in Kwale.
In many respects, this walk can be termed 'impossible'.
It's an epic 1,500 km walk that takes the walkers from Kenya's deep south and snakes its way 16 Counties, a kaleidoscope of desert, mountain, savanna and plateau terrain landscapes before eventually arriving in Moyale in the middle of May.
John urke Baidoo points ahead as he conducts the recce for the Zero violence254 walk outside Moyale
The team is determined to make the 'impossible' walk possible.
Along the way, John and Douglas will walk through vast spans of uninhabited land, the most formidable stretches being the section between Mazeras and Voi along the Mombasa-Nairobi highway and the stretch from Archer's Post to Marsabit.
In both cases, the road meanders through desert and National Game Reserves with occurrences of meeting wildlife very likely.
In each of these cases, they will have to walk more than 40 km before any sign of humans settlement. But they are not deterred! By God's grace, they will make it.
It goes to show the level of compassion and determination they have to make this vision a reality.
There will be a lot of domestic violence survivors who will have John and Douglas to thank by the time the walk concludes at the end of May.
Join John Burke Baidoo On His Incredible Quest!
John smiles as he conducts the recce for the Zero Violence254 walk along the Isiolo-Marsabit highway
Accompanied by Douglas Kinyua of Ripples International, John will be pushing the limits of human endurance by walking 30 km every day.
It's a distance of 1500 kilometers from the southern-most tip of Kenya in Kwale to Moyale – the northernmost tip of Kenya.
This feat has never been attempted before.
John intends to accomplish it in less than 60 days.
And judging by the intensity of the training marathons he's been conducting over the last 30 days, he will do it!
The Role Of Ripples International
Ripples International, a non profit organization, supports the walk as part of its agenda to champion the rights of orphans and vulnerable children (OVC); many of whom were victims of domestic and post-election violence in Kenya many years ago.
Championing Awareness Of The PDV Act Kenya
This historic walk will create awareness on the newly enacted 'Protection Against Domestic Violence Act', Electoral Violence and also to raise funds for its Access to Justice Program, a legal initiative that assists the less privileged in society with free access to professional legal justice.
This targeted national level campaign will promote new behaviors, amplify the voices against domestic violence and electoral violence to create positive changes in the citizenry, and promote action against the various and merging forms of violence plaguing the nation.
As part of the legal outreach, the duo will facilitate group discussions for adolescent girls and boys to challenge attitudes, promote debate and undertake collective action against all forms of violence.
You may not be able to join the walkers on the journey. But you can donate to this worthy initiative.
It only takes a contribution of Ksh 500/-
Simply click on this link, 'donation instructions' and you'll be instructed on what to do.
Providing free legal aid to needy members of society
Agitating an end to domestic violence in Kenya
Creating awareness for the "Protection Against Domestic Violence Act"
Championing ethnic sobriety and brotherly love
$10 Earns you a delightful ZeroViolence254 cap
$15 Buys you a trendy Zero Violence254 branded jersey
$50 Buys a Step of the Zero Violence254 1,500 km walk
$100 Enables a displaced family earn legal assistance in recovery of family property
$500 Will provide legal aid for 5 people
It's Time For The Zero Violence254 Initiative
The Zero Violence254 Initiative
The Zero Violence254 Initiative is a response to the various forms of violence in Kenya.
More specifically, it is a move to kick domestic and electoral violence out of Kenya once and for all.
Kicking Violence Out Of Kenya
To this end, the Zero Violence254 initiative team led by John Burke Baidoo will be launching a series of activities championing the awareness of the 'Protection Against Domestic Violence Act of Kenya'.
One of these activities is the Zero Violence254 Walk that launches on 15 March 2017 in Kwale.
The walk begins in Kwale and takes the Zero Violence254 team through 16 counties to eventually arrive in Moyale, the border town that crisscrosses Kenya and Ethiopia.
The public can get involved by buying a step for as low as Ksh 500/-. Corporates are also invited to fund the campaign which will see John and Douglas take over 10,000 steps.
Each step is a step closer to kicking violence out of Kenya once and for all.
Introducing The Zero Violence254 Team
John Burke Baidoo is attempting the walk together with Douglas Kinyua, a project officer with Adili (Access To Justice) a program of Ripples International.
The duo staged a recce mapping out the best possible route to take for the walk in April this year.
Read all about the amazing recce here.
As we mentioned, the purpose of the walk is to create awareness on the 'Protection Against Domestic Violence Act', and take an active stand against electoral and domestic violence.
In recent history, Kenya has seen an outbreak of violence in electoral years. Thousands of Kenyans have been displaced from their homes and property as a result.
In fact, a great part of the work that John and Douglas do is as a result of that electoral violence. It may seem a bit far fetched considering that the last elections was five years ago, but to some of these families that were displaced from their property, it still is a very real concern.
Many of the displaced families are yet to receive adequate compensation or their day of justice in court.
Court cases dag on for years. Hence the very real need to get to the bottom of the issue and champion a move that will promote peace, advocacy and justice to the less fortunate.
Domestic Violence: Another silent criminal on the loose…
Unfortunately, many people do not know what domestic violence constitutes and as a result suffer silently in the hands of those who perpetrate this crime.
There are many actions that are, according to the Protection Against Domestic Violence Act, termed as domestic violence.
But without knowing that these actions, no one can do anything about it.
More importantly, people are too scared to come forward either because of victimization, or abuse by family members or a compromised court system.
I think we all know instances like this, where perhaps your aunt, or friend was being beaten by a elder male figure and for years kept silent to avoid 'societal shame.'
It goes the other way too.
Perhaps you know a boy who was regularly beaten by an older female figure, burnt with hot water, whipped with a knife, forced to sleep outside in the rain, or some other heinous act.
This is where Adili, a program by Ripples International comes into play.
Through Adili, victims are guaranteed a fair and credible walk through the legal process. Most of the time, Adili dispenses free legal aid to its clients. They are walked through the legal process and given free advice and counsel right up to their day in court.
Hence the need for the Zero Violence254 walk. The funds raised through this walk will fund the legal aid given to deserving clients.
More importantly, by knowing what constitutes domestic violence, the perpetrators of this act will think twice before committing this travesty.
With adequate knowledge about domestic violence, thousands will be bold enough to take a stand against it in their homes and come forward when such occurrences do happen.
Get Involved! 13 Exciting Community Activities For You
Zero Violence254 Initiative: The Grand Finale
Zero Violence254 Walk: Meru To Isiolo Highlights
Joe mwangi on Ripples International Christian Schools – Nahal Academy
Kinyua Doug on Laare Policeman Defiles 13-Year Old School Girl: Gets 20 Years In Prison
Mercy Chidi Baidoo on Laare Policeman Defiles 13-Year Old School Girl: Gets 20 Years In Prison
160 girls 160 Girls Laare Policeman Jailed after defiling school girl Boresha Health Clinic child counseling children child sexual abuse Global Leadership Summit warning signs of child sexual abuse World Aids Day Zero Violence254
Follow #TeamRipples on Twitter
All Rights Reserved. Ripples International 2017
Your ticket for the: "I Take A Stand Against Domestic Violence!"

redpajama_set_name: RedPajamaCommonCrawl


Label: vintage dresser hardware pulls. vintage dresser drawer hardware. dressers at costco. vintage dresser hardware drawer pulls. home goods dressers. unique vintage dresser hardware. antique white dresser bedroom furniture. vintage looking dresser hardware.
Label: cheap nursing dresses or skirts for plus size. cheap nursery dresser. tall dressers with deep drawers. cheap dressers for nursery. modloft ludlow dresser. cheap nursing dresses. metal dresser chest. cheap nursing dresses breastfeeding.
Label: distressed grey wash dresser. grey wash wood dresser. tall narrow dresser. grey wash dresser. dresser for sale. white wash grey dresser. white baby dresser. gray wash dresser.
Label: ana white tall dresser. tall skinny white dresser. dresser with lots of drawers. off white tall dresser. changing topper for dresser. white tall dresser chest. dresser top mirror. white wicker tall dresser.
Label: chests and dressers. dressers and chests furniture. 7 drawer dresser with mirror. chest and dressers on sale. unfinished pine dresser. chest and dressers clearance. unique dressers for sale. chest and dressers clearance in ca.
Label: cheap nursing dresses or skirts for plus size. cheap nursing dresses. white dresser for baby room. cheap dressers for nursery. dresser media center. cheap nursery dresser. modern wood dresser. cheap nursing dresses breastfeeding.
Label: rustic dresser painted. rustic painted dresser. light wood dresser with mirror.
Label: white dresser craigslist vancouver. craigslist sacramento white dresser. tv dresser chest. craigslist search white dresser. sears baby furniture dressers. white dresser craigslist long island. white dresser 8 drawer. craigslist ikea white dresser.


Julius Comroe said, "Serendipity is looking in a haystack for a needle and discovering a farmer's daughter."
In 1754, the word "serendipity" was first coined. It's defined by Merriam-Webster as "the faculty or phenomenon of finding valuable or agreeable things not sought for." It was recently listed by a U.K. translation company as one of the English language's 10 most difficult words to translate. Other words to make their list include plenipotentiary, gobbledegook, poppycock, whimsy, spam, and kitsch.
The invention of many wonderful things have been attributed to "serendipity," including Kellogg's Corn Flakes, Charles Goodyear's vulcanization of rubber, inkjet printers, Silly Putty, the Slinky, and chocolate chip cookies.
Viagra had been developed to treat hypertension and angina pectoris; it didn't do such a good job at these things, researchers found during the first phase of clinical trials, but it was good for something else.
I remember learning the phenomenon of serendipity for the first time. It was used by one of my professors in a Modern Dance class to describe movement using improvisation instead of choreography. "The result," she said, "could be serendipitous." Then, like when you learn any new word, it started crawling out of the woodwork. It was in every newspaper, magazine, textbook, radio broadcast; it followed me like a shadow.
Regardless of its abundance, however, I thought of the term fondly until my English professor told us that some terms come in and out of fashion like the latest cut of boot. I was scandalized. A word I see everywhere, not to mention one that is so fun to say, was just another version of the latest kitsch. Since this revelation, I've decided to choose my words like I choose my boots: classics for everyday and the latest styles for the occasional night on the town.


text:
The Answer is No, No, A Thousand Times No
Last month, four respected researchers asked for data from the PACE trial. This is the umpteeth request, and, predictably, it was denied.
But this time the reason given was not that 1) the request was "vexatious," 2) the trial participants might somehow be harmed, 3) it might infringe on intellectual property rights, or 4) the study might be criticized.
None of the above. Their excuse this time was that "participants may be less willing to participate in a planned feasibility follow up study." In other words, if people with ME/CFS knew how bad the PACE trial really was, they might not be willing to participate in another trial.
Imagine a situation in which a drug is administered to a group of ill people, who then become more ill. But the authors of the trial hide the data and claim that the ill people appear to benefit. When asked for the data they refuse, because they don't want participants to know the drug is harmful in case they do future studies.
How illegal would that be?
The PACE trial authors have no moral compass. They are planning on rehashing their study endlessly to milk it for all its worth. They will continue to spin their "results" until someone in authority puts a stop to it.
At least we're not vexatious, Virology Blog
On 17 December 2015, Ron Davis, Bruce Levin, David Tuller and I requested trial data from the PACE study of treatments for ME/CFS published in The Lancet in 2011. Below is the response to our request from the Records & Compliance Manager of Queen Mary University of London. The bolded portion of our request, noted in the letter, is the following: "we would like the raw data for all four arms of the trial for the following measures: the two primary outcomes of physical function and fatigue (both bimodal and Likert-style scoring), and the multiple criteria for "recovery" as defined in the protocol published in 2007 in BMC Neurology, not as defined in the 2013 paper published in Psychological Medicine. The anonymized, individual-level data for "recovery" should be linked across the four criteria so it is possible to determine how many people achieved "recovery" according to the protocol definition."
Dear Prof. Racaniello
Thank you for your email of 17th December 2015. I have bolded your request below, made under the Freedom of Information Act 2000.
You have requested raw data, linked at an individual level, from the PACE trial. I can confirm that QMUL holds this data but I am afraid that I cannot supply it. Over the last five years QMUL has received a number of similar requests for data relating to the PACE trial. One of the resultant refusals, relating to Decision Notice FS50565190, is due to be tested at the First-tier Tribunal (Information Rights) during 2016. We believe that the information requested is similarly exempt from release in to the public domain. At this time, we are not in a position to speculate when this ongoing legal action will be concluded.
Any release of information under FOIA is a release to the world at large without limits. The data consists of (sensitive) personal data which was disclosed in the context of a confidential relationship, under a clear obligation of confidence. This is not only in the form of explicit guarantees to participants but also since this is data provided in the context of medical treatment, under the traditional obligation of confidence imposed on medical practitioners. See generally, General Medical Council, 'Confidentiality' (2009) available at http://www.gmc-uk.org/guidance/ethical_guidance/confidentiality.asp The information has the necessary quality of confidence and release to the public would lead to an actionable breach.
As such, we believe it is exempt from disclosure under s.41 of FOIA. This is an absolute exemption.
The primary outcomes requested are also exempt under s.22A of FOIA in that these data form part of an ongoing programme of research.
This exemption is subject to the public interest test. While there is a public interest in public authorities being transparent generally and we acknowledge that there is ongoing debate around PACE and research in to CFS/ME, which might favour disclosure, this is outweighed at this time by the prejudice to the programme of research and the interests of participants. This is because participants may be less willing to participate in a planned feasibility follow up study, since we have promised to keep their data confidential and planned papers from PACE, whether from QMUL or other collaborators, may be affected.
On balance we believe that the public interest in withholding this information outweighs the public interest in disclosing it.
In accordance with s.17, please accept this as a refusal notice.
For your information, the PACE PIs and their associated organisations are currently reviewing a data sharing policy.
If you are dissatisfied with this response, you may ask QMUL to conduct a review of this decision. To do this, please contact the College in writing (including by fax, letter or email), describe the original request, explain your grounds for dissatisfaction, and include an address for correspondence. You have 40 working days from receipt of this communication to submit a review request. When the review process has been completed, if you are still dissatisfied, you may ask the Information Commissioner to intervene. Please see www.ico.org.uk for details.
Paul Smallcombe
Records & Information Compliance Manager


text:
Discover Enchanted Rock
DRIPPING SPRINGSFAMILY FUNHEALTHY LIVINGNATURE
If there's one thing you should see in Texas it's Enchanted Rock. At least, according to Josh Abbott Band's "My Texas." It appears as the first line of the song.
If you haven't climbed up to Enchanted Rock,
Drank a cold Shiner down in Luckenbach,
Taken your baby to the River Walk,
Then you ain't met My Texas yet.
You can easily check off Enchanted Rock (16710 Ranch Rd 965, Fredericksburg, Texas) as it's about a 90-minute drive from our Dripping Springs community. The pink granite mountain makes a great adventure.
About Enchanted Rock
Although its address is in Fredericksburg, Enchanted Rock is about 18 miles north of the town. The pink rock is in Enchanted Rock State Natural Area in Gillespie and Llano Counties. It spans 1,644 acres and has an elevation of 1,825 feet above sea level. Designated a Texas Historic Landmark, the rock is the largest pink granite monadnock in the U.S. In 1971, the National Park Service designated it as a National Natural Landmark.
If you're into camping, a 2017 MSN.com survey rated the park as the best campsite in Texas. The campsite has toilets, hot showers, and tent sites. Along with camping, the park has almost 11 miles of hiking trails as well as interpretive exhibits, rock climbing, and a nature trail. It's also a great place to have a picnic, watch birds, geocache, and stargaze. Although the park has a store, they recommend you bring your own drinking water.
Plan Your Trip to Enchanted Rock
Be aware there is no swimming or bikes allowed on trails. Trails open 30 minutes after sunrise and close 30 minutes after sunset. The park welcomes visitors daily from 6:30 am to 10 pm. They recommend making reservations to guarantee entry. If the park reaches capacity, it closes. But it won't affect visitors who have day passes or camping reservations.
Before planning your trip, visit the Enchanted Rock State Natural Area website for scheduled trail and park closures. Rock climbers will need to sign a climbing release form and check-in at park headquarters. The website also lists outfitters and guide services that lead rock climbing tours. You can also request a hike or special group tour conducted by a park ranger.
If you'd like to extend your trip beyond Enchanted Rock, head to Fredericksburg for a taste of German culture. The town features more than 50 wineries and hundreds of cozy bed and breakfasts. Its historic district appears on the National Register of Historic Places in Texas.
Do you love nature and everything the Texas Hill Country has to offer like Fredericksburg and Enchanted Rock? And, you want to live close enough to Austin? Check out Caliterra, a master-planned community with new homes in Dripping Springs.
Categories: DRIPPING SPRINGS, FAMILY FUN, HEALTHY LIVING, NATUREBy Kyle January 16, 2020
PreviousPrevious post:Dripping Springs ISD Welcomes New SuperintendentNextNext post:Affordable Ways to Boost Your Curb Appeal
Nearby Must-Visit Cities
Porches & Patios in The Texas Hill Country


text:
Q: When would I use java Collections singletonMap method? I don't understand why you would need java Collections singletonMap?
Is it useful in multithreaded applications?

A: Also, a SingletonMap implementation returned by Collections.singletonMap() has a smaller memory footprint than a regular HashMap. It only has to contain two member fields: the key and the value, whereas a HashMap maintains an internal array of Node objects plus other member fields. So if you are creating a lot of these maps in memory, it would be a prudent choice to use Collections.singletonMap().

A: many answers told you when, but I want to point out when to not use it
don't use it if you want to put items later on,
because put implementation of singletonMap will throw UnsupportedOperationException

A: It's mainly for convenience and abstraction. Some APIs take a Collection as an argument and it's nice to have a simple way to convert objects to a Set or Map.
singletonMap() and singletonList() were actually introduced after singletonSet() in Java 1.3 because singletonSet() proved to be useful.

A: It is useful if you need to pass a map to some general code (as a parameter, or as a result from a method) and you know that in this particular case -- but perhaps not in other cases that pass map to the same general code -- the map you want to pass has only a single key. In that case, the SingletonMap is more efficient than a full-blown map implementation, and also more convenient for the programmer because everything you need to say can be said in the constructor.

A: Basically, it allows you to do this:
callAPIThatTakesAMap(Collections.singletonMap(key, value));

rather than this:
Map<KeyType, ValueType> m = new HashMap<KeyType, ValueType>();
m.put(key, value);
callAPIThatTakesAMap(m);

which is much nicer when you only have a single key/value pair. This situation probably does not arise very often, but singleton() and  singletonList() can quite frequently be useful.

A: This is just another example, but I wrote this line of code:
@Override public Map<Action, Promise<Boolean>> actOnResults() throws Exception {
    return Collections.singletonMap(Action.UPDATE_DATABASE, saver.save(results));
}

note the @Override. The interface more generally can take maps of many things; this particular instantiation just always returns a map containing one thing. Also note that the key to the map is an Enum. So the maps are never supposed to be big, they're just supposed to contain the results of whichever actions are specified. In my real example there are up to 5 actions, and this instantiation only uses one of them.
To be complete, EnumSet or EnumMap is often appropriate in these cases, but those are still annoyingly verbose compared to the code above.

redpajama_set_name: RedPajamaStackExchange


text:
Cinnamomum validinerve Hance – gatunek rośliny z rodziny wawrzynowatych (Lauraceae Juss.). Występuje naturalnie w południowych Chinach – w prowincji Guangdong oraz regionie autonomicznym Kuangsi.

Morfologia
 Pokrój Zimozielone drzewo. Gałęzie są szorstkie i nagie.
 Liście Naprzemianległe. Mają eliptyczny kształt. Mierzą 4–10 cm długości oraz 2–3,5 cm szerokości. Są skórzaste, lekko owłosione od spodu. Nasada liścia jest klinowa. Blaszka liściowa jest o krótko spiczastym wierzchołku. Ogonek liściowy jest nagi i dorasta do 13 mm długości.
 Kwiaty Są niepozorne, obupłciowe, zebrane po kilka wiechy o owłosionych osiach, rozwijają się w kątach pędów.

Biologia i ekologia
Rośnie w lasach. Kwitnie w lipcu.

Przypisy

Wawrzynowate

redpajama_set_name: RedPajamaWikipedia


text:
Police officers - Credit: Photo: Joeppoulssen/DepositPhotos
Martin Sitalsing
Gery Veldhous
Police aims to have 35% cops from ethnic minorities
In the coming five years, the Randstad police want to increase the proportion of its officers with ethically diverse backgrounds to 35 percent. "The aim of this is to make the organization more diverse and inclusive," police chiefs Martin Sitalsing of the Midden-Nederland unit and Gery Veldhous of the Noord-Nederland unit, who will supervise the implementation of this action plan, said to NRC.
Over the next five years, the Randstad police will need to recruit 17,000 new cops, as police officers retire. According to Sitalsing, this is the ideal "opportunity to invest in diversity and a new culture to bring about real change." The composition of the police force can change by "investing more in recruitment," he said.
The police force needs to be more diverse for it to continue doing "what we are good at as the Dutch police, namely establishing connections and fine meshing," Sitalsing said. "The community police officer is a little bit of cultural heritage and can go onto the street everywhere on their own. In some neighborhoods, that is under pressure."
"In view of the composition of the population in the Randstad, the police officers will have to change significantly in some districts. In some neighborhoods, 60 percent of the population have a migration background. In [Utrecht's] Kanaleneiland that percentage is 80. We are nowhere near reaching those numbers," Sitalsing said.


text:
Israel set to form 'most extremist government in history'
World Mena
Radical Lieberman's entry seen as a 'disaster' for peace efforts
Published: May 19, 2016 19:02 AFP
Israeli Prime Minister Benjamin Netanyahu (right) with Avigdor Lieberman. Ex-foreign minister Lieberman is expected to make a return to the cabinet as defence minister. Image Credit: REUTERS
Occupied Jerusalem: Israeli Prime Minister Benjamin Netanyahu looked set to form the most right-wing government in Israeli history on Thursday, with Avigdor Lieberman, a radical hardliner loathed by Palestinians, expected to join as defence minister.
Netanyahu's allies were set for fresh negotiations with representatives of Lieberman's far-right Yisrael Beitenu party to try to entice it to join the governing coalition and boost its currently wafer-thin majority in parliament.
Leaks to the Israeli media from both sides said a deal was close to being finalised.
Yisrael Beitenu holds six of the 120 seats in parliament and its entry into government would be a major boost for Netanyahu, who has not concealed his ambition to expand on the coalition's current 61 seats.
The return to government of Lieberman, who served as foreign minister under Netanyahu from 2009 to 2012 and again from 2013 to 2015, could raise international concern about his government's policies - especially on the conflict with the Palestinians.
As defence minister, Lieberman, who himself lives in a Jews-only colony in the occupied West Bank, would oversee military operations in the Palestinian territories and have a major say in policy towards the colonies.
The international community considers the colonies illegal and regards their persistent expansion by successive Netanyahu governments as one of the biggest obstacles to peace.
Since its formation in May 2015, Lieberman had repeatedly branded the current five-party coalition as "defeatist" but on Wednesday he told a news conference that he would be open to joining it if key demands were met.
He said one of them was the death penalty for perpetrators of anti-Israeli attacks and hinted that Netanyahu's government could accede to that demand.
Lieberman has long expressed mistrust in Palestinian president Mahmoud Abbas and called for his removal.
Just a month ago, he said that if he were defence minister, he would give Hamas's Gaza leader Esmail Haniya 48 hours to hand over detained Israeli civilians and the bodies of soldiers killed in the 2014 war "or you're dead".
A official said it would be a "disaster" for Palestinians living under Israeli occupation.
"He will be in charge of the occupation and it will be a disaster. He is a populist - either he talks too much or he puts his words into action."
He said such was the dislike of Lieberman that he was a "unifying factor for Palestinians."
In a statement, the Palestinian Foreign Ministry said the move proves Israel is no peace partner: "The Palestinian campaign to internationalise the conflict and seek a solution from the international community was undoubtedly right... This is Netanyahu's message to the world that the Israeli government prefers extremism and works to perpetuate occupation over the Palestinian territories".
Lieberman's looming return to government comes after weeks of frantic negotiations, not just with his party but also with the centre left.
Netanyahu had been widely expected to make a deal with the leader of the opposition Labour party, Isaac Herzog.
Months of secret talks between the two men made headlines in recent days, with Herzog tipped for the position of foreign minister ahead of a French-led push for renewed peace talks this summer.
But Netanyahu's 11th-hour tilt to the far right appeared to have torpedoed those hopes and also left the opposition in disarray as Herzog came under attack from the party rank and file for even considering serving under Netanyahu.
The centrist Yediot Aharonot newspaper criticised Netanyahu's about-turn, accusing him of being self-serving.
"Instead of presenting to the world, in advance of the serious diplomatic challenges that lie ahead of us in the autumn, a more moderate government, Netanyahu is presenting to the world the most extreme government ever to have served here," it said.
The right-wing Maariv newspaper agreed that Israel was about to get the "most right-wing and most extremist government since the founding of the state".
"But the main thing is that Netanyahu remains safe and confident," it added.
Lieberman's appointment to the defence ministry in place of former armed forces chief of staff Moshe Yaalon is also likely to raise the hackles of senior commanders.
Yaalon had been at loggerheads with Netanyahu over his insistence that senior officers be encouraged to "speak their mind."
- with inputs from Nassouh Nazaal, Ramallah correspondent
More From Mena
Saied blames hatred of parliament for low poll turnout
Blinken set to meet Abbas in bid to restore calm
10 'mega trends' that will change our world in 2023
Pink Caravan announces official routes
Dyche is the right man to save Everton from relegation
Visakhapatnam will be Andhra Pradesh's new capital: CM


Okay, so I took today off from work in advance because I knew I'd be worn out after my crazy long weekend with speech and debate and quickly following that, 2nd grade Sunday School packed with 20 kids (mostly hyper boys). I'm glad I did it! Perfect timing for a day off!!
After AF and my new realization that I need more time for me to grieve our Angel Baby, today has given me some time to do that... to cry, to read blogs, to listen to awesome music and pray. I feel good! I think I'll make this a tradition. At least once a month - mental health Monday!
This day has helped me to better come to terms with not obsessing about TTC. I'm REALLY - with God's help - going to try and just let baby number 3 happen without my constant worry.
In order to do this, I'm going to take days to concentrate on me and my Lord, and on things I want to do. And then I'm going to take days to concentrate on Beth, and days to concentrate on Michael. I'm going to try to be more deliberate about this.
I really am very blessed! With good health, a loving husband, a happy, healthy 3 year old cutie. I have a great church family, and a job. I don't have everything figured out, but that's okay. One day at a time with my savior, right?
Good for you Jamie! It is important to work through that grief surrounding your baby. I think too many people have early miscarriages and don't take the time to fully grieve that loss. I've seen a couple of people in my support groups come many years after their loss to work through it. You'll have to do it eventually but I think it's harder to deal with if you wait. Glad you had a good mental health day. I find I need those MUCH more often now after losing Mikayla and it's been 4 months for me but I still need them.
Hey girl - YEAAAA for Mental Health Monday!


Any issues relating to Club business should be directed to our Board of Directors at Board@sfge.com.
Please take notice that our Annual General Meeting (AGM) will be held at 5pm, on February 19, 2019 at the SFGE offices located at 2521 Judah Street, San Francisco, CA 94122. The primary order of business will be to elect our Board of Directors. Only SFGE Voting Members may vote in the election. Voting members are registered players within the club. Any player under the age of 18 may be represented by one parent or legal guardian. Coaches and Administrators may not vote in place of players, unless they are also a parent or legal guardian. Identification of all attendees will be required. Only Members, Voting Members, Club Directors and persons specifically invited by the Board of Directors will be allowed to attend the meeting. Voting will be restricted to Voting Members in attendance at the AGM.
All Directors are volunteers, and no Director may receive any income or remuneration from the Club or from any soccer-related activity. There are seven seats up for election. Any Member may nominate a candidate to the Board of Directors. Nominations for Director can be made by emailing board@sfge.org prior to February 5, 2019.
Each of the above individuals has agreed to serve if elected.


A mariner's dream.Evocative of leather boat shoes and squawking seagulls/ Vuarnet's VL 1312 Polarized Sunglasses are every mariner's best friend. With a sturdy acetate and metal frame/ these shades lend themselves well to a life spent by the sea. Adding to their around-water prowess/ the mineral glass lenses features a Blue Polar tint and polarized treatment that's ideal for activities like boating or beach-side hangs. Additionally/ the lenses are equipped with a hydrophobic/ NPE/ oleophobic and anti-glare coating that assure unobstructed optical clarity regardless of sweat/ blood/ ocean spray/ or tears. And in keeping with Vuarnet's legacy/ the VL 1312 sunglasses are made in France and feature unwavering protection from the sun's harmful UV rays. So whether you're meandering the island of Seychelles or boating along the Elba coast/ these sunnies offer smooth style that's both classic and technical.


text:
The effectiveness of a heating system is validated: Heating air from solar radiation
by University of Córdoba
The device installed by the research team. Credit: University of Córdoba
Heating and air conditioning in buildings make up almost half of the total energy consumption in the European Union. What is more, nearly 75% relies on fossil fuels, according to data from the European Commission. Hence, reducing this consumption and integrating renewable energy in heating and air conditioning processes in buildings is one of today's priorities for scientific research.
The research team from the Thermal Machines and Engines Section at the University of Cordoba performed an experimental study that validated the effectiveness of a heating system that heats air in buildings using solar radiation. The device uses a series of heat collectors, known as UTCs (unglazed transpired collectors), that absorb the heat generated in the outer layer of the facade when hit with sun rays. Later, using this energy, the ventilation air is preheated before going into the residences to heat them.
The system, patented decades ago, "has not had widespread use in Europe, other than a few experimental buildings," explains the lead author, Fernando Peci. The team installed the device on a test module of 4 x 2 meters subjected to the normal conditions of a home. Over the course of a month, during winter, this heat collector was monitored throughout different weather conditions such as solar radiation, room temperature, wind and solar radiation angle of impact.
According to the study's results, the heating demands needed to heat the building would be covered for 75% of the days accounted for in the study, proving that "this technology could offer great performance in order to heat buildings using solar energy," especially those without much glass on their facades and facing southwards, as the Northern Hemisphere receives more natural light during the day from that direction.
A strategy to refurbish buildings:
As the lead author of the research points out, this heating system could be advisable when renovating old buildings, since installing it does not alter the original facade. The heat collector is made up of a perforated metal plate, covered with a dark material, so it can connect to the ventilators and carry the heat inside, so the building would be minorly affected.
Furthermore, as Fernando Peci underscores, the team suggests using these ventilation systems in social housing, "in homes where most families can't afford to pay for heating costs." In this vein, the device would not only benefit the environment, but also translate into financial savings on the electricity bill, one of the most feared bills in the winter.
A new smart-facade lift for older buildings
More information: Fernando Peci et al, Experimental study of a modular Unglazed transpired collector Façade for building refurbishment, Solar Energy (2020). DOI: 10.1016/j.solener.2020.02.103
Journal information: Solar Energy
Provided by University of Córdoba
Citation: The effectiveness of a heating system is validated: Heating air from solar radiation (2020, May 28) retrieved 15 January 2021 from https://techxplore.com/news/2020-05-effectiveness-validated-air-solar.html
An algorithm for optimizing the cost and efficiency of human-robot collaborative assembly lines
Impulse Neuro-Controller executes game moves with thoughts instead of mouse clicks
AI algorithm over 70% accurate at guessing a person's political orientation
Evolvable neural units that can mimic the brain's synaptic plasticity
New research technique sheds light on least understood part of lithium batteries
Experts reduce search times for novel high-entropy alloys 13,000-fold using Cuckoo Search
New method makes better predictions of material properties using low quality data
Next-generation heat pump offers more affordable heating and cooling
Solar heating could cover more than 80 percent of domestic heating requirements in Nordic countries
Turbomachine expander offers efficient, safe strategy for heating, cooling
Our cities are hidden power stations
Energizing buildings
Concept for a hybrid-electric plane may reduce aviation's air pollution problem
The compound that makes chili peppers spicy also boosts perovskite solar cell performance
Flexible thermoelectric devices enable energy harvesting from human skin
Can sodium-ion batteries replace trusty lithium-ion ones?
Two-sided solar cells can collect scattered light to gather more energy
Your feedback will go directly to Tech Xplore editors.
Your email address is used only to let the recipient know who sent the email. Neither your address nor the recipient's address will be used for any other purpose. The information you enter will appear in your e-mail message and is not retained by Tech Xplore in any form.


text:
Q: Seleccionar solo el texto de etiqueta xml con xslt Tengo el siguiente xml:
<partido>Ha ganado el barcelona
                <equipos>
                    <nombre>Barcelona el liverpool</nom>
                    <resultado>3-0</resultado>
                </equipos>
 </partido>

Quiero con el xslt sacar el texto Ha ganado el Barcelona és decir el texto de la etiqueta partido pero solo eso no quiero que salga el texto que hay dentro de equipos.
He echo el siguiente value-of select.
<conclusion><xsl:value-of select="partido"/></conclusion>

Pero el resultado obtenido es el siguiente:
<conclusion>
Ha ganado el barcelona

                       Barcelona el liverpool
                      3-0

</conclusion>

Como puedo hacer para que solo me muestre lo que quiero?

A: Tienes un error al cerrar el nodo nombre, aunque entiendo que habrá sido por copiar el código en la pregunta, en cualquier caso sería:
<?xml version="1.0" encoding="UTF-8"?>
<partido>Ha ganado el barcelona
    <equipos>
        <nombre>Barcelona el liverpool</nombre>
        <resultado>3-0</resultado>
    </equipos>
</partido>

Y luego para que sólo salga Ha ganado el barcelona te bastaría con usar text() con el nodo partido, porque como lo estás haciendo ahora, saldrá todo lo de ese nodo y sus hijos:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <html>
             <body>
                 <conclusion>
                     <xsl:value-of select="partido/text()"/>
                 </conclusion>
             </body>
        </html>
     </xsl:template>
</xsl:stylesheet>


How Does Technology Entertain You?
If you work hard or are busy in studies at school, do you ever get to the point where you feel burned out?
For millions of individuals, that feeling of burnout is quite real.
So, how can you go about lessening the stress you feel in everyday life?
One of the ways to do this is finding out how technology can help you in your day-to-day living but also entertain you.
When you stop to think about it, technology has done a world of good for many people over the decades. In fact, it has changed the way countless individuals have lived from decade to decade.
With that in mind, ask yourself how technology is benefitting you these days.
From an info standpoint, technology likely plays a role weekly and even daily in your life.
As an example, you're headed out somewhere in your vehicle and need directions.
Before the Internet, you would have jotted down the directions on a piece of scratch paper and been on your way. In the world of technology, you plug that information into your phone and get directions. Now, how easy is that?
With mobile app reviews, you can see which app is best suited for giving you directions to wherever you want to go.
Meantime, need an app to find out the best ways to book airfares, hotel rooms, rental cars and more? Yes, there are plenty of apps out there that can direct you to the best sites for such needs.
As you begin to see, there pretty much is an app for everything one might need in their world.
Best of all, there are also mobile apps for playing games and doing other fun activities.
Yes, after a long day of work or school, you could find the right app that leads you to any number of online games. Once playing one or more games, you forget about all you have to do and the stress that can be part of your daily life.
Which Apps Are Best Suited to Your Lifestyle?
In trying to determine which apps are best suited to your lifestyle, take the time to review them online.
Keep in mind that there are services out there doing the reviewing for you and many other consumers. As such, you can get the info you need right at your fingertips.
In most cases, you want an app that is easy to download, is not complicated to understand, and is free.
You also want to allow your child when at the right age to have their own cell phone to be able to enjoy many apps.
There are many apps out there geared towards kids. They prove to be both educational and entertaining. As such, it allows your child to learn when he or she is not in the classroom. Before installing any apps on your child's phone, be sure to review them to make sure they are appropriate.
In allowing technology to entertain you, take some time to sit back and review all your options.
It is safe to say that mobile technology will never stop amazing and entertaining you at the same time.
Instagram Bot, Is it worth the Risk?


text:
Biilaachia-White Swan, Crow Warrior, Custer Scout, American Artist
The story of the Apsaalooke (Crow) men who scouted for the U.S. Seventh Cavalry in 1876 has been told by historians, the details sometimes distorted or fabricated. Biilaachia–better known as White Swan–survived the Battle of Little Bighorn despite severe wounds. One soldier recalled him standing beside his horse, firing at the Sioux: "He would not mount up and to try to get away but stood and fought." White Swan continued to scout off-and-on for the U.S. Army until 1881 and recorded his 22 combat actions in 37 paintings and drawings. Done in traditional Plains warrior biographic style, his complete body of work is presented here for the first time, along with the history behind each depiction. His life is detailed in photographs, some never before published, and four little-known interviews, as well as extensive research about the Apsaalooke people.


text:
Canoe Heads carry charity to best ever fundraising total
Published On June 4, 2019 | By Abbie Jack | Headlines, Life
Amici Camping Charity held its 14th annual Canoe Heads for Kids portage and paddle through Toronto's Harbourfront on June 1. (Abbie Jack)
Abbie Jack
For Canadian youth and adolescents fortunate enough to experience the magic of summer camp, it is the highlight of their summer and year.
Veronica Trask, a 25-year-old young professional from Toronto spent her summers at Oconto, an all-girls sleepaway camp in Eastern Ontario which was integral in shaping her into who she is today, she said.
For the average family, however, financial barriers make sending a child to summer camp difficult.
Amici Camping Charity aims to change the lives of underprivileged children by sending over 240 kids to camp throughout Ontario every summer.
This past Saturday, Amici held its 14th annual Canoe Heads for Kids, one of the many fundraising events the organization runs every year.
@Amici_Charity #CanoeHeads2019 team trout rock here we go! pic.twitter.com/XSzOxrsj3i
— Sean Mitchell (@sdmitch09) June 1, 2019
A forecasted storm would have made the 15 km portage and paddle along downtown Toronto's harbour shoreline difficult and dangerous, but the afternoon was clear.
Trask attended the event alongside her team of 10 former campers and staff.
Amici and Canoe Heads for Kids are particularly important to her as they are the reason she was able to attend Camp Oconto every summer.
"Growing up in a single parent household was hard on my mother financially," she said. "From the age of eight to 16, I was sponsored by Amici (and) sent to Camp Oconto in Tichborne, Ontario."
When Trask first attended the camp north of Kingston in 2004, she was extremely shy. After only two weeks at camp it was evident how it had already impacted her life greatly and made her into a more confident and capable nine-year-old, Trask said.
"Camp meant a lot of things to me but mostly consistency," she said. "Home life is hard, everyone has their struggles, but camp is the place that is always the same feeling of happiness for me."
Veronica Trask (middle), with counsellor peers Maddie Kotzer (left), and Katie Scott (right) at Camp Oconto where Trask spent 15 summers. (Veronica Trask)
After her nine years as a camper, she went on to become a counsellor at Camp Oconto for six years where she was able to see the positive influence camp had on her campers, she said.
Now as a young adult, Trask still finds herself involved in camp as part of the Amici Leadership Advisor Program.
"I got involved two years ago after hearing about the opportunity," Trask said. "Amici has supported me my whole life and I want children to reach their full potential as well."
The program works to inspire Amici campers to become active leaders outside of camp through activities and workshops.
"I wanted to make sure I could help Amici children not just at camp but to continue that positivity at home, throughout the school year," Trask said.
Robyn Short, Manager of Fund Development and Communications for Amici said that this year's Canoe Heads for Kids was the most successful one yet.
"We could not be more grateful for the generosity and passion of Amici's Canoe Heads," she said. "This year's event was the most fundraising we've seen with over $255,000 and counting."
As a lifelong camper herself, Short knew that accepting a job at Amici in 2016 would be a perfect fit.
Short said that providing the life-changing experience of camp to children who otherwise would not be able to go has been a dream job.
"I spent 14 summers at my beloved Glen Bernard Camp. It was where I really learned how to value myself and it provided me with the opportunity to learn important skills like leadership, independence, creativity, resilience and so much more," she said. "Not to mention all the fun and lifelong friendships I gained."
The cornerstone of the program is that once a child is an Amici camper, they are an Amici camper for their entire camping journey, Short said.
"We believe that the opportunity to return back to camp friends and supportive role models, year after year, is really where the magic happens," she said.
With the money raised this year, campers will be sent one of the 44 Amici partnered Ontario Camp Association accredited summer camps, two which are new this year, Short said.
Short was ecstatic with the outcome of Saturday's event. Everything went well, right down to the weather, she said.
Latest posts by Abbie Jack (see all)
Dog days of summer can be deadly for pets - July 9, 2019
Students feel the pressure of OSAP cuts - June 25, 2019
Gunshots sends crowd at Raptors' celebration into a panic - June 18, 2019