text:
package com.kdgregory.logging.aws;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import net.sf.kdgcommons.lang.ClassUtil;
import net.sf.kdgcommons.lang.StringUtil;

import org.slf4j.Logger;

import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sqs.SqsClient;

import com.kdgregory.logging.aws.facade.SNSFacade;
import com.kdgregory.logging.aws.sns.SNSConstants;
import com.kdgregory.logging.aws.sns.SNSLogWriter;
import com.kdgregory.logging.aws.sns.SNSWriterConfig;
import com.kdgregory.logging.aws.sns.SNSWriterFactory;
import com.kdgregory.logging.aws.sns.SNSWriterStatistics;
import com.kdgregory.logging.common.LogMessage;
import com.kdgregory.logging.common.util.DefaultThreadFactory;
import com.kdgregory.logging.common.util.MessageQueue.DiscardAction;
import com.kdgregory.logging.testhelpers.SNSTestHelper;
import com.kdgregory.logging.testhelpers.TestableInternalLogger;

public class SNSLogWriterIntegrationTest
{
    // "helper" clients are shared by all tests
    private static SnsClient helperSNSclient;
    private static SqsClient helperSQSclient;

    // these are created by the "alternate region" tests
    private SnsClient altSNSclient;
    private SqsClient altSQSclient;

    // this client is used in testFactoryMethod(), should be null everywhere else
    private static SnsClient factoryClient;

    // this is for logging within the test
    private Logger localLogger = LoggerFactory.getLogger(getClass());

    // this can be modified before calling init()
    private SNSWriterConfig config = new SNSWriterConfig()
                                     .setSubject(DEFAULT_SUBJECT)
                                     .setAutoCreate(true)
                                     .setDiscardThreshold(10000)
                                     .setDiscardAction(DiscardAction.oldest);

    // these are all assigned by init()
    private SNSTestHelper testHelper;
    private TestableInternalLogger internalLogger;
    private SNSWriterStatistics stats;
    private SNSWriterFactory factory;
    private SNSLogWriter writer;

//----------------------------------------------------------------------------
//  Helpers
//----------------------------------------------------------------------------

    private final static String DEFAULT_SUBJECT = "integration test";

    private void init(String testName, SnsClient snsClient, SqsClient sqsClient)
    throws Exception
    {
        MDC.put("testName", testName);
        localLogger.info("starting");

        testHelper = new SNSTestHelper(snsClient, sqsClient);

        testHelper.createTopicAndQueue();

        config.setTopicName(testHelper.getTopicName());

        stats = new SNSWriterStatistics();
        internalLogger = new TestableInternalLogger();
        factory = new SNSWriterFactory();
        writer = (SNSLogWriter)factory.newLogWriter(config, stats, internalLogger);

        new DefaultThreadFactory("test").startWriterThread(writer, null);
    }

    private class MessageWriter
    extends com.kdgregory.logging.testhelpers.MessageWriter
    {
        public MessageWriter(int numMessages)
        {
            super(numMessages);
        }

        @Override
        protected void writeLogMessage(String message)
        {
            writer.addMessage(new LogMessage(System.currentTimeMillis(), message));
        }
    }

    public static SnsClient staticClientFactory()
    {
        factoryClient = SnsClient.builder().build();
        return factoryClient;
    }

//----------------------------------------------------------------------------
//  JUnit Scaffolding
//----------------------------------------------------------------------------

    @BeforeClass
    public static void beforeClass()
    {
        helperSNSclient = SnsClient.builder().build();
        helperSQSclient = SqsClient.builder().build();
    }

    @After
    public void tearDown()
    {
        if (writer != null)
        {
            writer.stop();
        }

        if (altSNSclient != null)
        {
            altSNSclient.close();
        }

        if (altSQSclient != null)
        {
            altSQSclient.close();
        }

        if (factoryClient != null)
        {
            factoryClient.close();
            factoryClient = null;
        }

        localLogger.info("finished");
        MDC.clear();
    }

    @AfterClass
    public static void afterClass()
    {
        helperSNSclient.close();
        helperSQSclient.close();
    }

//----------------------------------------------------------------------------
//  Tests
//----------------------------------------------------------------------------

    @Test
    public void smoketest() throws Exception
    {
        final int numMessages = 11;

        init("smoketest", helperSNSclient, helperSQSclient);

        new MessageWriter(numMessages).run();

        List<Map<String,Object>> messages = testHelper.retrieveMessages(numMessages);

        assertEquals("number of messages", numMessages, messages.size());
        testHelper.assertMessageContent(messages, DEFAULT_SUBJECT);

        assertEquals("internal error log", Collections.emptyList(), internalLogger.errorMessages);

        testHelper.deleteTopicAndQueue();
    }

    @Test
    public void testFactoryMethod() throws Exception
    {
        final int numMessages = 11;

        config.setClientFactoryMethod(getClass().getName() + ".staticClientFactory");
        init("testFactoryMethod", helperSNSclient, helperSQSclient);

        new MessageWriter(numMessages).run();

        List<Map<String,Object>> messages = testHelper.retrieveMessages(numMessages);

        assertEquals("number of messages", numMessages, messages.size());
        testHelper.assertMessageContent(messages, DEFAULT_SUBJECT);

        assertNotNull("factory method was called", factoryClient);

        Object facade = ClassUtil.getFieldValue(writer, "facade", SNSFacade.class);
        Object client = ClassUtil.getFieldValue(facade, "client", SnsClient.class);
        assertSame("factory-created client used by writer", factoryClient, client);

        assertEquals("internal error log", Collections.emptyList(), internalLogger.errorMessages);

        testHelper.deleteTopicAndQueue();
    }

    @Test
    public void testAlternateRegion() throws Exception
    {
        final int numMessages = 11;

        altSNSclient = SnsClient.builder().region(Region.US_WEST_1).build();
        altSQSclient = SqsClient.builder().region(Region.US_WEST_1).build();

        config.setClientRegion("us-west-1");
        init("testAlternateRegion", altSNSclient, altSQSclient);

        new MessageWriter(numMessages).run();

        List<Map<String,Object>> messages = testHelper.retrieveMessages(numMessages);

        assertEquals("number of messages", numMessages, messages.size());
        testHelper.assertMessageContent(messages, DEFAULT_SUBJECT);

        assertNull("topic does not exist in default region",
                   (new SNSTestHelper(testHelper, helperSNSclient, helperSQSclient)).lookupTopic());

        assertEquals("internal error log", Collections.emptyList(), internalLogger.errorMessages);

        testHelper.deleteTopicAndQueue();
    }

    @Test
    public void testAlternateEndpoint() throws Exception
    {
        final int numMessages = 11;

        altSNSclient = SnsClient.builder().region(Region.US_EAST_2).build();
        altSQSclient = SqsClient.builder().region(Region.US_WEST_1).build();

        config.setClientEndpoint("https://sns.us-east-2.amazonaws.com")
              .setClientRegion("us-east-2");
        init("testAlternateEndpoint", altSNSclient, altSQSclient);

        new MessageWriter(numMessages).run();

        List<Map<String,Object>> messages = testHelper.retrieveMessages(numMessages);

        assertEquals("number of messages", numMessages, messages.size());
        testHelper.assertMessageContent(messages, DEFAULT_SUBJECT);

        assertNull("topic does not exist in default region",
                   (new SNSTestHelper(testHelper, helperSNSclient, helperSQSclient)).lookupTopic());

        assertEquals("internal error log", Collections.emptyList(), internalLogger.errorMessages);

        testHelper.deleteTopicAndQueue();
    }

    @Test
    public void testOversizeMessageTruncation() throws Exception
    {
        final int numMessages = 10;

        // this test verifies that what I think is the maximum message size is acceptable to SNS
        final int maxMessageSize = SNSConstants.MAX_MESSAGE_BYTES;

        final String expectedMessage = StringUtil.repeat('X', maxMessageSize - 1) + "Y";
        final String messageToWrite = expectedMessage + "Z";

        config.setTruncateOversizeMessages(true);
        init("testOversizeMessageTruncation", helperSNSclient, helperSQSclient);

        new MessageWriter(numMessages)
        {
            @Override
            protected void writeLogMessage(String ignored)
            {
                super.writeLogMessage(messageToWrite);
            }
        }.run();

        List<Map<String,Object>> messages = testHelper.retrieveMessages(numMessages);
        Set<String> messageBodies = new HashSet<>();
        for (Map<String,Object> message : messages)
        {
            messageBodies.add((String)message.get(SNSTestHelper.SQS_KEY_MESSAGE));
        }

        assertEquals("all messages should be truncated to same value",  1, messageBodies.size());
        assertEquals("message was truncated",                           expectedMessage, messageBodies.iterator().next());

        assertEquals("internal error log", Collections.emptyList(), internalLogger.errorMessages);

        testHelper.deleteTopicAndQueue();
    }
}


text:
@interface SCItunesAppService : NSObject<NSURLConnectionDelegate>

typedef void (^SCItunesServiceCompleteBlock)(SCItunesApp *app);

+ (SCItunesAppService *)instance;

- (void)getAppWithId:(NSString *)appId
         countryCode:(NSString *)countryCode
          onComplete:(SCItunesServiceCompleteBlock)onComplete;

@end

redpajama_set_name: RedPajamaGithub


text:
import sys
import os
import os.path
import operator
import logging
from ctypes import c_ubyte, POINTER, cast

parent_dir = os.path.split(os.getcwd())[0]

# if we are at PyUSB source tree, add usb package to python path
if os.path.exists(os.path.join(parent_dir, 'usb')):
    sys.path.insert(0, parent_dir)

import usb.core
import logging
import devinfo
import time
import unittest
import usb._interop as _interop

logger = logging.getLogger('usb.test')

# data generation functions
def get_array_data1(length = 8):
    return _interop.as_array(range(length))

def get_array_data2(length = 8):
    data = list(range(length))
    data.reverse()
    return _interop.as_array(data)

def get_list_data1(length = 8):
    return list(range(length))

def get_list_data2(length = 8):
    data = list(range(length))
    data.reverse()
    return data

def get_str_data1(length = 8):
    if sys.version_info[0] >= 3:
        # On Python 3, string char is 4 bytes long
        length = int(length / 4)
    return ''.join([chr(x) for x in range(length)])

def get_str_data2(length = 8):
    if sys.version_info[0] >= 3:
        length = int(length / 4)
    data = list(range(length))
    data.reverse()
    return ''.join([chr(x) for x in data])

def to_array(data):
    return _interop.as_array(data)

def delay_after_reset():
    time.sleep(3) # necessary to wait device reenumeration

# check if our test hardware is present
def find_my_device(backend = None):
    try:
        return usb.core.find(backend=backend,
                             idVendor=devinfo.ID_VENDOR,
                             idProduct=devinfo.ID_PRODUCT)
    except Exception:
        return None

def run_tests(suite):
    runner = unittest.TextTestRunner()
    runner.run(suite)

def data_len(data):
    a = _interop.as_array(data)
    return len(data) * a.itemsize

def array_equals(a1, a2):
    if a1.typecode != 'u' and a2.typecode != 'u':
        return a1 == a2
    else:
        # as python3 strings are unicode, loads of trouble,
        # because we read data from USB devices are byte arrays
        l1 = len(a1) * a1.itemsize
        l2 = len(a2) * a2.itemsize
        if l1 != l2:
            return False
        c_ubyte_p = POINTER(c_ubyte)
        p1 = cast(a1.buffer_info()[0], c_ubyte_p)
        p2 = cast(a2.buffer_info()[0], c_ubyte_p)
        # we do a item by item compare we unicode is involved
        return all(map(operator.eq, p1[:l1], p2[:l2]))

def is_windows():
    return 'getwindowsversion' in dir(sys)

def is_iso_test_allowed():
    return int(os.getenv('PYUSB_TEST_ISO_TRANSFER', 1))


text:
package com.shocktrade.server.dao.contest

import java.util.UUID

import com.shocktrade.common.models.contest.PositionLike
import io.scalajs.util.JsUnderOrHelper._
import io.scalajs.util.ScalaJsHelper._

import scala.scalajs.js

/**
  * Position Data
  * @author Lawrence Daniels <lawrence.daniels@gmail.com>
  */
class PositionData(var _id: js.UndefOr[String] = UUID.randomUUID().toString,
                   var symbol: js.UndefOr[String],
                   var exchange: js.UndefOr[String],
                   var pricePaid: js.UndefOr[Double],
                   var quantity: js.UndefOr[Double],
                   var commission: js.UndefOr[Double],
                   var processedTime: js.UndefOr[js.Date],
                   var accountType: js.UndefOr[String],
                   var netValue: js.UndefOr[Double]) extends PositionLike

/**
  * Position Companion
  * @author Lawrence Daniels <lawrence.daniels@gmail.com>
  */
object PositionData {

  /**
    * Position Enrichment
    * @param position the given [[PositionData position]]
    */
  implicit class PositionDataEnrichment(val position: PositionData) extends AnyVal {

    @inline
    def copy(_id: js.UndefOr[String] = js.undefined,
             symbol: js.UndefOr[String] = js.undefined,
             exchange: js.UndefOr[String] = js.undefined,
             pricePaid: js.UndefOr[Double] = js.undefined,
             quantity: js.UndefOr[Double] = js.undefined,
             commission: js.UndefOr[Double] = js.undefined,
             processedTime: js.UndefOr[js.Date] = js.undefined,
             accountType: js.UndefOr[String] = js.undefined,
             netValue: js.UndefOr[Double] = js.undefined) = {
      new PositionData(
        _id = _id ?? position._id,
        symbol = symbol ?? position.symbol,
        exchange = exchange ?? position.exchange,
        pricePaid = pricePaid ?? position.pricePaid,
        quantity = quantity ?? position.quantity,
        commission = commission ?? position.commission,
        processedTime = processedTime ?? position.processedTime,
        accountType = accountType ?? position.accountType,
        netValue = netValue ?? position.netValue)
    }

    @inline
    def fundingAsOfDate = {
      position match {
        case o if o.isCashAccount => "cashAccount.asOfDate"
        case o if o.isMarginAccount => "marginAccount.asOfDate"
        case o => die(s"Invalid account type (${position.accountType.orNull}) for order # ${position._id.orNull}")
      }
    }

    @inline
    def fundingSource = {
      position match {
        case o if o.isCashAccount => "cashAccount.funds"
        case o if o.isMarginAccount => "marginAccount.funds"
        case o => die(s"Invalid account type (${position.accountType.orNull}) for order # ${position._id.orNull}")
      }
    }

    @inline
    def toPerformance(priceSold: Double, commission: Double) = new PerformanceData(
      _id = UUID.randomUUID().toString,
      symbol = position.symbol,
      pricePaid = position.pricePaid,
      priceSold = priceSold,
      quantity = position.quantity,
      commissions = position.commission.map(_ + commission)
    )

  }

}


text:
import { formatISO } from 'date-fns';
import omit from 'lodash/omit';
import type { NativeDate, OptionalDeep, RawDate } from './types';

export const omitTypeName = <T extends Record<string, unknown>>(item: T): Omit<T, '__typename'> =>
  omit(item, '__typename');

type OmitDeep<T, U extends string> = T extends Record<string, unknown>
  ? { [K in keyof Omit<T, U>]: OmitDeep<T[K], U> }
  : T;

export function omitDeep<T, K extends string>(item: T | T[], key: K): OmitDeep<T, K> {
  if (Array.isArray(item)) {
    return item.map((i) => omitDeep(i, key)) as unknown as OmitDeep<T, K>;
  }
  if (typeof item === 'object' && item !== null) {
    return Object.entries(omit(item as Record<string, unknown>, key)).reduce<OmitDeep<T, K>>(
      (last, [objectKey, value]) => ({
        ...last,
        [objectKey]: omitDeep(value, key),
      }),
      {} as OmitDeep<T, K>,
    );
  }
  return item as OmitDeep<T, K>;
}

export function optionalDeep<T, K extends string>(item: T | T[], key: K): OptionalDeep<T, K> {
  if (Array.isArray(item)) {
    return item.map((i) => optionalDeep(i, key)) as unknown as OptionalDeep<T, K>;
  }
  if (typeof item === 'object' && item !== null) {
    return Object.entries(item as Record<string, unknown>).reduce<OptionalDeep<T, K>>(
      (last, [objectKey, value]) =>
        objectKey === key && value === null
          ? last
          : { ...last, [objectKey]: optionalDeep(value, key) },
      {} as OptionalDeep<T, K>,
    );
  }
  return item as OptionalDeep<T, K>;
}

export const coalesceKeys = <T extends Partial<Record<K, unknown>>, K extends string>(
  obj: T,
  ...keys: K[]
): T => keys.reduce<T>((last, key) => ({ ...last, [key]: last[key] ?? null }), obj);

export const enum Average {
  Mean,
  Median,
  Exp,
}

export function arrayAverage(values: number[], mode: Average = Average.Mean): number {
  if (!values.length) {
    return NaN;
  }
  if (mode === Average.Median) {
    const sorted = [...values].sort((prev, next) => prev - next);

    const oddLength = sorted.length & 1;
    if (oddLength) {
      // odd: get the middle value
      return sorted[Math.floor((sorted.length - 1) / 2)];
    }

    // even: get the middle two values and find the average of them
    const low = sorted[Math.floor(sorted.length / 2) - 1];
    const high = sorted[Math.floor(sorted.length / 2)];

    return (low + high) / 2;
  }
  if (mode === Average.Exp) {
    const weights = new Array(values.length)
      .fill(0)
      .map((_, index) => 2 ** -(index + 1))
      .reverse();

    const weightSum = weights.reduce((sum, value) => sum + value, 0);

    return (
      values.reduce((average, value, index) => average + value * weights[index], 0) / weightSum
    );
  }

  // mean
  return values.reduce((sum, value) => sum + value, 0) / values.length;
}

export const roundObject = <T extends Record<string, number>>(obj: T): T =>
  Object.entries(obj).reduce<T>(
    (last, [key, value]) => ({ ...last, [key]: Math.round(value) }),
    obj,
  );

export const withNativeDate =
  <K extends string, T extends Record<K, string>>(...keys: K[]) =>
  (item: T): NativeDate<T, K> =>
    keys.reduce<NativeDate<T, K>>(
      (last, key) => ({ ...last, [key]: new Date(item[key]) }),
      item as NativeDate<T, K>,
    );

export const withRawDate =
  <K extends string, T extends Record<K, Date>>(...keys: K[]) =>
  (item: T): RawDate<T, K> =>
    keys.reduce<RawDate<T, K>>(
      (last, key) => ({ ...last, [key]: formatISO(item[key], { representation: 'date' }) }),
      item as RawDate<T, K>,
    );


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
using System.IO;
using GME.MGA;

namespace MasterInterpreterTest.Projects
{
    public partial class MasterInterpreter : IUseFixture<MasterInterpreterFixture>
    {
    }
}


text:
{% extends 'two-column.html' %}

{% block title %}Plan de Alta{% endblock %}

{% block h2 %}Plan de Alta, {{exam.date}}{% endblock %}

{% block sidebar %}
    {% include 'tracker/sidebar.html' %}
{% endblock %}

{% block content %}

    {% include 'tracker/basic-info.html' %}

Resumen del Niño(a): {{ exam.summary }}

Fuerzas, Desafios, Consideraciones Especiales, etc.: {{ exam.strengths_challenges}}

Relaciones Familiares o Comunitarias: {{ exam.family }}

Enfoque de formación profesional: {{ exam.training }}

Futuras posibilidades de alojamiento: {{ exam.future_housing }}

Los Datos del Profesíonal

Nombre: {{ exam.signature_name }} {{ exam.signature_surname }}

EMP: {{ exam.signature_emp }}

Direccion: {{ exam.signature_direction }}

Celular: {{ exam.signature_cell }}

        {% if perms.tracker.add_edit_forms or perms.tracker.delete_info %}

            {% if perms.tracker.add_edit_forms %}

Edita Detalles

            {% endif %}
            {% if perms.tracker.delete_info %}

Borrar

            {% endif %}

        {% endif %}

            <form action ="" method="post" class="no-display">{% csrf_token %}

¿Estás seguro que quieres borrar este examen?

                <input type="submit" name="discard" value="Sí">
                <input type="submit" value="No" id="no">
            </form>

{% endblock %}


text:
/*
 * (c)2014 Tweag I/O
 *
 * The Static Pointer Table implementation.
 *
 * https://ghc.haskell.org/trac/ghc/wiki/StaticPointers
 * https://ghc.haskell.org/trac/ghc/wiki/StaticPointers/ImplementationPlan
 *
 */

#include "StaticPtrTable.h"
#include "Rts.h"
#include "RtsUtils.h"
#include "Hash.h"
#include "Stable.h"

static HashTable * spt = NULL;

#if defined(THREADED_RTS)
static Mutex spt_lock;
#endif

/// Hash function for the SPT.
static int hashFingerprint(HashTable *table, StgWord64 key[2]) {
  // Take half of the key to compute the hash.
  return hashWord(table, (StgWord)key[1]);
}

/// Comparison function for the SPT.
static int compareFingerprint(StgWord64 ptra[2], StgWord64 ptrb[2]) {
  return ptra[0] == ptrb[0] && ptra[1] == ptrb[1];
}

void hs_spt_insert_stableptr(StgWord64 key[2], StgStablePtr *entry) {
  // hs_spt_insert is called from constructor functions, so
  // the SPT needs to be initialized here.
  if (spt == NULL) {
    spt = allocHashTable_( (HashFunction *)hashFingerprint
                         , (CompareFunction *)compareFingerprint
                         );
#if defined(THREADED_RTS)
    initMutex(&spt_lock);
#endif
  }

  ACQUIRE_LOCK(&spt_lock);
  insertHashTable(spt, (StgWord)key, entry);
  RELEASE_LOCK(&spt_lock);
}

void hs_spt_insert(StgWord64 key[2], void *spe_closure) {
  // Cannot remove this indirection yet because getStablePtr()
  // might return NULL, in which case hs_spt_lookup() returns NULL
  // instead of the actual closure pointer.
  StgStablePtr * entry = stgMallocBytes( sizeof(StgStablePtr)
                                       , "hs_spt_insert: entry"
                                       );
  *entry = getStablePtr(spe_closure);
  hs_spt_insert_stableptr(key, entry);
}

static void freeSptEntry(void* entry) {
  freeStablePtr(*(StgStablePtr*)entry);
  stgFree(entry);
}

void hs_spt_remove(StgWord64 key[2]) {
   if (spt) {
     ACQUIRE_LOCK(&spt_lock);
     StgStablePtr* entry = removeHashTable(spt, (StgWord)key, NULL);
     RELEASE_LOCK(&spt_lock);

     if (entry)
       freeSptEntry(entry);
   }
}

StgPtr hs_spt_lookup(StgWord64 key[2]) {
  if (spt) {
    ACQUIRE_LOCK(&spt_lock);
    const StgStablePtr * entry = lookupHashTable(spt, (StgWord)key);
    const StgPtr ret = entry ? deRefStablePtr(*entry) : NULL;
    RELEASE_LOCK(&spt_lock);
    return ret;
  } else
    return NULL;
}

int hs_spt_keys(StgPtr keys[], int szKeys) {
  if (spt) {
    ACQUIRE_LOCK(&spt_lock);
    const int ret = keysHashTable(spt, (StgWord*)keys, szKeys);
    RELEASE_LOCK(&spt_lock);
    return ret;
  } else
    return 0;
}

int hs_spt_key_count() {
  return spt ? keyCountHashTable(spt) : 0;
}

void exitStaticPtrTable() {
  if (spt) {
    freeHashTable(spt, freeSptEntry);
    spt = NULL;
#if defined(THREADED_RTS)
    closeMutex(&spt_lock);
#endif
  }
}


text:
echo "start"
cd /home/ajha/git/g_d/rhs/rhs
make dist clean
./autogen.sh && ./configure --enable-debug CFLAGS='-ggdb -O0' && make -j4
make install && glusterd
mkdir -p /export2/rep_v2/b1
mkdir -p /export2/rep_v2/b2
mkdir -p /export2/v2/b1
mkdir -p /export2/v2/b2
printf "compiled and bricks created\n"
printf "create master volume (y/n)\t"
read var1
if [ "x$var1" = "xy" ] ;then
	gluster volume create v2 replica 2 geo:/export2/v2/b1/  geo:/export2/v2/b2  force
	gluster volume start v2
else
	exit 0
fi
printf "create slave volume (y/n)\t"
read var2
if [ "x$var2" = "xy" ] ;then
	gluster volume create rep_v2 replica 2 geo:/export2/rep_v2/b1 geo:/export2/rep_v2/b2  force
	gluster volume start rep_v2
else
	exit 0
fi
printf "volume created\n"
cp /home/ajha/git/g_d/rhs/rhs/extras/hook-scripts/S56glusterd-geo-rep-create-post.sh /var/lib/glusterd/hooks/1/gsync-create/post/
gluster system:: execute gsec_create
printf "create geo session (y/n)\t"
read var3
if [ "x$var3" = "xy" ] ;then
	gluster volume geo-replication v2 geo::rep_v2 create push-pem force
else
	exit 0
fi
echo "geo-rep create, please start using \"gluster volume geo-replication v2 geo::rep_v2 start\""


text:
package synergyspace.utils.network;

//import java.net.InetAddress;
//import java.net.NetworkInterface;
//import java.net.SocketException;
//import java.net.UnknownHostException;
//import java.util.Formatter;
//import java.util.Locale;

public class NetworkUtils {

//	public static byte[] getMacAddressBytes() throws SocketException, UnknownHostException {
//		InetAddress address = InetAddress.getLocalHost();
//		NetworkInterface ifa = NetworkInterface.getByInetAddress(address);
//		byte[] mac = ifa.getHardwareAddress();
//		return mac;
//	}

//	public static String getMacAddressString() throws SocketException, UnknownHostException {
//		byte[] mac = getMacAddressBytes();
//		StringBuffer sb = new StringBuffer();
//		Formatter formatter = new Formatter(sb, Locale.UK);
//		for(int i = 0; i < mac.length; i++) {
//			formatter.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
//		}
//		return formatter.toString();
//	}

//	public static void main(String[] args) {
//		try {
//			System.out.println(NetworkUtils.getMacAddressString());
//		} catch (SocketException e) {
//			e.printStackTrace();
//		} catch (UnknownHostException e) {
//			e.printStackTrace();
//		}
//	}
}


text:
from dateutil import parser
import eventlet
import json
import os
import pickle
import subprocess

from oslo_log import log as logging
from oslo_utils import uuidutils

from tacker.sol_refactored.common import config
from tacker.sol_refactored.common import exceptions as sol_ex
from tacker.sol_refactored.common import vnf_instance_utils as inst_utils
from tacker.sol_refactored.infra_drivers.openstack import heat_utils
from tacker.sol_refactored.infra_drivers.openstack import userdata_default
from tacker.sol_refactored import objects
from tacker.sol_refactored.objects.v2 import fields as v2fields

LOG = logging.getLogger(__name__)

CONF = config.CONF

LINK_PORT_PREFIX = 'req-'
CP_INFO_PREFIX = 'cp-'

# Id of the resources in instantiatedVnfInfo related methods.
# NOTE: instantiatedVnfInfo is re-created in each operation.
# Id of the resources in instantiatedVnfInfo is based on
# heat resource-id so that id is not changed at re-creation.
# Some ids are same as heat resource-id and some ids are
# combination of prefix and other ids.
def _make_link_port_id(link_port_id):
    # prepend 'req-' to distinguish from ports which are
    # created by heat.
    return '{}{}'.format(LINK_PORT_PREFIX, link_port_id)

def _is_link_port(link_port_id):
    return link_port_id.startswith(LINK_PORT_PREFIX)

def _make_cp_info_id(link_port_id):
    return '{}{}'.format(CP_INFO_PREFIX, link_port_id)

def _make_combination_id(a, b):
    return '{}-{}'.format(a, b)

class Openstack(object):

    def __init__(self):
        pass

    def instantiate(self, req, inst, grant_req, grant, vnfd):
        # make HOT
        fields = self._make_hot(req, inst, grant_req, grant, vnfd)

        LOG.debug("stack fields: %s", fields)

        stack_name = fields['stack_name']

        # create or update stack
        vim_info = inst_utils.select_vim_info(inst.vimConnectionInfo)
        heat_client = heat_utils.HeatClient(vim_info)
        status, _ = heat_client.get_status(stack_name)
        if status is None:
            heat_client.create_stack(fields)
        else:
            heat_client.update_stack(stack_name, fields)

        # get stack resource
        heat_reses = heat_client.get_resources(stack_name)

        # make instantiated_vnf_info
        self._make_instantiated_vnf_info(req, inst, grant_req, grant, vnfd,
            heat_reses)

    def instantiate_rollback(self, req, inst, grant_req, grant, vnfd):
        vim_info = inst_utils.select_vim_info(inst.vimConnectionInfo)
        heat_client = heat_utils.HeatClient(vim_info)
        stack_name = heat_utils.get_stack_name(inst)
        status, _ = heat_client.get_status(stack_name)
        if status is not None:
            heat_client.delete_stack(stack_name)

    def terminate(self, req, inst, grant_req, grant, vnfd):
        if req.terminationType == 'GRACEFUL':
            timeout = CONF.v2_vnfm.default_graceful_termination_timeout
            if req.obj_attr_is_set('gracefulTerminationTimeout'):
                timeout = req.gracefulTerminationTimeout
            eventlet.sleep(timeout)

        # delete stack
        vim_info = inst_utils.select_vim_info(inst.vimConnectionInfo)
        heat_client = heat_utils.HeatClient(vim_info)
        stack_name = heat_utils.get_stack_name(inst)
        heat_client.delete_stack(stack_name)

    def _update_nfv_dict(self, heat_client, stack_name, fields):
        parameters = heat_client.get_parameters(stack_name)
        LOG.debug("ORIG parameters: %s", parameters)
        # NOTE: parameters['nfv'] is string
        orig_nfv_dict = json.loads(parameters.get('nfv', '{}'))
        if 'nfv' in fields['parameters']:
            fields['parameters']['nfv'] = inst_utils.json_merge_patch(
                orig_nfv_dict, fields['parameters']['nfv'])
        LOG.debug("NEW parameters: %s", fields['parameters'])
        return fields

    def scale(self, req, inst, grant_req, grant, vnfd):
        vim_info = inst_utils.select_vim_info(inst.vimConnectionInfo)
        heat_client = heat_utils.HeatClient(vim_info)

        # make HOT
        fields = self._make_hot(req, inst, grant_req, grant, vnfd)

        LOG.debug("stack fields: %s", fields)

        stack_name = fields.pop('stack_name')

        # mark unhealthy to servers to be removed if scale in
        if req.type == 'SCALE_IN':
            vnfc_res_ids = [res_def.resource.resourceId
                            for res_def in grant_req.removeResources
                            if res_def.type == 'COMPUTE']
            for vnfc in inst.instantiatedVnfInfo.vnfcResourceInfo:
                if vnfc.computeResource.resourceId in vnfc_res_ids:
                    if 'parent_stack_id' not in vnfc.metadata:
                        # It means definition of VDU in the BaseHOT
                        # is inappropriate.
                        raise sol_ex.UnexpectedParentResourceDefinition()
                    heat_client.mark_unhealthy(
                        vnfc.metadata['parent_stack_id'],
                        vnfc.metadata['parent_resource_name'])

        # update stack
        fields = self._update_nfv_dict(heat_client, stack_name, fields)
        heat_client.update_stack(stack_name, fields)

        # get stack resource
        heat_reses = heat_client.get_resources(stack_name)

        # make instantiated_vnf_info
        self._make_instantiated_vnf_info(req, inst, grant_req, grant, vnfd,
            heat_reses)

    def scale_rollback(self, req, inst, grant_req, grant, vnfd):
        # NOTE: rollback is supported for scale out only
        vim_info = inst_utils.select_vim_info(inst.vimConnectionInfo)
        heat_client = heat_utils.HeatClient(vim_info)
        stack_name = heat_utils.get_stack_name(inst)
        heat_reses = heat_client.get_resources(stack_name)

        # mark unhealthy to added servers while scale out
        vnfc_ids = [vnfc.id
                    for vnfc in inst.instantiatedVnfInfo.vnfcResourceInfo]
        for res in heat_utils.get_server_reses(heat_reses):
            if res['physical_resource_id'] not in vnfc_ids:
                metadata = self._make_vnfc_metadata(res, heat_reses)
                if 'parent_stack_id' not in metadata:
                    # It means definition of VDU in the BaseHOT
                    # is inappropriate.
                    raise sol_ex.UnexpectedParentResourceDefinition()
                heat_client.mark_unhealthy(
                    metadata['parent_stack_id'],
                    metadata['parent_resource_name'])

        # update (put back) 'desired_capacity' parameter
        fields = self._update_nfv_dict(heat_client, stack_name,
            userdata_default.DefaultUserData.scale_rollback(
                req, inst, grant_req, grant, vnfd.csar_dir))

        heat_client.update_stack(stack_name, fields)

        # NOTE: instantiatedVnfInfo is not necessary to update since it
        # should be same as before scale API started.

    def _make_hot(self, req, inst, grant_req, grant, vnfd):
        if grant_req.operation == v2fields.LcmOperationType.INSTANTIATE:
            flavour_id = req.flavourId
        else:
            flavour_id = inst.instantiatedVnfInfo.flavourId

        hot_dict = vnfd.get_base_hot(flavour_id)
        if not hot_dict:
            raise sol_ex.BaseHOTNotDefined()

        userdata = None
        userdata_class = None
        if req.obj_attr_is_set('additionalParams'):
            userdata = req.additionalParams.get('lcm-operation-user-data')
            userdata_class = req.additionalParams.get(
                'lcm-operation-user-data-class')

        if userdata is None and userdata_class is None:
            LOG.debug("Processing default userdata %s", grant_req.operation)
            # NOTE: objects used here are dict compat.
            method = getattr(userdata_default.DefaultUserData,
                             grant_req.operation.lower())
            fields = method(req, inst, grant_req, grant, vnfd.csar_dir)
        elif userdata is None or userdata_class is None:
            # Both must be specified.
            raise sol_ex.UserdataMissing()
        else:
            LOG.debug("Processing %s %s %s", userdata, userdata_class,
                grant_req.operation)

            tmp_csar_dir = vnfd.make_tmp_csar_dir()
            script_dict = {
                'request': req.to_dict(),
                'vnf_instance': inst.to_dict(),
                'grant_request': grant_req.to_dict(),
                'grant_response': grant.to_dict(),
                'tmp_csar_dir': tmp_csar_dir
            }
            script_path = os.path.join(
                os.path.dirname(__file__), "userdata_main.py")

            out = subprocess.run(["python3", script_path],
                input=pickle.dumps(script_dict),
                capture_output=True)

            vnfd.remove_tmp_csar_dir(tmp_csar_dir)

            if out.returncode != 0:
                LOG.debug("execute userdata class instantiate failed: %s",
                    out.stderr)
                raise sol_ex.UserdataExecutionFailed(sol_detail=out.stderr)

            fields = pickle.loads(out.stdout)

        stack_name = heat_utils.get_stack_name(inst)
        fields['stack_name'] = stack_name
        fields['timeout_mins'] = (
            CONF.v2_vnfm.openstack_vim_stack_create_timeout)

        return fields

    def _get_checked_reses(self, nodes, reses):
        names = list(nodes.keys())

        def _check_res_in_vnfd(res):
            if res['resource_name'] in names:
                return True
            else:
                # should not occur. just check for consistency.
                LOG.debug("%s not in VNFD definition.", res['resource_name'])
                return False

        return {res['physical_resource_id']: res
                for res in reses if _check_res_in_vnfd(res)}

    def _address_range_data_to_info(self, range_data):
        obj = objects.ipOverEthernetAddressInfoV2_IpAddresses_AddressRange()
        obj.minAddress = range_data.minAddress
        obj.maxAddress = range_data.maxAddress
        return obj

    def _proto_data_to_info(self, proto_data):
        # make CpProtocolInfo (5.5.3.9b) from CpProtocolData (4.4.1.10b)
        proto_info = objects.CpProtocolInfoV2(
            layerProtocol=proto_data.layerProtocol
        )
        ip_info = objects.IpOverEthernetAddressInfoV2()

        ip_data = proto_data.ipOverEthernet
        if ip_data.obj_attr_is_set('macAddress'):
            ip_info.macAddress = ip_data.macAddress
        if ip_data.obj_attr_is_set('segmentationId'):
            ip_info.segmentationId = ip_data.segmentationId
        if ip_data.obj_attr_is_set('ipAddresses'):
            addr_infos = []
            for addr_data in ip_data.ipAddresses:
                addr_info = objects.IpOverEthernetAddressInfoV2_IpAddresses(
                    type=addr_data.type)
                if addr_data.obj_attr_is_set('fixedAddresses'):
                    addr_info.addresses = addr_data.fixedAddresses
                if addr_data.obj_attr_is_set('numDynamicAddresses'):
                    addr_info.isDynamic = True
                if addr_data.obj_attr_is_set('addressRange'):
                    addr_info.addressRange = self._address_range_data_to_info(
                        addr_data.addressRange)
                if addr_data.obj_attr_is_set('subnetId'):
                    addr_info.subnetId = addr_data.subnetId
                addr_infos.append(addr_info)
            ip_info.ipAddresses = addr_infos

        proto_info.ipOverEthernet = ip_info

        return proto_info

    def _make_ext_vl_info_from_req(self, req, grant, ext_cp_infos):
        # make extVirtualLinkInfo
        ext_vls = []
        req_ext_vls = []
        if grant.obj_attr_is_set('extVirtualLinks'):
            req_ext_vls = grant.extVirtualLinks
        elif req.obj_attr_is_set('extVirtualLinks'):
            req_ext_vls = req.extVirtualLinks

        for req_ext_vl in req_ext_vls:
            ext_vl = objects.ExtVirtualLinkInfoV2(
                id=req_ext_vl.id,
                resourceHandle=objects.ResourceHandle(
                    resourceId=req_ext_vl.resourceId
                ),
                currentVnfExtCpData=req_ext_vl.extCps
            )
            if req_ext_vl.obj_attr_is_set('vimConnectionId'):
                ext_vl.resourceHandle.vimConnectionId = (
                    req_ext_vl.vimConnectionId)
            if req_ext_vl.obj_attr_is_set('resourceProviderId'):
                ext_vl.resourceHandle.resourceProviderId = (
                    req_ext_vl.resourceProviderId)

            ext_vls.append(ext_vl)

            if not req_ext_vl.obj_attr_is_set('extLinkPorts'):
                continue
            link_ports = []
            for req_link_port in req_ext_vl.extLinkPorts:
                link_port = objects.ExtLinkPortInfoV2(
                    id=_make_link_port_id(req_link_port.id),
                    resourceHandle=req_link_port.resourceHandle,
                )
                ext_cp_info = objects.VnfExtCpInfoV2(
                    id=_make_cp_info_id(link_port.id),
                    extLinkPortId=link_port.id
                    # associatedVnfcCpId may set later
                )
                link_port.cpInstanceId = ext_cp_info.id

                for ext_cp in req_ext_vl.extCps:
                    found = False
                    for key, cp_conf in ext_cp.cpConfig.items():
                        if (cp_conf.obj_attr_is_set('linkPortId') and
                                cp_conf.linkPortId == req_link_port.id):
                            ext_cp_info.cpdId = ext_cp.cpdId
                            ext_cp_info.cpConfigId = key
                            # NOTE: cpProtocolInfo can't be filled
                            found = True
                            break
                    if found:
                        break

                link_ports.append(link_port)
                ext_cp_infos.append(ext_cp_info)

            ext_vl.extLinkPorts = link_ports

        return ext_vls

    def _make_ext_vl_info_from_inst(self, old_inst_vnf_info, ext_cp_infos):
        # make extVirtualLinkInfo from old inst.extVirtualLinkInfo
        ext_vls = []
        old_cp_infos = []

        if old_inst_vnf_info.obj_attr_is_set('extVirtualLinkInfo'):
            ext_vls = old_inst_vnf_info.extVirtualLinkInfo
        if old_inst_vnf_info.obj_attr_is_set('extCpInfo'):
            old_cp_infos = old_inst_vnf_info.extCpInfo

        for ext_vl in ext_vls:
            if not ext_vl.obj_attr_is_set('extLinkPorts'):
                continue
            new_link_ports = []
            for link_port in ext_vl.extLinkPorts:
                if not _is_link_port(link_port.id):
                    # port created by heat. re-create later
                    continue

                new_link_ports.append(link_port)
                for ext_cp in old_cp_infos:
                    if ext_cp.id == link_port.cpInstanceId:
                        ext_cp_infos.append(ext_cp)
                        break

            ext_vl.extLinkPorts = new_link_ports

        return ext_vls

    def _make_ext_mgd_vl_info_from_req(self, vnfd, flavour_id, req, grant):
        # make extManagedVirtualLinkInfo
        ext_mgd_vls = []
        req_mgd_vls = []
        if grant.obj_attr_is_set('extManagedVirtualLinks'):
            req_mgd_vls = grant.extManagedVirtualLinks
        elif req.obj_attr_is_set('extManagedVirtualLinks'):
            req_mgd_vls = req.extManagedVirtualLinks

        vls = vnfd.get_virtual_link_nodes(flavour_id)
        for req_mgd_vl in req_mgd_vls:
            vl_name = req_mgd_vl.vnfVirtualLinkDescId
            if vl_name not in list(vls.keys()):
                # should not occur. just check for consistency.
                LOG.debug("%s not in VNFD VL definition.", vl_name)
                continue
            ext_mgd_vl = objects.ExtManagedVirtualLinkInfoV2(
                id=req_mgd_vl.id,
                vnfVirtualLinkDescId=vl_name,
                networkResource=objects.ResourceHandle(
                    id=uuidutils.generate_uuid(),
                    resourceId=req_mgd_vl.resourceId
                )
            )
            if req_mgd_vl.obj_attr_is_set('vimConnectionId'):
                ext_mgd_vl.networkResource.vimConnectionId = (
                    req_mgd_vl.vimConnectionId)
            if req_mgd_vl.obj_attr_is_set('resourceProviderId'):
                ext_mgd_vl.networkResource.resourceProviderId = (
                    req_mgd_vl.resourceProviderId)

            ext_mgd_vls.append(ext_mgd_vl)

            if req_mgd_vl.obj_attr_is_set('vnfLinkPort'):
                ext_mgd_vl.vnfLinkPort = [
                    objects.VnfLinkPortInfoV2(
                        id=_make_link_port_id(req_link_port.vnfLinkPortId),
                        resourceHandle=req_link_port.resourceHandle,
                        cpInstanceType='EXT_CP',  # may be changed later
                        # cpInstanceId may set later
                    )
                    for req_link_port in req_mgd_vl.vnfLinkPort
                ]

        return ext_mgd_vls

    def _make_ext_mgd_vl_info_from_inst(self, old_inst_vnf_info):
        # make extManagedVirtualLinkInfo
        ext_mgd_vls = []

        if old_inst_vnf_info.obj_attr_is_set('extManagedVirtualLinkInfo'):
            ext_mgd_vls = old_inst_vnf_info.extManagedVirtualLinkInfo

        for ext_mgd_vl in ext_mgd_vls:
            if ext_mgd_vl.obj_attr_is_set('vnfLinkPorts'):
                ext_mgd_vl.vnfLinkPorts = [link_port
                    for link_port in ext_mgd_vl.vnfLinkPorts
                    if _is_link_port(link_port.id)]

        return ext_mgd_vls

    def _find_ext_vl_by_cp_name(self, cp_name, ext_vl_infos):
        for ext_vl_info in ext_vl_infos:
            for ext_cp_data in ext_vl_info.currentVnfExtCpData:
                if ext_cp_data.cpdId == cp_name:
                    return ext_vl_info, ext_cp_data

        return None, None

    def _link_ext_port_info(self, ext_port_infos, ext_vl_infos, ext_cp_infos,
            port_reses):
        for ext_port_info in ext_port_infos:
            res = port_reses[ext_port_info.id]
            cp_name = res['resource_name']
            ext_cp_info = objects.VnfExtCpInfoV2(
                id=_make_cp_info_id(ext_port_info.id),
                extLinkPortId=ext_port_info.id,
                cpdId=cp_name
                # associatedVnfcCpId may set later
            )
            ext_port_info.cpInstanceId = ext_cp_info.id

            ext_vl_info, ext_cp_data = self._find_ext_vl_by_cp_name(
                cp_name, ext_vl_infos)

            if ext_vl_info:
                if ext_vl_info.obj_attr_is_set('extLinkPorts'):
                    ext_vl_info.extLinkPorts.append(ext_port_info)
                else:
                    ext_vl_info.extLinkPorts = [ext_port_info]

                for key, cp_conf in ext_cp_data.cpConfig.items():
                    # NOTE: it is assumed that there is one item
                    # (with cpProtocolData) of cpConfig at the moment.
                    if cp_conf.obj_attr_is_set('cpProtocolData'):
                        proto_infos = []
                        for proto_data in cp_conf.cpProtocolData:
                            proto_info = self._proto_data_to_info(
                                proto_data)
                            proto_infos.append(proto_info)
                        ext_cp_info.cpProtocolInfo = proto_infos
                        ext_cp_info.cpConfigId = key
                        break

            ext_cp_infos.append(ext_cp_info)

    def _find_vnfc_cp_info(self, port_res, vnfc_res_infos, server_reses):
        for vnfc_res_info in vnfc_res_infos:
            if not vnfc_res_info.obj_attr_is_set('vnfcCpInfo'):
                continue
            vnfc_res = server_reses[vnfc_res_info.id]
            vdu_name = vnfc_res_info.vduId
            cp_name = port_res['resource_name']
            if (vdu_name in port_res.get('required_by', []) and
                    port_res.get('parent_resource') ==
                    vnfc_res.get('parent_resource')):
                for vnfc_cp in vnfc_res_info.vnfcCpInfo:
                    if vnfc_cp.cpdId == cp_name:
                        return vnfc_cp

    def _link_vnfc_cp_info(self, vnfc_res_infos, ext_port_infos,
            vnf_port_infos, ext_cp_infos, server_reses, port_reses):

        for ext_port_info in ext_port_infos:
            port_res = port_reses[ext_port_info.id]
            vnfc_cp = self._find_vnfc_cp_info(port_res, vnfc_res_infos,
                server_reses)
            if vnfc_cp:
                # should be found
                vnfc_cp.vnfExtCpId = ext_port_info.cpInstanceId
                for ext_cp_info in ext_cp_infos:
                    if ext_cp_info.extLinkPortId == ext_port_info.id:
                        ext_cp_info.associatedVnfcCpId = vnfc_cp.id
                        break

        for vnf_port_info in vnf_port_infos:
            port_res = port_reses[vnf_port_info.id]
            vnfc_cp = self._find_vnfc_cp_info(port_res, vnfc_res_infos,
                server_reses)
            if vnfc_cp:
                # should be found
                vnf_port_info.cpInstanceType = 'VNFC_CP'
                vnf_port_info.cpInstanceId = vnfc_cp.id
                vnfc_cp.vnfLinkPortId = vnf_port_info.id

    def _make_vnfc_metadata(self, server_res, heat_reses):
        metadata = {
            'creation_time': server_res['creation_time'],
        }
        parent_res = heat_utils.get_parent_resource(server_res, heat_reses)
        if parent_res:
            metadata['parent_stack_id'] = (
                heat_utils.get_resource_stack_id(parent_res))
            metadata['parent_resource_name'] = parent_res['resource_name']

        return metadata

    def _make_instantiated_vnf_info(self, req, inst, grant_req, grant, vnfd,
            heat_reses):
        init = False
        if grant_req.operation == v2fields.LcmOperationType.INSTANTIATE:
            init = True
            flavour_id = req.flavourId
        else:
            flavour_id = inst.instantiatedVnfInfo.flavourId
        vim_info = inst_utils.select_vim_info(inst.vimConnectionInfo)
        vducp_nodes = vnfd.get_vducp_nodes(flavour_id)

        storage_reses = self._get_checked_reses(
            vnfd.get_storage_nodes(flavour_id),
            heat_utils.get_storage_reses(heat_reses))
        server_reses = self._get_checked_reses(vnfd.get_vdu_nodes(flavour_id),
            heat_utils.get_server_reses(heat_reses))
        network_reses = self._get_checked_reses(
            vnfd.get_virtual_link_nodes(flavour_id),
            heat_utils.get_network_reses(heat_reses))
        port_reses = self._get_checked_reses(vducp_nodes,
            heat_utils.get_port_reses(heat_reses))

        def _res_to_handle(res):
            return objects.ResourceHandle(
                resourceId=res['physical_resource_id'],
                vimLevelResourceType=res['resource_type'],
                vimConnectionId=vim_info.vimId)

        storage_infos = [
            objects.VirtualStorageResourceInfoV2(
                id=res_id,
                virtualStorageDescId=res['resource_name'],
                storageResource=_res_to_handle(res)
            )
            for res_id, res in storage_reses.items()
        ]

        vnfc_res_infos = [
            objects.VnfcResourceInfoV2(
                id=res_id,
                vduId=res['resource_name'],
                computeResource=_res_to_handle(res),
                metadata=self._make_vnfc_metadata(res, heat_reses)
            )
            for res_id, res in server_reses.items()
        ]

        for vnfc_res_info in vnfc_res_infos:
            vdu_name = vnfc_res_info.vduId
            server_res = server_reses[vnfc_res_info.id]
            storage_ids = [storage_id
                for storage_id, storage_res in storage_reses.items()
                if (vdu_name in storage_res.get('required_by', []) and
                    server_res.get('parent_resource') ==
                    storage_res.get('parent_resource'))
            ]
            if storage_ids:
                vnfc_res_info.storageResourceIds = storage_ids

            vdu_cps = vnfd.get_vdu_cps(flavour_id, vdu_name)
            cp_infos = [
                objects.VnfcResourceInfoV2_VnfcCpInfo(
                    id=_make_combination_id(cp, vnfc_res_info.id),
                    cpdId=cp,
                    # vnfExtCpId or vnfLinkPortId may set later
                )
                for cp in vdu_cps
            ]
            if cp_infos:
                vnfc_res_info.vnfcCpInfo = cp_infos

        vnf_vl_res_infos = [
            objects.VnfVirtualLinkResourceInfoV2(
                id=res_id,
                vnfVirtualLinkDescId=res['resource_name'],
                networkResource=_res_to_handle(res)
            )
            for res_id, res in network_reses.items()
        ]

        ext_cp_infos = []
        if init:
            ext_vl_infos = self._make_ext_vl_info_from_req(
                req, grant, ext_cp_infos)
            ext_mgd_vl_infos = self._make_ext_mgd_vl_info_from_req(vnfd,
                flavour_id, req, grant)
        else:
            old_inst_vnf_info = inst.instantiatedVnfInfo
            ext_vl_infos = self._make_ext_vl_info_from_inst(
                old_inst_vnf_info, ext_cp_infos)
            ext_mgd_vl_infos = self._make_ext_mgd_vl_info_from_inst(
                old_inst_vnf_info)

        def _find_vl_name(port_res):
            cp_name = port_res['resource_name']
            return vnfd.get_vl_name_from_cp(flavour_id, vducp_nodes[cp_name])

        ext_port_infos = [
            objects.ExtLinkPortInfoV2(
                id=res_id,
                resourceHandle=_res_to_handle(res)
            )
            for res_id, res in port_reses.items()
            if _find_vl_name(res) is None
        ]

        self._link_ext_port_info(ext_port_infos, ext_vl_infos, ext_cp_infos,
            port_reses)

        vnf_port_infos = [
            objects.VnfLinkPortInfoV2(
                id=res_id,
                resourceHandle=_res_to_handle(res),
                cpInstanceType='EXT_CP'  # may be changed later
            )
            for res_id, res in port_reses.items()
            if _find_vl_name(res) is not None
        ]

        vl_name_to_info = {info.vnfVirtualLinkDescId: info
            for info in vnf_vl_res_infos + ext_mgd_vl_infos}

        for vnf_port_info in vnf_port_infos:
            port_res = port_reses[vnf_port_info.id]
            vl_info = vl_name_to_info.get(_find_vl_name(port_res))
            if vl_info is None:
                # should not occur. just check for consistency.
                continue

            if vl_info.obj_attr_is_set('vnfLinkPorts'):
                vl_info.vnfLinkPorts.append(vnf_port_info)
            else:
                vl_info.vnfLinkPorts = [vnf_port_info]

        self._link_vnfc_cp_info(vnfc_res_infos, ext_port_infos,
            vnf_port_infos, ext_cp_infos, server_reses, port_reses)

        # NOTE: The followings are not handled at the moment.
        # - handle tosca.nodes.nfv.VnfExtCp type
        #   Note that there is no example in current tacker examples which use
        #   tosca.nodes.nfv.VnfExtCp type and related BaseHOT definitions.
        # - in the case of specifying linkPortId of extVirtualLinks or
        #   extManagedVirtualLinks, the link of vnfcCpInfo is not handled
        #   because the association of compute resource and port resource
        #   is not identified.

        # make new instatiatedVnfInfo and replace
        inst_vnf_info = objects.VnfInstanceV2_InstantiatedVnfInfo(
            flavourId=flavour_id,
            vnfState='STARTED',
        )
        if storage_infos:
            inst_vnf_info.virtualStorageResourceInfo = storage_infos

        if vnfc_res_infos:
            # NOTE: scale-in specification of tacker SOL003 v2 API is that
            # newer VDU is selected for reduction. It is necessary to sort
            # vnfc_res_infos at this point so that the conductor should
            # choose VDUs from a head sequentially when making scale-in
            # grant request.

            def _get_key(vnfc):
                return parser.isoparse(vnfc.metadata['creation_time'])

            sorted_vnfc_res_infos = sorted(vnfc_res_infos, key=_get_key,
                                           reverse=True)
            inst_vnf_info.vnfcResourceInfo = sorted_vnfc_res_infos

        if vnf_vl_res_infos:
            inst_vnf_info.vnfVirtualLinkResourceInfo = vnf_vl_res_infos

        if ext_vl_infos:
            inst_vnf_info.extVirtualLinkInfo = ext_vl_infos

        if ext_mgd_vl_infos:
            inst_vnf_info.extManagedVirtualLinkInfo = ext_mgd_vl_infos

        if ext_cp_infos:
            inst_vnf_info.extCpInfo = ext_cp_infos

        # make vnfcInfo
        # NOTE: vnfcInfo only exists in SOL002
        if vnfc_res_infos:
            vnfc_infos = []
            old_vnfc_infos = []
            if (inst.obj_attr_is_set('instantiatedVnfInfo') and
                    inst.instantiatedVnfInfo.obj_attr_is_set('vnfcInfo')):
                old_vnfc_infos = inst.instantiatedVnfInfo.vnfcInfo

            for vnfc_res_info in sorted_vnfc_res_infos:
                vnfc_info = None
                vnfc_id = _make_combination_id(vnfc_res_info.vduId,
                                               vnfc_res_info.id)
                for old_vnfc_info in old_vnfc_infos:
                    if old_vnfc_info.id == vnfc_id:
                        # re-use current object since
                        # vnfcConfigurableProperties may be set.
                        vnfc_info = old_vnfc_info
                        break
                if vnfc_info is None:
                    vnfc_info = objects.VnfcInfoV2(
                        id=vnfc_id,
                        vduId=vnfc_res_info.vduId,
                        vnfcResourceInfoId=vnfc_res_info.id,
                        vnfcState='STARTED'
                    )
                vnfc_infos.append(vnfc_info)

            inst_vnf_info.vnfcInfo = vnfc_infos

        inst.instantiatedVnfInfo = inst_vnf_info


text:
package eu.mosaic_cloud.tools.exceptions.core;

import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;

public abstract class CaughtException
			extends Throwable
{
	CaughtException (final ExceptionResolution resolution, final Throwable caught) {
		super (caught);
		Preconditions.checkNotNull (caught);
		this.caught = caught;
		this.resolution = resolution;
		this.messageFormat = null;
		this.messageArguments = null;
	}

	CaughtException (final ExceptionResolution resolution, final Throwable caught, final String message) {
		super (message, caught);
		Preconditions.checkNotNull (caught);
		this.caught = caught;
		this.resolution = resolution;
		this.messageFormat = null;
		this.messageArguments = null;
	}

	CaughtException (final ExceptionResolution resolution, final Throwable caught, final String messageFormat, final Object ... messageArguments) {
		super (String.format (messageFormat, messageArguments), caught);
		Preconditions.checkNotNull (caught);
		this.caught = caught;
		this.resolution = resolution;
		this.messageFormat = messageFormat;
		this.messageArguments = messageArguments;
	}

	public final Throwable getCaught () {
		return (this.caught);
	}

	public final Object[] getMessageArguments () {
		return (this.messageArguments);
	}

	public final String getMessageFormat () {
		return (this.messageFormat);
	}

	public final ExceptionResolution getResolution () {
		return (this.resolution);
	}

	public final void rethrow () {
		Throwables.propagate (this.caught);
	}

	public final void trace (final ExceptionResolution resolution, final ExceptionTracer tracer) {
		tracer.trace (ExceptionResolution.Handled, this);
		final Throwable cause = this.getCause ();
		if (this.messageFormat != null) {
			final String message = this.getMessage ();
			if (message != null)
				tracer.trace (resolution, cause, message);
			else
				tracer.trace (resolution, cause);
		} else
			tracer.trace (resolution, cause, this.messageFormat, this.messageArguments);
	}

	public final void trace (final ExceptionTracer tracer) {
		this.trace (this.resolution, tracer);
	}

	public final Wrapper wrap () {
		return (new Wrapper (this));
	}

	public final Throwable caught;
	public final ExceptionResolution resolution;
	protected final Object[] messageArguments;
	protected final String messageFormat;

	public static final CaughtException create (final ExceptionResolution resolution, final Throwable caught) {
		switch (resolution) {
			case Handled :
				return (new HandledException (caught));
			case Deferred :
				return (new DeferredException (caught));
			case Ignored :
				return (new IgnoredException (caught));
			default :
				throw (new AssertionError ());
		}
	}

	public static final CaughtException create (final ExceptionResolution resolution, final Throwable caught, final String message) {
		switch (resolution) {
			case Handled :
				return (new HandledException (caught, message));
			case Deferred :
				return (new DeferredException (caught, message));
			case Ignored :
				return (new IgnoredException (caught, message));
			default :
				throw (new AssertionError ());
		}
	}

	public static final CaughtException create (final ExceptionResolution resolution, final Throwable caught, final String messageFormat, final Object ... messageArguments) {
		switch (resolution) {
			case Handled :
				return (new HandledException (caught, messageFormat, messageArguments));
			case Deferred :
				return (new DeferredException (caught, messageFormat, messageArguments));
			case Ignored :
				return (new IgnoredException (caught, messageFormat, messageArguments));
			default :
				throw (new AssertionError ());
		}
	}

	private static final long serialVersionUID = 1L;

	public static final class Wrapper
				extends Error
	{
		Wrapper (final CaughtException exception) {
			super (exception);
			this.exception = exception;
		}

		public final void rethrow () {
			this.exception.rethrow ();
		}

		public final void trace (final ExceptionResolution resolution, final ExceptionTracer tracer) {
			tracer.trace (ExceptionResolution.Handled, this);
			this.exception.trace (resolution, tracer);
		}

		public final void trace (final ExceptionTracer tracer) {
			tracer.trace (ExceptionResolution.Handled, this);
			this.exception.trace (tracer);
		}

		public final CaughtException exception;
		private static final long serialVersionUID = 1L;
	}
}


text:
//
//  IBAAbstractCoreDataService.h
//  IttyBittyBits
//
//  Created by Oliver Jones on 24/06/11.
//  Copyright 2011 Itty Bitty Apps Pty. Ltd. All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@class IBAAbstractCoreDataService;

@protocol IBAAbstractCoreDataServiceDelegate <NSObject>

/*!
 \brief     Notifies the delegate that the \a context failed to save the managed object \a context.
 \param     dataService The IBAAbstractCoreDataService instance.
 \param     context     The NSManagedObjectContext instance that failed to save.
 \param     error       The error generated.
 \return    YES if the error was resolved/handled; NO if the IBAAbstractCoreDataService should perform its own default error handling.
 */
@optional
- (BOOL)              dataService:(IBAAbstractCoreDataService *)dataService
didFailToSaveManagedObjectContext:(NSManagedObjectContext*)context
                        withError:(NSError*)error;

- (BOOL)        shouldDataService:(IBAAbstractCoreDataService *)dataService
          mergeChangesFromContext:(NSManagedObjectContext*)context;

- (void)              dataService:(IBAAbstractCoreDataService *)dataService
  didMergeSavedChangesFromContext:(NSManagedObjectContext*)context;
@end

@interface IBAAbstractCoreDataService : NSObject
{
@private
}

@property (nonatomic, retain, readonly) NSManagedObjectContext *defaultManagedObjectContext;
@property (nonatomic, assign) id<IBAAbstractCoreDataServiceDelegate> delegate;

- (id) initWithObjectModelURL:(NSURL *)modelURL
                     storeURL:(NSURL *)storeURL;

- (NSManagedObjectContext *)newManagedObjectContext;
- (void)save;

- (BOOL) shouldRetryAddingPersistentStoreForModel:(NSManagedObjectModel *)model
                                         storeURL:(NSURL *)storeURL
                                        withError:(NSError *)error;

- (void) handleUnresolvedError:(NSError *)error;
@end


text:
#pragma once

#include <folly/Baton.h>

#include <folly/fibers/Baton.h>

namespace folly {
namespace fibers {

typedef Baton GenericBaton;
} // namespace fibers
} // namespace folly


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/bitisworkshop.iml" filepath="$PROJECT_DIR$/.idea/bitisworkshop.iml" />
    </modules>
  </component>
</project>


text:
#pragma once
#include <aws/lightsail/Lightsail_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/lightsail/model/Disk.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace Lightsail
{
namespace Model
{
  class AWS_LIGHTSAIL_API GetDisksResult
  {
  public:
    GetDisksResult();
    GetDisksResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    GetDisksResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
An array of objects containing information about all block storage disks.

     */
    inline const Aws::Vector<Disk>& GetDisks() const{ return m_disks; }

    /**
     *
An array of objects containing information about all block storage disks.

     */
    inline void SetDisks(const Aws::Vector<Disk>& value) { m_disks = value; }

    /**
     *
An array of objects containing information about all block storage disks.

     */
    inline void SetDisks(Aws::Vector<Disk>&& value) { m_disks = std::move(value); }

    /**
     *
An array of objects containing information about all block storage disks.

     */
    inline GetDisksResult& WithDisks(const Aws::Vector<Disk>& value) { SetDisks(value); return *this;}

    /**
     *
An array of objects containing information about all block storage disks.

     */
    inline GetDisksResult& WithDisks(Aws::Vector<Disk>&& value) { SetDisks(std::move(value)); return *this;}

    /**
     *
An array of objects containing information about all block storage disks.

     */
    inline GetDisksResult& AddDisks(const Disk& value) { m_disks.push_back(value); return *this; }

    /**
     *
An array of objects containing information about all block storage disks.

     */
    inline GetDisksResult& AddDisks(Disk&& value) { m_disks.push_back(std::move(value)); return *this; }

    /**
     *
A token used for advancing to the next page of results from your GetDisks
     * request.

     */
    inline const Aws::String& GetNextPageToken() const{ return m_nextPageToken; }

    /**
     *
A token used for advancing to the next page of results from your GetDisks
     * request.

     */
    inline void SetNextPageToken(const Aws::String& value) { m_nextPageToken = value; }

    /**
     *
A token used for advancing to the next page of results from your GetDisks
     * request.

     */
    inline void SetNextPageToken(Aws::String&& value) { m_nextPageToken = std::move(value); }

    /**
     *
A token used for advancing to the next page of results from your GetDisks
     * request.

     */
    inline void SetNextPageToken(const char* value) { m_nextPageToken.assign(value); }

    /**
     *
A token used for advancing to the next page of results from your GetDisks
     * request.

     */
    inline GetDisksResult& WithNextPageToken(const Aws::String& value) { SetNextPageToken(value); return *this;}

    /**
     *
A token used for advancing to the next page of results from your GetDisks
     * request.

     */
    inline GetDisksResult& WithNextPageToken(Aws::String&& value) { SetNextPageToken(std::move(value)); return *this;}

    /**
     *
A token used for advancing to the next page of results from your GetDisks
     * request.

     */
    inline GetDisksResult& WithNextPageToken(const char* value) { SetNextPageToken(value); return *this;}

  private:

    Aws::Vector<Disk> m_disks;

    Aws::String m_nextPageToken;
  };

} // namespace Model
} // namespace Lightsail
} // namespace Aws


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('container', '0201_squashed'),
    ]

    operations = [
        migrations.AlterField(
            model_name='containerrun',
            name='submit_time',
            field=models.DateTimeField(auto_now_add=True, help_text='When this job was put in the queue.'),
        ),
    ]


text:
using System.Collections.Generic;
using DotNetNuke.Data;

namespace Brafton.Modules.BraftonImporter7_02_02.Components
{
    class ItemController
    {
        public void CreateItem(Item t)
        {
            using (IDataContext ctx = DataContext.Instance())
            {
                var rep = ctx.GetRepository<Item>();
                rep.Insert(t);
            }
        }

        public void DeleteItem(int itemId, int moduleId)
        {
            var t = GetItem(itemId, moduleId);
            DeleteItem(t);
        }

        public void DeleteItem(Item t)
        {
            using (IDataContext ctx = DataContext.Instance())
            {
                var rep = ctx.GetRepository<Item>();
                rep.Delete(t);
            }
        }

        public IEnumerable<Item> GetItems(int moduleId)
        {
            IEnumerable<Item> t;
            using (IDataContext ctx = DataContext.Instance())
            {
                var rep = ctx.GetRepository<Item>();
                t = rep.Get(moduleId);
            }
            return t;
        }

        public Item GetItem(int itemId, int moduleId)
        {
            Item t;
            using (IDataContext ctx = DataContext.Instance())
            {
                var rep = ctx.GetRepository<Item>();
                t = rep.GetById(itemId, moduleId);
            }
            return t;
        }

        public void UpdateItem(Item t)
        {
            using (IDataContext ctx = DataContext.Instance())
            {
                var rep = ctx.GetRepository<Item>();
                rep.Update(t);
            }
        }

    }
}


text:
layout: post
title: "The Eight Queens Problem"
excerpt: "An introduction to the eight queens problem, and a recursive solution"
tags: [eight_queens, code_snippet]
comments: true
image:
  feature: queen2.jpg
  credit: AlmostQueen
  creditlink: http://www.almostqueen.com/photos/
---

Overview

*  Auto generated table of contents
{:toc}

> Part One of Three

This is the first part in a four part series on the eight queens problem. This first part will focus on introducing the Eight Queens problem, as well as recursively generating a set of all possible solutions.

## The 8 Queens Problem

The eight queens puzzle involves arranging eight queens on one `8x8` chessboard such that no queens are able to attack each other. This problem is one specific instance of the **n-queens** problem, where `n` queens occupy an `nxn` grid without attacking each other.

Computing each solution can be expensive for the 8-queens problem as there are roughly **4.5 billion** possible arrangements of eight queens on an 8x8 board, and only *92* solutions.

There are several techniques to do this. In the first three parts of this series, I will discuss a recursive solution, a genetic algorithm solution, and a simulated annealing solution. In the final part, I will compare the three approaches.

## The Recursive Solution

Solving this recursively is pretty straightforward once the logic is reasoned out. Let's represent our chessboard as an array. In order to do that, let's define the size of our grid (and the number of our queens) as a constant.

{% highlight java %}
private final int GRID_SIZE = 8;
{% endhighlight %}

Each value of the array can be treated as the measure the row, and each position in the array as a measure of its column. Let's examine the recursive logic to be implemented:

{% gist hesham8/68f0a31cd18c0546721d %}

Following this logic, this is actually a fairly straightforward solution to implement.

{% highlight java %}
//Does not include mirror image solutions. (i.e., 42061753 is not distinct from 35716024)
Integer[] placeQueens(int row, Integer[] columns, List<Integer[]> results) {
  Integer[] returnValue;
    if (row == GRID_SIZE) {
        return columns;
    } else {
        for (int col = 0; col < GRID_SIZE; col++) {
            if (checkValid(columns, row, col)) {
                columns[row] = col;
                returnValue = placeQueens(row + 1, columns, results);
                if (returnValue != null)
                    return returnValue;
            }
        }
    }
    return null;
}
private boolean checkValid(Integer[] columns, int row1, int column1) {
    for (int row2 = 0; row2 < row1; row2++) {
        int column2 = columns[row2];
        if (column1 == column2)
            return false;

        int columnDistance = Math.abs(column2 - column1);
        int rowDistance = row1 - row2;
        if (columnDistance == rowDistance)
            return false;
    }
    return true;
}
{% endhighlight %}

Currently, the `placeQueens()` method is written such that it can only written a single valid solution. Modifying it such that it returns *all* valid solutions is fairly trivial:

{% highlight java %}
//Does not include mirror image solutions. (i.e., 42061753 is not distinct from 35716024)
void placeQueens(int row, Integer[] columns, List<Integer[]> results, boolean withDuplicates) {
    if (row == GRID_SIZE) {
        results.add(columns.clone());
        if (withDuplicates) {
          Integer[] reverseSolution = new Integer[GRID_SIZE];
          for (int i = 0; i < GRID_SIZE; i++) {
              reverseSolution[i] = columns[columns.length - i - 1];
          }
          results.add(reverseSolution);
        }
    } else {
        for (int col = 0; col < GRID_SIZE; col++) {
            if (checkValid(columns, row, col)) {
                columns[row] = col;
                placeQueens(row + 1, columns, results);
            }
        }
    }
}
{% endhighlight %}

Note that in order to list all valid unique solutions, the mirror image of each solution generated this way must also be included.


text:
package org.apache.helix.integration;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.helix.PropertyKey.Builder;
import org.apache.helix.TestHelper;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.ZkTestHelper;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.manager.zk.ZKHelixDataAccessor;
import org.apache.helix.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.IdealState.RebalanceMode;
import org.apache.helix.tools.ClusterSetup;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;

public class TestDisable extends ZkTestBase {

  @Test
  public void testDisableNodeCustomIS() throws Exception {
    // Logger.getRootLogger().setLevel(Level.INFO);
    String className = TestHelper.getTestClassName();
    String methodName = TestHelper.getTestMethodName();
    String clusterName = className + "_" + methodName;
    final int n = 5;
    String disableNode = "localhost_12918";

    System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));

    MockParticipantManager[] participants = new MockParticipantManager[n];

    TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
        "localhost", // participant name prefix
        "TestDB", // resource name prefix
        1, // resources
        8, // partitions per resource
        n, // number of nodes
        3, // replicas
        "MasterSlave", true); // do rebalance

    // set ideal state to customized mode
    ZkBaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<>(_gZkClient);
    ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, baseAccessor);
    Builder keyBuilder = accessor.keyBuilder();
    IdealState idealState = accessor.getProperty(keyBuilder.idealStates("TestDB0"));
    idealState.setRebalanceMode(RebalanceMode.CUSTOMIZED);
    accessor.setProperty(keyBuilder.idealStates("TestDB0"), idealState);

    // start controller
    ClusterControllerManager controller =
        new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
    controller.syncStart();

    // start participants
    for (int i = 0; i < n; i++) {
      String instanceName = "localhost_" + (12918 + i);

      participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
      participants[i].syncStart();
    }

    ZkHelixClusterVerifier _clusterVerifier =
        new BestPossibleExternalViewVerifier.Builder(clusterName).setZkAddr(ZK_ADDR).build();
    Assert.assertTrue(_clusterVerifier.verifyByPolling());

    // disable localhost_12918
    String command =
        "--zkSvr " + ZK_ADDR + " --enableInstance " + clusterName + " " + disableNode + " false";
    ClusterSetup.processCommandLineArgs(command.split("\\s+"));
    Assert.assertTrue(_clusterVerifier.verifyByPolling());

    // make sure localhost_12918 is in OFFLINE state
    Map<String, Map<String, String>> expectStateMap = new HashMap<>();
    Map<String, String> expectInstanceStateMap = new HashMap<>();
    expectInstanceStateMap.put(disableNode, "OFFLINE");
    expectStateMap.put(".*", expectInstanceStateMap);
    boolean result =
        ZkTestHelper.verifyState(_gZkClient, clusterName, "TestDB0", expectStateMap, "==");
    Assert.assertTrue(result, disableNode + " should be in OFFLINE");

    // re-enable localhost_12918
    command =
        "--zkSvr " + ZK_ADDR + " --enableInstance " + clusterName + " " + disableNode + " true";
    ClusterSetup.processCommandLineArgs(command.split("\\s+"));
    Assert.assertTrue(_clusterVerifier.verifyByPolling());

    // make sure localhost_12918 is NOT in OFFLINE state
    result = ZkTestHelper.verifyState(_gZkClient, clusterName, "TestDB0", expectStateMap, "!=");
    Assert.assertTrue(result, disableNode + " should NOT be in OFFLINE");

    // clean up
    // wait for all zk callbacks done
    controller.syncStop();
    for (int i = 0; i < 5; i++) {
      participants[i].syncStop();
    }

    deleteCluster(clusterName);
    System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
  }

  @Test
  public void testDisableNodeAutoIS() throws Exception {
    String className = TestHelper.getTestClassName();
    String methodName = TestHelper.getTestMethodName();
    String clusterName = className + "_" + methodName;
    final int n = 5;
    String disableNode = "localhost_12919";

    System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));

    MockParticipantManager[] participants = new MockParticipantManager[n];

    TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
        "localhost", // participant name prefix
        "TestDB", // resource name prefix
        1, // resources
        8, // partitions per resource
        n, // number of nodes
        3, // replicas
        "MasterSlave", true); // do rebalance

    // start controller
    ClusterControllerManager controller =
        new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
    controller.syncStart();

    // start participants
    for (int i = 0; i < n; i++) {
      String instanceName = "localhost_" + (12918 + i);

      participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
      participants[i].syncStart();
    }

    ZkHelixClusterVerifier _clusterVerifier =
        new BestPossibleExternalViewVerifier.Builder(clusterName).setZkAddr(ZK_ADDR).build();
    Assert.assertTrue(_clusterVerifier.verifyByPolling());

    // disable localhost_12919
    String command =
        "--zkSvr " + ZK_ADDR + " --enableInstance " + clusterName + " " + disableNode + " false";
    ClusterSetup.processCommandLineArgs(command.split(" "));
    Assert.assertTrue(_clusterVerifier.verifyByPolling());

    // make sure localhost_12919 is in OFFLINE state
    Map<String, Map<String, String>> expectStateMap = new HashMap<>();
    Map<String, String> expectInstanceStateMap = new HashMap<>();
    expectInstanceStateMap.put(disableNode, "OFFLINE");
    expectStateMap.put(".*", expectInstanceStateMap);
    boolean result =
        ZkTestHelper.verifyState(_gZkClient, clusterName, "TestDB0", expectStateMap, "==");
    Assert.assertTrue(result, disableNode + " should be in OFFLINE");

    // re-enable localhost_12919
    command =
        "--zkSvr " + ZK_ADDR + " --enableInstance " + clusterName + " " + disableNode + " true";
    ClusterSetup.processCommandLineArgs(command.split("\\s+"));
    result = ClusterStateVerifier
        .verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
    Assert.assertTrue(result);

    // make sure localhost_12919 is NOT in OFFLINE state
    result = ZkTestHelper.verifyState(_gZkClient, clusterName, "TestDB0", expectStateMap, "!=");
    Assert.assertTrue(result, disableNode + " should NOT be in OFFLINE");

    // clean up
    // wait for all zk callbacks done
    controller.syncStop();
    for (int i = 0; i < 5; i++) {
      participants[i].syncStop();
    }

    deleteCluster(clusterName);
    System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
  }

  @Test
  public void testDisablePartitionCustomIS() throws Exception {
    // Logger.getRootLogger().setLevel(Level.INFO);
    String className = TestHelper.getTestClassName();
    String methodName = TestHelper.getTestMethodName();
    String clusterName = className + "_" + methodName;
    final int n = 5;

    System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));

    MockParticipantManager[] participants = new MockParticipantManager[n];

    TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
        "localhost", // participant name prefix
        "TestDB", // resource name prefix
        1, // resources
        8, // partitions per resource
        n, // number of nodes
        3, // replicas
        "MasterSlave", true); // do rebalance

    // set ideal state to customized mode
    ZkBaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient);
    ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, baseAccessor);
    Builder keyBuilder = accessor.keyBuilder();
    IdealState idealState = accessor.getProperty(keyBuilder.idealStates("TestDB0"));
    idealState.setRebalanceMode(RebalanceMode.CUSTOMIZED);
    accessor.setProperty(keyBuilder.idealStates("TestDB0"), idealState);

    // start controller
    ClusterControllerManager controller =
        new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
    controller.syncStart();

    // start participants
    for (int i = 0; i < n; i++) {
      String instanceName = "localhost_" + (12918 + i);
      participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
      participants[i].syncStart();
    }

    BestPossibleExternalViewVerifier _clusterVerifier =
        new BestPossibleExternalViewVerifier.Builder(clusterName).setZkAddr(ZK_ADDR)
            .setZkClient(_gZkClient).build();
    Assert.assertTrue(_clusterVerifier.verifyByPolling());

    // disable [TestDB0_0, TestDB0_5] on localhost_12919
    String command = "--zkSvr " + ZK_ADDR + " --enablePartition false " + clusterName
        + " localhost_12919 TestDB0 TestDB0_0 TestDB0_5";
    ClusterSetup.processCommandLineArgs(command.split("\\s+"));

    Assert.assertTrue(_clusterVerifier.verifyByPolling());

    // make sure localhost_12918 is in OFFLINE state for [TestDB0_0, TestDB0_5]
    Map<String, Map<String, String>> expectStateMap = new HashMap<>();
    Map<String, String> expectInstanceStateMap = new HashMap<>();
    expectInstanceStateMap.put("localhost_12919", "OFFLINE");
    expectStateMap.put("TestDB0_0", expectInstanceStateMap);
    expectStateMap.put("TestDB0_5", expectInstanceStateMap);
    boolean result =
        ZkTestHelper.verifyState(_gZkClient, clusterName, "TestDB0", expectStateMap, "==");
    Assert.assertTrue(result,
        "localhost_12919" + " should be in OFFLINE for [TestDB0_0, TestDB0_5]");

    // re-enable localhost_12919 for [TestDB0_0, TestDB0_5]
    command = "--zkSvr " + ZK_ADDR + " --enablePartition true " + clusterName
        + " localhost_12919 TestDB0 TestDB0_0 TestDB0_5";
    ClusterSetup.processCommandLineArgs(command.split("\\s+"));
    result = ClusterStateVerifier
        .verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
    Assert.assertTrue(result);

    // make sure localhost_12919 is NOT in OFFLINE state for [TestDB0_0, TestDB0_5]
    result = ZkTestHelper.verifyState(_gZkClient, clusterName, "TestDB0", expectStateMap, "!=");
    Assert.assertTrue(result, "localhost_12919" + " should NOT be in OFFLINE");

    // clean up
    // wait for all zk callbacks done
    controller.syncStop();
    for (int i = 0; i < 5; i++) {
      participants[i].syncStop();
    }

    deleteCluster(clusterName);
    System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
  }

  @Test
  public void testDisablePartitionAutoIS() throws Exception {
    // Logger.getRootLogger().setLevel(Level.INFO);
    String className = TestHelper.getTestClassName();
    String methodName = TestHelper.getTestMethodName();
    String clusterName = className + "_" + methodName;
    final int n = 5;

    System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));

    MockParticipantManager[] participants = new MockParticipantManager[n];

    TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
        "localhost", // participant name prefix
        "TestDB", // resource name prefix
        1, // resources
        8, // partitions per resource
        n, // number of nodes
        3, // replicas
        "MasterSlave", true); // do rebalance

    // start controller
    ClusterControllerManager controller =
        new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
    controller.syncStart();

    // start participants
    for (int i = 0; i < n; i++) {
      String instanceName = "localhost_" + (12918 + i);

      participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
      participants[i].syncStart();
    }

    ZkHelixClusterVerifier _clusterVerifier =
        new BestPossibleExternalViewVerifier.Builder(clusterName).setZkAddr(ZK_ADDR).build();
    Assert.assertTrue(_clusterVerifier.verifyByPolling());

    // disable [TestDB0_0, TestDB0_5] on localhost_12919
    String command = "--zkSvr " + ZK_ADDR + " --enablePartition false " + clusterName
        + " localhost_12919 TestDB0 TestDB0_0 TestDB0_5";
    ClusterSetup.processCommandLineArgs(command.split("\\s+"));

    Assert.assertTrue(_clusterVerifier.verifyByPolling());

    // make sure localhost_12918 is in OFFLINE state for [TestDB0_0, TestDB0_5]
    Map<String, Map<String, String>> expectStateMap = new HashMap<>();
    Map<String, String> expectInstanceStateMap = new HashMap<>();
    expectInstanceStateMap.put("localhost_12919", "OFFLINE");
    expectStateMap.put("TestDB0_0", expectInstanceStateMap);
    expectStateMap.put("TestDB0_5", expectInstanceStateMap);
    boolean result =
        ZkTestHelper.verifyState(_gZkClient, clusterName, "TestDB0", expectStateMap, "==");
    Assert.assertTrue(result,
        "localhost_12919" + " should be in OFFLINE for [TestDB0_0, TestDB0_5]");

    // re-enable localhost_12919 for [TestDB0_0, TestDB0_5]
    command = "--zkSvr " + ZK_ADDR + " --enablePartition true " + clusterName
        + " localhost_12919 TestDB0 TestDB0_0 TestDB0_5";
    ClusterSetup.processCommandLineArgs(command.split("\\s+"));
    Assert.assertTrue(_clusterVerifier.verifyByPolling());

    // make sure localhost_12919 is NOT in OFFLINE state for [TestDB0_0, TestDB0_5]
    result = ZkTestHelper.verifyState(_gZkClient, clusterName, "TestDB0", expectStateMap, "!=");
    Assert.assertTrue(result, "localhost_12919" + " should NOT be in OFFLINE");

    // clean up
    // wait for all zk callbacks done
    controller.syncStop();
    for (int i = 0; i < 5; i++) {
      participants[i].syncStop();
    }

    deleteCluster(clusterName);
    System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
  }
}


text:
@interface LoLStaticChampion : LoLBaseDTO

@property (nonatomic, strong) NSArray *allytips; // List[string]
@property (nonatomic, strong) NSString *blurb;
@property (nonatomic, strong) NSArray *enemytips; // List[string]
@property (nonatomic, assign) NSInteger id;
@property (nonatomic, strong) LoLStaticImage *image;
@property (nonatomic, strong) LoLStaticInfo *info;
@property (nonatomic, strong) NSString *key;
@property (nonatomic, strong) NSString *lore;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *partype;
@property (nonatomic, strong) LoLStaticPassive *passive;
@property (nonatomic, strong) NSArray *recommended; // List[RecommendedDto]
@property (nonatomic, strong) NSArray *skins; // List[SkinDto]
@property (nonatomic, strong) NSArray *spells; // List[ChampionSpellDto]
@property (nonatomic, strong) LoLStaticStats *stats; // StatsDto
@property (nonatomic, strong) NSArray *tags; // List[string]
@property (nonatomic, strong) NSString *title;

@end


text:
from burp import IBurpExtender
from burp import IHttpListener
from burp import IProxyListener
import re
import sys
import os

#This is where you put the name of the token that is being used in the application you are testing. It searches for __VIEWSTATE by default. The
#extension will search for this token in every request and tell you which requests do NOT have a token, so you can manually explore.
anticsrf_token_name='securityRequestParameter'

excluded_file_extensions=['.jpg','.gif','.bmp','.png','.css','.js','.htc','.jpeg','.ico','.svg']
urls_in_scope=['blah.test.com']

#Adding directory to the path where Python searches for modules
module_folder = os.path.dirname('/home/arvind/Documents/Me/My_Projects/Git/WebAppsec/BurpExtensions/modules')
sys.path.insert(0, module_folder)
import webcommon

class BurpExtender(IBurpExtender, IHttpListener, IProxyListener):
  def registerExtenderCallbacks(self,callbacks):
    # Get a reference to the Burp helpers object
    self._helpers = callbacks.getHelpers()

    # set our extension name
    callbacks.setExtensionName("CSRF Token Detector")

    # register ourselves as an HTTP listener
    callbacks.registerHttpListener(self)

    # register ourselves as a Proxy listener
    callbacks.registerProxyListener(self)

  def processProxyMessage(self,messageIsRequest,message):
    request_url = BurpExtender.detect_csrf_token(self,messageIsRequest,message)
    if request_url:
      print request_url

  def detect_csrf_token(self,messageIsRequest,message):
    #Only process requests as that's where the Token should be
    request_byte_array=message.getMessageInfo().getRequest()
    if messageIsRequest:
      t1=[]
      t2=[]
      flag=0

      requestInfo = self._helpers.analyzeRequest(request_byte_array)

      #Extract hostname from header
      hostname=webcommon.get_host_header_from_request(self,requestInfo)

      #Check if the URL is in scope. This is to eliminate stray traffic.
      if hostname and hostname[1] in urls_in_scope:
        csrf_token_value=self._helpers.getRequestParameter(request_byte_array,anticsrf_token_name)
        request_string=self._helpers.bytesToString(request_byte_array)
        urlpath=request_string.split("\n")
        tmp2=urlpath[0].split(' ')

      #If there's no token, check if it's an image, js or css file. In this case, a token isn't needed
        if not csrf_token_value:
          for tmp3 in excluded_file_extensions:
            #Search for file extension. If you want a more complex regex..remember to compile the regex. DO.NOT.FORGET :)
            tmp4=re.search(tmp3,tmp2[-2])
            if tmp4:
              flag=1

          #Not to be excluded and the request doesn't contain a token
          if flag != 1:
            return urlpath[0]


text:
<?php
class Kwc_Box_SwitchLanguage_Plugin extends Kwf_Component_Plugin_Abstract
    implements Kwf_Component_Plugin_Interface_ViewAfterChildRender
{
    public function processOutput($output)
    {
        if (isset($_SERVER['QUERY_STRING'])) {
            $output = preg_replace('/href="(.*)"/U', 'href="$1?' . $_SERVER['QUERY_STRING'] . '"', $output);
        }
        return $output;
    }
}


text: export { Group as default } from "../../";


text:
<?php
/**
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 */
namespace Piwik\Plugins\VisitorInterest\Reports;

abstract class Base extends \Piwik\Plugin\Report
{
    protected function init()
    {
        $this->category = 'General_Visitors';
    }

}


text:
(async function() {
  TestRunner.addResult(`Verify that dirty network uiSourceCodes are bound to filesystem.\n`);
  await TestRunner.loadTestModule('bindings_test_runner');
  BindingsTestRunner.overrideNetworkModificationTime(
      {'http://127.0.0.1:8000/devtools/persistence/resources/foo.js': null});
  TestRunner.addScriptTag('resources/foo.js');
  var networkUISourceCode = await TestRunner.waitForUISourceCode('foo.js', Workspace.projectTypes.Network);
  var { content } = await networkUISourceCode.requestContent();
  content = content.replace(/foo/g, 'bar');
  networkUISourceCode.setWorkingCopy(content);

  var fs = new BindingsTestRunner.TestFileSystem('/var/www');
  BindingsTestRunner.addFooJSFile(fs);
  fs.reportCreated(function() {});

  var binding = await BindingsTestRunner.waitForBinding('foo.js');
  TestRunner.addResult('Binding created: ' + binding);
  TestRunner.addResult('FileSystem is dirty: ' + binding.fileSystem.isDirty());
  TestRunner.addResult('FileSystem working copy: ');
  TestRunner.addResult(binding.fileSystem.workingCopy());

  TestRunner.completeTest();
})();


text:
/* ==========================================================
File:        CustomEditorMouseMotionListener.java
Description: Logs time from mouse motion events.
Maintainer:  WakaTime <support@wakatime.com>
License:     BSD, see LICENSE for more details.
Website:     https://wakatime.com/
===========================================================*/

package com.wakatime.intellij.plugin;

import com.intellij.openapi.editor.event.VisibleAreaEvent;
import com.intellij.openapi.editor.event.VisibleAreaListener;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;

public class CustomVisibleAreaListener implements VisibleAreaListener {
    @Override
    public void visibleAreaChanged(VisibleAreaEvent visibleAreaEvent) {
        FileDocumentManager instance = FileDocumentManager.getInstance();
        VirtualFile file = instance.getFile(visibleAreaEvent.getEditor().getDocument());
        Project project = visibleAreaEvent.getEditor().getProject();
        WakaTime.appendHeartbeat(file, project, false);
    }
}


text:
<?php

namespace Magento\Catalog\Test\Unit\Block\Product;

class PriceTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Catalog\Block\Product\Price
     */
    protected $block;

    protected function setUp()
    {
        $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
        $this->block = $objectManager->getObject('Magento\Catalog\Block\Product\Price');
    }

    protected function tearDown()
    {
        $this->block = null;
    }

    public function testGetIdentities()
    {
        $productTags = ['catalog_product_1'];
        $product = $this->getMock('Magento\Catalog\Model\Product', [], [], '', false);
        $product->expects($this->once())->method('getIdentities')->will($this->returnValue($productTags));
        $this->block->setProduct($product);
        $this->assertEquals($productTags, $this->block->getIdentities());
    }
}


text:
require File.join(File.dirname(__FILE__),"..","..","lib","babel_bridge")

class TuringParser < BabelBridge::Parser
  ignore_whitespace

  def store
    @store||=[]
  end

  rule :statements, many(:statement,";"), match?(";") do
    def evaluate
      ret = nil
      statement.each do |s|
        ret = s.evaluate
      end
      ret
    end
  end

  rule :statement, "if", :statement, "then", :statements, :else_clause?, "end" do
    def evaluate
      if statement.evaluate
        statements.evaluate
      else
        else_clause.evaluate if else_clause
      end
    end
  end
  rule :else_clause, "else", :statements

  rule :statement, "while", :statement, "do", :statements, "end" do
    def evaluate
      while statement.evaluate
        statements.evaluate
      end
    end
  end

  binary_operators_rule :statement, :operand, [[:/, :*], [:+, :-], [:<, :<=, :>, :>=, :==]] do
    def evaluate
      case operator
      when :<, :<=, :>, :>=, :==
        (left.evaluate.send operator, right.evaluate) ? 1 : nil
      else
        left.evaluate.send operator, right.evaluate
      end
    end
  end

  rule :operand, "(", :statement, ")"

  rule :operand, "[", :statement, "]", "=", :statement do
    def evaluate
      parser.store[statement[0].evaluate] = statement[1].evaluate
    end
  end

  rule :operand, "[", :statement, "]" do
    def evaluate
      parser.store[statement.evaluate]
    end
  end

  rule :operand, /[-]?[0-9]+/ do
    def evaluate
      to_s.to_i
    end
  end
end

BabelBridge::Shell.new(TuringParser.new).start