text:
import binance
import asyncio

# Turn logging on, its off by default
binance.enable_logging(True)

api_key = ""
api_secret_key = ""

def market_data():
    print("\nMarket data examples\n")

    # ping binance to see if it's online and verify we can hit it
    print("Connection ok? ", binance.ping())

    # Get the current server time in milliseconds
    print("Server time: ", binance.server_time())

    # Get the order book for a symbol with max 5 entries
    order_book = binance.order_book("BNBBTC", 5)
    print(order_book)

    print("Order book for BNB-BTC")
    print("asks")
    for (price, quantity) in order_book.asks:
        print(price, quantity)

    print("bids")
    for (price, quantity) in order_book.bids:
        print(price, quantity)

    # Get aggregated trades
    print(binance.aggregate_trades("BNBBTC", limit=5))

    candles = binance.candlesticks("BNBBTC", "1m")
    print(candles)

    # Ticker operations
    print("Current ticker prices")
    prices = binance.ticker_prices()
    print(prices)

    print("Current ticker for order books")
    order_books = binance.ticker_order_books()
    print(order_books["ETHBTC"])

    print("Order book ticker for ETHBTC")
    book = order_books["ETHBTC"]
    print(book)

    print("Order book ticker for BNBBTC")
    book = order_books["BNBBTC"]
    print(book)

    last_24hr = binance.ticker_24hr("BNBBTC")
    print(last_24hr)

def account():
    print("\nAccount data examples\n")

    # For signed requests we create an Account instance and give it the api key and secret
    account = binance.Account(api_key, api_secret_key)

    account.set_receive_window(5000)

    new_order = account.new_order("ETHBTC", "BUY", "LIMIT", .1, 0.01)
    new_order_id = new_order["orderId"]
    print("new order id = ", new_order_id)

    order = account.query_order("ETHBTC", new_order_id)
    print(order)

    order = account.cancel_order("ETHBTC", new_order_id)
    print(order)

    open_orders = account.open_orders("ETHBTC")
    print(open_orders)

    all_orders = account.all_orders("ETHBTC")
    print(all_orders)

    info = account.account_info()
    print(info)

    trades = account.my_trades("ETHBTC")
    print(trades)

def user_stream():
    print("\nUser Stream examples\n")

    stream = binance.Streamer()

    async def stop():
        await(asyncio.sleep(5))
        stream.close_all()
        asyncio.get_event_loop().stop()

    def on_user_data(data):
        print("new user data: ", data)

    stream.start_user(api_key, on_user_data)

    asyncio.Task(stop())

    asyncio.get_event_loop().run_forever()

def data_streams():
    print("\nData Stream examples\n")

    stream = binance.Streamer()

    async def stop():
        await(asyncio.sleep(5))
        stream.close_all()
        asyncio.get_event_loop().stop()

    def on_order_book(data):
        print("order book canges - ", data)
        print("full orderbook - ", stream.get_order_book("ETHBTC"))

    stream.add_order_book("ETHBTC", on_order_book)

    def on_candlestick(data):
        print("new candlesticks - ", data)
        print("all candlesticks- ", stream.get_candlesticks("ETHBTC"))

    stream.add_candlesticks("ETHBTC", "1m", on_candlestick)

    def on_trades(data):
        print("trade update - ", data)

    stream.add_trades("ETHBTC", on_trades)

    asyncio.Task(stop())

    asyncio.get_event_loop().run_forever()

market_data()
account()
user_stream()
data_streams()


text:
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.containers;

import com.intellij.openapi.util.Key;
import org.jetbrains.annotations.NotNull;

/**
 * @author peter
 */
public abstract class ImmutableUserMap {
  public static final ImmutableUserMap EMPTY = new ImmutableUserMap() {
    @Override
    public <T> T get(@NotNull final Key<T> key) {
      return null;
    }
  };

  private ImmutableUserMap() {
  }

  public abstract <T> T get(@NotNull Key<T> key);

  public final <T> ImmutableUserMap put(@NotNull final Key<T> key, final T value) {
    return new ImmutableUserMapImpl<>(key, value, this);
  }

  private static final class ImmutableUserMapImpl<V> extends ImmutableUserMap {
    private final Key<V> myKey;
    private final V myValue;
    private final ImmutableUserMap myNext;

    private ImmutableUserMapImpl(final Key<V> key, final V value, final ImmutableUserMap next) {
      myKey = key;
      myNext = next;
      myValue = value;
    }

    @Override
    public <T> T get(@NotNull final Key<T> key) {
      if (key.equals(myKey)) return (T)myValue;
      return myNext.get(key);
    }

  }
}

redpajama_set_name: RedPajamaGithub


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Internal.Runtime.CompilerServices;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;

namespace System
{
    // The BitConverter class contains methods for
    // converting an array of bytes to one of the base data
    // types, as well as for converting a base data type to an
    // array of bytes.
    public static class BitConverter
    {
        // This field indicates the "endianess" of the architecture.
        // The value is set to true if the architecture is
        // little endian; false if it is big endian.
#if BIGENDIAN
        public static readonly bool IsLittleEndian /* = false */;
#else
        public static readonly bool IsLittleEndian = true;
#endif

        // Converts a Boolean into an array of bytes with length one.
        public static byte[] GetBytes(bool value)
        {
            Contract.Ensures(Contract.Result<byte[]>() != null);
            Contract.Ensures(Contract.Result<byte[]>().Length == 1);

            byte[] r = new byte[1];
            r[0] = (value ? (byte)1 : (byte)0);
            return r;
        }

        // Converts a char into an array of bytes with length two.
        public static byte[] GetBytes(char value)
        {
            Contract.Ensures(Contract.Result<byte[]>() != null);
            Contract.Ensures(Contract.Result<byte[]>().Length == 2);

            return GetBytes((short)value);
        }

        // Converts a short into an array of bytes with length
        // two.
        public static unsafe byte[] GetBytes(short value)
        {
            Contract.Ensures(Contract.Result<byte[]>() != null);
            Contract.Ensures(Contract.Result<byte[]>().Length == 2);

            byte[] bytes = new byte[2];
            fixed (byte* b = &bytes[0])
                *((short*)b) = value;
            return bytes;
        }

        // Converts an int into an array of bytes with length
        // four.
        public static unsafe byte[] GetBytes(int value)
        {
            Contract.Ensures(Contract.Result<byte[]>() != null);
            Contract.Ensures(Contract.Result<byte[]>().Length == 4);

            byte[] bytes = new byte[4];
            fixed (byte* b = &bytes[0])
                *((int*)b) = value;
            return bytes;
        }

        // Converts a long into an array of bytes with length
        // eight.
        public static unsafe byte[] GetBytes(long value)
        {
            Contract.Ensures(Contract.Result<byte[]>() != null);
            Contract.Ensures(Contract.Result<byte[]>().Length == 8);

            byte[] bytes = new byte[8];
            fixed (byte* b = &bytes[0])
                *((long*)b) = value;
            return bytes;
        }

        // Converts an ushort into an array of bytes with
        // length two.
        [CLSCompliant(false)]
        public static byte[] GetBytes(ushort value)
        {
            Contract.Ensures(Contract.Result<byte[]>() != null);
            Contract.Ensures(Contract.Result<byte[]>().Length == 2);

            return GetBytes(unchecked((short)value));
        }

        // Converts an uint into an array of bytes with
        // length four.
        [CLSCompliant(false)]
        public static byte[] GetBytes(uint value)
        {
            Contract.Ensures(Contract.Result<byte[]>() != null);
            Contract.Ensures(Contract.Result<byte[]>().Length == 4);

            return GetBytes(unchecked((int)value));
        }

        // Converts an unsigned long into an array of bytes with
        // length eight.
        [CLSCompliant(false)]
        public static byte[] GetBytes(ulong value)
        {
            Contract.Ensures(Contract.Result<byte[]>() != null);
            Contract.Ensures(Contract.Result<byte[]>().Length == 8);

            return GetBytes(unchecked((long)value));
        }

        // Converts a float into an array of bytes with length
        // four.
        public static unsafe byte[] GetBytes(float value)
        {
            Contract.Ensures(Contract.Result<byte[]>() != null);
            Contract.Ensures(Contract.Result<byte[]>().Length == 4);

            return GetBytes(*(int*)&value);
        }

        // Converts a double into an array of bytes with length
        // eight.
        public static unsafe byte[] GetBytes(double value)
        {
            Contract.Ensures(Contract.Result<byte[]>() != null);
            Contract.Ensures(Contract.Result<byte[]>().Length == 8);

            return GetBytes(*(long*)&value);
        }

        // Converts an array of bytes into a char.
        public static char ToChar(byte[] value, int startIndex)
        {
            if (value == null)
                ThrowValueArgumentNull();
            if (unchecked((uint)startIndex) >= value.Length)
                ThrowStartIndexArgumentOutOfRange();
            if (startIndex > value.Length - 2)
                ThrowValueArgumentTooSmall();
            Contract.EndContractBlock();

            return unchecked((char)ToInt16(value, startIndex));
        }

        // Converts an array of bytes into a short.
        public static unsafe short ToInt16(byte[] value, int startIndex)
        {
            if (value == null)
                ThrowValueArgumentNull();
            if (unchecked((uint)startIndex) >= value.Length)
                ThrowStartIndexArgumentOutOfRange();
            if (startIndex > value.Length - 2)
                ThrowValueArgumentTooSmall();
            Contract.EndContractBlock();

            fixed (byte* pbyte = &value[startIndex])
            {
                if (startIndex % 2 == 0)
                {
                    // data is aligned
                    return *((short*)pbyte);
                }
                else if (IsLittleEndian)
                {
                    return (short)((*pbyte) | (*(pbyte + 1) << 8));
                }
                else
                {
                    return (short)((*pbyte << 8) | (*(pbyte + 1)));
                }
            }
        }

        // Converts an array of bytes into an int.
        public static unsafe int ToInt32(byte[] value, int startIndex)
        {
            if (value == null)
                ThrowValueArgumentNull();
            if (unchecked((uint)startIndex) >= value.Length)
                ThrowStartIndexArgumentOutOfRange();
            if (startIndex > value.Length - 4)
                ThrowValueArgumentTooSmall();
            Contract.EndContractBlock();

            fixed (byte* pbyte = &value[startIndex])
            {
                if (startIndex % 4 == 0)
                {
                    // data is aligned
                    return *((int*)pbyte);
                }
                else if (IsLittleEndian)
                {
                    return (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24);
                }
                else
                {
                    return (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3));
                }
            }
        }

        // Converts an array of bytes into a long.
        public static unsafe long ToInt64(byte[] value, int startIndex)
        {
            if (value == null)
                ThrowValueArgumentNull();
            if (unchecked((uint)startIndex) >= value.Length)
                ThrowStartIndexArgumentOutOfRange();
            if (startIndex > value.Length - 8)
                ThrowValueArgumentTooSmall();
            Contract.EndContractBlock();

            fixed (byte* pbyte = &value[startIndex])
            {
                if (startIndex % 8 == 0)
                {
                    // data is aligned
                    return *((long*)pbyte);
                }
                else if (IsLittleEndian)
                {
                    int i1 = (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24);
                    int i2 = (*(pbyte + 4)) | (*(pbyte + 5) << 8) | (*(pbyte + 6) << 16) | (*(pbyte + 7) << 24);
                    return unchecked((uint)i1) | ((long)i2 << 32);
                }
                else
                {
                    int i1 = (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3));
                    int i2 = (*(pbyte + 4) << 24) | (*(pbyte + 5) << 16) | (*(pbyte + 6) << 8) | (*(pbyte + 7));
                    return unchecked((uint)i2) | ((long)i1 << 32);
                }
            }
        }

        // Converts an array of bytes into an ushort.
        //
        [CLSCompliant(false)]
        public static ushort ToUInt16(byte[] value, int startIndex)
        {
            if (value == null)
                ThrowValueArgumentNull();
            if (unchecked((uint)startIndex) >= value.Length)
                ThrowStartIndexArgumentOutOfRange();
            if (startIndex > value.Length - 2)
                ThrowValueArgumentTooSmall();
            Contract.EndContractBlock();

            return unchecked((ushort)ToInt16(value, startIndex));
        }

        // Converts an array of bytes into an uint.
        //
        [CLSCompliant(false)]
        public static uint ToUInt32(byte[] value, int startIndex)
        {
            if (value == null)
                ThrowValueArgumentNull();
            if (unchecked((uint)startIndex) >= value.Length)
                ThrowStartIndexArgumentOutOfRange();
            if (startIndex > value.Length - 4)
                ThrowValueArgumentTooSmall();
            Contract.EndContractBlock();

            return unchecked((uint)ToInt32(value, startIndex));
        }

        // Converts an array of bytes into an unsigned long.
        //
        [CLSCompliant(false)]
        public static ulong ToUInt64(byte[] value, int startIndex)
        {
            if (value == null)
                ThrowValueArgumentNull();
            if (unchecked((uint)startIndex) >= value.Length)
                ThrowStartIndexArgumentOutOfRange();
            if (startIndex > value.Length - 8)
                ThrowValueArgumentTooSmall();
            Contract.EndContractBlock();

            return unchecked((ulong)ToInt64(value, startIndex));
        }

        // Converts an array of bytes into a float.
        public static unsafe float ToSingle(byte[] value, int startIndex)
        {
            if (value == null)
                ThrowValueArgumentNull();
            if (unchecked((uint)startIndex) >= value.Length)
                ThrowStartIndexArgumentOutOfRange();
            if (startIndex > value.Length - 4)
                ThrowValueArgumentTooSmall();
            Contract.EndContractBlock();

            int val = ToInt32(value, startIndex);
            return *(float*)&val;
        }

        // Converts an array of bytes into a double.
        public static unsafe double ToDouble(byte[] value, int startIndex)
        {
            if (value == null)
                ThrowValueArgumentNull();
            if (unchecked((uint)startIndex) >= value.Length)
                ThrowStartIndexArgumentOutOfRange();
            if (startIndex > value.Length - 8)
                ThrowValueArgumentTooSmall();
            Contract.EndContractBlock();

            long val = ToInt64(value, startIndex);
            return *(double*)&val;
        }

        private static char GetHexValue(int i)
        {
            Debug.Assert(i >= 0 && i < 16, "i is out of range.");
            if (i < 10)
            {
                return (char)(i + '0');
            }

            return (char)(i - 10 + 'A');
        }

        // Converts an array of bytes into a String.
        public static string ToString(byte[] value, int startIndex, int length)
        {
            if (value == null)
                ThrowValueArgumentNull();
            if (startIndex < 0 || startIndex >= value.Length && startIndex > 0)
                ThrowStartIndexArgumentOutOfRange();
            if (length < 0)
                throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_GenericPositive);
            if (startIndex > value.Length - length)
                ThrowValueArgumentTooSmall();
            Contract.EndContractBlock();

            if (length == 0)
            {
                return string.Empty;
            }

            if (length > (int.MaxValue / 3))
            {
                // (Int32.MaxValue / 3) == 715,827,882 Bytes == 699 MB
                throw new ArgumentOutOfRangeException(nameof(length), SR.Format(SR.ArgumentOutOfRange_LengthTooLarge, (int.MaxValue / 3)));
            }

            int chArrayLength = length * 3;
            const int StackLimit = 512; // arbitrary limit to switch from stack to heap allocation
            unsafe
            {
                if (chArrayLength < StackLimit)
                {
                    char* chArrayPtr = stackalloc char[chArrayLength];
                    return ToString(value, startIndex, length, chArrayPtr, chArrayLength);
                }
                else
                {
                    char[] chArray = new char[chArrayLength];
                    fixed (char* chArrayPtr = &chArray[0])
                        return ToString(value, startIndex, length, chArrayPtr, chArrayLength);
                }
            }
        }

        private static unsafe string ToString(byte[] value, int startIndex, int length, char* chArray, int chArrayLength)
        {
            Debug.Assert(length > 0);
            Debug.Assert(chArrayLength == length * 3);

            char* p = chArray;
            int endIndex = startIndex + length;
            for (int i = startIndex; i < endIndex; i++)
            {
                byte b = value[i];
                *p++ = GetHexValue(b >> 4);
                *p++ = GetHexValue(b & 0xF);
                *p++ = '-';
            }

            // We don't need the last '-' character
            return new string(chArray, 0, chArrayLength - 1);
        }

        // Converts an array of bytes into a String.
        public static string ToString(byte[] value)
        {
            if (value == null)
                ThrowValueArgumentNull();
            Contract.Ensures(Contract.Result<string>() != null);
            Contract.EndContractBlock();
            return ToString(value, 0, value.Length);
        }

        // Converts an array of bytes into a String.
        public static string ToString(byte[] value, int startIndex)
        {
            if (value == null)
                ThrowValueArgumentNull();
            Contract.Ensures(Contract.Result<string>() != null);
            Contract.EndContractBlock();
            return ToString(value, startIndex, value.Length - startIndex);
        }

        /*==================================ToBoolean===================================
        **Action:  Convert an array of bytes to a boolean value.  We treat this array
        **         as if the first 4 bytes were an Int4 an operate on this value.
        **Returns: True if the Int4 value of the first 4 bytes is non-zero.
        **Arguments: value -- The byte array
        **           startIndex -- The position within the array.
        **Exceptions: See ToInt4.
        ==============================================================================*/
        // Converts an array of bytes into a boolean.
        public static bool ToBoolean(byte[] value, int startIndex)
        {
            if (value == null)
                ThrowValueArgumentNull();
            if (startIndex < 0)
                ThrowStartIndexArgumentOutOfRange();
            if (startIndex > value.Length - 1)
                ThrowStartIndexArgumentOutOfRange(); // differs from other overloads, which throw base ArgumentException
            Contract.EndContractBlock();

            return value[startIndex] != 0;
        }

        public static unsafe long DoubleToInt64Bits(double value)
        {
            return *((long*)&value);
        }

        public static unsafe double Int64BitsToDouble(long value)
        {
            return *((double*)&value);
        }

        public static unsafe int SingleToInt32Bits(float value)
        {
            return *((int*)&value);
        }

        public static unsafe float Int32BitsToSingle(int value)
        {
            return *((float*)&value);
        }

        private static void ThrowValueArgumentNull()
        {
            throw new ArgumentNullException("value");
        }

        private static void ThrowStartIndexArgumentOutOfRange()
        {
            throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index);
        }

        private static void ThrowValueArgumentTooSmall()
        {
            throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall, "value");
        }
    }
}


text:
if not table.unpack then
	table.unpack = unpack
end

local Log
local Game

--	main() - Errors are caught from within here
local function main()
	Game = require "lua/game"
	Log = require "lua/log"

	--	the Game object is instantiated
	Game:init()
	Game:start()

	--	the Game object will now take control of all user interactions
	Game:loop()

	--	terminate the game
	Game:terminate()
end

local function errorHandler(errmsg)
	return debug.traceback(errmsg, 2)
end

local success, errmsg = xpcall(main, errorHandler)
if not success then
	--	Need to terminate curses, otherwise the C code will, which will wipe
	--	the stacktrace from the screen
	if curses.running then
		curses.terminate()
	end
	print(errmsg)
	if Log then
		Log:write(errmsg)
	end
end


text:
import com.smartsheet.api.Smartsheet;
import com.smartsheet.api.SmartsheetException;
import com.smartsheet.api.models.*;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

public class UserResourcesIT extends ITResourcesImpl{
    Smartsheet smartsheet;
    User user;

    @Before
    public void setUp() throws Exception {
        smartsheet = createAuthentication();
    }

    @Test
    public void testGetCurrentUser() throws SmartsheetException, IOException {
        UserProfile user = smartsheet.userResources().getCurrentUser();
        Account account = user.getAccount();
        assertNotNull(user);
    }

    @Test
    public void testGetUser() throws SmartsheetException, IOException {
        UserProfile user = smartsheet.userResources().getUser(smartsheet.userResources().getCurrentUser().getId());
        assertNotNull(user);
    }

    @Test
    public void testListUsers() throws SmartsheetException, IOException {
        PaginationParameters parameters = new PaginationParameters.PaginationParametersBuilder().setIncludeAll(true).build();

        PagedResult<User> userWrapper = smartsheet.userResources().listUsers(new HashSet(Arrays.asList("aditi.nioding@gmail.com")), parameters);
        List<User> users = userWrapper.getData();

        //assertTrue(users.size() > 0);
    }

    @Test
    public void testAddProfileImage() throws SmartsheetException, IOException {
        UserProfile me = smartsheet.userResources().getCurrentUser();
        assertNotNull(me);
        smartsheet.userResources().addProfileImage(me.getId(), "src/integration-test/resources/exclam.png", "image/png");
        me = smartsheet.userResources().getCurrentUser();
        assertNotNull(me.getProfileImage());
        final Long squareProfileImageSize = 1050L;
        assertEquals(squareProfileImageSize, me.getProfileImage().getWidth());
        assertEquals(squareProfileImageSize, me.getProfileImage().getHeight());
    }

    @Test
    //not executed in test due to low permission
    public void testAddUser() throws IOException, SmartsheetException {
//        User user = new User.AddUserBuilder().setAdmin(false).setEmail("aditi.nioding@gmail.com").setFirstName("Aditi").setLastName("N").setLicensedSheetCreator(true).build();
//        User newUser = smartsheet.userResources().addUser(user);
//        String name = newUser.getFirstName();
//        assertTrue(name.equals("Aditi"));
//        testUpdateUser(newUser.getId());
    }

    //not executed in test due to low permission
    public void testUpdateUser(long userId) throws SmartsheetException, IOException {
//        User user = new User.UpdateUserBuilder().setAdmin(true).setUserId(userId).setFirstName("Adi").setLicensedSheetCreator(true).build();
//        User updatedUser = smartsheet.userResources().updateUser(user);
//        assertNotNull(updatedUser);
    }

    @Test
    public void testListOrgSheets() throws SmartsheetException, IOException {
        //PagedResult<Sheet> sheets = smartsheet.userResources().listOrgSheets();
        //not executed in test due to low permission
        //assertNotNull(sheets);
    }

    @Test
    //not executed in test due to low permission
    public void testDeleteUser() throws IOException, SmartsheetException {
//        User user = new User.AddUserBuilder().setAdmin(false).setEmail("test@test.com").setFirstName("Aditi").setLastName("N").setLicensedSheetCreator(true).build();
//        User newUser = smartsheet.userResources().addUser(user);
//        Long toId = newUser.getId();
//
//        DeleteUserParameters parameters = new DeleteUserParameters(toId, true, true);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape
  xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#f0a0a0a0" />
    <stroke android:width="2.0dip" color="#A00080FF" />
    <padding android:left="5.0dip" android:top="0.0dip" android:right="5.0dip" android:bottom="1.0dip" />
</shape>


text:
import os
import time
import pytumblr
import urllib
import uuid
from subprocess import call

frequency = 10 # Loop interval
frames = 20 # Fames to take
delay = 0.2 # Delay between frames
gifDelay = 20 # Used for timing GIF generation

# Tumblr config
tumblrName = config.tumblrName
consumerKey = config.consumerKey
consumerSecret = config.consumerSecret
oauthToken = config.oauthToken
oauthSecret = config.oauthSecret
tags = config.tags

# Authenticate via OAuth to Tumblr
tumblr = pytumblr.TumblrRestClient(consumerKey, consumerSecret, oauthToken, oauthSecret)

# Files config
data = "data/"
tmp = data + "tmp/"
output = data + "output/"

# GoPro
goProUrl = "http://10.5.5.9:8080/live/amba.mp4"

def getGif():

  # Remove tmp files
  call("rm -f " + tmp + "*", shell=True)

  # Get MP4 files from GoPro
  print "[+] Talking to GoPro"
  for i in range(frames):
    num = str(i).zfill(3)
    goGoPro(num)
    time.sleep(delay)

  # Convert MP4 files into single GIF images
  print "[+] Converting GoPro files"
  for i in range(frames):
    num = str(i).zfill(3)
    mp4ToGif(num)

  # Make the final GIF
  print "[+] Making GIF"
  filename = makeGif()

  # Post
  post(filename)

  print "Done: " + filename

def mp4ToGif(num):

  call("ffmpeg -i " + tmp + num + ".mp4 -ss 00:00:00 -vframes 1  " + tmp + num + ".png", shell=True)
  call("convert " + tmp + num + ".png " + tmp + num + ".gif", shell=True)

def makeGif():

  uid = str(uuid.uuid4())
  filename = output + uid + ".gif"

  call("gifsicle --colors 256 --delay=" + str(gifDelay) + " --loop " + tmp + "*.gif >" + filename, shell=True)

  return filename

def goGoPro(num):

  urllib.urlretrieve(goProUrl, tmp + num + ".mp4")

def post(filename):

  try:
    tumblr.create_photo(tumblrName, state="published", tags=tags, data=filename)
  except:
    pass

  return True

def status(state):

  print state

  return True

if __name__ == "__main__":

  if not os.path.exists(data):
    os.makedirs(data)
    os.makedirs(tmp)
    os.makedirs(output)

  while 1 == 1:

    try:
      getGif()
    except:
      print "[!] Failed for some reason"

    time.sleep(frequency)


text:
namespace Nz
{
	class ThreadImpl;

	class NAZARA_CORE_API Thread
	{
		public:
			class Id;

			Thread();
			template<typename F> Thread(F function);
			template<typename F, typename... Args> Thread(F function, Args&&... args);
			template<typename C> Thread(void (C::*function)(), C* object);
			Thread(const Thread&) = delete;
			Thread(Thread&& other) noexcept;
			~Thread();

			void Detach();
			Id GetId() const;
			bool IsJoinable() const;
			void Join();

			Thread& operator=(const Thread&) = delete;
			Thread& operator=(Thread&& thread);

			static unsigned int HardwareConcurrency();
			static void Sleep(UInt32 milliseconds);

		private:
			void CreateImpl(Functor* functor);

			ThreadImpl* m_impl;
	};

	class NAZARA_CORE_API Thread::Id
	{
		friend Thread;

		public:
			NAZARA_CORE_API friend bool operator==(const Id& lhs, const Id& rhs);
			NAZARA_CORE_API friend bool operator!=(const Id& lhs, const Id& rhs);
			NAZARA_CORE_API friend bool operator<(const Id& lhs, const Id& rhs);
			NAZARA_CORE_API friend bool operator<=(const Id& lhs, const Id& rhs);
			NAZARA_CORE_API friend bool operator>(const Id& lhs, const Id& rhs);
			NAZARA_CORE_API friend bool operator>=(const Id& lhs, const Id& rhs);

			NAZARA_CORE_API friend std::ostream& operator<<(std::ostream& o, const Id& id);

		private:
			Id(ThreadImpl* thread);

			ThreadImpl* m_id = nullptr;
	};
}

#include <Nazara/Core/Thread.inl>

#endif // NAZARA_THREAD_HPP


text:
@interface AppViewController : UIViewController<UIWebViewDelegate>
{

    IBOutlet UIView * _webView;

    NSUserDefaults *_user;
    UIImageView *_Backimage;//背景图片

    int _i;

    NSMutableArray *_FenUrlArray;//存储分类'url'
    NSMutableArray *_UrlArray;//存储子图片'url'
    NSMutableArray *_Array;//存储'name'
    NSArray *_DataArray;//存储所有数据数组
    UIImageView *_imageView;//最底层image
    //    UIImageView *_imageView1;//
    UIImage *_placeholder;//
    NSMutableArray *_Array1;

    UIActivityIndicatorView *_activityIndicator;//活动指示器
    UIView *_BackView;//活动指示器背景

}

- (id)initViewController;

@property(nonatomic,retain)UIImageView *imageView1;

@end


text:
This provider is being **deprecated** in favor of https://github.com/mevansam/terraform-provider-cf which aims at moving to the https://github.com/terraform-providers github organization and becoming an official terraform provider.

The migration from `terraform-provider-cloudfoundry` to `terraform-provider-cf` can follow the procedure below:
* manually convert the config file from the `terraform-provider-cloudfoundry` resource to `terraform-provider-cf` resources. This can be made easier through IDE completion, see https://github.com/mevansam/terraform-provider-cf/pull/4
* import CF resources into TF state. For each resource type:
   * Identify current resources and their ids, e.g. ``terraform state list | grep cloudfoundry_domain | xargs -n 1 terraform state show ``
   * Import the resource in TF state (manually for through upcoming [importeability support in terraform-provider-cf](https://github.com/mevansam/terraform-provider-cf/issues/6)
   * Remove the `terraform-provider-cloudfoundry` resource from tfstate e.g. ``terraform state list | grep cloudfoundry_domain | xargs -n 1 terraform state remove ``

Potentially, such migration steps can be automated and scheduled into CI/CD such as https://github.com/ljfranklin/terraform-resource/issues/41

## Overview

This terraform provider supports the use-case of managing a Cloud Foundry instance, with current support for:
- [Organizations](#organizations)
- [Spaces](#spaces)
- [Quotas](#quotas) (Space and Organization ones)
- [Security groups](#security-groups) (On space, staging or running)
- [Buildpacks](#buildpacks)
- [Feature flags](#feature-flags)
- [Services](#services)
- [Domains](#domains)
- [Routes](#routes)
- [Isolation Segments](#isolation-segments)
- [Isolation Segments Entitlement](#isolation-segments-entitlement)
- [Isolation Segments Space](#isolation-segments-space)
- [Stacks](#stacks)
- [Environment Variable Group](#environment-variable-group)
- [Applications](#applications)
- [Service brokers](#service-brokers) ([Support gpg encryption on password](#enable-password-encryption))

You can also find useful [terraform modules](https://www.terraform.io/docs/modules/index.html) at https://github.com/orange-cloudfoundry/terraform-cloudfoundry-modules.

## Installations

**Requirements:** You need, of course, terraform (**>=0.8**) which is available here: https://www.terraform.io/downloads.html

### Automatic

To install a specific version, set PROVIDER_CLOUDFOUNDRY_VERSION before executing the following command

```bash
$ export PROVIDER_CLOUDFOUNDRY_VERSION="v0.9.1"
```

#### via curl

```bash
$ bash -c "$(curl -fsSL https://raw.github.com/orange-cloudfoundry/terraform-provider-cloudfoundry/master/bin/install.sh)"
```

#### via wget

```bash
$ bash -c "$(wget https://raw.github.com/orange-cloudfoundry/terraform-provider-cloudfoundry/master/bin/install.sh -O -)"
```

### Manually

1. Get the build for your system in releases: https://github.com/orange-cloudfoundry/terraform-provider-cloudfoundry/releases/latest
2. Create a `providers` directory inside terraform user folder: `mkdir -p ~/.terraform.d/providers`
3. Move the provider previously downloaded in this folder: `mv /path/to/download/directory/terraform-provider-cloudfoundry ~/.terraform.d/providers`
4. Ensure provider is executable: `chmod +x ~/.terraform.d/providers/terraform-provider-cloudfoundry`
5. add `providers` path to your `.terraformrc`:
```bash
cat <<EOF > ~/.terraformrc
providers {
    cloudfoundry = "/full/path/to/.terraform.d/providers/terraform-provider-cloudfoundry"
}
EOF
```

6. you can now performs any terraform action on Cloud Foundry resources

## provider configuration

```tf
provider "cloudfoundry" {
  api_endpoint = "https://api.of.your.cloudfoundry.com"
  username = "user"
  password = "mypassword"
  skip_ssl_validation = true
  enc_private_key = "${file("secring_b64.gpg")}"
  enc_passphrase = "mypassphrase"
  verbose = false
  user_access_token = "bearer key"
  user_refresh_token = "bearer key"
}
```

- **name**: (**Required**, *Env Var: `CF_API`*) Your Cloud Foundry api url.
- **username**: *(Optional, default: `null`, Env Var: `CF_USERNAME`)* The username of an admin user. (Optional if you use an access token)
- **password**: *(Optional, default: `null`, Env Var: `CF_PASSWORD`)* The password of an admin user. (Optional if you use an access token)
- **skip_ssl_validation**: *(Optional, default: `false`)* Set to true to skip verification of the API endpoint. Not recommended!.
- **enc_private_key**: *(Optional, default: `null`, Env Var: `CF_ENC_PRIVATE_KEY`)* A GPG private key(s) generate from `gpg --export-secret-key -a <real name>` . Need a passphrase with `enc_passphrase`..
- **enc_passphrase**: *(Optional, default: `null`, Env Var: `CF_ENC_PASSPHRASE`)* The passphrase for your gpg key.
- **verbose**: *(Optional, default: `null`)* Set to true to see requests sent to Cloud Foundry. (Use `TF_LOG=1` to see them)
- **user_access_token**: *(Optional, default: `null`, Env Var: `CF_TOKEN`)* The OAuth token used to connect to a Cloud Foundry. (Optional if you use 'username' and 'password')
- **user_refresh_token**: *(Optional, default: `null`)* The OAuth refresh token used to refresh your token.

## Resources and Data sources

----

### Organizations

#### Resource

```tf
resource "cloudfoundry_organization" "org_mysuperorg" {
  name = "mysuperorg"
  is_system_domain = true
  quota_id = "${cloudfoundry_quota.quota_mysuperquota.id}"
}
```

- **name**: (**Required**) Name of your organization.
- **is_system_domain**: *(Optional, default: `false`)* set it to true only if this organization is a system_domain organization, it will prevent deletion on Cloud Foundry.
- **quota_id**: *(Optional, default: `null`)* Give a quota id (created from resource [cloudfoundry_quota](#quotas)) to set a quota on this org.

#### Data source

##### Get one org with all details

**Note**: every parameters from resource which are not used here are marked as computed and will be filled.

```tf
data "cloudfoundry_organization" "org_mysuperorg" {
  name = "mysuperorg"
  // or by_id = "a-guid"
}

// get quota id for example: ${data.cloudfoundry_organization.cloudfoundry_organization.quota_id}
```

- **name**: (**Required if by_id not set**) Name of your organization.
- **by_id**: (**Required if name not set**) by_id of your organization.

##### Get all orgs

```hcl
data "cloudfoundry_organizations" "available" {}

data "cloudfoundry_organization" "cloudfoundry_organization" {
    name = "${data.cloudfoundry_organizations.available.names[0]}"
}
```

- **names**: (*Computed*) List of the organizations name found.
- **ids**: (*Computed*) List of the organizations id found. (same order as `names`)

----

### Spaces

#### Resource

```tf
resource "cloudfoundry_space" "space_mysuperspace" {
    name = "mysuperspace"
    org_id = "${cloudfoundry_organization.org_mysuperorg.id}"
    quota_id = "${cloudfoundry_quota.quota_mysuperquota.id}"
    sec_groups = ["${cloudfoundry_sec_group.sec_group_mysupersecgroup.id}"]
    allow_ssh = true
}
```

- **name**: (**Required**) Name of your space.
- **org_id**: (**Required**) Organization id created from resource or data source [cloudfoundry_organization](#organizations).
- **allow_ssh**: *(Optional, default: `true`)* Set to `false` to remove ssh access on app instances inside this space.
- **sec_groups**: *(Optional, default: `null`)* This is a list of security groups id created from [cloudfoundry_sec_group](#security-groups), it will bind each security group on this space.
- **quota_id**: *(Optional, default: `null`)* Give a quota id (created from resource [cloudfoundry_quota](#quotas)) to set a quota on this space.

#### Data source

##### Get one space with all details

**Note**: every parameters from resource which are not used here are marked as computed and will be filled.

```tf
data "cloudfoundry_space" "space_mysuperspace" {
    name = "mysuperspace"
    org_id = "${cloudfoundry_organization.org_mysuperorg.id}"
    // or by_id = "a-guid"
}
```

- **name**: (**Required if by_id not set**) Name of your space.
- **org_id**: (**Required if by_id not set**) Organization id created from resource or data source [cloudfoundry_organization](#organizations).
- **by_id**: (**Required if name not set**) by_id of your space.

##### Get all spaces

```hcl
data "cloudfoundry_spaces" "available" {
  org_id = "${cloudfoundry_organization.org_mysuperorg.id}"
}

data "cloudfoundry_space" "space_mysuperspace" {
    name = "${data.cloudfoundry_spaces.available.names[0]}"
    org_id = "${cloudfoundry_organization.org_mysuperorg.id}"
}
```

- **org_id**: (*Optional, Default: Empty*) Organization id created from resource or data source [cloudfoundry_organization](#organizations).
If not set all spaces will be retrieve.
- **names**: (*Computed*) List of the spaces name found.
- **ids**: (*Computed*) List of the spaces id found. (same order as `names`)

----

### Quotas

#### Resource

**Note**: There is two kinds of quotas inside Cloud Foundry: a space's quota, an organization's quota. This resource is able to find what kind of quota you defined. If you omit *`org_id`* the resource will consider this
quota as an organization's quota. With it will consider it's a space's quota.

```tf
resource "cloudfoundry_quota" "quota_for_ahalet" {
  name = "quotaAhalet"
  org_id = "${cloudfoundry_organization.org_mysuperorg.id}"
  total_memory = "10G"
  instance_memory = "1G"
  routes = 200
  service_instances = 10
  app_instances = -1
  allow_paid_service_plans = true
  reserved_route_ports = 0
}
```

- **name**: (**Required**) Name of your quota.
- **org_id**: *(Optional, default: `null`)* If set to an organization id created from resource or data source [cloudfoundry_organization](#organizations), it will be considered as organization quota, else it will be a space quota.
- **total_memory**: *(Optional, default: `20G`)* Total amount of memory a space can have (e.g. 1024M, 1G, 10G).
- **total_instance_memory**: *(Optional, default: `-1`)* Maximum amount of memory an application instance can have (e.g. 1024M, 1G, 10G). -1 represents an unlimited amount.
- **routes**: *(Optional, default: `2000`)* Total number of routes that a space can have.
- **service_instances**: *(Optional, default: `200`)* Total number of service instances which can be created that a space can have.
- **app_instances**: *(Optional, default: `-1`)* Total number of application instances that a space can have. -1 represents an unlimited amount.
- **app_allow_paid_service_plans**: *(Optional, default: `true`)* Can provision instances of paid service plans.
- **reserved_route_ports**: *(Optional, default: `0`)* Maximum number of routes that may be created with reserved ports in a space.

#### Data source

**Note**: every parameters from resource which are not used here are marked as computed and will be filled.

```tf
data "cloudfoundry_quota" "quota_for_ahalet" {
  name = "quotaAhalet"
  org_id = "${cloudfoundry_organization.org_mysuperorg.id}"
  // or by_id = "a-guid"
}
```

- **name**: (**Required if by_id not set**) Name of your quota.
- **org_id**: *(Optional, default: `null`)* If set to an organization id created from resource or data source [cloudfoundry_organization](#organizations), it will be considered as organization quota, else it will be a space quota.
- **by_id**: (**Required if name not set**) by_id of your quota.

----

### Security groups

#### Resource

```tf
resource "cloudfoundry_sec_group" "sec_group_mysupersecgroup" {
  name = "mysupersecgroup"
  on_staging = false
  on_running = false
  rules {
    protocol = "tcp"
    destination = "10.0.0.2"
    ports = "65000"
    log = false
    description = "my description"
  }
  rules {
    protocol = "icmp"
    destination = "192.0.2.0-192.0.1-4"
    type = 3
    code = 1
  }
  rules {
      protocol = "all"
      destination = "10.0.0.0/24"
      log = true
    }
}
```

- **name**: (**Required**) Name of your security group.
- **on_staging**: *(Optional, default: `false`)* Set to true to apply this security group during staging an app.
- **on_running**: *(Optional, default: `false`)* Set to true to apply this security group during running an app.
- **rules**: *(Optional, default: `null`)* Add rules as many as you need:
  - **protocol**: (**Required**) The protocol to use, it can be `tcp`, `udp`, `icmp`, or `all`
  - **destination**: *(Optional, default: `null`)* A single IP address, an IP address range (e.g. 192.0.2.0-192.0.1-4), or a CIDR block to allow network access to.
  - **ports**: *(Optional, default: `null`)* A single port, multiple comma-separated ports, or a single range of ports that can receive traffic, e.g. `"443"`, `"80,8080,8081"`, `"8080-8081"`. Required when `protocol` is `tcp` or `udp`.
  - **code**: *(Optional, default: `null`)* ICMP code. Required when `protocol` is `icmp`.
  - **type**: *(Optional, default: `null`)* ICMP type. Required when `protocol` is `icmp`.
  - **log**: *(Optional, default: `false`)* Set to `true` to enable logging. For more information about how to configure system logs to be sent to a syslog drain, see [Using Log Management Services](https://docs.cloudfoundry.org/devguide/services/log-management.html) topic.
  - **description**: *(Optional, default: `null`)* This is an optional field that contains useful text for operators to manage security group rules. This field is available in Cloud Foundry v238 and later.

#### Data source

**Note**: every parameters from resource which are not used here are marked as computed and will be filled.

```tf
data "cloudfoundry_sec_group" "sec_group_mysupersecgroup" {
  name = "mysupersecgroup"
  // or by_id = "a-guid"
}
```

- **name**: (**Required if by_id not set**) Name of your security group.
- **by_id**: (**Required if name not set**) by_id of your security group.

----

### Buildpacks

#### Resource

```tf
resource "cloudfoundry_buildpack" "buildpack_mysuperbuildpack" {
  name = "mysuperbuildpack"
  path = "https://github.com/cloudfoundry/staticfile-buildpack/releases/download/v1.3.13/staticfile_buildpack-cached-v1.3.13.zip"
  position = 13
  locked = false
  enabled = false
}
```

- **name**: (**Required**) Name of your buildpack. **Note**: if there is only name inside your buildpack the provider will consider your buildpack as a system managed buildpack (e.g.: `php_buildpack`, `java_buildpack`), so if you remove it from your tf file it will not be removed from your Cloud Foundry.
- **path**: *(Optional, default: `null`)* Path should be a zip file, a url to a zip file, or a local directory which contains your buildpack code.
- **position**: *(Optional, default: `null`)* Position is a positive integer, sets priority, and is sorted from lowest to highest.
- **enabled**: *(Optional, default: `true`)* Set to `false` to disable the buildpack to be used for staging.
- **locked**: *(Optional, default: `false`)* Set to `true` to lock the buildpack to prevent updates.

#### Data source

**Note**: every parameters from resource which are not used here are marked as computed and will be filled.

```tf
resource "cloudfoundry_buildpack" "buildpack_mysuperbuildpack" {
  name = "mysuperbuildpack"
  // or by_id = "a-guid"
}
```

- **name**: (**Required if by_id not set**) Name of your buildpack.
- **by_id**: (**Required if name not set**) by_id of your buildpack.

----

### Feature flags

#### Resource

```tf
resource "cloudfoundry_feature_flags" "feature_flags" {
  diego_docker = true
  custom_flag {
    name = "my_flag"
    enabled = true
  }
}
```
List of default feature flags:
- **user_org_creation**: *(Optional, default: `false`)*
- **private_domain_creation**: *(Optional, default: `true`)*
- **app_bits_upload**: *(Optional, default: `true`)*
- **app_scaling**: *(Optional, default: `true`)*
- **route_creation**: *(Optional, default: `true`)*
- **service_instance_creation**: *(Optional, default: `true`)*
- **diego_docker**: *(Optional, default: `false`)*
- **set_roles_by_username**: *(Optional, default: `true`)*
- **unset_roles_by_username**: *(Optional, default: `true`)*
- **task_creation**: *(Optional, default: `false`)*
- **env_var_visibility**: *(Optional, default: `true`)*
- **space_scoped_private_broker_creation**: *(Optional, default: `true`)*
- **space_developer_env_var_visibility**: *(Optional, default: `true`)*

Custom flags made for feature flags not in the default resource:
- **custom_flag**: *(Optional, default: `null`)* Add cutom feature flags as many as you need:
  - **name**: (**Required**) Name of the feature
  - **enabled**: (**Required**) Set to `true` to enable the feature in your cloud foundry.

#### Data source

**Feature flags cannot be used as data source**

----

### Services

#### Resource

Service from marketplace:

```tf
resource "cloudfoundry_service" "svc_db" {
  name = "my-db"
  space_id = "${cloudfoundry_space.space_mysuperspace.id}"
  service = "p-mysql"
  plan = "100mb"
  params = "{ \"my-param\": 1}"
  update_params = "{ \"my-param\": 1}"
  tags = [ "tag1", "tag2" ]
}
```

An user provided service:

```tf
resource "cloudfoundry_service" "svc_ups" {
  name = "my-ups"
  space_id = "${cloudfoundry_space.space_mysuperspace.id}"
  user_provided = true
  params = "{ \"my-credential\": 1}"
  route_service_url = "http://my.route.com"
  syslog_drain_url = "http://my.syslog.com"
  tags = [ "tag1", "tag2" ]
}
```

- **name**: (**Required**) Name of your service.
- **space_id**: (**Required**) Space id created from resource or data source [cloudfoundry_space](#spaces) to register service inside.
- **user_provided**: *(Optional, default: `false`)* Set to `true` to create an user provided service. **Note**: `service` and `plan` params will not be used.
- **params**: *(Optional, default: `null`)* Must be json, if it's an user provided service it will be credential for your service instead it will be params sent to service broker when creating service.
- **update_params**: *(Optional, default: `null`)* Must be json, Params sent to service broker when updating service.
- **tags**: *(Optional, default: `null`)* list of tags for your service.
- **service**: (**Required when not user provided service**) name of service from marketplace.
- **plan**: (**Required when not user provided service**) name of the plan to use.
- **route_service_url**: *(Optional, default: `null`)* Only works for user provided, an url to create a [route service](https://docs.cloudfoundry.org/services/route-services.html)
- **syslog_drain_url**: *(Optional, default: `null`)* Only works for user provided, an url to drain logs as a service on an app.

#### Data source

**Note**: every parameters from resource which are not used here are marked as computed and will be filled, except:
- `params`
- `update_params`

```tf
data "cloudfoundry_service" "svc_ups" {
  name = "my-ups"
  space_id = "${cloudfoundry_space.space_mysuperspace.id}"
  // or by_id = "a-guid"
}
```

- **name**: (**Required if by_id not set**) Name of your service.
- **space_id**: (**Required if by_id not set**) Space id created from resource or data source [cloudfoundry_space](#spaces) to register service inside.
- **by_id**: (**Required if name not set**) by_id of your service.

----

### Domains

#### Resource

```tf
resource "cloudfoundry_domain" "domain_mydomain" {
  name = "my.domain.com"
  org_owner_id = "${cloudfoundry_organization.org_mysuperorg.id}"
  router_group = "default-router"
  orgs_shared_id = ["${cloudfoundry_organization.org_mysecondorg.id}"]
  shared = false
}
```

- **name**: (**Required**) Your domain name.
- **org_owner_id**: (**Required if not shared**) Organization id created from resource or data source which own the domain [cloudfoundry_organization](#organizations).
- **orgs_shared_id**: *(Optional, default: `null`)* Set of organization id which can have access to domain. **Note**: Only can used when not a shared domain
- **router_group**: *(Optional, default: `null`)* Routes for this domain will be configured only on the specified router group. **Note**: Only when when it's a shared domain
- **shared**: *(Optional, default: `false`)* If `True` this domain will be a shared domain.

#### Data source

##### Get one domain with all details

**Note**: every parameters from resource which are not used here are marked as computed and will be filled.

```tf
data "cloudfoundry_domain" "domain_mydomain" {
  name = "my.domain.com"
  org_owner_id = "${cloudfoundry_organization.org_mysuperorg.id}"
  first = false
  // or by_id = "a-guid"
}
```

- **name**: *(Optional if `first` param set to `true`, default: `null`)* Your domain name.
- **first**: *(Optional, default: `null`)* If set to `true` parameter `name` or `by_id` become unnecessary and will give the first domain found in your Cloud Foundry (it will be the first shared domain if `org_owner_id` is not set).
- **org_owner_id**: (**Required if not shared**) Organization id created from resource or data source which own the domain [cloudfoundry_organization](#organizations).
- **by_id**: *(Optional if `first` param set to `true` or `name` param set, default: `null`)* by_id of your domain.

##### Get all domains

```hcl
data "cloudfoundry_domains" "available" {
  org_owner_id = "${cloudfoundry_organization.org_mysuperorg.id}"
}

data "cloudfoundry_domain" "space_mysuperspace" {
    name = "${data.cloudfoundry_domains.available.names[0]}"
    org_owner_id = "${cloudfoundry_organization.org_mysuperorg.id}"
}
```

- **org_owner_id**: (*Optional, Default: Empty*) Organization id created from resource or data source which own the domain [cloudfoundry_organization](#organizations).
If not set all spaces will be retrieve.
- **names**: (*Computed*) List of the domains name found.
- **ids**: (*Computed*) List of the domains id found. (same order as `names`)

----

### Routes

#### Resource

```tf
resource "cloudfoundry_route" "route_superroute" {
  hostname = "superroute"
  space_id = "${cloudfoundry_space.space_mysuperspace.id}"
  domain_id = "${cloudfoundry_domain.domain_mydomain.id}"
  port = -1
  path = ""
  service_id = "${cloudfoundry_service.svc_ups.id}"
  service_params = "{ \"my-param\": 1}"
}
```

- **hostname**: (**Required**) Your hostname.
- **domain_id**: (**Required**) Domain id created from resource or data source [domains](#domains).
- **space_id**: (**Required**) Space id created from resource or data source [cloudfoundry_space](#spaces) to register route inside.
- **port**: *(Optional, default: `-1`)* Set a port for your route (only works with a tcp domain). **Note**: If `0` a random port will be chose
- **path**: *(Optional, default: `null`)* Set a path for your route (only works with a http(s) domain).
- **service_id**: *(Optional, default: `null`)* Set a service id created from resource or data source [services](#services) this will bind a route service on your route. **Note**: It obviously needs a service which is a route service.
- **service_params**: *(Optional, default: `null`)*  Must be in json, set params to send to service when binding on it.
- **protocol**: *(Optional, default: `null`)*  This parameter is only for uri computed parameter it permits to override
  the protocol when generating uri (generated uri will use always `https` protocol when it's an http route, you can found useful to force in `http`).
- **uri**: *(Computed)*  This is an uri generated by the resource, you can use this for service brokers resource for example. **Note**: It autodetects when it's an http route or a tcp route.

#### Data source

**Note**: every parameters from resource which are not used here are marked as computed and will be filled, except:
- `service_params`

```tf
resource "cloudfoundry_route" "route_superroute" {
  hostname = "superroute"
  domain_id = "${cloudfoundry_domain.domain_mydomain.id}"
  port = -1
  path = ""
  // or by_id = "a-guid"
}
```

- **name**: (**Required if by_id not set**) Your hostname.
- **domain_id**: (**Required if by_id not set**) Domain id created from resource or data source [domains](#domains).
- **port**: *(Optional, default: `-1`)* Set a port for your route (only works with a tcp domain). **Note**: If `0` a random port will be chose
- **path**: *(Optional, default: `null`)* Set a path for your route (only works with a http(s) domain).
- **protocol**: *(Optional, default: `null`)*  This parameter is only for uri computed parameter it permits to override
  the protocol when generating uri (generated uri will use always `https` protocol when it's an http route, you can found useful to force in `http`).
- **by_id**: (**Required if name not set**) by_id of your route.

----

### Isolation segments

#### Resource

```tf
resource "cloudfoundry_isolation_segment" "my_isolation_segment" {
  name = "isolation_segment_name_set_in_cf_deployment"
}
```

- **name**: (**Required if by_id not set**) Isolation segment that you have set on your cloud foundry deployment.
- **orgs_id**: **DEPRACTED USE [entitlement](#isolation-segments-entitlement) instead** (**Required**) *(Optional, default: `null`)* You can pass a list of organization created from resource or data source [cloudfoundry_organization](#organizations), this will put those organizations in the isolation segment.
- **by_id**: (**Required if name not set**) by_id of your isolation segment.

#### Data source

**Note**: every parameters from resource which are not used here are marked as computed and will be filled.

```tf
data "cloudfoundry_isolation_segment" "my_isolation_segment" {
  name = "isolation_segment_name_set_in_cf_deployment"
}
```

- **name**: (**Required if `first` not set**) Isolation segment that you have set on your cloud foundry deployment.
- **first**:  Get the first non `shared` isolation segment.

---

### Isolation segments entitlement

#### Resource

```tf
resource "cloudfoundry_isolation_segment_entitlement" "private_mysuperorg" {
  segment_id = "${cloudfoundry_isolation_segment.my_isolation_segment.id}"
  org_id = "${cloudfoundry_organization.org_mysuperorg.id}"
  default = false
}
```

- **segment_id**: (**Required**) Isolation segment id to use.
- **org_id**: (**Required**) Organization id to be entitled by this segment.
- **default**: *(Optional, default: `false`)* Set this isolation segment as default segment for this organization.

---

### Isolation segments space

#### Resource

```tf
resource "cloudfoundry_isolation_segment_space" "private_mysuperspace" {
  segment_id = "${cloudfoundry_isolation_segment.my_isolation_segment.id}"
  space_id = "${cloudfoundry_organization.space_mysuperspace.id}"
}
```

- **segment_id**: (**Required**) Isolation segment id to use.
- **space_id**: (**Required**) Space id where assign segment.\

----

### Stacks

#### Resource

**Stacks cannot be used as a resource**

#### Data source

**Note**: every parameters from resource which are not used here are marked as computed and will be filled.

```tf
data "cloudfoundry_stack" "my_stack" {
  name = "cflinuxfs2"
  first = false
  // or by_id = "a-guid"
}
```

- **name**: *(Optional if `first` param set to `true`, default: `null`)* Name of the stack.
- **first**: *(Optional, default: `null`)* If set to `true` parameter `name` become unnecessary and will give the first stack found in your Cloud Foundry.
- **by_id**: *(Optional if `first` param set to `true` or `name` param set, default: `null`)* by_id of your stack.

----

### Environment Variable Group

#### Resource

```tf
resource "cloudfoundry_env_var_group" "env_var_group" {
  env_var {
    key = "myvar1"
    value = "myvalue1"
    running = true
    staging = true
  }
  env_var {
    key = "myvar2"
    value = "myvalue1"
    running = true
    staging = true
  }
}
```

- **env_var**: (**Required**) Add any variable you want to environment variable group:
  - **key**: (**Required**) Env var key.
  - **value**: (**Required**) Env var value.
  - **running**: (**Required**) if set to `true` this env var will be use on all running app.
  - **staging**: (**Required**) if set to `true` this env var will be use during staging step when creating an app.

#### Data source

**Environment Variable Group cannot be used as a data source**

----

### Service brokers

#### Resource

```tf
resource "cloudfoundry_service_broker" "service_broker_mysuperbroker" {
  name = "mysuperbroker"
  url = "http://url.of.my.service.broker.com"
  username = "user"
  password = "mypassword"
  service_access {
    service = "service_name_from_service_broker_catalog"
    plan = "plan_from_service_broker_catalog"
    org_id = "${cloudfoundry_organization.org_mysuperorg.id}"
  }
  service_access {
    service = "service_name_from_service_broker_catalog"
    plan = "plan2_from_service_broker_catalog"
    org_id = "${cloudfoundry_organization.org_mysuperorg.id}"
  }
  #...
}
```

- **name**: (**Required**) Name of your service broker.
- **url**: (**Required**) URL to access to your service broker.
- **username**: *(Optional, default: `null`)* Username to authenticate to your service broker.
- **password**: *(Optional, default: `null`)* Password to authenticate to your service broker. **Note**: you can pass a base 64 encrypted gpg message if you [enabled password encryption](#enable-password-encryption).
- **catalog_sha1**: *(Computed)* Do not modify yourself, this permits to detect a change in the service broker catalog.
- **space_id**: *(Optional, default: `null`)* If set, your service broker will be created as a space-scoped service broker on this space.
- **service_access**: (**Required if space_id not set**) Add service access as many as you need, service access make you service broker accessible on marketplace:
  - **service**: (**Required**) Service name from your service broker catalog to activate. **Note**: if there is only service in your service access it will enable all plan on all orgs on your Cloud Foundry.
  - **plan**: *(Optional, default: `null`)* Plan from your service broker catalog attached to this service to activate. **Note**: if no `org_id` is given it will enable this plan on all orgs.
  - **org_id**: *(Optional, default: `null`)* Org id created from resource or data source [cloudfoundry_organization](#organizations) to activate this service. **Note**: if no `plan` is given it will all plans on this org.

**BUG FOUND**: if you set both `plan` and `org_id` in your `service_access` Cloud Foundry will enable all plans on this org. It's maybe only on the version of Cloud Foundry I am. Feedbacks are needed on other versions.

#### Data source

**Note**: every parameters from resource which are not used here are marked as computed and will be filled, except:
- `username`
- `password`

```tf
resource "cloudfoundry_service_broker" "service_broker_mysuperbroker" {
  name = "mysuperbroker"
  // or by_id = "a-guid"
}
```

- **name**: (**Required if by_id not set**) Name of your service broker.
- **by_id**: (**Required if name not set**) by_id of your service broker.

### Applications

This resource is used in order to deploy and update an application. It can see changes between code you have locally and code you have in your cloud foundry to do the update fastly (It compares a checksum from a chunk of data between local and remotely)

**By default, when updating, your app will never shutdown**. It always use blue-green deployment when app bits changed, rename or scale number of instances instantly and do blue-green restage in all others modification.

As a terraform resource, creating an app give you more control but can also be more painful than using the cli.
To be painless, [terraform modules](https://www.terraform.io/docs/modules/index.html) can be use to deploy you app like you could do with a `manifest.yml` file.
This can be found on https://github.com/orange-cloudfoundry/terraform-cloudfoundry-modules

#### Resource

```tf
resource "cloudfoundry_app" "myapp" {
  name = "myapp"
  stack_id = "${data.cloudfoundry_stack.my_stack.id}"
  space_id = "${data.cloudfoundry_space.space_mysuperspace.id}"
  started = true
  instances = 2
  memory = "64M"
  disk_quota = "1G"
  command = ""
  path = "/path/to/folder"
  diego = true
  buildpack = "php_buildpack"
  health_check_type = "port"
  health_check_http_endpoint = ""
  health_check_timeout = ""
  docker_image = ""
  enable_ssh = false
  ports = [8080]
  routes = ["${cloudfoundry_route.route_superroute.id}"]
  services = ["${cloudfoundry_service.svc_db.id}"]
  env_var = {
    "MY_ENV_KEY" = "myvalue"
    "MY_ENV_KEY2" = "myvalue2"
    #...
  }
}
```

- **name**: (**Required**) Name of your application.
- **space_id**: (**Required**) Space id created from resource or data source [spaces](#spaces).
- **stack_id**: (**Required**) Stack id retrieve from data source [Stacks](#stacks).
- **path**: (**Required**) Path to a folder which contains application code, url to a zip/jar, url to a tgz/tar or a git url following the scheme: https://[user:password@]mygit.com/myrepo.git[#tag-or-branch-or-commit-hash]
- **started**: *(Optional, default: `true`)* State of your application (should be start or not).
- **instances**: *(Optional, default: `1`)*  The number of instances of the app to run.
- **memory**: *(Optional, default: `512M`)* The amount of memory each instance should have.
- **disk_quota**: *(Optional, default: `1G`)* The maximum amount of disk available to an instance of an app.
- **command**: *(Optional, default: `NULL`)* The command to start an app after it is staged.
- **diego**: *(Optional, default: `true`)* Use diego to stage and to run when available (Diego should be always available because DEA is not supported anymore).
- **buildpack**: *(Optional, default: `NULL`)* Buildpack to build the app. 3 options: a) Blank means autodetection; b) A Git Url pointing to a buildpack; c) Name of an installed buildpack.
- **health_check_type**: *(Optional, default: `port`)* Type of health check to perform. Others values are:
  - http (Diego only)
  - port
  - process
  - none
- **started**: *(Optional, default: `true`)* when set to false app will not be started.
- **health_check_http_endpoint**: *(Optional, default: `NULL`)* Endpoint called to determine if the app is healthy. (Can  be use only when check type is http)
- **health_check_timeout**: *(Optional, default: `NULL`)* Timeout in seconds for health checking of an staged app when starting up.
- **docker_image**: *(Optional, default: `NULL`)* Name of the Docker image containing the app. The "diego_docker" feature flag must be enabled in order to create Docker image apps.
- **enable_ssh**: *(Optional, default: `false`)* Enable SSHing into the app. Supported for Diego only.
- **ports**: *(Optional, default: `8080` when diego is set to `true`)* List of ports on which application may listen. Overwrites previously configured ports.
  Ports must be in range 1024-65535. Supported for Diego only. (**Note**: This is a copy of the default behaviour of cloud foundry cli, it always create a default port to 8080 when using diego backend)
- **routes**: *(Optional, default: `NULL`)* List of route guid retrieve from resource or data source [routes](#routes) to attach routes to your app.
- **services**: *(Optional, default: `NULL`)* List of service guid retrieve from resource or data source [services](#services) to bind services to your app.
- **env_var**: *(Optional, default: `NULL`)* Add any variable you want to the app environment.
- **no_blue_green_restage**: *(Optional, default: `false`)* If set to `true` no blue green restage will be performed (it will restart the app).
- **no_blue_green_deploy**: *(Optional, default: `false`)* If set to `true` no blue green deployment will be performed.

**Note**:
- Cloud controller doesn't support multipart upload in chunk (could not stream chunk of files) this actually mean that an intermediate file need to be created containing the request and data (this is actually the current behaviour from cli)
- When retrieving source from a zip file url the stream will be passed directly
- When retrieving source from a tgz/tar file url this will be converted as zip directly from the stream
- When retrieving source from a git repo a folder will be created containing source before push them
- A git repo fetch data only for the branch or tag with a depth of 1, if a commit hash is set everything from repo will be fetched before force to commit (this mean that passing a commit hash will make things slower)

#### Data source

**Note**: every parameters from resource which are not used here are marked as computed and will be filled.

```tf
resource "cloudfoundry_service_broker" "myapp" {
  name = "mysuperbroker"
  space_id = "${data.cloudfoundry_space.space_mysuperspace.id}"
  // or by_id = "a-guid"
}
```

- **name**: (**Required if by_id not set**) Name of your app. If `space_id` set it will try to find the first matching app found in all spaces you have access to.
- **space_id**: *(Optional, default: `null`)* Space id created from resource or data source [spaces](#spaces).
- **by_id**: (**Required if name not set**) by_id of your service broker.

## Enable password encryption

You can use gpg encryption to encrypt your service broker password.

### Create a private key for the provider

**Requirements**: you will need to have `gpg` on your system.

1. run `gpg --gen-key`, next steps will assume that you put `cloudfoudry` as real name. (Do not forget to remember your passphrase!)
2. go on your terraform folder config in command line
3. run `gpg --export-secret-key -a cloudfoudry > private.key`
4. inside provider configuration put those two key/value pairs (you can also copy content of `private.key` and `export CF_ENC_PRIVATE_KEY=content_of_private.key && export CF_ENC_PASSPHRASE=your_passphrase_that_you_remembered:)`):
```tf
provider "cloudfoundry" {
  enc_private_key = "${file("private.key")}"
  enc_passphrase = "your_passphrase_that_you_remembered:)"
}
```
5. create the public key with `gpg --export -a cloudfoudry > public.key`
6. Share the public key to the rest of your team to let them encrypt password with it (see [Encrypt password](#encrypt-password))
7. you're done

### Encrypt password

1. Get the public key previously created (`public.key`)
2. Import the key with `gpg --import public.key`
3. generate the encrypted password with commands `echo "mypassword" | gpg --encrypt --armor -r cloudfoudry > encrypted_pass.key`
4. Retrieve it from your resource, e.g.:
```tf
resource "cloudfoundry_service_broker" "service_broker_mysuperbroker" {
  name = "mysuperbroker"
  url = "http://url.of.my.service.broker.com"
  username = "user"
  password = "${file("encrypted_pass.key")}"
  service_access {
    service = "service_name_from_service_broker_catalog"
  }
}
```
5. you're done


text:
'use strict'

function getSubCategory (data) {
  if (Array.isArray(data)) {
    return data.join(', ')
  } else {
    return data
  }
}

module.exports = document => {
  const tiltak = document.tiltak
  const finanser = document.finanser
  const isFolkehelse = /folkehelse/.test(document.formal.formal)
  const isIdrett = /idrett/.test(document.formal.formal)
  var output = []

  output.push(`Navn: ${tiltak.navn}`)

  if (document.formal && document.formal.formal) {
    output.push(`Formål: ${document.formal.formal}`)
  }

  if (document.target && document.target.target) {
    if (Array.isArray(document.target.target)) {
      output.push(`Målgrupper: ${document.target.target.join(', ')}`)
    } else {
      output.push(`Målgruppe: ${document.target.target}`)
    }
  }

  if (isFolkehelse) {
    output.push(`Kategori: ${getSubCategory(document.kategorier.beskrivelse)}`)
  }

  if (isIdrett) {
    output.push(`Kategori:  ${getSubCategory(document.kategorier.beskrivelse)}`)
  }

  output.push(`Beskrivelse: ${tiltak.beskrivelse}`)
  output.push(`Periode: ${tiltak.startdato} - ${tiltak.sluttdato}`)
  output.push(`Frekvens: ${tiltak.antall}`)
  output.push(`Sted: ${tiltak.hvor}`)
  output.push('')
  output.push('Økonomi')
  output.push(`Søkebeløp: ${finanser.soknadsSum}`)
  output.push(`Total kostnadsramme: ${finanser.totalRamme}`)
  output.push(`Egne midler: ${finanser.egneMidler}`)
  output.push(`Andre midler (søkt om eller innvilget): ${finanser.andreMidler}`)
  output.push('')
  output.push('Samarbeidsparter')
  if (document.collaboration.samarbeid === 'ja') {
    if (document.partners && document.partners.partner) {
      if (Array.isArray(document.partners.partner)) {
        output.push(`${document.partners.partner.join(', ')}`)
      } else {
        output.push(`${document.partners.partner}`)
      }
    }
    output.push(`${document.samarbeidsparter.beskrivelse}`)
    if (document.bidrag && document.bidrag.bidrag) {
      if (Array.isArray(document.bidrag.bidrag)) {
        output.push(`Bidrag: ${document.bidrag.bidrag.join(', ')}`)
      } else {
        output.push(`Bidrag: ${document.bidrag.bidrag}`)
      }
    }
  } else {
    output.push('Ingen samarbeidsparter')
  }

  return output.map((item) => item.trim())
}