text:
/*********************************************************************/
/*                                                                   */
/*             Optimized BLAS libraries                              */
/*                     By Kazushige Goto <kgoto@tacc.utexas.edu>     */
/*                                                                   */
/* Copyright (c) The University of Texas, 2009. All rights reserved. */
/* UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING  */
/* THIS SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF      */
/* MERCHANTABILITY, FITNESS FOR ANY PARTICULAR PURPOSE,              */
/* NON-INFRINGEMENT AND WARRANTIES OF PERFORMANCE, AND ANY WARRANTY  */
/* THAT MIGHT OTHERWISE ARISE FROM COURSE OF DEALING OR USAGE OF     */
/* TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH RESPECT TO   */
/* THE USE OF THE SOFTWARE OR DOCUMENTATION.                         */
/* Under no circumstances shall University be liable for incidental, */
/* special, indirect, direct or consequential damages or loss of     */
/* profits, interruption of business, or related expenses which may  */
/* arise from use of Software or Documentation, including but not    */
/* limited to those resulting from defects in Software and/or        */
/* Documentation, or loss or inaccuracy of data of any kind.         */
/*********************************************************************/

#include <stdio.h>
#include "common.h"
#ifdef FUNCTION_PROFILE
#include "functable.h"
#endif

#ifndef CBLAS

FLOATRET NAME(blasint *N, FLOAT *a, FLOAT *x, blasint *INCX, FLOAT *y, blasint *INCY){

  BLASLONG n    = *N;
  BLASLONG incx = *INCX;
  BLASLONG incy = *INCY;
  FLOATRET ret;

  PRINT_DEBUG_NAME;

  if (n <= 0) return 0.;

  IDEBUG_START;

  FUNCTION_PROFILE_START();

  if (incx < 0) x -= (n - 1) * incx;
  if (incy < 0) y -= (n - 1) * incy;

  ret = (FLOATRET)(SDSDOT_K(n, x, incx, y, incy) + *a);

  FUNCTION_PROFILE_END(1, 2 * n, 2 * n);

  IDEBUG_END;

  return ret;

}

#else

FLOAT CNAME(blasint n, FLOAT alpha, FLOAT *x, blasint incx, FLOAT *y, blasint incy){

  FLOAT ret;

  PRINT_DEBUG_CNAME;

  if (n <= 0) return 0.;

  IDEBUG_START;

  FUNCTION_PROFILE_START();

  if (incx < 0) x -= (n - 1) * incx;
  if (incy < 0) y -= (n - 1) * incy;

  ret = SDSDOT_K(n, x, incx, y, incy) + alpha;

  FUNCTION_PROFILE_END(1, 2 * n, 2 * n);

  IDEBUG_END;

  return ret;
}

#endif


text:
tags:
  - sharing
  - open-data
author:
  display_name: UGRC Office
  email: ugrc@utah.gov
date: 2020-01-13 17:00:00
title: Submitting Data to the SGID Open Data Site
categories: []
---

ArcGIS Online items are added to [SGID Open Data]({% link sgid/index.html %}#sgid-open-data-site) by sharing them with one of our SGID groups in ArcGIS Online. This process gives both you and UGRC a chance to review the quality of the item before it is shared. We reserve the right to remove items from SGID Open Data if they don't go through this process.

We use [issues](https://guides.github.com/features/issues/) in our [Porter](https://github.com/agrc/porter/issues) repository on GitHub to track a dataset's progress in the submission process and to keep an open and transparent record of everything that happened.

<!-- If you've never used GitHub issues before, click here to watch a short tutorial (TBA) about creating an issue. -->

If you've still got questions after reading this, {% include contact.html subject="SGID Data Additions" contact=site.data.contacts.sgid text='reach out to ' hide-punctuation=true %}; or you can contact anyone else on the [UGRC team]({% link about/contact/index.html %}).

### Step 1: 📋 Qualifications (You)
{: .text-left}

First, make sure your dataset meets the SGID qualifications:

- [General qualifications]({% link about/policy/sgid/index.md %}#general-qualifications)
- [SGID Open Data-specific qualifications]({% link about/policy/sgid/index.md %}#sgid-open-data-qualifications)

### Step 2: ✏ Data Preparation (You)
{: .text-left}

SGID Open Data relies on a lot of information from the source ArcGIS Online item:

![An annotated Open Data item]({% link images/od_card_anno.png %}){: .flex .flex--center loading="lazy" }

As noted in the qualifications, make sure the following items are taken care of:

- The ArcGIS Online item is publicly shared
- The item has a good title, description, and tags
- The `Allow others to export data to different formats` in the `Settings` tab is enabled (if possible)
- The `source` value should be set using the method described below

##### Setting the SGID Open Data "Source"

SGID Open Data displays the `source` value on each item and also uses it to sort search results. Thus, it's important for every organization to have a single, unified `source`. Esri explains where this value comes from [in this FAQ](https://doc.arcgis.com/en/hub/get-started/frequently-asked-questions.htm#GUID-9843B713-46D2-4938-A961-EC0CD81AE410). Basically, it first searches the ArcGIS Online item's metadata for an organization name. If it doesn't find anything there, it falls back to your ArcGIS organization name.

If you want to customize the name displayed, we suggest setting it in the `Resource > Citation > Contact > Organization Name` metadata field. Otherwise, just leave the metadata contact fields empty and it will use your ArcGIS Online organization name. We use this second way to show `Utah Automated Geographic Reference Center (AGRC)` as the source for all our datasets.

You may need to go in and remove any values in the metadata contact fields if you just want to use your default organization name.

To edit the organization name in the ArcGIS Online item's metadata, you need to make sure your ArcGIS Online organization has [metadata enabled](https://doc.arcgis.com/en/arcgis-online/administer/configure-details.htm#ESRI_SECTION1_7FE1F060E03046E692BB36E5F6E3B2AE). Then you can use the Metadata editor on the ArcGIS Online item page to set either field:

![Organization name sources in ArcGIS Online metadata]({% link images/od_agol_md.png %}){: .flex .flex--center .outline loading="lazy" }

The way you upload or overwrite your ArcGIS Online data may also overwrite the item's metadata with info from the local source's metadata. We suggest you make any changes in both the feature class and ArcGIS Online metadata to avoid problems in the future. In the FGDC CSDGM metadata style, the `Resource > Citation > Contact > Organization Name` field is in `Overview > Citation Contacts`. The `Resource > Contact > Organization Name` field is in `Resource > Points of Contact`.

### Step 3: 💠 Sharing (You)
{: .text-left}

Once your item is prepared, share it with the [SGID Open Data Staging Group](https://utah.maps.arcgis.com/home/group.html?id=3d3bd0d238f24f45b2c4b84f1015a317#overview) (and request access to the group if you're not already a member). This gives us a place to review items before they make it to SGID Open Data.

### Step 4: 📂 Open an Issue (You)
{: .text-left}

Now that all the preparation work is finished, [submit an issue](https://github.com/agrc/porter/issues/new/choose) in Porter using the `Add ArcGIS Online services to SGID Open Data` template. Fill out the `Summary` information and check the relevant boxes in the `Submitter's Process` section.

### Step 5: 🔎 Review (You and Us)
{: .text-left}

We will review your submission against the qualifications and reach out with any questions. You can track this in the `UGRC's Process` section of the issue. Once everything looks good, we'll send you an invite to the appropriate SGID group if you're not already a member.

### Step 6: 📤 Publish (You)
{: .text-left}

Once we've worked together to resolve any questions or problems, we'll let you know that the item is ready to be added to SGID Open Data. At this point, you'll need to unshare it from the staging group and share it with the appropriate SGID group.

redpajama_set_name: RedPajamaGithub


text:
using UnityEngine;
using System;
using LuaInterface;
using SLua;
using System.Collections.Generic;
public class Lua_UnityEngine_UI_Button_ButtonClickedEvent : LuaObject {
	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static public int constructor(IntPtr l) {
		LuaDLL.lua_remove(l,1);
		UnityEngine.UI.Button.ButtonClickedEvent o;
		if(matchType(l,1)){
			o=new UnityEngine.UI.Button.ButtonClickedEvent();
			pushObject(l,o);
			return 1;
		}
		return 0;
	}
	static public void reg(IntPtr l) {
		getTypeTable(l,"UnityEngine.UI.Button.ButtonClickedEvent");
		newType(l, constructor);
		createTypeMetatable(l, typeof(UnityEngine.UI.Button.ButtonClickedEvent),typeof(UnityEngine.Events.UnityEvent));
		LuaDLL.lua_pop(l, 1);
	}
}


text:
package org.usfirst.frc.team3164.robot.comms;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.usfirst.frc.team3164.robot.electrical.motor.BasicMotor;;

public class Watchcat {
	//private static int timeout;//In ms
	//private static Thread wdTrd;
	//private static WDTask wdTsk;
	public static boolean isRobotDead = false;
	//private static long last;
	private static MotorRegistry mReg;

	public static void init() {
		//timeout = 200;
		//last = new Date().getTime();
		mReg = new MotorRegistry();
		//wdTsk = new WDTask();
		//wdTrd = new Thread(wdTsk);
		//wdTrd.start();
	}

//	private static class WDTask implements Runnable {
//		@Override
//		public void run() {
//			while(true) {
//				long now = new Date().getTime();
//				if(last+timeout <= now) {
//					killRobot();
//				}
//				try {
//					Thread.sleep(10);
//				} catch(Exception ex) {}
//			}
//		}
//	}

	public static class MotorRegistry {
		private Map<UUID, BasicMotor> motors = new HashMap<UUID, BasicMotor>();

		public void addMotor(BasicMotor m) {
			if(!isHere(m)) {
				motors.put(UUID.randomUUID(), m);
			}
		}

		private boolean isHere(BasicMotor m) {
			for(BasicMotor mo : motors.values()) {
				if(m.getLoc() == mo.getLoc()) {
					return true;
				}
			}
			return false;
		}
	}

	public static void killRobot() {
		if(isRobotDead)
			return;
		isRobotDead = true;
		for(BasicMotor m : mReg.motors.values()) {
			m.setDead(true);
		}
	}

	public static void reviveRobot() {
		if(!isRobotDead)
			return;
		isRobotDead = false;
		for(BasicMotor m : mReg.motors.values()) {
			m.setDead(false);
		}
	}

	public static void feed() {
		//last = new Date().getTime();
		reviveRobot();
	}

	public static void registerMotor(BasicMotor m) {
		mReg.addMotor(m);
	}
}


text:
module.exports = function(kernelP) {
  return (function() {
    var Utils = require('../../utils.js');

    var gKernelP = kernelP;

    /**
     * @classdesc
     * Extracts a vocabulary from document collections and generates a {@link CountVectorizerModel}.
     * @class
     * @memberof module:eclairjs/ml/feature
     */

    /**
     * @param {string} uid
     * @constructor
     */
    function CountVectorizer() {
      Utils.handleConstructor(this, arguments, gKernelP);
    }

    /**
     * @param {string} value
     * @returns {module:eclairjs/ml/feature.CountVectorizer}
     */
    CountVectorizer.prototype.setInputCol = function(value) {
      var args = {
        target: this,
        method: 'setInputCol',
        args: Utils.wrapArguments(arguments),
        returnType: CountVectorizer
      };

      return Utils.generate(args);
    };

    /**
     * @param {string} value
     * @returns {module:eclairjs/ml/feature.CountVectorizer}
     */
    CountVectorizer.prototype.setOutputCol = function(value) {
      var args = {
        target: this,
        method: 'setOutputCol',
        args: Utils.wrapArguments(arguments),
        returnType: CountVectorizer
      };

      return Utils.generate(args);
    };

    /**
     * @param {number} value
     * @returns {module:eclairjs/ml/feature.CountVectorizer}
     */
    CountVectorizer.prototype.setVocabSize = function(value) {
      var args = {
        target: this,
        method: 'setVocabSize',
        args: Utils.wrapArguments(arguments),
        returnType: CountVectorizer
      };

      return Utils.generate(args);
    };

    /**
     * @param {number} value
     * @returns {module:eclairjs/ml/feature.CountVectorizer}
     */
    CountVectorizer.prototype.setMinDF = function(value) {
      var args = {
        target: this,
        method: 'setMinDF',
        args: Utils.wrapArguments(arguments),
        returnType: CountVectorizer
      };

      return Utils.generate(args);
    };

    /**
     * @param {number} value
     * @returns {module:eclairjs/ml/feature.CountVectorizer}
     */
    CountVectorizer.prototype.setMinTF = function(value) {
      var args = {
        target: this,
        method: 'setMinTF',
        args: Utils.wrapArguments(arguments),
        returnType: CountVectorizer
      };

      return Utils.generate(args);
    };

    /**
      * @param {boolean} value
      * @returns {type}
      */
     CountVectorizer.prototype.setBinary = function(value) {
       var args ={
         target: this,
         method: 'setBinary',
         args: Utils.wrapArguments(arguments),
         returnType: CountVectorizer

       };

       return Utils.generate(args);
     };

    /**
     * @param {module:eclairjs/sql.Dataset} dataset
     * @returns {module:eclairjs/ml/feature.CountVectorizerModel}
     */
    CountVectorizer.prototype.fit = function(dataset) {
      var CountVectorizerModel = require('./CountVectorizerModel')();
      var args = {
        target: this,
        method: 'fit',
        args: Utils.wrapArguments(arguments),
        returnType: CountVectorizerModel
      };

      return Utils.generate(args);
    };

    /**
     * @param {module:eclairjs/sql/types.StructType} schema
     * @returns {module:eclairjs/sql/types.StructType}
     */
    CountVectorizer.prototype.transformSchema = function(schema) {
      var StructType = require('../../sql/types/StructType.js')();

      var args = {
        target: this,
        method: 'transformSchema',
        args: Utils.wrapArguments(arguments),
        returnType: StructType
      };

      return Utils.generate(args);
    };

    /**
     * @param {module:eclairjs/ml/param.ParamMap} extra
     * @returns {module:eclairjs/ml/feature.CountVectorizer}
     */
    CountVectorizer.prototype.copy = function(extra) {
      var args = {
        target: this,
        method: 'copy',
        args: Utils.wrapArguments(arguments),
        returnType: CountVectorizer
      };

      return Utils.generate(args);
    };

    //
    // static methods
    //

    /**
     * @param {string} path
     * @returns {module:eclairjs/ml/feature.CountVectorizer}
     */
    CountVectorizer.load = function(path) {
      var args = {
        target: CountVectorizer,
        method: 'load',
        kernelP: gKernelP,
        static: true,
        args: Utils.wrapArguments(arguments),
        returnType: CountVectorizer
      };

      return Utils.generate(args);
    };

    CountVectorizer.moduleLocation = '/ml/feature/CountVectorizer';

    return CountVectorizer;
  })();
};


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateBasketTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('basket', function (Blueprint $table) {
            $table->increments('id');
            $table->string('session_id');
            // $table->foreign('session_id')
            //     ->references('id')
            //     ->on('session')
            //     ->onUpdate('cascade')
            //     ->onDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('basket');
    }
}


text:
/*
 * This program, created 2002-10-03 by Garrett A. Wollman
 * <wollman@FreeBSD.org>, is in the public domain.  Use at your own risk.
 *
 * $FreeBSD: soc2013/dpl/head/tools/tools/find-sb/mini_ufs.h 163891 2006-10-31 22:18:33Z pjd $
 */

/*
 * Small extract from ufs/ffs/fs.h to get definition of superblock
 * in order to make this tool portable to other unix-like systems.
 *
 * Based upon:
 *
 * FreeBSD: src/sys/ufs/ffs/fs.h,v 1.48 2005/02/20 08:02:15 delphij
 * FreeBSD: src/sys/ufs/ufs/dinode.h,v 1.15 2005/01/07 02:29:26 imp
 */

#include <sys/types.h>

#define	SBLOCKSIZE	8192
#define	DEV_BSIZE	(1<<9)
#define	FS_UFS1_MAGIC	0x011954
#define	FS_UFS2_MAGIC	0x19540119
#define	SBLOCK_UFS1	8192
#define	SBLOCK_UFS2	65536
#define	MAXMNTLEN	468
#define	MAXVOLLEN	32
#define	NOCSPTRS	((128 / sizeof(void *)) - 4)
#define	FSMAXSNAP	20

typedef int64_t ufs_time_t;
typedef int64_t ufs2_daddr_t;

struct csum {
        int32_t cs_ndir;                /* number of directories */
        int32_t cs_nbfree;              /* number of free blocks */
        int32_t cs_nifree;              /* number of free inodes */
        int32_t cs_nffree;              /* number of free frags */
};

struct csum_total {
        int64_t cs_ndir;                /* number of directories */
        int64_t cs_nbfree;              /* number of free blocks */
        int64_t cs_nifree;              /* number of free inodes */
        int64_t cs_nffree;              /* number of free frags */
        int64_t cs_numclusters;         /* number of free clusters */
        int64_t cs_spare[3];            /* future expansion */
};

/*
 * Super block for an FFS filesystem.
 */
struct fs {
        int32_t  fs_firstfield;         /* historic filesystem linked list, */
        int32_t  fs_unused_1;           /*     used for incore super blocks */
        int32_t  fs_sblkno;             /* offset of super-block in filesys */
        int32_t  fs_cblkno;             /* offset of cyl-block in filesys */
        int32_t  fs_iblkno;             /* offset of inode-blocks in filesys */
        int32_t  fs_dblkno;             /* offset of first data after cg */
        int32_t  fs_old_cgoffset;       /* cylinder group offset in cylinder */
        int32_t  fs_old_cgmask;         /* used to calc mod fs_ntrak */
        int32_t  fs_old_time;           /* last time written */
        int32_t  fs_old_size;           /* number of blocks in fs */
        int32_t  fs_old_dsize;          /* number of data blocks in fs */
        int32_t  fs_ncg;                /* number of cylinder groups */
        int32_t  fs_bsize;              /* size of basic blocks in fs */
        int32_t  fs_fsize;              /* size of frag blocks in fs */
        int32_t  fs_frag;               /* number of frags in a block in fs */
/* these are configuration parameters */
        int32_t  fs_minfree;            /* minimum percentage of free blocks */
        int32_t  fs_old_rotdelay;       /* num of ms for optimal next block */
        int32_t  fs_old_rps;            /* disk revolutions per second */
/* these fields can be computed from the others */
        int32_t  fs_bmask;              /* ``blkoff'' calc of blk offsets */
        int32_t  fs_fmask;              /* ``fragoff'' calc of frag offsets */
        int32_t  fs_bshift;             /* ``lblkno'' calc of logical blkno */
        int32_t  fs_fshift;             /* ``numfrags'' calc number of frags */
/* these are configuration parameters */
        int32_t  fs_maxcontig;          /* max number of contiguous blks */
        int32_t  fs_maxbpg;             /* max number of blks per cyl group */
/* these fields can be computed from the others */
        int32_t  fs_fragshift;          /* block to frag shift */
        int32_t  fs_fsbtodb;            /* fsbtodb and dbtofsb shift constant */
        int32_t  fs_sbsize;             /* actual size of super block */
        int32_t  fs_spare1[2];          /* old fs_csmask */
                                        /* old fs_csshift */
        int32_t  fs_nindir;             /* value of NINDIR */
        int32_t  fs_inopb;              /* value of INOPB */
        int32_t  fs_old_nspf;           /* value of NSPF */
/* yet another configuration parameter */
        int32_t  fs_optim;              /* optimization preference, see below */
        int32_t  fs_old_npsect;         /* # sectors/track including spares */
        int32_t  fs_old_interleave;     /* hardware sector interleave */
        int32_t  fs_old_trackskew;      /* sector 0 skew, per track */
        int32_t  fs_id[2];              /* unique filesystem id */
/* sizes determined by number of cylinder groups and their sizes */
        int32_t  fs_old_csaddr;         /* blk addr of cyl grp summary area */
        int32_t  fs_cssize;             /* size of cyl grp summary area */
        int32_t  fs_cgsize;             /* cylinder group size */
        int32_t  fs_spare2;             /* old fs_ntrak */
        int32_t  fs_old_nsect;          /* sectors per track */
        int32_t  fs_old_spc;            /* sectors per cylinder */
        int32_t  fs_old_ncyl;           /* cylinders in filesystem */
        int32_t  fs_old_cpg;            /* cylinders per group */
        int32_t  fs_ipg;                /* inodes per group */
        int32_t  fs_fpg;                /* blocks per group * fs_frag */
/* this data must be re-computed after crashes */
        struct  csum fs_old_cstotal;    /* cylinder summary information */
/* these fields are cleared at mount time */
        int8_t   fs_fmod;               /* super block modified flag */
        int8_t   fs_clean;              /* filesystem is clean flag */
        int8_t   fs_ronly;              /* mounted read-only flag */
        int8_t   fs_old_flags;          /* old FS_ flags */
        u_char   fs_fsmnt[MAXMNTLEN];   /* name mounted on */
        u_char   fs_volname[MAXVOLLEN]; /* volume name */
        u_int64_t fs_swuid;             /* system-wide uid */
        int32_t  fs_pad;                /* due to alignment of fs_swuid */
/* these fields retain the current block allocation info */
        int32_t  fs_cgrotor;            /* last cg searched */
        void    *fs_ocsp[NOCSPTRS];     /* padding; was list of fs_cs buffers */
        u_int8_t *fs_contigdirs;        /* (u) # of contig. allocated dirs */
        struct  csum *fs_csp;           /* (u) cg summary info buffer */
        int32_t *fs_maxcluster;         /* (u) max cluster in each cyl group */
        u_int   *fs_active;             /* (u) used by snapshots to track fs */
        int32_t  fs_old_cpc;            /* cyl per cycle in postbl */
        int32_t  fs_maxbsize;           /* maximum blocking factor permitted */
        int64_t  fs_unrefs;             /* number of unreferenced inodes */
        int64_t  fs_sparecon64[16];     /* old rotation block list head */
        int64_t  fs_sblockloc;          /* byte offset of standard superblock */
        struct  csum_total fs_cstotal;  /* (u) cylinder summary information */
        ufs_time_t fs_time;             /* last time written */
        int64_t  fs_size;               /* number of blocks in fs */
        int64_t  fs_dsize;              /* number of data blocks in fs */
        ufs2_daddr_t fs_csaddr;         /* blk addr of cyl grp summary area */
        int64_t  fs_pendingblocks;      /* (u) blocks being freed */
        int32_t  fs_pendinginodes;      /* (u) inodes being freed */
        int32_t  fs_snapinum[FSMAXSNAP];/* list of snapshot inode numbers */
        int32_t  fs_avgfilesize;        /* expected average file size */
        int32_t  fs_avgfpdir;           /* expected # of files per directory */
        int32_t  fs_save_cgsize;        /* save real cg size to use fs_bsize */
        int32_t  fs_sparecon32[26];     /* reserved for future constants */
        int32_t  fs_flags;              /* see FS_ flags below */
        int32_t  fs_contigsumsize;      /* size of cluster summary array */
        int32_t  fs_maxsymlinklen;      /* max length of an internal symlink */
        int32_t  fs_old_inodefmt;       /* format of on-disk inodes */
        u_int64_t fs_maxfilesize;       /* maximum representable file size */
        int64_t  fs_qbmask;             /* ~fs_bmask for use with 64-bit size */
        int64_t  fs_qfmask;             /* ~fs_fmask for use with 64-bit size */
        int32_t  fs_state;              /* validate fs_clean field */
        int32_t  fs_old_postblformat;   /* format of positional layout tables */
        int32_t  fs_old_nrpos;          /* number of rotational positions */
        int32_t  fs_spare5[2];          /* old fs_postbloff */
                                        /* old fs_rotbloff */
        int32_t  fs_magic;              /* magic number */
};


text:
<?xml version="1.0" ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<link rel="stylesheet" type="text/css" href="../../../scineplex.css">
<title></title>
<link rel="stylesheet" href="../../../Active.css" type="text/css" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rev="made" href="mailto:" />

NAME

SYNOPSIS

DESCRIPTION

SUPPORT

AUTHORS

SEE ALSO

COPYRIGHT

NAME

File::HomeDir::Windows - Find your home and other directories on Windows

SYNOPSIS

  use File::HomeDir;

  # Find directories for the current user (eg. using Windows XP Professional)
  $home    = File::HomeDir->my_home;        # C:\Documents and Settings\mylogin
  $desktop = File::HomeDir->my_desktop;     # C:\Documents and Settings\mylogin\Desktop
  $docs    = File::HomeDir->my_documents;   # C:\Documents and Settings\mylogin\My Documents
  $music   = File::HomeDir->my_music;       # C:\Documents and Settings\mylogin\My Documents\My Music
  $pics    = File::HomeDir->my_pictures;    # C:\Documents and Settings\mylogin\My Documents\My Pictures
  $videos  = File::HomeDir->my_videos;      # C:\Documents and Settings\mylogin\My Documents\My Video
  $data    = File::HomeDir->my_data;        # C:\Documents and Settings\mylogin\Local Settings\Application Data

DESCRIPTION

This module provides Windows-specific implementations for determining common user directories. In normal usage this module will always be used via File::HomeDir.

Internally this module will use Win32::GetFolderPath to fetch the location of your directories. As a result of this, in certain unusual situations (usually found inside large organisations) the methods may return UNC paths such as \\cifs.local\home$.

If your application runs on Windows and you want to have it work comprehensively everywhere, you may need to implement your own handling for these paths as they can cause strange behaviour.

For example, stat calls to UNC paths may work but block for several seconds, but opendir() may not be able to read any files (creating the appearance of an existing but empty directory).

To avoid complicating the problem any further, in the rare situation that a UNC path is returned by GetFolderPath the usual -d validation checks will not be done.

SUPPORT

See the support section the main File::HomeDir module.

AUTHORS

Adam Kennedy <adamk@cpan.org>

Sean M. Burke <sburke@cpan.org>

SEE ALSO

File::HomeDir, File::HomeDir::Win32 (legacy)

COPYRIGHT

Copyright 2005 - 2011 Adam Kennedy.

Some parts copyright 2000 Sean M. Burke.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

The full text of the license can be found in the LICENSE file included with this module.


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using Tweetinvi;
using Tweetinvi.Core.Enum;
using Tweetinvi.Core.Extensions;
using Tweetinvi.Core.Interfaces;
using Tweetinvi.Core.Interfaces.Controllers;
using Tweetinvi.Core.Interfaces.DTO;
using Tweetinvi.Core.Interfaces.DTO.QueryDTO;
using Tweetinvi.Core.Interfaces.Models;
using Tweetinvi.Core.Interfaces.Models.Parameters;
using Tweetinvi.Core.Interfaces.oAuth;
using Tweetinvi.Core.Interfaces.Streaminvi;
using Tweetinvi.Json;
using Stream = Tweetinvi.Stream;

namespace Examplinvi
{
    // IMPORTANT
    // This cheat sheet provide examples for all the features provided by Tweetinvi.

    // WINDOWS PHONE 8 developers
    // If you are a windows phone developer, please use the Async classes
    // User.GetLoggedUser(); -> await UserAsync.GetLoggedUser();

    class Program
    {
        private const string USER_SCREEN_NAME_TO_TEST = "ladygaga";

        static void Main()
        {
            TwitterCredentials.SetCredentials("Access_Token", "Access_Token_Secret", "Consumer_Key", "Consumer_Secret");

            GenerateCredentialExamples();
            UserLiveFeedExamples();
            TweetExamples();
            UserExamples();
            LoggedUserExamples();
            TimelineExamples();
            MessageExamples();
            TweetListExamples();
            GeoExamples();
            SearchExamples();
            SavedSearchesExamples();
            RateLimitExamples();
            HelpExamples();
            JsonExamples();
            StreamExamples();
            OtherFeaturesExamples();
            ConfigureTweetinvi();
            GlobalEvents();

            Console.WriteLine(@"END");
            Console.ReadLine();
        }

        #region Examples Store

        // ReSharper disable LocalizableElement
        // ReSharper disable UnusedMember.Local

        private static void GenerateCredentialExamples()
        {
            // With captcha
            //CredentialsCreator_WithCaptcha_StepByStep("CONSUMER_KEY", "CONSUMER_SECRET");
            //CredentialsCreator_WithCaptcha_SingleStep(ConfigurationManager.AppSettings["token_ConsumerKey"], ConfigurationManager.AppSettings["token_ConsumerSecret"]);

            // With callback URL
            //CredentialsCreator_CreateFromRedirectedCallbackURL_StepByStep(ConfigurationManager.AppSettings["token_ConsumerKey"], ConfigurationManager.AppSettings["token_ConsumerSecret"]);
            //CredentialsCreator_CreateFromRedirectedCallbackURL_SingleStep(ConfigurationManager.AppSettings["token_ConsumerKey"], ConfigurationManager.AppSettings["token_ConsumerSecret"]);

            //CredentialsCreator_CreateFromRedirectedVerifierCode_StepByStep(ConfigurationManager.AppSettings["token_ConsumerKey"], ConfigurationManager.AppSettings["token_ConsumerSecret"]);
            //CredentialsCreator_CreateFromRedirectedVerifierCode_SingleStep(ConfigurationManager.AppSettings["token_ConsumerKey"], ConfigurationManager.AppSettings["token_ConsumerSecret"]);
        }

        private static void UserLiveFeedExamples()
        {
            // Stream_UserStreamExample();
        }

        private static void TweetExamples()
        {
            // Tweet_GetExistingTweet(210462857140252672);

            // Tweet_PublishTweet(String.Format("I love tweetinvi! ({0})", Guid.NewGuid()));
            // Tweet_PublishTweetWithImage("Uploadinvi?", "YOUR_FILE_PATH.png");

            // Tweet_PublishTweetInReplyToAnotherTweet(String.Format("I love tweetinvi! ({0})", Guid.NewGuid()), 392711547081854976);
            // Tweet_PublishTweetWithGeo(String.Format("I love tweetinvi! ({0})", Guid.NewGuid()));
            // Tweet_PublishTweetWithGeo_Coordinates(String.Format("I love tweetinvi! ({0})", Guid.NewGuid()));

            // Tweet_Destroy();

            // Tweet_GetRetweets(210462857140252672);
            // Tweet_PublishRetweet(210462857140252672);

            // Tweet_GenerateOEmbedTweet();

            // Tweet_DestroyRetweet(210462857140252672);

            // Tweet_SetTweetAsFavorite(392711547081854976);
        }

        private static void UserExamples()
        {
            // User_GetCurrentUser();

            // User_GetUserFromName(1478171);
            // User_GetUserFromName(USER_SCREEN_NAME_TO_TEST);

            // User_GetFavorites(USER_SCREEN_NAME_TO_TEST);

            // User_GetFriends(USER_SCREEN_NAME_TO_TEST);
            // User_GetFriendIds(USER_SCREEN_NAME_TO_TEST);
            // User_GetFriendIdsUpTo(USER_SCREEN_NAME_TO_TEST, 10000);

            // User_GetFollowers(USER_SCREEN_NAME_TO_TEST);
            // User_GetFollowerIds(USER_SCREEN_NAME_TO_TEST);
            // User_GetFollowerIdsUpTo(USER_SCREEN_NAME_TO_TEST, 10000);

            // User_GetRelationshipBetween("tweetinvitest", USER_SCREEN_NAME_TO_TEST);

            // User_BlockUser(USER_SCREEN_NAME_TO_TEST);
            // User_UnBlockUser(USER_SCREEN_NAME_TO_TEST);
            // User_GetBlockedUsers();
            // User_DownloadProfileImage(USER_SCREEN_NAME_TO_TEST);
            // User_DownloadProfileImageAsync(USER_SCREEN_NAME_TO_TEST);
            // User_GenerateProfileImageStream(USER_SCREEN_NAME_TO_TEST);
            // User_GenerateProfileImageBitmap(USER_SCREEN_NAME_TO_TEST);
        }

        private static void LoggedUserExamples()
        {
            //LoggedUser_GetMultipleRelationships();
            //LoggedUser_GetIncomingRequests();
            //LoggedUser_GetOutgoingRequests();
            //LoggedUser_FollowUser(USER_SCREEN_NAME_TO_TEST);
            //LoggedUser_UnFollowUser(USER_SCREEN_NAME_TO_TEST);
            //LoggedUser_UpdateFollowAuthorizationsForUser(USER_SCREEN_NAME_TO_TEST);
            //LoggedUser_GetLatestReceivedMessages();
            //LoggedUser_GetLatestSentMessages();
            //LoggedUser_GetAccountSettings();
        }

        private static void TimelineExamples()
        {
            // Timeline_GetHomeTimeline();
            // Timeline_GetUserTimeline(USER_SCREEN_NAME_TO_TEST);
            // Timeline_GetMentionsTimeline();
        }

        private static void MessageExamples()
        {
            // TokenUser_GetLatestReceivedMessages();
            // Message_GetMessageFromId(381069551028293633);
            // Message_PublishMessage(USER_SCREEN_NAME_TO_TEST);
            // Message_PublishMessageTo(USER_SCREEN_NAME_TO_TEST);
        }

        private static void TweetListExamples()
        {
            // TweetList_GetUserLists();
            // TweetList_CreateList();
            // TweetList_GetExistingListById(105601767);
            // TweetList_UpdateList(105601767);
            // TweetList_DestroyList(105601767);
            // TweetList_GetTweetsFromList(105601767);
            // TweetList_GetMembersOfList(105601767);
        }

        private static void GeoExamples()
        {
            // Geo_GetPlaceFromId("df51dec6f4ee2b2c");
            // Trends_GetTrendsFromWoeId(1);
        }

        private static void SearchExamples()
        {
            // Search_SimpleTweetSearch();
            // Search_SearchTweet();
            // Search_SearchWithMetadata();
            // Search_FilteredSearch();
        }

        private static void SavedSearchesExamples()
        {
            // SavedSearch_CreateSavedSearch("tweetinvi");
            // SavedSearch_GetSavedSearches();
            // SavedSearch_GetSavedSearch(307102135);
            // SavedSearch_DestroySavedSearch(307102135);
        }

        private static void RateLimitExamples()
        {
            // RateLimits_Track_Examples();
            // GetCredentialsRateLimits();
            // GetCurrentCredentialsRateLimits();
        }

        private static void HelpExamples()
        {
            // GetTwitterPrivacyPolicy();
        }

        private static void JsonExamples()
        {
            // Json_GetJsonForAccountRequestExample();
            // Json_GetJsonForMessageRequestExample();
            // Json_GetJsonCursorRequestExample();
            // Json_GetJsonForGeoRequestExample();
            // Json_GetJsonForHelpRequestExample();
            // Json_GetJsonForSavedSearchRequestExample();
            // Json_GetJsonForTimelineRequestExample();
            // Json_GetJsonForTrendsRequestExample();
            // Json_GetJsonForTweetRequestExample();
            // Json_GetJsonForUserRequestExample();
        }

        private static void StreamExamples()
        {
            // Stream_SampleStreamExample();
            // Stream_FilteredStreamExample();
            // Stream_UserStreamExample();
            // SimpleStream_Events();
        }

        private static void OtherFeaturesExamples()
        {
            //Exceptions_GetExceptionsInfo();
            //ManualQuery_Example();
        }

        #endregion

        #region Credentials and Login

        // Get credentials with captcha system
        // ReSharper disable UnusedMethodReturnValue.Local
        private static IOAuthCredentials CredentialsCreator_WithCaptcha_StepByStep(string consumerKey, string consumerSecret)
        {
            var applicationCredentials = CredentialsCreator.GenerateApplicationCredentials(consumerKey, consumerSecret);
            var url = CredentialsCreator.GetAuthorizationURL(applicationCredentials);
            Console.WriteLine("Go on : {0}", url);
            Console.WriteLine("Enter the captch : ");
            var captcha = Console.ReadLine();

            var newCredentials = CredentialsCreator.GetCredentialsFromVerifierCode(captcha, applicationCredentials);
            Console.WriteLine("Access Token = {0}", newCredentials.AccessToken);
            Console.WriteLine("Access Token Secret = {0}", newCredentials.AccessTokenSecret);

            return newCredentials;
        }

        private static IOAuthCredentials CredentialsCreator_WithCaptcha_SingleStep(string consumerKey, string consumerSecret)
        {
            Func<string, string> retrieveCaptcha = url =>
            {
                Console.WriteLine("Go on : {0}", url);
                Console.WriteLine("Enter the captch : ");
                return Console.ReadLine();
            };

            var newCredentials = CredentialsCreator.GetCredentialsFromCaptcha(retrieveCaptcha, consumerKey, consumerSecret);
            Console.WriteLine("Access Token = {0}", newCredentials.AccessToken);
            Console.WriteLine("Access Token Secret = {0}", newCredentials.AccessTokenSecret);

            return newCredentials;
        }

        // Get credentials with callbackURL system
        private static IOAuthCredentials CredentialsCreator_CreateFromRedirectedCallbackURL_StepByStep(string consumerKey, string consumerSecret)
        {
            var applicationCredentials = CredentialsCreator.GenerateApplicationCredentials(consumerKey, consumerSecret);
            var url = CredentialsCreator.GetAuthorizationURLForCallback(applicationCredentials, "https://tweetinvi.codeplex.com");
            Console.WriteLine("Go on : {0}", url);
            Console.WriteLine("When redirected to your website copy and paste the URL: ");

            // Enter a value like: https://tweeetinvi.codeplex.com?oauth_token={tokenValue}&oauth_verifier={verifierValue}

            var callbackURL = Console.ReadLine();

            // Here we provide the entire URL where the user has been redirected
            var newCredentials = CredentialsCreator.GetCredentialsFromCallbackURL(callbackURL, applicationCredentials);
            Console.WriteLine("Access Token = {0}", newCredentials.AccessToken);
            Console.WriteLine("Access Token Secret = {0}", newCredentials.AccessTokenSecret);

            return newCredentials;
        }

        private static IOAuthCredentials CredentialsCreator_CreateFromRedirectedVerifierCode_StepByStep(string consumerKey, string consumerSecret)
        {
            var applicationCredentials = CredentialsCreator.GenerateApplicationCredentials(consumerKey, consumerSecret);
            var url = CredentialsCreator.GetAuthorizationURLForCallback(applicationCredentials, "https://tweetinvi.codeplex.com");
            Console.WriteLine("Go on : {0}", url);
            Console.WriteLine("When redirected to your website copy and paste the value of the oauth_verifier : ");

            // For the following redirection https://tweetinvi.codeplex.com?oauth_token=UR3eTEwDXFNhkMnjqz0oFbRauvAm4YhnF67KE6hO8Q&oauth_verifier=woXaKhpDtX6vhDVPl7TU6955qdQeH3cgz6xDvRZRA4A
            // Enter the value : woXaKhpDtX6vhDVPl7TU6955qdQeH3cgz6xDvRZRA4A

            var verifierCode = Console.ReadLine();

            // Here we only provide the verifier code
            var newCredentials = CredentialsCreator.GetCredentialsFromVerifierCode(verifierCode, applicationCredentials);
            Console.WriteLine("Access Token = {0}", newCredentials.AccessToken);
            Console.WriteLine("Access Token Secret = {0}", newCredentials.AccessTokenSecret);

            return newCredentials;
        }

        private static IOAuthCredentials CredentialsCreator_CreateFromRedirectedCallbackURL_SingleStep(string consumerKey, string consumerSecret)
        {
            Func<string, string> retrieveCallbackURL = url =>
            {
                Console.WriteLine("Go on : {0}", url);
                Console.WriteLine("When redirected to your website copy and paste the URL: ");

                // Enter a value like: https://tweeetinvi.codeplex.com?oauth_token={tokenValue}&oauth_verifier={verifierValue}

                var callbackURL = Console.ReadLine();
                return callbackURL;
            };

            // Here we provide the entire URL where the user has been redirected
            var newCredentials = CredentialsCreator.GetCredentialsFromCallbackURL_UsingRedirectedCallbackURL(retrieveCallbackURL, consumerKey, consumerSecret, "https://tweetinvi.codeplex.com");
            Console.WriteLine("Access Token = {0}", newCredentials.AccessToken);
            Console.WriteLine("Access Token Secret = {0}", newCredentials.AccessTokenSecret);

            return newCredentials;
        }

        private static IOAuthCredentials CredentialsCreator_CreateFromRedirectedVerifierCode_SingleStep(string consumerKey, string consumerSecret)
        {
            Func<string, string> retrieveVerifierCode = url =>
            {
                Console.WriteLine("Go on : {0}", url);
                Console.WriteLine("When redirected to your website copy and paste the value of the oauth_verifier : ");

                // For the following redirection https://tweetinvi.codeplex.com?oauth_token=UR3eTEwDXFNhkMnjqz0oFbRauvAm4YhnF67KE6hO8Q&oauth_verifier=woXaKhpDtX6vhDVPl7TU6955qdQeH3cgz6xDvRZRA4A
                // Enter the value : woXaKhpDtX6vhDVPl7TU6955qdQeH3cgz6xDvRZRA4A

                var verifierCode = Console.ReadLine();
                return verifierCode;
            };

            // Here we provide the entire URL where the user has been redirected
            var newCredentials = CredentialsCreator.GetCredentialsFromCallbackURL_UsingRedirectedVerifierCode(retrieveVerifierCode, consumerKey, consumerSecret, "https://tweetinvi.codeplex.com");
            Console.WriteLine("Access Token = {0}", newCredentials.AccessToken);
            Console.WriteLine("Access Token Secret = {0}", newCredentials.AccessTokenSecret);

            return newCredentials;
        }
        // ReSharper restore UnusedMethodReturnValue.Local

        #endregion

        #region Tweet

        private static void Tweet_GetExistingTweet(long tweetId)
        {
            var tweet = Tweet.GetTweet(tweetId);
            Console.WriteLine(tweet.Text);
        }

        private static void Tweet_PublishTweet(string text)
        {
            var newTweet = Tweet.CreateTweet(text);
            newTweet.Publish();

            Console.WriteLine(newTweet.IsTweetPublished);
        }

        private static void Tweet_PublishTweetWithImage(string text, string filePath, string filepath2 = null)
        {
            byte[] file1 = File.ReadAllBytes(filePath);

            // Create a tweet with a single image
            var tweet = Tweet.CreateTweetWithMedia(text, file1);

            // !! MOST ACCOUNTS ARE LIMITED TO 1 File per Tweet     !!
            // !! IF YOU ADD 2 MEDIA, YOU MAY HAVE ONLY 1 PUBLISHED !!
            if (filepath2 != null)
            {
                byte[] file2 = File.ReadAllBytes(filepath2);
                tweet.AddMedia(file2);
            }

            tweet.Publish();
        }

        private static void Tweet_PublishTweetInReplyToAnotherTweet(string text, long tweetIdtoRespondTo)
        {
            var newTweet = Tweet.CreateTweet(text);
            newTweet.PublishInReplyTo(tweetIdtoRespondTo);

            Console.WriteLine(newTweet.IsTweetPublished);
        }

        private static void Tweet_PublishTweetWithGeo(string text)
        {
            const double longitude = -122.400612831116;
            const double latitude = 37.7821120598956;

            var newTweet = Tweet.CreateTweet(text);
            newTweet.PublishWithGeo(longitude, latitude);

            Console.WriteLine(newTweet.IsTweetPublished);
        }

        private static void Tweet_PublishTweetWithGeo_Coordinates(string text)
        {
            const double longitude = -122.400612831116;
            const double latitude = 37.7821120598956;
            var coordinates = Geo.GenerateCoordinates(longitude, latitude);

            var newTweet = Tweet.CreateTweet(text);
            newTweet.PublishWithGeo(coordinates);

            Console.WriteLine(newTweet.IsTweetPublished);
        }

        private static void Tweet_PublishRetweet(long tweetId)
        {
            var tweet = Tweet.GetTweet(tweetId);
            var retweet = tweet.PublishRetweet();

            Console.WriteLine("You retweeted : '{0}'", retweet.Text);
        }

        private static void Tweet_DestroyRetweet(long tweetId)
        {
            var tweet = Tweet.GetTweet(tweetId);
            var retweet = tweet.PublishRetweet();

            retweet.Destroy();
        }

        private static void Tweet_GetRetweets(long tweetId)
        {
            var tweet = Tweet.GetTweet(tweetId);
            IEnumerable<ITweet> retweets = tweet.GetRetweets();

            var firstRetweeter = retweets.ElementAt(0).Creator;
            var originalTweet = retweets.ElementAt(0).RetweetedTweet;
            Console.WriteLine("{0} retweeted : '{1}'", firstRetweeter.Name, originalTweet.Text);
        }

        private static void Tweet_GenerateOEmbedTweet()
        {
            var newTweet = Tweet.CreateTweet("to be oembed");
            newTweet.Publish();

            var oembedTweet = newTweet.GenerateOEmbedTweet();

            Console.WriteLine("Oembed tweet url : {0}", oembedTweet.URL);

            if (newTweet.IsTweetPublished)
            {
                newTweet.Destroy();
            }
        }

        private static void Tweet_Destroy()
        {
            var newTweet = Tweet.CreateTweet("to be destroyed!");
            newTweet.Publish();
            bool isTweetPublished = newTweet.IsTweetPublished;

            if (isTweetPublished)
            {
                newTweet.Destroy();
            }

            bool tweetDestroyed = newTweet.IsTweetDestroyed;
            Console.WriteLine("Has the tweet destroyed? {0}", tweetDestroyed);
        }

        private static void Tweet_SetTweetAsFavorite(long tweetId)
        {
            var tweet = Tweet.GetTweet(tweetId);
            tweet.Favourite();
            Console.WriteLine("Is tweet now favourite? -> {0}", tweet.Favourited);
        }

        #endregion

        #region User

        private static void User_GetCurrentUser()
        {
            var user = User.GetLoggedUser();
            Console.WriteLine(user.ScreenName);
        }

        private static void User_GetUserFromId(long userId)
        {
            var user = User.GetUserFromId(userId);
            Console.WriteLine(user.ScreenName);
        }

        private static void User_GetUserFromName(string userName)
        {
            var user = User.GetUserFromScreenName(userName);
            Console.WriteLine(user.Id);
        }

        private static void User_GetFriendIds(string userName)
        {
            var user = User.GetUserFromScreenName(userName);
            var friendIds = user.GetFriendIds();

            Console.WriteLine("{0} has {1} friends, here are some of them :", user.Name, user.FriendsCount);
            foreach (var friendId in friendIds)
            {
                Console.WriteLine("- {0}", friendId);
            }
        }

        private static void User_GetFriendIdsUpTo(string userName, int limit)
        {
            var user = User.GetUserFromScreenName(userName);
            var friendIds = user.GetFriendIds(limit);

            Console.WriteLine("{0} has {1} friends, here are some of them :", user.Name, user.FriendsCount);
            foreach (var friendId in friendIds)
            {
                Console.WriteLine("- {0}", friendId);
            }
        }

        private static void User_GetFriends(string userName)
        {
            var user = User.GetUserFromScreenName(userName);
            var friends = user.GetFriends();

            Console.WriteLine("{0} has {1} friends, here are some of them :", user.Name, user.FriendsCount);
            foreach (var friend in friends)
            {
                Console.WriteLine("- {0}", friend.Name);
            }
        }

        private static void User_GetFollowerIds(string userName)
        {
            var user = User.GetUserFromScreenName(userName);
            var followerIds = user.GetFollowerIds();

            Console.WriteLine("{0} has {1} followers, here are some of them :", user.Name, user.FollowersCount);
            foreach (var followerId in followerIds)
            {
                Console.WriteLine("- {0}", followerId);
            }
        }

        private static void User_GetFollowerIdsUpTo(string userName, int limit)
        {
            var user = User.GetUserFromScreenName(userName);
            var followerIds = user.GetFollowerIds(limit);

            Console.WriteLine("{0} has {1} followers, here are some of them :", user.Name, user.FollowersCount);
            foreach (var followerId in followerIds)
            {
                Console.WriteLine("- {0}", followerId);
            }
        }

        private static void User_GetFollowers(string userName)
        {
            var user = User.GetUserFromScreenName(userName);
            var followers = user.GetFollowers();

            Console.WriteLine("{0} has {1} followers, here are some of them :", user.Name, user.FollowersCount);
            foreach (var follower in followers)
            {
                Console.WriteLine("- {0}", follower.Name);
            }
        }

        private static void User_GetRelationshipBetween(string sourceUserName, string targetUsername)
        {
            var sourceUser = User.GetUserFromScreenName(sourceUserName);
            var targetUser = User.GetUserFromScreenName(targetUsername);

            var relationship = sourceUser.GetRelationshipWith(targetUser);
            Console.WriteLine("You are{0} following {1}", relationship.Following ? "" : " not", targetUsername);
            Console.WriteLine("You are{0} being followed by {1}", relationship.FollowedBy ? "" : " not", targetUsername);
        }

        private static void User_GetFavorites(string userName)
        {
            var user = User.GetUserFromScreenName(userName);
            var favorites = user.GetFavorites();

            Console.WriteLine("{0} has {1} favorites, here are some of them :", user.Name, user.FavouritesCount);
            foreach (var favoriteTweet in favorites)
            {
                Console.WriteLine("- {0}", favoriteTweet.Text);
            }
        }

        private static void User_BlockUser(string userName)
        {
            var user = User.GetUserFromScreenName(userName);

            if (user.BlockUser())
            {
                Console.WriteLine("{0} has been blocked.", userName);
            }
            else
            {
                Console.WriteLine("{0} has not been blocked.", userName);
            }
        }

        private static void User_UnBlockUser(string userName)
        {
            var user = User.GetUserFromScreenName(userName);
            user.UnBlockUser();
        }

        private static void User_GetBlockedUsers()
        {
            var loggedUser = User.GetLoggedUser();
            loggedUser.GetBlockedUsers();
            loggedUser.GetBlockedUserIds();
        }

        private static void User_DownloadProfileImage(string userName)
        {
            var user = User.GetUserFromScreenName(userName);
            var stream = user.GetProfileImageStream(ImageSize.bigger);
            var fileStream = new FileStream(String.Format("{0}.jpg", user.Id), FileMode.Create);
            stream.CopyTo(fileStream);

            string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
            if (assemblyPath != null)
            {
                Process.Start(assemblyPath);
            }
        }

        #endregion

        #region LoggedUser

        private static void LoggedUser_GetMultipleRelationships()
        {
            var loggedUser = User.GetLoggedUser();

            var user1 = User.GetUserFromScreenName("tweetinviapi");
            var user2 = User.GetUserFromScreenName(USER_SCREEN_NAME_TO_TEST);

            var userList = new List<IUser>
            {
                user1,
                user2
            };

            var relationships = loggedUser.GetRelationshipStatesWith(userList);
            foreach (var relationship in relationships)
            {
                Console.WriteLine("You are{0} following {1}", relationship.Following ? "" : " not", relationship.TargetScreenName);
                Console.WriteLine("You are{0} being followed by {1}", relationship.FollowedBy ? "" : " not", relationship.TargetScreenName);
                Console.WriteLine();
            }
        }

        private static void LoggedUser_GetIncomingRequests()
        {
            var loggedUser = User.GetLoggedUser();
            var usersRequestingFriendship = loggedUser.GetUsersRequestingFriendship();

            foreach (var user in usersRequestingFriendship)
            {
                Console.WriteLine("{0} wants to follow you!", user.Name);
            }
        }

        private static void LoggedUser_GetOutgoingRequests()
        {
            var loggedUser = User.GetLoggedUser();
            var usersRequestingFriendship = loggedUser.GetUsersYouRequestedToFollow();

            foreach (var user in usersRequestingFriendship)
            {
                Console.WriteLine("You sent a request to follow {0}!", user.Name);
            }
        }

        private static void LoggedUser_FollowUser(string userName)
        {
            var loggedUser = User.GetLoggedUser();
            var userToFollow = User.GetUserFromScreenName(userName);

            if (loggedUser.FollowUser(userToFollow))
            {
                Console.WriteLine("You have successfully sent a request to follow {0}", userToFollow.Name);
            }
        }

        private static void LoggedUser_UnFollowUser(string userName)
        {
            var loggedUser = User.GetLoggedUser();
            var userToFollow = User.GetUserFromScreenName(userName);

            if (loggedUser.UnFollowUser(userToFollow))
            {
                Console.WriteLine("You are not following {0} anymore", userToFollow.Name);
            }
        }

        private static void LoggedUser_UpdateFollowAuthorizationsForUser(string userName)
        {
            var loggedUser = User.GetLoggedUser();
            var userToFollow = User.GetUserFromScreenName(userName);

            if (loggedUser.UpdateRelationshipAuthorizationsWith(userToFollow, false, false))
            {
                Console.WriteLine("Authorizations updated");
            }
        }

        private static void LoggedUser_GetLatestReceivedMessages()
        {
            var loggedUser = User.GetLoggedUser();
            var messages = loggedUser.GetLatestMessagesReceived(20);

            Console.WriteLine("Messages Received : ");
            foreach (var message in messages)
            {
                Console.WriteLine("- '{0}'", message.Text);
            }
        }

        private static void LoggedUser_GetLatestSentMessages()
        {
            var loggedUser = User.GetLoggedUser();
            var messages = loggedUser.GetLatestMessagesSent(20);

            Console.WriteLine("Messages Received : ");
            foreach (var message in messages)
            {
                Console.WriteLine("- '{0}'", message.Text);
            }
        }

        private static void LoggedUser_GetAccountSettings()
        {
            var loggedUser = User.GetLoggedUser();
            var settings = loggedUser.GetAccountSettings();

            // Store information
            loggedUser.AccountSettings = settings;

            Console.WriteLine("{0} uses lang : {1}", settings.ScreenName, settings.Language);
        }

        #endregion

        #region Timeline

        private static void Timeline_GetUserTimeline(string username)
        {
            var user = User.GetUserFromScreenName(username);

            var timelineTweets = user.GetUserTimeline();
            foreach (var tweet in timelineTweets)
            {
                Console.WriteLine(tweet.Text);
            }
        }

        private static void Timeline_GetHomeTimeline()
        {
            var loggedUser = User.GetLoggedUser();

            var homeTimelineTweets = loggedUser.GetHomeTimeline();
            foreach (var tweet in homeTimelineTweets)
            {
                Console.WriteLine(tweet.Text);
            }
        }

        private static void Timeline_GetMentionsTimeline()
        {
            var loggedUser = User.GetLoggedUser();

            var mentionsTimelineTweets = loggedUser.GetMentionsTimeline();
            foreach (var mention in mentionsTimelineTweets)
            {
                Console.WriteLine(mention.Text);
            }
        }

        #endregion

        #region Message

        private static void Message_GetLatests()
        {
            // Messages Received
            var latestMessagesReceived = Message.GetLatestMessagesReceived();
            var latestMessagesReceivedParameter = Message.GenerateGetLatestsReceivedRequestParameter();
            latestMessagesReceivedParameter.SinceId = 10029230923;
            var latestMessagesReceivedFromParameter = Message.GetLatestMessagesReceived(latestMessagesReceivedParameter);

            // Messages Sent
            var latestMessagesSent = Message.GetLatestMessagesSent();
            var latestMessagesSentParameter = Message.GenerateGetLatestsSentRequestParameter();
            latestMessagesSentParameter.PageNumber = 239823;
            var latestMessagesSentFromParameter = Message.GetLatestMessagesSent(latestMessagesSentParameter);
        }

        private static void Message_GetMessageFromId(long messageId)
        {
            var message = Message.GetExistingMessage(messageId);
            Console.WriteLine("Message from {0} to {1} : {2}", message.Sender, message.Receiver, message.Text);
        }

        private static void Message_DestroyMessageFromId(long messageId)
        {
            var message = Message.GetExistingMessage(messageId);
            if (message.Destroy())
            {
                Console.WriteLine("Message successfully destroyed!");
            }
        }

        private static void Message_PublishMessage(string username)
        {
            var recipient = User.GetUserFromScreenName(username);
            var message = Message.CreateMessage("piloupe", recipient);

            if (message.Publish())
            {
                Console.WriteLine("Message published : {0}", message.IsMessagePublished);
            }
        }

        private static void Message_PublishMessageTo(string username)
        {
            var recipient = User.GetUserFromScreenName(username);
            var message = Message.CreateMessage("piloupe");

            if (message.PublishTo(recipient))
            {
                Console.WriteLine("Message published : {0}", message.IsMessagePublished);
            }
        }

        #endregion

        #region Lists

        private static void TweetList_GetUserLists()
        {
            var currentUser = User.GetLoggedUser();
            var tweetLists = TweetList.GetUserLists(currentUser, true);

            tweetLists.ForEach(list => Console.WriteLine("- {0}", list.FullName));
        }

        private static void TweetList_GetExistingListById(long listId)
        {
            var tweetList = TweetList.GetExistingList(listId);
            Console.WriteLine("You have retrieved the list {0}", tweetList.Name);
        }

        private static void TweetList_CreateList()
        {
            var list = TweetList.CreateList("plop", PrivacyMode.Public, "description");
            Console.WriteLine("List '{0}' has been created!", list.FullName);
        }

        private static void TweetList_UpdateList(long listId)
        {
            var list = TweetList.GetExistingList(listId);
            var updateParameters = TweetList.GenerateUpdateParameters();
            updateParameters.Name = "piloupe";
            updateParameters.Description = "pilouping description";
            updateParameters.PrivacyMode = PrivacyMode.Private;
            list.Update(updateParameters);

            Console.WriteLine("List new name is : {0}", list.Name);
        }

        private static void TweetList_DestroyList(long listId)
        {
            var list = TweetList.GetExistingList(listId);
            var hasBeenDestroyed = list.Destroy();
            Console.WriteLine("Tweet {0} been destroyed.", hasBeenDestroyed ? "has" : "has not");
        }

        private static void TweetList_GetTweetsFromList(long listId)
        {
            var list = TweetList.GetExistingList(listId);
            var tweets = list.GetTweets();

            tweets.ForEach(t => Console.WriteLine(t.Text));
        }

        private static void TweetList_GetMembersOfList(long listId)
        {
            var list = TweetList.GetExistingList(listId);
            var members = list.GetMembers();

            members.ForEach(x => Console.WriteLine(x.Name));
        }

        #endregion

        #region Geo/Trends

        private static void Geo_GetPlaceFromId(string placeId)
        {
            var geoController = TweetinviContainer.Resolve<IGeoController>();
            var place = geoController.GetPlaceFromId(placeId);
            Console.WriteLine(place.Name);
        }

        private static void Trends_GetTrendsFromWoeId(long woeid)
        {
            var trendsController = TweetinviContainer.Resolve<ITrendsController>();
            var placeTrends = trendsController.GetPlaceTrendsAt(woeid);
            Console.WriteLine(placeTrends.woeIdLocations.First().Name);
        }

        #endregion

        #region Search

        private static void Search_SimpleTweetSearch()
        {
            // IF YOU DO NOT RECEIVE ANY TWEET, CHANGE THE PARAMETERS!
            var tweets = Search.SearchTweets("#obama");

            foreach (var tweet in tweets)
            {
                Console.WriteLine("{0}", tweet.Text);
            }
        }

        private static void Search_SearchTweet()
        {
            // IF YOU DO NOT RECEIVE ANY TWEET, CHANGE THE PARAMETERS!

            var searchParameter = Search.GenerateTweetSearchParameter("obama");

            searchParameter.SetGeoCode(Geo.GenerateCoordinates(-122.398720, 37.781157), 1, DistanceMeasure.Miles);
            searchParameter.Lang = Language.English;
            searchParameter.SearchType = SearchResultType.Popular;
            searchParameter.MaximumNumberOfResults = 100;
            searchParameter.Since = new DateTime(2013, 12, 1);
            searchParameter.Until = new DateTime(2013, 12, 11);
            searchParameter.SinceId = 399616835892781056;
            searchParameter.MaxId = 405001488843284480;

            var tweets = Search.SearchTweets(searchParameter);
            tweets.ForEach(t => Console.WriteLine(t.Text));
        }

        private static void Search_SearchWithMetadata()
        {
            Search.SearchTweetsWithMetadata("hello");
        }

        private static void Search_FilteredSearch()
        {
            var searchParameter = Search.GenerateTweetSearchParameter("#tweetinvi");
            searchParameter.TweetSearchFilter = TweetSearchFilter.OriginalTweetsOnly;

            var tweets = Search.SearchTweets(searchParameter);
            tweets.ForEach(t => Console.WriteLine(t.Text));
        }

        private static void Search_SearchAndGetMoreThan100Results()
        {
            var searchParameter = Search.GenerateTweetSearchParameter("us");
            searchParameter.MaximumNumberOfResults = 200;

            var tweets = Search.SearchTweets(searchParameter);
            tweets.ForEach(t => Console.WriteLine(t.Text));
        }

        #endregion

        #region Saved Searches

        private static void SavedSearch_GetSavedSearches()
        {
            var loggedUser = User.GetLoggedUser();
            var savedSearches = loggedUser.GetSavedSearches();

            Console.WriteLine("Saved Searches");
            foreach (var savedSearch in savedSearches)
            {
                Console.WriteLine("- {0} => {1}", savedSearch.Name, savedSearch.Query);
            }
        }

        private static void SavedSearch_CreateSavedSearch(string query)
        {
            var savedSearch = SavedSearch.CreateSavedSearch(query);
            Console.WriteLine("Saved Search created as : {0}", savedSearch.Name);
        }

        private static void SavedSearch_GetSavedSearch(long searchId)
        {
            var savedSearch = SavedSearch.GetSavedSearch(searchId);
            Console.WriteLine("Saved searched query is : '{0}'", savedSearch.Query);
        }

        private static void SavedSearch_DestroySavedSearch(long searchId)
        {
            var savedSearch = SavedSearch.GetSavedSearch(searchId);

            if (SavedSearch.DestroySavedSearch(savedSearch))
            {
                Console.WriteLine("You destroyed the search successfully!");
            }
        }

        #endregion

        #region Rate Limit / Help

        private static void RateLimits_Track_Examples()
        {
            // Enable Tweetinvi RateLimit Handler
            RateLimit.UseRateLimitAwaiter = true;

            // Get notified when your application is being stopped to wait for RateLimits to be available
            RateLimit.QueryAwaitingForRateLimit += (sender, args) =>
            {
                Console.WriteLine("{0} is awaiting {1}ms for RateLimit to be available", args.Query, args.ResetInMilliseconds);
            };

            // Get the RateLimit associated with a query, this can return null
            var queryRateLimit = RateLimit.GetQueryRateLimit("https://api.twitter.com/1.1/application/rate_limit_status.json");

            // Pause the current thread until the specific RateLimit can be used
            RateLimit.AwaitForQueryRateLimit(queryRateLimit);

            // This stop the execution of the current thread until the RateLimits are available
            RateLimit.AwaitForQueryRateLimit("https://api.twitter.com/1.1/application/rate_limit_status.json");

            // Tweetinvi uses a cache mechanism to store credentials RateLimits, this operation allows you to clear it.
            // If the UseRateLimitAwaiter option is enabled this will result in the RateLimits to be retrieved during the next query.
            RateLimit.ClearRateLimitCache();
        }

        private static void RateLimits_ManualAwait()
        {
             TweetinviEvents.QueryBeforeExecute += (sender, args) =>
            {
                var queryRateLimit = RateLimit.GetQueryRateLimit(args.Query);
                RateLimit.AwaitForQueryRateLimit(queryRateLimit);
            };
        }

        private static void GetCurrentCredentialsRateLimits()
        {
            var tokenRateLimits = RateLimit.GetCurrentCredentialsRateLimits();

            Console.WriteLine("Remaning Requests for GetRate : {0}", tokenRateLimits.ApplicationRateLimitStatusLimit.Remaining);
            Console.WriteLine("Total Requests Allowed for GetRate : {0}", tokenRateLimits.ApplicationRateLimitStatusLimit.Limit);
            Console.WriteLine("GetRate limits will reset at : {0} local time", tokenRateLimits.ApplicationRateLimitStatusLimit.ResetDateTime.ToLongTimeString());
        }

        private static void GetCredentialsRateLimits()
        {
            var credentials = TwitterCredentials.CreateCredentials("ACCESS_TOKEN", "ACCESS_TOKEN_SECRET", "CONSUMER_KEY", "CONSUMER_SECRET");
            var tokenRateLimits = RateLimit.GetCredentialsRateLimits(credentials);

            Console.WriteLine("Remaning Requests for GetRate : {0}", tokenRateLimits.ApplicationRateLimitStatusLimit.Remaining);
            Console.WriteLine("Total Requests Allowed for GetRate : {0}", tokenRateLimits.ApplicationRateLimitStatusLimit.Limit);
            Console.WriteLine("GetRate limits will reset at : {0} local time", tokenRateLimits.ApplicationRateLimitStatusLimit.ResetDateTime.ToLongTimeString());
        }

        private static void GetTwitterPrivacyPolicy()
        {
            Console.WriteLine(Help.GetTwitterPrivacyPolicy());
        }

        #endregion

        #region Json

        private static void Json_GetJsonForAccountRequestExample()
        {
            string jsonResponse = AccountJson.GetLoggedUserSettingsJson();
            Console.WriteLine(jsonResponse);
        }

        private static void Json_GetJsonForMessageRequestExample()
        {
            IUser user = User.GetUserFromScreenName("tweetinviapi");
            string jsonResponse = MessageJson.PublishMessage("salut", user.UserDTO);

            Console.WriteLine(jsonResponse);
        }

        private static void Json_GetJsonForGeoRequestExample()
        {
            var jsonResponse = GeoJson.GetPlaceFromId("df51dec6f4ee2b2c");
            Console.WriteLine(jsonResponse);
        }

        private static void Json_GetJsonForHelpRequestExample()
        {
            var jsonResponse = HelpJson.GetTokenRateLimits();
            Console.WriteLine(jsonResponse);
        }

        private static void Json_GetJsonForSavedSearchRequestExample()
        {
            var jsonResponse = SavedSearchJson.GetSavedSearches();
            Console.WriteLine(jsonResponse);
        }

        private static void Json_GetJsonForTimelineRequestExample()
        {
            var jsonResponse = TimelineJson.GetHomeTimeline(2);
            Console.WriteLine(jsonResponse);
        }

        private static void Json_GetJsonForTrendsRequestExample()
        {
            var jsonResponse = TrendsJson.GetTrendsAt(1);
            Console.WriteLine(jsonResponse);
        }

        private static void Json_GetJsonForTweetRequestExample()
        {
            var tweet = Tweet.CreateTweet("Hello there!");
            var jsonResponse = TweetJson.PublishTweet(tweet);
            Console.WriteLine(jsonResponse);
        }

        private static void Json_GetJsonForUserRequestExample()
        {
            var loggedUser = User.GetLoggedUser();
            var jsonResponse = UserJson.GetFriendIds(loggedUser);
            Console.WriteLine(jsonResponse.ElementAt(0));
        }

        private static void Json_GetJsonCursorRequestExample()
        {
            // This query is a cursor query
            var jsonResponses = FriendshipJson.GetUserIdsRequestingFriendship();

            foreach (var jsonResponse in jsonResponses)
            {
                Console.WriteLine(jsonResponse);
            }
        }

        #endregion

        #region Stream

        private static void SimpleStream_Events()
        {
            var stream = Stream.CreateTweetStream();
            stream.TweetReceived += (sender, args) => { };
            stream.TweetDeleted += (sender, args) => { };
            stream.TweetLocationInfoRemoved += (sender, args) => { };

            stream.TweetWitheld += (sender, args) => { };
            stream.UserWitheld += (sender, args) => { };

            stream.LimitReached += (sender, args) => { };
            stream.DisconnectMessageReceived += (sender, args) => { };
            stream.WarningFallingBehindDetected += (sender, args) => { };

            stream.UnmanagedEventReceived += (sender, args) => { };
        }

        private static void Stream_SampleStreamExample()
        {
            var stream = Stream.CreateSampleStream();
            stream.TweetReceived += (sender, args) =>
            {
                Console.WriteLine(args.Tweet.Text);
            };
            stream.StartStream();
        }

        private static void Stream_FilteredStreamExample()
        {
            var stream = Stream.CreateFilteredStream();
            var location = Geo.GenerateLocation(-124.75, 36.8, -126.89, 32.75);

            stream.AddLocation(location);
            stream.AddTrack("tweetinvi");
            stream.AddTrack("linvi");

            stream.MatchingTweetAndLocationReceived += (sender, args) =>
            {
                var tweet = args.Tweet;
                Console.WriteLine("{0} was detected between the following tracked locations:", tweet.Id);

                IEnumerable<ILocation> matchingLocations = args.MatchedLocations;
                foreach (var matchingLocation in matchingLocations)
                {
                    Console.Write("({0}, {1}) ;", matchingLocation.Coordinate1.Latitude, matchingLocation.Coordinate1.Longitude);
                    Console.WriteLine("({0}, {1})", matchingLocation.Coordinate2.Latitude, matchingLocation.Coordinate2.Longitude);
                }
            };

            stream.StartStreamMatchingAllConditions();
        }

        private static void Stream_UserStreamExample()
        {
            var userStream = Stream.CreateUserStream();

            // Tweet Published
            EventsRelatedWithTweetCreation(userStream);

            // Messages
            EventsRelatedWithMessages(userStream);

            // Favourited - Unfavourited
            EventsRelatedWithTweetAndFavourite(userStream);

            // Lists
            EventsRelatedWithLists(userStream);

            // Block - Unblock
            EventsRelatedWithBlock(userStream);

            // User Update
            userStream.LoggedUserProfileUpdated += (sender, args) =>
            {
                var newLoggedUser = args.LoggedUser;
                Console.WriteLine("Logged user '{0}' has been updated!", newLoggedUser.Name);
            };

            // Friends the stream will analyze - A UserStream cannot analyze more than 10.000 people at the same time
            userStream.FriendIdsReceived += (sender, args) =>
            {
                var friendIds = args.Value;
                Console.WriteLine(friendIds.Count());
            };

            userStream.StartStream();
        }

        private static void EventsRelatedWithTweetCreation(IUserStream userStream)
        {
            userStream.TweetCreatedByAnyone += (sender, args) =>
            {
                Console.WriteLine("Tweet created by anyone");
            };

            userStream.TweetCreatedByMe += (sender, args) =>
            {
                Console.WriteLine("Tweet created by me");
            };

            userStream.TweetCreatedByAnyoneButMe += (sender, args) =>
            {
                Console.WriteLine("Tweet created by {0}", args.Tweet.Creator.Name);
            };
        }

        private static void EventsRelatedWithMessages(IUserStream userStream)
        {
            userStream.MessageSent += (sender, args) => { Console.WriteLine("message '{0}' sent", args.Message.Text); };
            userStream.MessageReceived += (sender, args) => { Console.WriteLine("message '{0}' received", args.Message.Text); };
        }

        private static void EventsRelatedWithTweetAndFavourite(IUserStream userStream)
        {
            // Favourite
            userStream.TweetFavouritedByAnyone += (sender, args) =>
            {
                var tweet = args.Tweet;
                var userWhoFavouritedTheTweet = args.FavouritingUser;
                Console.WriteLine("User '{0}' favourited tweet '{1}'", userWhoFavouritedTheTweet.Name, tweet.Id);
            };

            userStream.TweetFavouritedByMe += (sender, args) =>
            {
                var tweet = args.Tweet;
                var loggedUser = args.FavouritingUser;
                Console.WriteLine("Logged User '{0}' favourited tweet '{1}'", loggedUser.Name, tweet.Id);
            };

            userStream.TweetFavouritedByAnyoneButMe += (sender, args) =>
            {
                var tweet = args.Tweet;
                var userWhoFavouritedTheTweet = args.FavouritingUser;
                Console.WriteLine("User '{0}' favourited tweet '{1}'", userWhoFavouritedTheTweet.Name, tweet.Id);
            };

            // Unfavourite
            userStream.TweetUnFavouritedByAnyone += (sender, args) =>
            {
                var tweet = args.Tweet;
                var userWhoFavouritedTheTweet = args.FavouritingUser;
                Console.WriteLine("User '{0}' unfavourited tweet '{1}'", userWhoFavouritedTheTweet.Name, tweet.Id);
            };

            userStream.TweetUnFavouritedByMe += (sender, args) =>
            {
                Console.WriteLine("Tweet unfavourited by me!");
            };

            userStream.TweetUnFavouritedByAnyoneButMe += (sender, args) =>
            {
                var tweet = args.Tweet;
                var userWhoFavouritedTheTweet = args.FavouritingUser;
                Console.WriteLine("User '{0}' favourited tweet '{1}'", userWhoFavouritedTheTweet.Name, tweet.Id);
            };
        }

        private static void EventsRelatedWithLists(IUserStream userStream)
        {
            userStream.ListCreated += (sender, args) =>
            {
                Console.WriteLine("List '{0}' created!", args.List.Name);
            };

            userStream.ListUpdated += (sender, args) =>
            {
                Console.WriteLine("List '{0}' updated!", args.List.Name);
            };

            userStream.ListDestroyed += (sender, args) =>
            {
                Console.WriteLine("List '{0}' destroyed!", args.List.Name);
            };

            // User Added
            userStream.LoggedUserAddedMemberToList += (sender, args) =>
            {
                var newUser = args.User;
                var list = args.List;
                Console.WriteLine("You added '{0}' to the list : '{1}'", newUser.Name, list.Name);
            };

            userStream.LoggedUserAddedToListBy += (sender, args) =>
            {
                var newUser = args.User;
                var list = args.List;
                Console.WriteLine("You haved been added to the list '{0}' by '{1}'", list.Name, newUser.Name);
            };

            // User Removed
            userStream.LoggedUserRemovedMemberFromList += (sender, args) =>
            {
                var newUser = args.User;
                var list = args.List;
                Console.WriteLine("You removed '{0}' from the list : '{1}'", newUser.Name, list.Name);
            };

            userStream.LoggedUserRemovedFromListBy += (sender, args) =>
            {
                var newUser = args.User;
                var list = args.List;
                Console.WriteLine("You haved been removed from the list '{0}' by '{1}'", list.Name, newUser.Name);
            };

            // User Subscribed
            userStream.LoggedUserSubscribedToListCreatedBy += (sender, args) =>
            {
                var list = args.List;
                Console.WriteLine("You have subscribed to the list '{0}", list.Name);
            };

            userStream.UserSubscribedToListCreatedByMe += (sender, args) =>
            {
                var list = args.List;
                var user = args.User;
                Console.WriteLine("'{0}' have subscribed to your list '{1}'", user.Name, list.Name);
            };

            // User Unsubscribed
            userStream.LoggedUserUnsubscribedToListCreatedBy += (sender, args) =>
            {
                var list = args.List;
                Console.WriteLine("You have unsubscribed from the list '{0}'", list.Name);
            };

            userStream.UserUnsubscribedToListCreatedByMe += (sender, args) =>
            {
                var list = args.List;
                var user = args.User;
                Console.WriteLine("'{0}' have unsubscribed from your list '{1}'", user.Name, list.Name);
            };
        }

        private static void EventsRelatedWithBlock(IUserStream userStream)
        {
            userStream.BlockedUser += (sender, args) =>
            {
                Console.WriteLine("I blocked a '{0}'", args.User.ScreenName);
            };

            userStream.UnBlockedUser += (sender, args) =>
            {
                Console.WriteLine("I un blocked a '{0}'", args.User.ScreenName);
            };
        }

        #endregion

        #region Exception

        private static void Exceptions_GetExceptionsInfo()
        {
            TwitterCredentials.Credentials = null;

            var user = User.GetLoggedUser();
            if (user == null)
            {
                var lastException = ExceptionHandler.GetLastException();
                Console.WriteLine(lastException.TwitterDescription);
            }
        }

        #endregion

        #region Manual Query

        private static void ManualQuery_Example()
        {
            const string getHomeTimelineQuery = "https://api.twitter.com/1.1/statuses/home_timeline.json";

            // Execute Query can either return a json or a DTO interface
            var tweetsDTO = TwitterAccessor.ExecuteGETQuery<IEnumerable<ITweetDTO>>(getHomeTimelineQuery);
            tweetsDTO.ForEach(tweetDTO => Console.WriteLine(tweetDTO.Text));
        }

        #endregion

        #region Configuration (Timeout/Proxy)

        private static void ConfigureTweetinvi()
        {
            // TweetinviConfig.CURRENT_PROXY_URL = "http://228.23.13.21:4287";

            // Configure a proxy with Proxy with username and password
            // TweetinviConfig.CURRENT_PROXY_URL = "http://user:pass@228.23.13.21:4287";

            // TweetinviConfig.CURRENT_WEB_REQUEST_TIMEOUT = 5000;
            // TweetinviConfig.CURRENT_SHOW_DEBUG = false;
        }

        private static void GlobalEvents()
        {
            //TweetinviEvents.QueryBeforeExecute += (sender, args) =>
            //{
            //    Console.WriteLine("The query {0} is about to be executed.", args.Query);
            //};

            //TweetinviEvents.QueryAfterExecute += (sender, args) =>
            //{
            //    Console.WriteLine("The query {0} has just been executed.", args.Query);
            //};
        }

        #endregion
    }
}