update date

update date

---
title: "Dance as a metaphor of life"
url: "/dance_as_a_metaphor_of_life"
aliases: []
description:
date: 2018-01-13
draft: true
acknowledgement:
categories: ["Writings"]
tags: []
people: []
places: []
locations: []
---

= Dance as a metaphor of life
Anton Podviaznikov <anton@podviaznikov.com>
:revdate: 2018-01-14
:docdate: 2018-01-14
:nofooter:
:document_type: writing
:tags: ""

Remember when you were a kid you could dance and enjoy it enormously even if you _didn't know how_ to dance?

After you grow out of childhood, you lose that bliss.
You're starting to learn how to dance in the school.
It's painful, and it takes time, and it might be not fun.
And those years are filled with effort, tears, setbacks, lost hope, varying levels of motivation, ups and downs, defeats and victories.

And then, maybe, if you're persistent and lucky, you might rediscover the joy from your childhood again.
And that is the point where you know how to dance as professional, and you feel it and enjoy it as a kid.
That is the integration point: your inner child integrated with an adult to form a mature creature.

For me, that is the metaphor of life.
You go from childhood - which most people enjoy, to sometimes painful period of adulthood where you to learn how to live and how to bring that joy back,
and when you're done - you are a mature person.
The one, who has a deep understanding of life and know how to enjoy it and appreciate it.
It is not about just rediscovering what was lost during adulthood.
It's about bringing together all sides: mind and body and soul.
It's this three-dimensionality that gives new depth to the joy.
That is the whole point of growing up - to lose joy so you can find it again in a new broader sense and with new intensity.

---
title: "Dance as a metaphor of life"
url: "/dance_as_a_metaphor_of_life"
aliases: []
description:
date: 0-00-00
draft: true
acknowledgement:
categories: ["Writings"]
tags: []
people: []
places: []
locations: []
---

= Dance as a metaphor of life
Anton Podviaznikov <anton@podviaznikov.com>
:revdate: 2018-01-14
:docdate: 2018-01-14
:nofooter:
:document_type: writing
:tags: ""

Remember when you were a kid you could dance and enjoy it enormously even if you _didn't know how_ to dance?

After you grow out of childhood, you lose that bliss.
You're starting to learn how to dance in the school.
It's painful, and it takes time, and it might be not fun.
And those years are filled with effort, tears, setbacks, lost hope, varying levels of motivation, ups and downs, defeats and victories.

And then, maybe, if you're persistent and lucky, you might rediscover the joy from your childhood again.
And that is the point where you know how to dance as professional, and you feel it and enjoy it as a kid.
That is the integration point: your inner child integrated with an adult to form a mature creature.

For me, that is the metaphor of life.
You go from childhood - which most people enjoy, to sometimes painful period of adulthood where you to learn how to live and how to bring that joy back,
and when you're done - you are a mature person.
The one, who has a deep understanding of life and know how to enjoy it and appreciate it.
It is not about just rediscovering what was lost during adulthood.
It's about bringing together all sides: mind and body and soul.
It's this three-dimensionality that gives new depth to the joy.
That is the whole point of growing up - to lose joy so you can find it again in a new broader sense and with new intensity.


Update 2019-09-10-Model-Distillation.adoc

= Model Distillation
:hp-image: https://github.com/anshu92/blog/raw/gh-pages/images/carolien-van-oijen-GRlRHqEqZTc-unsplash.jpg
:published_at: 2019-09-10
:hp-tags: distillation, machine learning

[.lead]
*How most of the information in large models can be transferred to a small model using soft targets, and what that says about the relationship of information to the dynamics of learning.*

image::https://github.com/anshu92/blog/raw/gh-pages/images/carolien-van-oijen-GRlRHqEqZTc-unsplash.jpg[Bee]

'''
.Recent NLP language models
[width="50%",cols="<,<",frame="all",grid="all"]
|===
|*model*
|*parameters*

|BERT-base
|110 million

|BERT-large
|340 million

|Facebook XLM
|665 million

|OpenAI GPT-2
|774 million
|===
'''

The upward trend of model sizes raises hurdles for the application of these models in the shape of computation and scalability, and requires decisions on the trade-off between accuracy, potency and deployability. Following reading http://www.nlp.town/blog/distilling-bert/[this blog post], I decided to try to summarize (distill) the concept of model distillation, and talk about why this struck me as such an interesting idea.

.Model Distillation. graphic by Anshuman Sahoo
image::https://github.com/anshu92/blog/raw/gh-pages/images/distill.png[Model Distillation]

'''

As shown above, the method of distillation relies on the idea of *_soft targets_* and *_softmax temperature_*.

'''

.Softmax Function with Temperature
image::https://github.com/anshu92/blog/raw/gh-pages/images/tempsoftmax.png[Model Distillation]

'''

https://arxiv.org/pdf/1503.02531.pdf[Hinton et al., 2015] introduced the concept of "softmax temperature". The probability p~i~ of class i is calculated from the logits z. T is the temperature parameter - as you can see, setting T = 1 gives us the standard softmax function. In the paper, they also found that if the ground truth labels are available, it improves the model if the loss to optimize includes training on ground truth labels in addition to the soft target outputs of the teacher model(as shown in the figure, student loss is added to distillation loss).

On a philosophical line of thought, the paper presents an analogy of some insects in nature that optimize based on their stage-of-life requirement - larval forms to extract nutrition from environment and an adult form for travellig and reproduction; whereas cumbersome, large and often ensemble models remain the same during training and deployment. A conceptual block that may explain our hesitation of modifying trained models is our assumption that changing learned parameters may lead to loss of knowledge. Another assumption made is that the optimizing an objective function for the training set is close to optimizing the user's true objective - generalizing well to unseen data. However, ideal generalization to the user objective requires knowledge that might not be available in the training data.

= Model Distillation
:hp-image: https://github.com/anshu92/blog/raw/gh-pages/images/carolien-van-oijen-GRlRHqEqZTc-unsplash.jpg
:published_at: 2019-09-10
:hp-tags: distillation, machine learning

[.lead]
*How most of the information in large models can be transferred to a small model using soft targets, and what that says about the relationship of information to the dynamics of learning.*

image::https://github.com/anshu92/blog/raw/gh-pages/images/carolien-van-oijen-GRlRHqEqZTc-unsplash.jpg[Bee]

'''
.Recent NLP language models
[width="50%",cols="<,<",frame="all",grid="all"]
|===
|*model*
|*parameters*

|BERT-base
|110 million

|BERT-large
|340 million

|Facebook XLM
|665 million

|OpenAI GPT-2
|774 million
|===
'''

The upward trend of model sizes raises hurdles for the application of these models in the shape of computation and scalability, and requires decisions on the trade-off between accuracy, potency and deployability. Following reading http://www.nlp.town/blog/distilling-bert/[this blog post], I decided to try to summarize (distill) the concept of model distillation, and talk about why this struck me as such an interesting idea.

image::https://github.com/anshu92/blog/raw/gh-pages/images/distill.png[Model Distillation]

'''

As shown above, the method of distillation relies on the idea of *_soft targets_* and *_softmax temperature_*.

'''

image::https://github.com/anshu92/blog/raw/gh-pages/images/tempsoftmax.png[Model Distillation]

'''

https://arxiv.org/pdf/1503.02531.pdf[Hinton et al., 2015] introduced the concept of "softmax temperature". The probability p~i~ of class i is calculated from the logits z. T is the temperature parameter - as you can see, setting T = 1 gives us the standard softmax function. In the paper, they also found that if the ground truth labels are available, it improves the model if the loss to optimize includes training on ground truth labels in addition to the soft target outputs of the teacher model(as shown in the figure, student loss is added to distillation loss).

On a philosophical line of thought, the paper presents an analogy of some insects in nature that optimize based on their stage-of-life requirement - larval forms to extract nutrition from environment and an adult form for travellig and reproduction; whereas cumbersome, large and often ensemble models remain the same during training and deployment. A conceptual block that may explain our hesitation of modifying trained models is our assumption that changing learned parameters may lead to loss of knowledge. Another assumption made is that the optimizing an objective function for the training set is close to optimizing the user's true objective - generalizing well to unseen data. However, ideal generalization to the user objective requires knowledge that might not be available in the training data.


Update 2016-01-13-how-to-install-python-on-linux.adoc

= როგორ დავაყენოთ პითონი ლინუქსზე
:hp-alt-title: how to install python on linux

პითონის დაყენება შეიძლება ნებისმიერ ოპერაციულ სისტემაზე. როგორებიცაა მაგ. Windows, Unix და Linux ოპერაციულ სისტემებზე.
მარტივი გზა პითონის დასაყენებლად არის package manager ის გამოყენება, მაგ. apt-get, yum, pacman და ა.შ.

debian/ubuntu დისტრიბუტივებზე შეგვიძლია გავუშვათ ბრძანება
მაგ. თუ გვინდა 2.x ვერსიის დაყენება

 * sudo apt-get install python2.7

თუ გვინდა 3.x ვერსიის დაყენება

 * sudo apt-get install python3.3

ასევე შეგვიძლია დავაყენოთ ბოლო ვერსია სორსიდან, სორსის გადმოწერა შეგიძლიათ პითონის ოფიციალური გვერდიდან ან Ftp დან - https://www.python.org/ftp/python/ [Python Source Code] ვირჩევთ ბოლო ვერსიას 3.5.1 და ვიწერთ *.tgz ფორმატის ფაილს Python-3.5.1.tgz შემდეგ ვხსნით ტერმინალს და ვუშვებთ ქვემოთ მოცემულ ბრძანებებს

 * wget http://python.org/ftp/python/3.5.1/Python-3.5.1.tgz
 * tar -xvf Python-3.5.1.tgz
 * cd Python-3.5.1
 * ./configure
 * make
 * make altinstall

პითონის დაყენების პროცესი წარმატებით დასრულდა.
იხ. სურათი
image:: pythonge.png

:hp-tags: title[პითონი],title[ლინუქსი]

= როგორ დავაყენოთ პითონი ლინუქსზე
:hp-alt-title: how to install python on linux

პითონის დაყენება შეიძლება ნებისმიერ ოპერაციულ სისტემაზე. როგორებიცაა მაგ. Windows, Unix და Linux ოპერაციულ სისტემებზე.
მარტივი გზა პითონის დასაყენებლად არის package manager ის გამოყენება, მაგ. apt-get, yum, pacman და ა.შ.

debian/ubuntu დისტრიბუტივებზე შეგვიძლია გავუშვათ ბრძანება
მაგ. თუ გვინდა 2.x ვერსიის დაყენება

 * sudo apt-get install python2.7

თუ გვინდა 3.x ვერსიის დაყენება

 * sudo apt-get install python3.3

ასევე შეგვიძლია დავაყენოთ ბოლო ვერსია სორსიდან, სორსის გადმოწერა შეგიძლიათ პითონის ოფიციალური გვერდიდან ან Ftp დან - https://www.python.org/ftp/python/ [Python Source Code] ვირჩევთ ბოლო ვერსიას 3.5.1 და ვიწერთ *.tgz ფორმატის ფაილს Python-3.5.1.tgz შემდეგ ვხსნით ტერმინალს და ვუშვებთ ქვემოთ მოცემულ ბრძანებებს

 * wget http://python.org/ftp/python/3.5.1/Python-3.5.1.tgz
 * tar -xvf Python-3.5.1.tgz
 * cd Python-3.5.1
 * ./configure
 * make
 * make altinstall

პითონის დაყენების პროცესი წარმატებით დასრულდა.

:hp-tags: title[პითონი],title[ლინუქსი]


Update 2016-11-28-An-Introduction-to-Finagle-by-example.adoc

= An Introduction to Finagle by example
<vgrente@gmail.com>
:hp-image: /covers/cover.png
:published_at: 2016-11-28
:hp-tags: Finagle

It is a challenging task to build a large-scale web application, there are fundamental characteristics to take into account: for example, efficiency, safety and robustness. Finagle is a asynchronous, Netty based JVM RPC system made by Twitter which makes it easy to build high available clients and servers in Java and Scala. And it can even simplify your application architecture. Here I want to show you how powerful Finagle is.

== Quickstart
Let's first have a quick look about how to create a Finagle micro web service and a Finagle http client to consume this api.Create a sbt project and import dependencies.
[source,scala]
----
libraryDependencies ++= Seq(
"com.twitter" %% "finagle-http" % "6.38.0",
"org.scalatest" %% "scalatest" % "2.2.4" % "test"
)
----
First, let's define a service. Here we define a service to receive a http request and get its url parameter as Integer then return a http response by plus 10.
[source,scala]
----
import com.twitter.finagle.Serviceimport com.twitter.util.Futureimport com.twitter.finagle.http

This is a plus 10 serviceclass PlusTenService extends Service[http.Request, http.Response] {

  override def apply(request: http.Request): Future[http.Response] = {
  Future {
  val input = request.getIntParam("num")
  val output = input + 10
  val response = http.Response(request.version, http.Status.Ok)      response.setContentString(output.toString)
  response    }  }
}
----
Then initiate and start our server
[source,scala]
----
import com.twitter.finagle.{http, Service, Http}import com.twitter.util.Await

object QuickLookServer {  def main(args: Array[String]): Unit = {    val service: Service[http.Request, http.Response] = new PlusTenService    val server = Http.serve(":9090", service)    Await.ready(server)  }}
----
Last let's define a client to consume this server.
[source,scala]
----
import com.twitter.finagle.{Service, Http}import com.twitter.finagle.httpimport com.twitter.util.Await

object QuickLookClient {  def main(args: Array[String]): Unit = {    //define a client    val client: Service[http.Request, http.Response] = Http.newService("localhost:9090")
//define a request
val request = http.Request(http.Method.Get, "/?num=5")
//apply request on the client
val response = client(request)
//print response
response.foreach(rep => println(rep.getContentString()))
Await.result(response)  }
}
----
If you run the two application you will see the server running on localhost:9090 and client get response 15. Simple right? As you can see our service and client are both type of Service[http.Request, http.Response] . This data type really confuse me in the beginning. I will explan what's the differences between them.

== The core of Finagle
Service

Now let's first have a look at the core of finagle Service[-Req, +Rep] . You can find the definition in com.twitter.finagle.Service . In Finagle 6.38.0 the definition of Service is an abstract class, in previous version it was a trait
[source,scala]
----
abstract class Service[-Req, +Rep] extends (Req => Future[Rep])
----
A service is a function that takes request of type Req, and return a response of Future of Rep. This Services type are used to represent both clients and servers. To answer my previous question, the differences between service and client is that a Finagle client “imports” a Service from the network. However, a Finagle server “exports” a Service to the network.Note: the Future here is twitter future not scala future. There is no differences on conception.

Filter

Some times we want to add application-agnostic behaviour, we can use Filter to achieve this.
[source,scala]
----
abstract class Filter[-ReqIn, +RepOut, +ReqOut, -RepIn]
extends ((ReqIn, Service[ReqOut, RepIn])
=> Future[RepOut])
----

image

If it is not clear please check image below.

image

In most common cases, ReqIn is equal to ReqOut, and RepIn is equal to RepOut. So we have this SimpleFilter class

[source,scala]
----
abstract class SimpleFilter[Req, Rep] extends Filter[Req, Rep, Req, Rep]
----
A filter can attached to client and server side. Let's try to implement a simple timeout filter.
[source,scala]
----
import com.twitter.finagle.{SimpleFilter, Service}import com.twitter.util.{Duration, Timer, Future}

class TimeoutFilter[Req, Rep](timeout: Duration, timer: Timer)
extends SimpleFilter[Req, Rep] {

  def apply(request: Req, service: Service[Req, Rep]): Future[Rep] = {
  val res = service(request)
  res.within(timer, timeout)  }
  }
----
Here, a timeout filter is a class extends SimpleFilter trait. Below is how to use this filter on client side
[source,scala]
----
client = Http.newService("localhost:9090")

val timeoutFilter = new TimeoutFilter[http.Request, http.Response](Duration.fromSeconds(1),
new JavaTimer(false))

val clientWithTimeoutFilter = timeoutFilter.andThen(quickLookClient)
----

A filter can be applied on server side too. Here is an example. First let's define a filter.

[source,scala]
----
class CountFilter[Req, Rep](countClient: Service[http.Request, http.Response])
extends SimpleFilter[Req, Rep]
{  override def apply(request: Req, service: Service[Req, Rep]): Future[Rep] =
{    val countRequest = http.Request(http.Method.Post, "/?count=5")    countClient(countRequest)    service(request)  }}
----
And then let's use it on our plusTen service
[source,scala]
----
al service: Service[http.Request, http.Response] = new PlusTenService

val countClient = Http.newService("localhost:9010")

val countFilter = new CountFilter[http.Request, http.Response](countClient)

val serviceWithCountFilter = countFilter.andThen(service)
----
You may notice the way to chain filter and service together is by using andThen method. Actually andThen method can not only chain filter with service but also chain multiple filters, like filter1 andThen filter2 andThen myservice

## Client
This is the part that I like the most in finagle. Finagle http client is designed to maximize success and minimize latency. Each request will flow through various modules. These modules are logically separated into three stacks: Client stack, Endpoint stack, connection stack.

*Client stack*

manages name resolution and balances requests across multiple endpoints.

*Endpoint stack*

provides circuit breakers and connection pooling.

*connection stack*

provides connection life-cycle management and implements the wire protocol.

To use finagle http client is very simple. Define a client first and define a http request, then apply request on the client.

[source,scala]
----
// create a http clientval client =
Http.client.newService("example.com:80")
// create a http requestval req =
Request("/foo", ("my-query-string", "bar")
)
// apply request on the clientval resp: Future[Response] = client(req)Note: client(req) is equal to client.apply(req)
----
What I want to emphasis here is the Load Balancer module. This module brings a lot of benefit for your application. It can simplify your application infstracture. Let's compare it with traditional solution.

image

As you can see, the traditional solution highly rely on nginx as load balancer, once nginx dead your service is not reachable, in real production environment, you have master-slave nginx wiht keeplived installed on nginx machine for heartbeat detection. This looks really complex, what about if we can get rid of these nginx?Let's have look at following code.
[source,scala]
----
name: Name =
Name.bound(Address("localhost", 10010), Address("localhost", 10011), Address("localhost", 10012)
)
//define a clientval client: Service[http.Request, http.Response] = Http.newService(name, "client")
----
This means you supply three addresses and put it into finagle http client. Finagle client will dispatch the request to one of address based on certain load balance algorithmn. The default algorithmn is "Exponentially Weighted Moving Average (EWMA)". Now your infstracture architechture becomes like following

image

Pretty simple right. Your apis talk to each other directly.

## Protocol-agnostic

Finagle is a protocol-agnostic RPC system. It means Finagle supports every protocol if people implement it. For example: finagle-thrift is using thrift protocol. finagle-mysql implements the mysql protocol.Now, let's look at this scenario

image

We want to make a api count service to count how many times the web service has been called. In section Service and Filter. We send http request and put number as query parameter. It just feel strange that I just want to send a number to count server, to achieve that I have to send a http request. Because I don't use any data from header, cookie and body. If the application is running on AWS, it those junk information cost money. So it's ideal to just send a integer number to api count service. Let's implement this by customize finagle protocol.First, we should tell finagle how to converts an scodec codec into a Netty encoder

[source,scala]
----
import org.jboss.netty.buffer.{ChannelBuffer, ChannelBuffers}import org.jboss.netty.channel.{Channel, ChannelHandlerContext}import org.jboss.netty.handler.codec.oneone.{OneToOneDecoder, OneToOneEncoder}import scodec.Codecimport scodec.bits.BitVector

trait CodecConversions {  /**    * Converts an scodec codec into a Netty encoder.    */  protected def encoder[A: Codec] =
new OneToOneEncoder {
override def encode(ctx: ChannelHandlerContext, channel: Channel, msg: Object) =

ChannelBuffers.wrappedBuffer(        Codec.encodeValid(msg.asInstanceOf[A]).toByteBuffer      )
}

  /**    * Converts an scodec codec into a Netty decoder.
  */  protected def decoder[A: Codec] = new OneToOneDecoder {
  override def decode(ctx: ChannelHandlerContext, channel: Channel, msg: Object) =
  msg match {
  case cb: ChannelBuffer =>          Codec.decodeValidValue[A](BitVector(cb.toByteBuffer)).asInstanceOf[Object]        case other => other      }
  }
  }
----
And then channel pipeline and codec factories
[source,scala]
----
trait Factories { this: CodecConversions =>  import com.twitter.finagle.{Codec => FinagleCodec, CodecFactory}  import org.jboss.netty.channel.{ChannelPipelineFactory, Channels}

  /**   * Creates a Netty channel pipeline factory given input and output types.   */  private[this] def pipeline[I: Codec, O: Codec] = new ChannelPipelineFactory {    def getPipeline = {      val pipeline = Channels.pipeline()      pipeline.addLast("encoder", encoder[I])      pipeline.addLast("decoder", decoder[O])
  pipeline    }
  }
  /**   * Creates a Finagle codec factory given input and output types.   */  protected def codecFactory[I: Codec, O: Codec] = new CodecFactory[I, O] {
  def server = Function.const {
  new FinagleCodec[I, O] { def pipelineFactory = pipeline[O, I] }
  }
    def client = Function.const {
    new FinagleCodec[I, O] { def pipelineFactory = pipeline[I, O] }
    }
    }
    }
----

And then the code that actually creates our Finagle server and client

[source,scala]
----
import java.net.InetSocketAddress

import com.twitter.conversions.time._import com.twitter.finagle.Serviceimport com.twitter.finagle.builder.{ClientBuilder, ServerBuilder}import com.twitter.util.{Duration, Future}import scodec.Codec

object IntegerServerAndClient extends Factories with CodecConversions {

  /**    * Creates a Finagle server from a service that we have scodec codecs    * for both the input and output types.    */  def server[I, O](port: Int)(service: Service[I, O])(implicit ic: Codec[I], oc: Codec[O]) =    ServerBuilder()
  .name("server")
  .codec(codecFactory[I, O])
  .bindTo(new InetSocketAddress(port))      .build(service)

  /**    * Creates a Finagle client given input and output types with scodec codecs.    */  def client[I, O](host: String, timeout: Duration = 3.second)                  (implicit ic: Codec[I], oc: Codec[O]) =    ClientBuilder()
  .name("client")
  .codec(codecFactory[I, O])
  .hosts(host)
  .timeout(timeout)
  .build()
  }
----

Define our simple service
[scala,source]
----
import com.twitter.finagle.Serviceimport com.twitter.util.Future

class IntegerService extends Service[Int, Int]{  var count = 0  override def apply(request: Int): Future[Int] = {    Future.value(count + request)  }
}
----

Run a server

[source,scala]
----
import com.twitter.finagle.Serviceimport com.twitter.util.Awaitimport scodec.codecs.implicits.{ implicitIntCodec => _, _ }

object Server {  def main(args: Array[String]): Unit = {    implicit val intgerCodec =
scodec.codecs.uint8

    val service: Service[Int, Int] =
    new IntegerService
    val server = IntegerServerAndClient.server[Int, Int](9191)(service)    Await.ready(server)
    }
    }
----
Run a client
[source,scala]
----
import com.twitter.finagle.Serviceimport com.twitter.util.Awaitimport scodec.codecs.implicits.{ implicitIntCodec => _, _ }

object Client {  def main(args: Array[String]): Unit = {

    implicit val intgerCodec = scodec.codecs.uint8

    //define a client
    val client: Service[Int, Int] = IntegerServerAndClient.client[Int, Int]("localhost:9191")    //define a request
    val request = 4
    //apply request on the client
    val response = client(request)
    //print response    response.foreach(rep => println(s"This is response $rep"))
    Await.result(response)
    }
    }
----
## Conclusion
Finagle is a very flexible asychronous, protocol-agnostic RPC framework. It can help you to build high performance micro service with any protocol. It is worth to take a look at Finch the web framework based on Finagle. You can find more detail introduction from https://blog.twitter.com/2011/finagle-a-protocol-agnostic-rpc-system[Twitter blog] and more detailed example from http://twitter.github.io/scala_school/searchbird.html[Twitter scala school].

= An Introduction to Finagle by example
(Yue;Li)
:hp-image: /covers/cover.png
:published_at: 2016-11-28
:hp-tags: Finagle

It is a challenging task to build a large-scale web application, there are fundamental characteristics to take into account: for example, efficiency, safety and robustness. Finagle is a asynchronous, Netty based JVM RPC system made by Twitter which makes it easy to build high available clients and servers in Java and Scala. And it can even simplify your application architecture. Here I want to show you how powerful Finagle is.

== Quickstart
Let's first have a quick look about how to create a Finagle micro web service and a Finagle http client to consume this api.Create a sbt project and import dependencies.
[source,scala]
----
libraryDependencies ++= Seq(
"com.twitter" %% "finagle-http" % "6.38.0",
"org.scalatest" %% "scalatest" % "2.2.4" % "test"
)
----
First, let's define a service. Here we define a service to receive a http request and get its url parameter as Integer then return a http response by plus 10.
[source,scala]
----
import com.twitter.finagle.Serviceimport com.twitter.util.Futureimport com.twitter.finagle.http

This is a plus 10 serviceclass PlusTenService extends Service[http.Request, http.Response] {

  override def apply(request: http.Request): Future[http.Response] = {
  Future {
  val input = request.getIntParam("num")
  val output = input + 10
  val response = http.Response(request.version, http.Status.Ok)      response.setContentString(output.toString)
  response    }  }
}
----
Then initiate and start our server
[source,scala]
----
import com.twitter.finagle.{http, Service, Http}import com.twitter.util.Await

object QuickLookServer {  def main(args: Array[String]): Unit = {    val service: Service[http.Request, http.Response] = new PlusTenService    val server = Http.serve(":9090", service)    Await.ready(server)  }}
----
Last let's define a client to consume this server.
[source,scala]
----
import com.twitter.finagle.{Service, Http}import com.twitter.finagle.httpimport com.twitter.util.Await

object QuickLookClient {  def main(args: Array[String]): Unit = {    //define a client    val client: Service[http.Request, http.Response] = Http.newService("localhost:9090")
//define a request
val request = http.Request(http.Method.Get, "/?num=5")
//apply request on the client
val response = client(request)
//print response
response.foreach(rep => println(rep.getContentString()))
Await.result(response)  }
}
----
If you run the two application you will see the server running on localhost:9090 and client get response 15. Simple right? As you can see our service and client are both type of Service[http.Request, http.Response] . This data type really confuse me in the beginning. I will explan what's the differences between them.

== The core of Finagle
Service

Now let's first have a look at the core of finagle Service[-Req, +Rep] . You can find the definition in com.twitter.finagle.Service . In Finagle 6.38.0 the definition of Service is an abstract class, in previous version it was a trait
[source,scala]
----
abstract class Service[-Req, +Rep] extends (Req => Future[Rep])
----
A service is a function that takes request of type Req, and return a response of Future of Rep. This Services type are used to represent both clients and servers. To answer my previous question, the differences between service and client is that a Finagle client “imports” a Service from the network. However, a Finagle server “exports” a Service to the network.Note: the Future here is twitter future not scala future. There is no differences on conception.

Filter

Some times we want to add application-agnostic behaviour, we can use Filter to achieve this.
[source,scala]
----
abstract class Filter[-ReqIn, +RepOut, +ReqOut, -RepIn]
extends ((ReqIn, Service[ReqOut, RepIn])
=> Future[RepOut])
----

image

If it is not clear please check image below.

image

In most common cases, ReqIn is equal to ReqOut, and RepIn is equal to RepOut. So we have this SimpleFilter class

[source,scala]
----
abstract class SimpleFilter[Req, Rep] extends Filter[Req, Rep, Req, Rep]
----
A filter can attached to client and server side. Let's try to implement a simple timeout filter.
[source,scala]
----
import com.twitter.finagle.{SimpleFilter, Service}import com.twitter.util.{Duration, Timer, Future}

class TimeoutFilter[Req, Rep](timeout: Duration, timer: Timer)
extends SimpleFilter[Req, Rep] {

  def apply(request: Req, service: Service[Req, Rep]): Future[Rep] = {
  val res = service(request)
  res.within(timer, timeout)  }
  }
----
Here, a timeout filter is a class extends SimpleFilter trait. Below is how to use this filter on client side
[source,scala]
----
client = Http.newService("localhost:9090")

val timeoutFilter = new TimeoutFilter[http.Request, http.Response](Duration.fromSeconds(1),
new JavaTimer(false))

val clientWithTimeoutFilter = timeoutFilter.andThen(quickLookClient)
----

A filter can be applied on server side too. Here is an example. First let's define a filter.

[source,scala]
----
class CountFilter[Req, Rep](countClient: Service[http.Request, http.Response])
extends SimpleFilter[Req, Rep]
{  override def apply(request: Req, service: Service[Req, Rep]): Future[Rep] =
{    val countRequest = http.Request(http.Method.Post, "/?count=5")    countClient(countRequest)    service(request)  }}
----
And then let's use it on our plusTen service
[source,scala]
----
al service: Service[http.Request, http.Response] = new PlusTenService

val countClient = Http.newService("localhost:9010")

val countFilter = new CountFilter[http.Request, http.Response](countClient)

val serviceWithCountFilter = countFilter.andThen(service)
----
You may notice the way to chain filter and service together is by using andThen method. Actually andThen method can not only chain filter with service but also chain multiple filters, like filter1 andThen filter2 andThen myservice

## Client
This is the part that I like the most in finagle. Finagle http client is designed to maximize success and minimize latency. Each request will flow through various modules. These modules are logically separated into three stacks: Client stack, Endpoint stack, connection stack.

*Client stack*

manages name resolution and balances requests across multiple endpoints.

*Endpoint stack*

provides circuit breakers and connection pooling.

*connection stack*

provides connection life-cycle management and implements the wire protocol.

To use finagle http client is very simple. Define a client first and define a http request, then apply request on the client.

[source,scala]
----
// create a http clientval client =
Http.client.newService("example.com:80")
// create a http requestval req =
Request("/foo", ("my-query-string", "bar")
)
// apply request on the clientval resp: Future[Response] = client(req)Note: client(req) is equal to client.apply(req)
----
What I want to emphasis here is the Load Balancer module. This module brings a lot of benefit for your application. It can simplify your application infstracture. Let's compare it with traditional solution.

image

As you can see, the traditional solution highly rely on nginx as load balancer, once nginx dead your service is not reachable, in real production environment, you have master-slave nginx wiht keeplived installed on nginx machine for heartbeat detection. This looks really complex, what about if we can get rid of these nginx?Let's have look at following code.
[source,scala]
----
name: Name =
Name.bound(Address("localhost", 10010), Address("localhost", 10011), Address("localhost", 10012)
)
//define a clientval client: Service[http.Request, http.Response] = Http.newService(name, "client")
----
This means you supply three addresses and put it into finagle http client. Finagle client will dispatch the request to one of address based on certain load balance algorithmn. The default algorithmn is "Exponentially Weighted Moving Average (EWMA)". Now your infstracture architechture becomes like following

image

Pretty simple right. Your apis talk to each other directly.

## Protocol-agnostic

Finagle is a protocol-agnostic RPC system. It means Finagle supports every protocol if people implement it. For example: finagle-thrift is using thrift protocol. finagle-mysql implements the mysql protocol.Now, let's look at this scenario

image

We want to make a api count service to count how many times the web service has been called. In section Service and Filter. We send http request and put number as query parameter. It just feel strange that I just want to send a number to count server, to achieve that I have to send a http request. Because I don't use any data from header, cookie and body. If the application is running on AWS, it those junk information cost money. So it's ideal to just send a integer number to api count service. Let's implement this by customize finagle protocol.First, we should tell finagle how to converts an scodec codec into a Netty encoder

[source,scala]
----
import org.jboss.netty.buffer.{ChannelBuffer, ChannelBuffers}import org.jboss.netty.channel.{Channel, ChannelHandlerContext}import org.jboss.netty.handler.codec.oneone.{OneToOneDecoder, OneToOneEncoder}import scodec.Codecimport scodec.bits.BitVector

trait CodecConversions {  /**    * Converts an scodec codec into a Netty encoder.    */  protected def encoder[A: Codec] =
new OneToOneEncoder {
override def encode(ctx: ChannelHandlerContext, channel: Channel, msg: Object) =

ChannelBuffers.wrappedBuffer(        Codec.encodeValid(msg.asInstanceOf[A]).toByteBuffer      )
}

  /**    * Converts an scodec codec into a Netty decoder.
  */  protected def decoder[A: Codec] = new OneToOneDecoder {
  override def decode(ctx: ChannelHandlerContext, channel: Channel, msg: Object) =
  msg match {
  case cb: ChannelBuffer =>          Codec.decodeValidValue[A](BitVector(cb.toByteBuffer)).asInstanceOf[Object]        case other => other      }
  }
  }
----
And then channel pipeline and codec factories
[source,scala]
----
trait Factories { this: CodecConversions =>  import com.twitter.finagle.{Codec => FinagleCodec, CodecFactory}  import org.jboss.netty.channel.{ChannelPipelineFactory, Channels}

  /**   * Creates a Netty channel pipeline factory given input and output types.   */  private[this] def pipeline[I: Codec, O: Codec] = new ChannelPipelineFactory {    def getPipeline = {      val pipeline = Channels.pipeline()      pipeline.addLast("encoder", encoder[I])      pipeline.addLast("decoder", decoder[O])
  pipeline    }
  }
  /**   * Creates a Finagle codec factory given input and output types.   */  protected def codecFactory[I: Codec, O: Codec] = new CodecFactory[I, O] {
  def server = Function.const {
  new FinagleCodec[I, O] { def pipelineFactory = pipeline[O, I] }
  }
    def client = Function.const {
    new FinagleCodec[I, O] { def pipelineFactory = pipeline[I, O] }
    }
    }
    }
----

And then the code that actually creates our Finagle server and client

[source,scala]
----
import java.net.InetSocketAddress

import com.twitter.conversions.time._import com.twitter.finagle.Serviceimport com.twitter.finagle.builder.{ClientBuilder, ServerBuilder}import com.twitter.util.{Duration, Future}import scodec.Codec

object IntegerServerAndClient extends Factories with CodecConversions {

  /**    * Creates a Finagle server from a service that we have scodec codecs    * for both the input and output types.    */  def server[I, O](port: Int)(service: Service[I, O])(implicit ic: Codec[I], oc: Codec[O]) =    ServerBuilder()
  .name("server")
  .codec(codecFactory[I, O])
  .bindTo(new InetSocketAddress(port))      .build(service)

  /**    * Creates a Finagle client given input and output types with scodec codecs.    */  def client[I, O](host: String, timeout: Duration = 3.second)                  (implicit ic: Codec[I], oc: Codec[O]) =    ClientBuilder()
  .name("client")
  .codec(codecFactory[I, O])
  .hosts(host)
  .timeout(timeout)
  .build()
  }
----

Define our simple service
[scala,source]
----
import com.twitter.finagle.Serviceimport com.twitter.util.Future

class IntegerService extends Service[Int, Int]{  var count = 0  override def apply(request: Int): Future[Int] = {    Future.value(count + request)  }
}
----

Run a server

[source,scala]
----
import com.twitter.finagle.Serviceimport com.twitter.util.Awaitimport scodec.codecs.implicits.{ implicitIntCodec => _, _ }

object Server {  def main(args: Array[String]): Unit = {    implicit val intgerCodec =
scodec.codecs.uint8

    val service: Service[Int, Int] =
    new IntegerService
    val server = IntegerServerAndClient.server[Int, Int](9191)(service)    Await.ready(server)
    }
    }
----
Run a client
[source,scala]
----
import com.twitter.finagle.Serviceimport com.twitter.util.Awaitimport scodec.codecs.implicits.{ implicitIntCodec => _, _ }

object Client {  def main(args: Array[String]): Unit = {

    implicit val intgerCodec = scodec.codecs.uint8

    //define a client
    val client: Service[Int, Int] = IntegerServerAndClient.client[Int, Int]("localhost:9191")    //define a request
    val request = 4
    //apply request on the client
    val response = client(request)
    //print response    response.foreach(rep => println(s"This is response $rep"))
    Await.result(response)
    }
    }
----
## Conclusion
Finagle is a very flexible asychronous, protocol-agnostic RPC framework. It can help you to build high performance micro service with any protocol. It is worth to take a look at Finch the web framework based on Finagle. You can find more detail introduction from https://blog.twitter.com/2011/finagle-a-protocol-agnostic-rpc-system[Twitter blog] and more detailed example from http://twitter.github.io/scala_school/searchbird.html[Twitter scala school].


NMS-6672: Documentation MemcachedMonitor

- Added generic description
- Added table with collected metrics

=== MemcachedMonitor

This monitor allows to monitor link:http://memcached.org[Memcached], a distributed memory object caching system.
To monitor the service availability the monitor tests if the _Memcached_ statistics can be requested.
The statistics are processed and stored in RRD files.
The following metrics are collected:

.Collected metrics using the MemcachedMonitor
[options="header, autowidth"]
|===
| Metric                | Description
| _uptime_              | Seconds the _Memcached_ server has been running since last restart.
| _rusageuser_          | User time seconds for the server process.
| _rusagesystem_        | System time secondes for the server process.
| _curritems_           | Number of items in this servers cache.
| _totalitems_          | Number of items stored on this server.
| _bytes_               | Number of bytes currently used for caching items.
| _limitmaxbytes_       | Maximum configured cache size.
| _currconnections_     | Number of open connections to this _Memached_.
| _totalconnections_    | Number of successful connect attempts to this server since start.
| _connectionstructure_ | Number of internal connection handles currently held by the server.
| _cmdget_              | Number of _GET_ commands received since server startup.
| _cmdset_              | Number of _SET_ commands received since server startup.
| _gethits_             | Number of successful _GET_ commands (cache hits) since startup.
| _getmisses_           | Number of failed _GET_ requests, because nothing was cached.
| _evictions_           | Number of objects removed from the cache to free up memory.
| _bytesread_           | Number of bytes received from the network.
| _byteswritten_        | Number of bytes send to the network.
| _threads_             | Number of threads used by this server.
|===

==== Monitor facts

[options="autowidth"]
|===
| Class Name     | `org.opennms.netmgt.poller.monitors.MemcachedMonitor`
| Remote Enabled | true
|===

==== Configuration and Usage

.Monitor specific parameters for the MemcachedMonitor
[options="header, autowidth"]
|===
| Parameter       | Description                                                                    | Required | Default value
| `timeout`       | Timeout in milliseconds for Memcached connection establishment.                | optional | `3000`
| `retry`         | Number of attempts to establish the Memcached connnection.                     | optional | `0`
| `port`          | TCP port connecting to Memcached.                                              | optional | `11211`
|===

==== Examples

The following example shows a configuration in the 'poller-configuration.xml'.

[source, xml]
----
<service name="Memcached" interval="300000" user-defined="false" status="on">
  <parameter key="port" value="11211" />
  <parameter key="retry" value="2" />
  <parameter key="timeout" value="3000" />
  <parameter key="rrd-repository" value="/opt/opennms/share/rrd/response" />
  <parameter key="ds-name" value="memcached" />
  <parameter key="rrd-base-name" value="memcached" />
</service>

<monitor service="Memcached" class-name="org.opennms.netmgt.poller.monitors.MemcachedMonitor" />
----

=== MemcachedMonitor

==== Monitor facts

[options="autowidth"]
|===
| Class Name     | `org.opennms.netmgt.poller.monitors.MemcachedMonitor`
| Remote Enabled | true
|===

==== Configuration and Usage

.Monitor specific parameters for the MemcachedMonitor
[options="header, autowidth"]
|===
| Parameter       | Description                                                                    | Required | Default value
| `timeout`       | Timeout in milliseconds for Memcached connection establishment.                | optional | `3000`
| `retry`         | Number of attempts to establish the Memcached connnection.                     | optional | `0`
| `port`          | TCP port connecting to Memcached.                                              | optional | `11211`
|===

==== Examples

[source, xml]
----
<service name="SSH" interval="300000" user-defined="false" status="on">
  <parameter key="retry" value="1"/>
  <parameter key="banner" value="SSH"/>
  <parameter key="client-banner" value="OpenNMS poller"/>
  <parameter key="timeout" value="5000"/>
  <parameter key="rrd-repository" value="/var/lib/opennms/rrd/response"/>
  <parameter key="rrd-base-name" value="ssh"/>
  <parameter key="ds-name" value="ssh"/>
</service>
<monitor service="SSH" class-name="org.opennms.netmgt.poller.monitors.SshMonitor"/>
----


Update 2017-07-21-101-Tips-To-Improve-Your-Relationship.adoc

= 101 Tips To Improve Your Relationship
:hp-image: https://user-images.githubusercontent.com/19504323/34144297-e38e3492-e4cb-11e7-939e-27d271d97f4d.png
:published_at: 2017-07-21
:hp-tags: tips, relationship
:hp-alt-title: 101 Tips To Improve Your Relationship
:linkattrs:

Being part of a couple is hard, but the best relationship tips are really all about maintenance. You’ve got to keep things fresh, find time for each other, and come up with ways to navigate the tricky ups and downs every partnership faces. That all sounds a lot easier than it really is, so we’ve come up with 101 ways to make your relationship even better.

From how to deal with jealousy to how to get over a potentially deadly lull, we’ve got 101 relationship tips that you can start implementing right now.

Also Read: http://amzn.to/2CCdNo4[How to Be an Adult in Relationships: The Five Keys to Mindful Loving^]

1. Listen.
It might sound obvious, but when you really allow yourself to listen—and ask questions about—what your partner says, it not only leads to better conversations, but also better communication.
2. Take a few days apart.
Missing each other is a great way to reconnect. Try grabbing some girlfriends for an overnight or a weekend getaway every few months.
3. Find a support team.
Have a handful of great friends or family members you can call so your significant other doesn’t have to hear every small grievance going on your life.
MORE: 9 Things Every Woman Deserves in a Relationship
4. Put away your phones.
One of the biggest relationship tips is to give your undivided attention when your partner is speaking. It’s is one of the most important things you can do.
5. Volunteer together.
Giving back is a great way to keep perspective of how great your relationship is, and how lucky you both are.
6. Create a checklist.
Jot down new and fun things you want to accomplish for a day as a duo.
7. Talk to couples over 65 years old.
Get relationship tips from them, and see what you can take away to apply to your relationship.
8. Stop and appreciate all that your relationship is this very second.
Stop living for what it can be.  This person is choosing to be in your life every day, not every day in the future.
9. Revisit the questions you asked in the beginning.
What are you hoping to accomplish in the next year? What are you scared of? These answers change, so we need to keep asking these questions.
. Find 10 things you really love about them and tell them.
Guys need confidence boosters, too!
. Stop nagging.
Seriously, stop. Take a step back and figure out the big things about your partner that truly bother you, and approach them from a place of concern and support instead of nitpicking for sport. That’ll get you nowhere.
. Get over needing to be right.
Learning to say “I was wrong” is a skill worth learning.
. Take care of yourself.
No relationship can be successful if you don’t feel good about yourself, both inside and out.
. Know what you need and then ask for it.
You’re dating a human, not a magical psychic.
. Take a class.
It’s proven that couples who learn together connect deeper. Find some common ground (cooking? art? science?) and go from there.
. Stop complicating things that aren’t complicated enough.
Don’t pull a Carrie Bradshaw during the Aiden years: If you bemoan the fact that your relationship is going too well, you might need to revisit why you’re constantly seeking out drama.
. Assume that if something was said that hurt your feelings, it wasn’t intended that way.
Why would they want to upset you or hurt you? Give your partner the benefit of the doubt, but if it’s really bothering you, don’t be afraid to bring it up.
. Write notes.
Whether you have study hall together or live together, handwritten notes are personal touches in today’s highly digital world.
. Pitch in.
Help each other with chores and other necessary, if banal, activities — cooking, cleaning, re-organizing, etc. Not doing them if you live together can create tension, and always doing them can create unfair expectations. Act as team of equals.
. Disconnect.
Step away from the laptop during quality time. Everything on the Internet will still be there later.
MORE: The Best Short-Lived Celebrity Relationships of 2016
. Allow things to be what they are.
Sometimes bad days and bad moods happen. Don’t go crazy trying to make everything better. Just be supportive and loving, because just being there at the end of a bad day can make it better for both of you.
. Create mini-traditions.
Creating small rituals can really help hold up a couple because they become “your thing.” Whether it’s a fancy night out during the holiday season, or watching a certain show every week, these are things that’ll give you both something to look forward to, and it’ll bring you closer together.
. Be an open book.
They can either deal with it or they can’t, but if you can’t be your most honest self with this person, it’ll come out eventually.
. Compliment, and often.
You’re there to make each other feel like your best selves, so let the genuine praise flow freely. Like his outfit? Tell him! Like her hair today? Let her know!
. Make promises that you really can keep.
Say things that you want to follow through with out loud. It’ll make you work harder to make them happen. Having—and setting—levels of reasonable expectations for your relationship is a healthy way to keep it strong.
. Acknowledge positive actions.
When you and your partner see positive actions, solutions, or behavior in one another, acknowledge it and remind each other to keep it up.
. Establish genuine connections with the other’s friends and family.
Hang out together with both of your friends and family. This is the stuff that makes the world go ’round, people!
. Pay attention to the tiny things that bother your partner, and if it’s painless for you, work to change them.
We’re not talking changing your laugh or your style, but if you know that your partner really hates it when you leave the kitchen counter cluttered, try to make a point of clearing it off before he gets home. It’s an easy enough thing to do and it makes their day better, so why not?
. Never, never forget to ask about the other person’s day.
It’s such an easy slight to avoid!
. Only one person gets to have the bad day.
If your partner’s day sucked and yours was just “eh,” let them have the pity (and the control of the remote, and the choice of take-out). If it’s you, announce it early and let them know you need the support. If it’s a toss-up, trade stories about why your days were so awful and you’ll end up laughing while trying to figure out who wins.
. Small gifts go a long way.
Bringing home a pack of their favorite candy/magazine/book by a favorite author never gets old.
. Graham Parsons has a song lyric that says “I just want to hold you, I don’t want to hold you down.”
Let that be your motto when you’re giving your partner advice.
. Log onto Instagram and like all their photos.
Just because.
. Plan a date where you revisit the spot you went on your first date.
Remember all the amazing things that brought you from then to now.
. Go on a walk together somewhere beautiful.
And don’t forget to turn off your cell phones.
. Surprise them with dinner.
One unexpected night, surprise your partner with a home-cooked meal, and a nicely-set table.
. Review your top five favorite funny things your partner has done.
Because your partner is funny! That’s part of why you like them.
. Go to a yoga class together.
Or other exercise class together. Your body and relationship will thank you!
. Go on a road trip, even if you’re not going anywhere far.
It’s nice to get out of town sometimes.
. Pick up a six-pack of toilet paper or (even better) a six-pack of beer.
Without even being asked.
. Keep the surprises coming.
Think of your relationship as a creative challenge. To keep the romance fresh, come up with new date ideas, new sex positions, and new ways to demonstrate your love.
. Plan small outings.
Whether its brunch this weekend, or a trip to a new neighborhood.
. Make out.
Kissing is something that is often set to the side the longer a couple has been together. Out of blue one day, initiate a high-school style make-out session.
. Let it go.
Don’t hold onto that thing your lover said or did six months ago and bring it up each time you get mad at him. Do both of you a favor and let it go
. Don’t interrupt.
Even if what you think your significant other is saying is uninteresting, don’t bulldoze over his or her words. Being able to listen to each other—even when the details are mundane—is important.
. Say thanks.
Let him know that you notice the little things he does by saying thank you for routine tasks like walking the dog or picking up groceries.
. Cook a meal together.
Come up with a menu, shop, and prepare the food together.
. Have fun with hypotheticals.
Conversation can become routine. Break from the ordinary and have a silly dinner conversation made entirely of imaginary situations—for example, “If you were on an island and could only bring five movies, which movies would you bring?
. Keep a couple’s journal.
Write down your desires and fantasies and leave them out for your significant other to find—encourage him to write back.
. Agree to disagree.
This is one of the most important relationship tips, as you both have strong opinions and therefore some issues will never be resolved. Respect each other’s point of view and agree not to argue about the same issue, unless it’s something that could get in the way of your future, like politics, religion, or values.+++

+++
. Set goals.
In addition to setting life goals, set relationship goals. For example: We aim to spend more time together outside rather than in front of the TV.
. Take responsibility for your own happiness
Love is grand, but at the end of the day the only person we can hold accountable for our happiness is ourselves. Do volunteer work, exercise, host dinner parties—find what satisfies you, and go from there.
MORE: WTF! Taylor Swift Has Never Walked a Red Carpet with a Boyfriend
. Learn each other’s conflict habits.
Make an effort to understand you and your partner’s conflict habits so you can break bad patterns and find a middle ground that’s productive and respectful.
. Define love.
While “I love you,” is an extraordinary thing to say—and an equally wonderful thing to hear—it means something different to each person. Tell each other what you’re saying when you declare these magic words. It could be a list of many sentiments such as, “I would do anything for you,” and “I trust you completely.”
. Take turns planning date nights that are actual, real, capital-D Dates
Takeout and TV doesn’t count.
. Approach your partner’s issues in the context of how they affect the relationship.
It’ll reduce the chances they feel personally attacked for no reason.
. Cuddle.
Make ample time for cuddling. Whether or not it leads to sex, physical affection is important.
. Don’t forget to say “I Like You.”
The greatest compliment you can give a partner (especially a long-term partner) is reminding them that not only do you love them, but also like them.
. Have a spontaneous midday tryst.
Send him a text as he’s about to go on his lunch break, take time out on a Saturday, however you want to play it.
Photo: Imaxtree
Photo: Imaxtree
. Travel together.
Seeing the world together creates amazing shared memories.
. Tell them EXACTLY why you love and appreciate them as often as possible.
“I love you” is good. “I love the way you make sure no one ever feels left out” is even better.
. Stay out of their family drama.
It’s so not worth it.
. Really look at each other.
We spend a lot of time with our partners but sometimes we don’t actually see them. Take the time to actually look into one another’s eyes.
. Give each other a pet name.
It may be super annoying to other people (and you may want to reserve it for when you’re in private), but a pet name can add an extra layer of intimacy to your relationship.
. Spend time alone.
As important as it is to spend quality time with your partner, it’s equally necessary that you develop a good sense of who you are without them. Kahlil Gibran said “let there be spaces in your togetherness,” and we stand by that.
. Eat at the dinner table.
Do you eat in front of the TV? Try actually sitting down to a meal with your partner at an actual table. You may find it a welcome change.
. In fact, turn the TV off all together.
Why not try instituting a TV-free night in your apartment? See what else happens when you spend time together sans the talking box.
. Ask for clarity.
If you’re confused about what your partner means, ask for clarity instead of making assumptions about what they mean. Use an open phrase like, “What did you mean when you said, ‘xyz'” rather than instantly going on the offensive.
. Own your feelings.
Passive-aggressiveness is a total relationship killer. Quash it by practicing assertiveness and clarity. Saying “I’m fine” when you’re not fine is a prime example of not owning your feelings.
. Communicate in a constructive way.
For instance, we think the phrase construction “When ____ happens, it makes me feel ____” can be particularly helpful.
. Take an interest in what your partner’s into.
He’s into chess, or cheese, or cheese that looks like a chess board (maybe?). You don’t have to love it, but give it a shot. You may surprise yourself!
. But also cultivate your own.
You and your partner don’t need to have everything in common. Seriously. That’s actually really annoying.
. Let your partner teach you something they’re good at, and vice versa.
Everyone—everyone—loves the feeling of being able to teach somebody they like about something they’re good at.
. Bring your groups together.
It’s easy to silo your social lives and create separate his-and-hers worlds, but bringing your friends, siblings, or colleagues together can be a fun thing.
. Don’t forget about sex.
Work, stress, and other responsibilities can get in the way of your sex life, and before you know it, you’ve gone a month without getting busy. Don’t let this happen. Schedule it in if you have to, just make sure to connect in an intimate way.
. But do forget about jealousy.
Jealousy can be completely toxic to relationships, so keep yours in check. If you’re always jealous, figure out if it’s your personal issue, or if your partner is doing things to appear less trustworthy.
. Cultivate your appreciation.
Spread what you love about your partner. Practice your appreciation by sharing it with others— not in a gross, gratuitous, braggy way, but don’t miss out on the opportunity to tell others why your partner is awesome. In turn, it’ll remind you why you like them, too.
. Laugh. In bed.
Sex should be sexy, sure. But it should also be fun. Don’t be afraid to have a laugh if things take a turn for the ridiculous.
. Let yourself be taken care of when you need it.We all need special care on occasion. Let your partner help you when you’re feeling sick or down. It doesn’t mean you’re not strong, it just means you’re willing to accept help.
. Check your competitive edge.
You and your partner are there to support each other, not compete with one another. If you find yourself comparing yourself or competing with your significant other, check your behavior. That’s not healthy!
. Have a bed day.
Allow yourselves a totally lazy day where you lie around and do nothing of note except enjoy each other’s company.
. Be kind to yourself.
The best way to develop positive patterns in a relationship is to develop them first with yourself. Don’t be so critical of yourself, and you’ll set a good example for your relationship.
. Express gratitude for the little things, and for specific things.
Big gestures are great, but it’s great to recognize the little things your partner does that make you feel happy and loved, too.
Photo: Getty Images
Photo: Getty Images
. Date like you dated in high school.
Ask each other out. Get excited. Take forever to get ready. Make out. Repeat.
. Be present.
We can ruin a perfectly great relationship by focusing too much on the past, or worrying too much about what may happen in the future. Learn to enjoy where you are, and who you’re with right now.
. Don’t try to control.
A relationship isn’t a battle of wills, it’s two people who are choosing to be together, so don’t treat your partner like they’re some kind of wild animal you’re trying to tame.
. Embrace your common goals.
What is it that you both want to accomplish? Can you support each other to reach those goals? That’ll be a big piece of what will hold you two to together as a couple in the long run.
. Have a cultural experience together.
See a movie, a play, or an art exhibition together — and then talk about them afterward. You may be pleasantly surprised by how differently—or similarly—you viewed things.
. Go on a long bike ride.
Bike rides are deeply freeing experiences, and it’s nice to be able to do that with someone you love.
. Try talking on the phone. Yes, we know this sounds crazy, but phone calls are a different sort of communication than texting, or even in person communicating will allow. You may actually deepen your connection through a phone chat.
. Make a mix for each other. It’s cute, romantic and something out of a rom-com. Although in this day and age, you might want to make a Spotify playlist rather than a mixed CD.
. Keep yourself in check. We spend so much time paying attention to how our partners behave, but take a second to notice how you’re acting — especially if you’re fired up or in a bad mood. And then give yourself a second to…
. Breathe. Before you say something you don’t mean, take a breath and ask yourself if that’s really the way you want to move forward. Chances are, taking a second out will help you recalibrate and think of a more constructive way of handling the situation.
. Help each other. This one is so easy, but if your partner’s having a hard time with something — whether it’s doing their taxes or organizing their closet — offer a helping hand.
. Be their biggest cheerleader. If your partner’s accomplished something amazing, let them know it, and let them shine.
. In your craziest moments of frustration or anger, remember what it is that you like about them the most. There’s a reason you’re with them after all, right?
. Remember that a relationship should always make your life better on the whole, not worse. And aim to make sure yours is doing just that. If it’s not, it may be time to reconsider.
. Enjoy the quiet moments you spend with each other. Not everything has to be a big adventure or a big deal Sometimes the best times are the quiet unplanned things you do together.
. Make sure you’re taking care of yourself. Don’t let yourself get so invested in your partner that you forget to take care of yourself.
. Let go of the past. We often let our past hurts dictate our present. Learn to let go of past resentments and fears in order to live more fully with your partner right now.
100. Touch each other often. Simple touch builds intimacy — espeically non-sexual touch. It’s a non-verbal way of saying, “yes, I’m here for you, and I care about you” and it helps reinforce your emotional bond.
101. The best relationships are ones in which both partners feel like the luckiest person in the world. Find ways to communicate that and foster that feeling in each other, and you’ll be good.

= 101 Tips To Improve Your Relationship
:hp-image: https://user-images.githubusercontent.com/19504323/34144297-e38e3492-e4cb-11e7-939e-27d271d97f4d.png
:published_at: 2017-07-21
:hp-tags: tips, relationship
:hp-alt-title: 101 Tips To Improve Your Relationship
:linkattrs:

Being part of a couple is hard, but the best relationship tips are really all about maintenance. You’ve got to keep things fresh, find time for each other, and come up with ways to navigate the tricky ups and downs every partnership faces. That all sounds a lot easier than it really is, so we’ve come up with 101 ways to make your relationship even better.

From how to deal with jealousy to how to get over a potentially deadly lull, we’ve got 101 relationship tips that you can start implementing right now.

Also Read: http://amzn.to/2CCdNo4[How to Be an Adult in Relationships: The Five Keys to Mindful Loving^]

1. Listen.
It might sound obvious, but when you really allow yourself to listen—and ask questions about—what your partner says, it not only leads to better conversations, but also better communication.
2. Take a few days apart.
Missing each other is a great way to reconnect. Try grabbing some girlfriends for an overnight or a weekend getaway every few months.
3. Find a support team.
Have a handful of great friends or family members you can call so your significant other doesn’t have to hear every small grievance going on your life.
MORE: 9 Things Every Woman Deserves in a Relationship
4. Put away your phones.
One of the biggest relationship tips is to give your undivided attention when your partner is speaking. It’s is one of the most important things you can do.
5. Volunteer together.
Giving back is a great way to keep perspective of how great your relationship is, and how lucky you both are.
6. Create a checklist.
Jot down new and fun things you want to accomplish for a day as a duo.
7. Talk to couples over 65 years old.
Get relationship tips from them, and see what you can take away to apply to your relationship.
8. Stop and appreciate all that your relationship is this very second.
Stop living for what it can be.  This person is choosing to be in your life every day, not every day in the future.
9. Revisit the questions you asked in the beginning.
What are you hoping to accomplish in the next year? What are you scared of? These answers change, so we need to keep asking these questions.
10. Find 10 things you really love about them and tell them.
Guys need confidence boosters, too!
11. Stop nagging.
Seriously, stop. Take a step back and figure out the big things about your partner that truly bother you, and approach them from a place of concern and support instead of nitpicking for sport. That’ll get you nowhere.
12. Get over needing to be right.
Learning to say “I was wrong” is a skill worth learning.
13. Take care of yourself.
No relationship can be successful if you don’t feel good about yourself, both inside and out.
14. Know what you need and then ask for it.
You’re dating a human, not a magical psychic.
15. Take a class.
It’s proven that couples who learn together connect deeper. Find some common ground (cooking? art? science?) and go from there.
16. Stop complicating things that aren’t complicated enough.
Don’t pull a Carrie Bradshaw during the Aiden years: If you bemoan the fact that your relationship is going too well, you might need to revisit why you’re constantly seeking out drama.
17. Assume that if something was said that hurt your feelings, it wasn’t intended that way.
Why would they want to upset you or hurt you? Give your partner the benefit of the doubt, but if it’s really bothering you, don’t be afraid to bring it up.
18. Write notes.
Whether you have study hall together or live together, handwritten notes are personal touches in today’s highly digital world.
19. Pitch in.
Help each other with chores and other necessary, if banal, activities — cooking, cleaning, re-organizing, etc. Not doing them if you live together can create tension, and always doing them can create unfair expectations. Act as team of equals.
20. Disconnect.
Step away from the laptop during quality time. Everything on the Internet will still be there later.
MORE: The Best Short-Lived Celebrity Relationships of 2016
21. Allow things to be what they are.
Sometimes bad days and bad moods happen. Don’t go crazy trying to make everything better. Just be supportive and loving, because just being there at the end of a bad day can make it better for both of you.
22. Create mini-traditions.
Creating small rituals can really help hold up a couple because they become “your thing.” Whether it’s a fancy night out during the holiday season, or watching a certain show every week, these are things that’ll give you both something to look forward to, and it’ll bring you closer together.
23. Be an open book.
They can either deal with it or they can’t, but if you can’t be your most honest self with this person, it’ll come out eventually.
24. Compliment, and often.
You’re there to make each other feel like your best selves, so let the genuine praise flow freely. Like his outfit? Tell him! Like her hair today? Let her know!
25. Make promises that you really can keep.
Say things that you want to follow through with out loud. It’ll make you work harder to make them happen. Having—and setting—levels of reasonable expectations for your relationship is a healthy way to keep it strong.
26. Acknowledge positive actions.
When you and your partner see positive actions, solutions, or behavior in one another, acknowledge it and remind each other to keep it up.
27. Establish genuine connections with the other’s friends and family.
Hang out together with both of your friends and family. This is the stuff that makes the world go ’round, people!
28. Pay attention to the tiny things that bother your partner, and if it’s painless for you, work to change them.
We’re not talking changing your laugh or your style, but if you know that your partner really hates it when you leave the kitchen counter cluttered, try to make a point of clearing it off before he gets home. It’s an easy enough thing to do and it makes their day better, so why not?
29. Never, never forget to ask about the other person’s day.
It’s such an easy slight to avoid!
30. Only one person gets to have the bad day.
If your partner’s day sucked and yours was just “eh,” let them have the pity (and the control of the remote, and the choice of take-out). If it’s you, announce it early and let them know you need the support. If it’s a toss-up, trade stories about why your days were so awful and you’ll end up laughing while trying to figure out who wins.
31. Small gifts go a long way.
Bringing home a pack of their favorite candy/magazine/book by a favorite author never gets old.
32. Graham Parsons has a song lyric that says “I just want to hold you, I don’t want to hold you down.”
Let that be your motto when you’re giving your partner advice.
33. Log onto Instagram and like all their photos.
Just because.
34. Plan a date where you revisit the spot you went on your first date.
Remember all the amazing things that brought you from then to now.
35. Go on a walk together somewhere beautiful.
And don’t forget to turn off your cell phones.
36. Surprise them with dinner.
One unexpected night, surprise your partner with a home-cooked meal, and a nicely-set table.
37. Review your top five favorite funny things your partner has done.
Because your partner is funny! That’s part of why you like them.
38. Go to a yoga class together.
Or other exercise class together. Your body and relationship will thank you!
39. Go on a road trip, even if you’re not going anywhere far.
It’s nice to get out of town sometimes.
40. Pick up a six-pack of toilet paper or (even better) a six-pack of beer.
Without even being asked.
41. Keep the surprises coming.
Think of your relationship as a creative challenge. To keep the romance fresh, come up with new date ideas, new sex positions, and new ways to demonstrate your love.
42. Plan small outings.
Whether its brunch this weekend, or a trip to a new neighborhood.
43. Make out.
Kissing is something that is often set to the side the longer a couple has been together. Out of blue one day, initiate a high-school style make-out session.
44. Let it go.
Don’t hold onto that thing your lover said or did six months ago and bring it up each time you get mad at him. Do both of you a favor and let it go
45. Don’t interrupt.
Even if what you think your significant other is saying is uninteresting, don’t bulldoze over his or her words. Being able to listen to each other—even when the details are mundane—is important.
46. Say thanks.
Let him know that you notice the little things he does by saying thank you for routine tasks like walking the dog or picking up groceries.
47. Cook a meal together.
Come up with a menu, shop, and prepare the food together.
48. Have fun with hypotheticals.
Conversation can become routine. Break from the ordinary and have a silly dinner conversation made entirely of imaginary situations—for example, “If you were on an island and could only bring five movies, which movies would you bring?
49. Keep a couple’s journal.
Write down your desires and fantasies and leave them out for your significant other to find—encourage him to write back.
50. Agree to disagree.
This is one of the most important relationship tips, as you both have strong opinions and therefore some issues will never be resolved. Respect each other’s point of view and agree not to argue about the same issue, unless it’s something that could get in the way of your future, like politics, religion, or values.+++

+++
51. Set goals.
In addition to setting life goals, set relationship goals. For example: We aim to spend more time together outside rather than in front of the TV.
52. Take responsibility for your own happiness
Love is grand, but at the end of the day the only person we can hold accountable for our happiness is ourselves. Do volunteer work, exercise, host dinner parties—find what satisfies you, and go from there.
MORE: WTF! Taylor Swift Has Never Walked a Red Carpet with a Boyfriend
53. Learn each other’s conflict habits.
Make an effort to understand you and your partner’s conflict habits so you can break bad patterns and find a middle ground that’s productive and respectful.
54. Define love.
While “I love you,” is an extraordinary thing to say—and an equally wonderful thing to hear—it means something different to each person. Tell each other what you’re saying when you declare these magic words. It could be a list of many sentiments such as, “I would do anything for you,” and “I trust you completely.”
55. Take turns planning date nights that are actual, real, capital-D Dates
Takeout and TV doesn’t count.
56. Approach your partner’s issues in the context of how they affect the relationship.
It’ll reduce the chances they feel personally attacked for no reason.
57. Cuddle.
Make ample time for cuddling. Whether or not it leads to sex, physical affection is important.
58. Don’t forget to say “I Like You.”
The greatest compliment you can give a partner (especially a long-term partner) is reminding them that not only do you love them, but also like them.
59. Have a spontaneous midday tryst.
Send him a text as he’s about to go on his lunch break, take time out on a Saturday, however you want to play it.
Photo: Imaxtree
Photo: Imaxtree
60. Travel together.
Seeing the world together creates amazing shared memories.
61. Tell them EXACTLY why you love and appreciate them as often as possible.
“I love you” is good. “I love the way you make sure no one ever feels left out” is even better.
62. Stay out of their family drama.
It’s so not worth it.
63. Really look at each other.
We spend a lot of time with our partners but sometimes we don’t actually see them. Take the time to actually look into one another’s eyes.
64. Give each other a pet name.
It may be super annoying to other people (and you may want to reserve it for when you’re in private), but a pet name can add an extra layer of intimacy to your relationship.
65. Spend time alone.
As important as it is to spend quality time with your partner, it’s equally necessary that you develop a good sense of who you are without them. Kahlil Gibran said “let there be spaces in your togetherness,” and we stand by that.
66. Eat at the dinner table.
Do you eat in front of the TV? Try actually sitting down to a meal with your partner at an actual table. You may find it a welcome change.
67. In fact, turn the TV off all together.
Why not try instituting a TV-free night in your apartment? See what else happens when you spend time together sans the talking box.
68. Ask for clarity.
If you’re confused about what your partner means, ask for clarity instead of making assumptions about what they mean. Use an open phrase like, “What did you mean when you said, ‘xyz'” rather than instantly going on the offensive.
69. Own your feelings.
Passive-aggressiveness is a total relationship killer. Quash it by practicing assertiveness and clarity. Saying “I’m fine” when you’re not fine is a prime example of not owning your feelings.
70. Communicate in a constructive way.
For instance, we think the phrase construction “When ____ happens, it makes me feel ____” can be particularly helpful.
71. Take an interest in what your partner’s into.
He’s into chess, or cheese, or cheese that looks like a chess board (maybe?). You don’t have to love it, but give it a shot. You may surprise yourself!
72. But also cultivate your own.
You and your partner don’t need to have everything in common. Seriously. That’s actually really annoying.
73. Let your partner teach you something they’re good at, and vice versa.
Everyone—everyone—loves the feeling of being able to teach somebody they like about something they’re good at.
74. Bring your groups together.
It’s easy to silo your social lives and create separate his-and-hers worlds, but bringing your friends, siblings, or colleagues together can be a fun thing.
75. Don’t forget about sex.
Work, stress, and other responsibilities can get in the way of your sex life, and before you know it, you’ve gone a month without getting busy. Don’t let this happen. Schedule it in if you have to, just make sure to connect in an intimate way.
76. But do forget about jealousy.
Jealousy can be completely toxic to relationships, so keep yours in check. If you’re always jealous, figure out if it’s your personal issue, or if your partner is doing things to appear less trustworthy.
77. Cultivate your appreciation.
Spread what you love about your partner. Practice your appreciation by sharing it with others— not in a gross, gratuitous, braggy way, but don’t miss out on the opportunity to tell others why your partner is awesome. In turn, it’ll remind you why you like them, too.
78. Laugh. In bed.
Sex should be sexy, sure. But it should also be fun. Don’t be afraid to have a laugh if things take a turn for the ridiculous.
79. Let yourself be taken care of when you need it.We all need special care on occasion. Let your partner help you when you’re feeling sick or down. It doesn’t mean you’re not strong, it just means you’re willing to accept help.
80. Check your competitive edge.
You and your partner are there to support each other, not compete with one another. If you find yourself comparing yourself or competing with your significant other, check your behavior. That’s not healthy!
81. Have a bed day.
Allow yourselves a totally lazy day where you lie around and do nothing of note except enjoy each other’s company.
81. Be kind to yourself.
The best way to develop positive patterns in a relationship is to develop them first with yourself. Don’t be so critical of yourself, and you’ll set a good example for your relationship.
82. Express gratitude for the little things, and for specific things.
Big gestures are great, but it’s great to recognize the little things your partner does that make you feel happy and loved, too.
Photo: Getty Images
Photo: Getty Images
83. Date like you dated in high school.
Ask each other out. Get excited. Take forever to get ready. Make out. Repeat.
84. Be present.
We can ruin a perfectly great relationship by focusing too much on the past, or worrying too much about what may happen in the future. Learn to enjoy where you are, and who you’re with right now.
85. Don’t try to control.
A relationship isn’t a battle of wills, it’s two people who are choosing to be together, so don’t treat your partner like they’re some kind of wild animal you’re trying to tame.
86. Embrace your common goals.
What is it that you both want to accomplish? Can you support each other to reach those goals? That’ll be a big piece of what will hold you two to together as a couple in the long run.
87. Have a cultural experience together.
See a movie, a play, or an art exhibition together — and then talk about them afterward. You may be pleasantly surprised by how differently—or similarly—you viewed things.
88. Go on a long bike ride.
Bike rides are deeply freeing experiences, and it’s nice to be able to do that with someone you love.
89. Try talking on the phone.
Yes, we know this sounds crazy, but phone calls are a different sort of communication than texting, or even in person communicating will allow. You may actually deepen your connection through a phone chat.
90. Make a mix for each other.
It’s cute, romantic and something out of a rom-com. Although in this day and age, you might want to make a Spotify playlist rather than a mixed CD.
91. Keep yourself in check.
We spend so much time paying attention to how our partners behave, but take a second to notice how you’re acting — especially if you’re fired up or in a bad mood. And then give yourself a second to…
92. … Breathe.
Before you say something you don’t mean, take a breath and ask yourself if that’s really the way you want to move forward. Chances are, taking a second out will help you recalibrate and think of a more constructive way of handling the situation.
93. Help each other.
This one is so easy, but if your partner’s having a hard time with something — whether it’s doing their taxes or organizing their closet — offer a helping hand.
94. Be their biggest cheerleader
If your partner’s accomplished something amazing, let them know it, and let them shine.
95. In your craziest moments of frustration or anger, remember what it is that you like about them the most.
There’s a reason you’re with them after all, right?
96. Remember that a relationship should always make your life better on the whole, not worse.
And aim to make sure yours is doing just that. If it’s not, it may be time to reconsider.
97. Enjoy the quiet moments you spend with each other.
Not everything has to be a big adventure or a big deal Sometimes the best times are the quiet unplanned things you do together.
98. Make sure you’re taking care of yourself.
Don’t let yourself get so invested in your partner that you forget to take care of yourself.
99. Let go of the past.
We often let our past hurts dictate our present. Learn to let go of past resentments and fears in order to live more fully with your partner right now.
100. Touch each other often.
Simple touch builds intimacy — espeically non-sexual touch. It’s a non-verbal way of saying, “yes, I’m here for you, and I care about you” and it helps reinforce your emotional bond.
101. The best relationships are ones in which both partners feel like the luckiest person in the world.
Find ways to communicate that and foster that feeling in each other, and you’ll be good.