text:
package io.realm.internal.objectstore;

import org.bson.types.Decimal128;
import org.bson.types.ObjectId;

import java.io.Closeable;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.annotation.Nullable;

import io.realm.ImportFlag;
import io.realm.RealmAny;
import io.realm.RealmAnyNativeFunctionsImpl;
import io.realm.MutableRealmInteger;
import io.realm.RealmDictionary;
import io.realm.RealmList;
import io.realm.RealmModel;
import io.realm.RealmSet;
import io.realm.internal.RealmAnyNativeFunctions;
import io.realm.internal.NativeContext;
import io.realm.internal.OsSharedRealm;
import io.realm.internal.RealmObjectProxy;
import io.realm.internal.Table;
import io.realm.internal.UncheckedRow;

/**
 * This class is a wrapper around building up object data for calling `Object::create()`
 *

 * Fill the object data by calling the various `addX()` methods, then create a new Object or update
 * an existing one by calling {@link #createNewObject()}, {@link #updateExistingTopLevelObject()} or
 * {@link #updateExistingEmbeddedObject(RealmObjectProxy)}.
 *

 * This class assumes it is only being used from within a write transaction. Using it outside one
 * will result in undefined behaviour.
 *

 * The native
 * resources are created in the constructor of this class and destroyed when calling either of the
 * above two methods.
 *

 *
Design thoughts

 *

 * Ideally we would have sent all properties across in one JNI call, but the only way to do that would
 * have been using two `Object[]` arrays which would have resulted in a ton of JNI calls back
 * again for resolving the primitive values of boxed types (since JNI do not know about boxed
 * primitives).
 *

 * The upside of making a JNI call for each property is that we do minimal allocations on the Java
 * side. Also each method call is fairly lightweight as no checks are performed compared to using
 * Proxy setters and {@link io.realm.internal.UncheckedRow}. The only downside is the current need for
 * sending the key as well. Hopefully we can change that to schema indices at some point.
 *

 * There is quite a few variants we can attempt to optimize this, but at this point we lack data
 * that can guide any architectural design and the only way to really find out is to build out each
 * solution and benchmark it.
 */
public class OsObjectBuilder implements Closeable {

    private final Table table;
    private final long sharedRealmPtr;
    private final long builderPtr;
    private final long tablePtr;
    private final NativeContext context;

    // ------------------------------------------
    // List handlers
    // ------------------------------------------

    private static ItemCallback<? extends RealmModel> objectItemCallback = new ItemCallback<RealmModel>() {
        @Override
        public void handleItem(long containerPtr, RealmModel item) {
            RealmObjectProxy proxyItem = (RealmObjectProxy) item;
            nativeAddIntegerListItem(containerPtr, ((UncheckedRow) proxyItem.realmGet$proxyState().getRow$realm()).getNativePtr());
        }
    };

    private static ItemCallback<String> stringItemCallback = new ItemCallback<String>() {
        @Override
        public void handleItem(long containerPtr, String item) {
            nativeAddStringListItem(containerPtr, item);
        }
    };

    private static ItemCallback<Byte> byteItemCallback = new ItemCallback<Byte>() {
        @Override
        public void handleItem(long containerPtr, Byte item) {
            nativeAddIntegerListItem(containerPtr, item.longValue());
        }
    };

    private static ItemCallback<Short> shortItemCallback = new ItemCallback<Short>() {
        @Override
        public void handleItem(long containerPtr, Short item) {
            nativeAddIntegerListItem(containerPtr, item);
        }
    };

    private static ItemCallback<Integer> integerItemCallback = new ItemCallback<Integer>() {
        @Override
        public void handleItem(long containerPtr, Integer item) {
            nativeAddIntegerListItem(containerPtr, item);
        }
    };

    private static ItemCallback<Long> longItemCallback = new ItemCallback<Long>() {
        @Override
        public void handleItem(long containerPtr, Long item) {
            nativeAddIntegerListItem(containerPtr, item);
        }
    };

    private static ItemCallback<Boolean> booleanItemCallback = new ItemCallback<Boolean>() {
        @Override
        public void handleItem(long containerPtr, Boolean item) {
            nativeAddBooleanListItem(containerPtr, item);
        }
    };

    private static ItemCallback<Float> floatItemCallback = new ItemCallback<Float>() {
        @Override
        public void handleItem(long containerPtr, Float item) {
            nativeAddFloatListItem(containerPtr, item);
        }
    };

    private static ItemCallback<Double> doubleItemCallback = new ItemCallback<Double>() {
        @Override
        public void handleItem(long containerPtr, Double item) {
            nativeAddDoubleListItem(containerPtr, item);
        }
    };

    private static ItemCallback<Date> dateItemCallback = new ItemCallback<Date>() {
        @Override
        public void handleItem(long containerPtr, Date item) {
            nativeAddDateListItem(containerPtr, item.getTime());
        }
    };

    private static ItemCallback<byte[]> byteArrayItemCallback = new ItemCallback<byte[]>() {
        @Override
        public void handleItem(long containerPtr, byte[] item) {
            nativeAddByteArrayListItem(containerPtr, item);
        }
    };

    private static ItemCallback<MutableRealmInteger> mutableRealmIntegerItemCallback = new ItemCallback<MutableRealmInteger>() {
        @Override
        public void handleItem(long containerPtr, MutableRealmInteger item) {
            Long value = item.get();
            if (value == null) {
                nativeAddNullListItem(containerPtr);
            } else {
                nativeAddIntegerListItem(containerPtr, value);
            }
        }
    };

    private static ItemCallback<Decimal128> decimal128ItemCallback = new ItemCallback<Decimal128>() {
        @Override
        public void handleItem(long containerPtr, Decimal128 item) {
            nativeAddDecimal128ListItem(containerPtr, item.getLow(), item.getHigh());
        }
    };

    private static ItemCallback<ObjectId> objectIdItemCallback = new ItemCallback<ObjectId>() {
        @Override
        public void handleItem(long containerPtr, ObjectId item) {
            nativeAddObjectIdListItem(containerPtr, item.toString());
        }
    };

    private static ItemCallback<UUID> uuidItemCallback = new ItemCallback<UUID>() {
        @Override
        public void handleItem(long containerPtr, UUID item) {
            nativeAddUUIDListItem(containerPtr, item.toString());
        }
    };

    // ------------------------------------------
    // Map/Dictionary handlers
    // ------------------------------------------

    private static ItemCallback<Map.Entry<String, Boolean>> booleanMapItemCallback = new ItemCallback<Map.Entry<String, Boolean>>() {
        @Override
        public void handleItem(long containerPtr, Map.Entry<String, Boolean> item) {
            nativeAddBooleanDictionaryEntry(containerPtr, item.getKey(), item.getValue());
        }
    };

    private static ItemCallback<Map.Entry<String, String>> stringMapItemCallback = new ItemCallback<Map.Entry<String, String>>() {
        @Override
        public void handleItem(long containerPtr, Map.Entry<String, String> item) {
            nativeAddStringDictionaryEntry(containerPtr, item.getKey(), item.getValue());
        }
    };

    private static ItemCallback<Map.Entry<String, Integer>> integerMapItemCallback = new ItemCallback<Map.Entry<String, Integer>>() {
        @Override
        public void handleItem(long containerPtr, Map.Entry<String, Integer> item) {
            nativeAddIntegerDictionaryEntry(containerPtr, item.getKey(), item.getValue());
        }
    };

    private static ItemCallback<Map.Entry<String, Float>> floatMapItemCallback = new ItemCallback<Map.Entry<String, Float>>() {
        @Override
        public void handleItem(long containerPtr, Map.Entry<String, Float> item) {
            nativeAddFloatDictionaryEntry(containerPtr, item.getKey(), item.getValue());
        }
    };

    private static ItemCallback<Map.Entry<String, Long>> longMapItemCallback = new ItemCallback<Map.Entry<String, Long>>() {
        @Override
        public void handleItem(long containerPtr, Map.Entry<String, Long> item) {
            nativeAddIntegerDictionaryEntry(containerPtr, item.getKey(), item.getValue());
        }
    };

    private static ItemCallback<Map.Entry<String, Short>> shortMapItemCallback = new ItemCallback<Map.Entry<String, Short>>() {
        @Override
        public void handleItem(long containerPtr, Map.Entry<String, Short> item) {
            nativeAddIntegerDictionaryEntry(containerPtr, item.getKey(), item.getValue());
        }
    };

    private static ItemCallback<Map.Entry<String, Byte>> byteMapItemCallback = new ItemCallback<Map.Entry<String, Byte>>() {
        @Override
        public void handleItem(long containerPtr, Map.Entry<String, Byte> item) {
            nativeAddIntegerDictionaryEntry(containerPtr, item.getKey(), item.getValue());
        }
    };

    private static ItemCallback<Map.Entry<String, Double>> doubleMapItemCallback = new ItemCallback<Map.Entry<String, Double>>() {
        @Override
        public void handleItem(long containerPtr, Map.Entry<String, Double> item) {
            nativeAddDoubleDictionaryEntry(containerPtr, item.getKey(), item.getValue());
        }
    };

    private static ItemCallback<Map.Entry<String, byte[]>> binaryMapItemCallback = new ItemCallback<Map.Entry<String, byte[]>>() {
        @Override
        public void handleItem(long containerPtr, Map.Entry<String, byte[]> item) {
            nativeAddBinaryDictionaryEntry(containerPtr, item.getKey(), item.getValue());
        }
    };

    private static ItemCallback<Map.Entry<String, Date>> dateMapItemCallback = new ItemCallback<Map.Entry<String, Date>>() {
        @Override
        public void handleItem(long containerPtr, Map.Entry<String, Date> item) {
            nativeAddDateDictionaryEntry(containerPtr, item.getKey(), item.getValue().getTime());
        }
    };

    private static ItemCallback<Map.Entry<String, Decimal128>> decimal128MapItemCallback = new ItemCallback<Map.Entry<String, Decimal128>>() {
        @Override
        public void handleItem(long containerPtr, Map.Entry<String, Decimal128> item) {
            nativeAddDecimal128DictionaryEntry(containerPtr, item.getKey(), item.getValue().getHigh(), item.getValue().getLow());
        }
    };

    private static ItemCallback<Map.Entry<String, ObjectId>> objectIdMapItemCallback = new ItemCallback<Map.Entry<String, ObjectId>>() {
        @Override
        public void handleItem(long containerPtr, Map.Entry<String, ObjectId> item) {
            nativeAddObjectIdDictionaryEntry(containerPtr, item.getKey(), item.getValue().toString());
        }
    };

    private static ItemCallback<Map.Entry<String, UUID>> uuidMapItemCallback = new ItemCallback<Map.Entry<String, UUID>>() {
        @Override
        public void handleItem(long containerPtr, Map.Entry<String, UUID> item) {
            nativeAddUUIDDictionaryEntry(containerPtr, item.getKey(), item.getValue().toString());
        }
    };

    private static ItemCallback<Map.Entry<String, RealmAny>> realmAnyMapItemCallback = new ItemCallback<Map.Entry<String, RealmAny>>() {
        private final RealmAnyNativeFunctions realmAnyNativeFunctions = new RealmAnyNativeFunctionsImpl();

        @Override
        public void handleItem(long containerPtr, Map.Entry<String, RealmAny> item) {
            realmAnyNativeFunctions.handleItem(containerPtr, item);
        }
    };

    private static ItemCallback<RealmAny> realmAnyItemCallback = new ItemCallback<RealmAny>() {
        private final RealmAnyNativeFunctions realmAnyNativeFunctions = new RealmAnyNativeFunctionsImpl();

        @Override
        public void handleItem(long listPtr, RealmAny realmAny) {
            realmAnyNativeFunctions.handleItem(listPtr, realmAny);
        }
    };

    // If true, fields will not be updated if the same value would be written to it.
    private final boolean ignoreFieldsWithSameValue;

    public OsObjectBuilder(Table table, Set<ImportFlag> flags) {
        OsSharedRealm sharedRealm = table.getSharedRealm();
        this.sharedRealmPtr = sharedRealm.getNativePtr();
        this.table = table;
        this.table.getColumnNames();
        this.tablePtr = table.getNativePtr();
        this.builderPtr = nativeCreateBuilder();
        this.context = sharedRealm.context;
        this.ignoreFieldsWithSameValue = flags.contains(ImportFlag.CHECK_SAME_VALUES_BEFORE_SET);
    }

    public void addInteger(long columnKey, @Nullable Byte val) {
        if (val == null) {
            nativeAddNull(builderPtr, columnKey);
        } else {
            nativeAddInteger(builderPtr, columnKey, val);
        }
    }

    public void addInteger(long columnKey, @Nullable Short val) {
        if (val == null) {
            nativeAddNull(builderPtr, columnKey);
        } else {
            nativeAddInteger(builderPtr, columnKey, val);
        }
    }

    public void addInteger(long columnKey, @Nullable Integer val) {
        if (val == null) {
            nativeAddNull(builderPtr, columnKey);
        } else {
            nativeAddInteger(builderPtr, columnKey, val);
        }
    }

    public void addInteger(long columnKey, @Nullable Long val) {
        if (val == null) {
            nativeAddNull(builderPtr, columnKey);
        } else {
            nativeAddInteger(builderPtr, columnKey, val);
        }
    }

    public void addMutableRealmInteger(long columnKey, @Nullable MutableRealmInteger val) {
        if (val == null || val.get() == null) {
            nativeAddNull(builderPtr, columnKey);
        } else {
            nativeAddInteger(builderPtr, columnKey, val.get());
        }
    }

    public void addRealmAny(long columnKey, long realmAnyPtr) {
        nativeAddRealmAny(builderPtr, columnKey, realmAnyPtr);
    }

    public void addString(long columnKey, @Nullable String val) {
        if (val == null) {
            nativeAddNull(builderPtr, columnKey);
        } else {
            nativeAddString(builderPtr, columnKey, val);
        }
    }

    public void addFloat(long columnKey, @Nullable Float val) {
        if (val == null) {
            nativeAddNull(builderPtr, columnKey);
        } else {
            nativeAddFloat(builderPtr, columnKey, val);
        }
    }

    public void addDouble(long columnKey, @Nullable Double val) {
        if (val == null) {
            nativeAddNull(builderPtr, columnKey);
        } else {
            nativeAddDouble(builderPtr, columnKey, val);
        }
    }

    public void addBoolean(long columnKey, @Nullable Boolean val) {
        if (val == null) {
            nativeAddNull(builderPtr, columnKey);
        } else {
            nativeAddBoolean(builderPtr, columnKey, val);
        }
    }

    public void addDate(long columnKey, @Nullable Date val) {
        if (val == null) {
            nativeAddNull(builderPtr, columnKey);
        } else {
            nativeAddDate(builderPtr, columnKey, val.getTime());
        }
    }

    public void addByteArray(long columnKey, @Nullable byte[] val) {
        if (val == null) {
            nativeAddNull(builderPtr, columnKey);
        } else {
            nativeAddByteArray(builderPtr, columnKey, val);
        }
    }

    public void addDecimal128(long columnKey, @Nullable Decimal128 val) {
        if (val == null) {
            nativeAddNull(builderPtr, columnKey);
        } else {
            nativeAddDecimal128(builderPtr, columnKey, val.getLow(), val.getHigh());
        }
    }

    public void addObjectId(long columnKey, @Nullable ObjectId val) {
        if (val == null) {
            nativeAddNull(builderPtr, columnKey);
        } else {
            nativeAddObjectId(builderPtr, columnKey, val.toString());
        }
    }

    public void addUUID(long columnKey, @Nullable UUID val) {
        if (val == null) {
            nativeAddNull(builderPtr, columnKey);
        } else {
            nativeAddUUID(builderPtr, columnKey, val.toString());
        }
    }

    public void addNull(long columnKey) {
        nativeAddNull(builderPtr, columnKey);
    }

    public void addObject(long columnKey, @Nullable RealmModel val) {
        if (val == null) {
            nativeAddNull(builderPtr, columnKey);
        } else {
            RealmObjectProxy proxy = (RealmObjectProxy) val;
            UncheckedRow row = (UncheckedRow) proxy.realmGet$proxyState().getRow$realm();
            nativeAddObject(builderPtr, columnKey, row.getNativePtr());
        }
    }

    private <T> void addListItem(long builderPtr, long columnKey, @Nullable List<T> list, ItemCallback<T> itemCallback) {
        if (list != null) {
            long listPtr = nativeStartList(list.size());
            boolean isNullable = (columnKey == 0) || table.isColumnNullable(columnKey);
            for (int i = 0; i < list.size(); i++) {
                T item = list.get(i);
                if (item == null) {
                    if (!isNullable) {
                        throw new IllegalArgumentException("This 'RealmList' is not nullable. A non-null value is expected.");
                    }
                    nativeAddNullListItem(listPtr);
                } else {
                    itemCallback.handleItem(listPtr, item);
                }
            }
            nativeStopList(builderPtr, columnKey, listPtr);
        } else {
            addEmptyList(columnKey);
        }
    }

    public <T extends RealmModel> void addObjectList(long columnKey, @Nullable RealmList<T> list) {
        // Null objects references are not allowed. So we can optimize the JNI boundary by
        // sending all object references in one long[] array.
        if (list != null) {
            long[] rowPointers = new long[list.size()];
            for (int i = 0; i < list.size(); i++) {
                RealmObjectProxy item = (RealmObjectProxy) list.get(i);
                if (item == null) {
                    throw new IllegalArgumentException("Null values are not allowed in RealmLists containing Realm models");
                } else {
                    rowPointers[i] = ((UncheckedRow) item.realmGet$proxyState().getRow$realm()).getNativePtr();
                }
            }
            nativeAddObjectList(builderPtr, columnKey, rowPointers);
        } else {
            nativeAddObjectList(builderPtr, columnKey, new long[0]);
        }
    }

    public void addStringList(long columnKey, RealmList<String> list) {
        addListItem(builderPtr, columnKey, list, stringItemCallback);
    }

    public void addByteList(long columnKey, RealmList<Byte> list) {
        addListItem(builderPtr, columnKey, list, byteItemCallback);
    }

    public void addShortList(long columnKey, RealmList<Short> list) {
        addListItem(builderPtr, columnKey, list, shortItemCallback);
    }

    public void addIntegerList(long columnKey, RealmList<Integer> list) {
        addListItem(builderPtr, columnKey, list, integerItemCallback);
    }

    public void addLongList(long columnKey, RealmList<Long> list) {
        addListItem(builderPtr, columnKey, list, longItemCallback);
    }

    public void addBooleanList(long columnKey, RealmList<Boolean> list) {
        addListItem(builderPtr, columnKey, list, booleanItemCallback);
    }

    public void addFloatList(long columnKey, RealmList<Float> list) {
        addListItem(builderPtr, columnKey, list, floatItemCallback);
    }

    public void addDoubleList(long columnKey, RealmList<Double> list) {
        addListItem(builderPtr, columnKey, list, doubleItemCallback);
    }

    public void addDateList(long columnKey, RealmList<Date> list) {
        addListItem(builderPtr, columnKey, list, dateItemCallback);
    }

    public void addByteArrayList(long columnKey, RealmList<byte[]> list) {
        addListItem(builderPtr, columnKey, list, byteArrayItemCallback);
    }

    public void addMutableRealmIntegerList(long columnKey, RealmList<MutableRealmInteger> list) {
        addListItem(builderPtr, columnKey, list, mutableRealmIntegerItemCallback);
    }

    public void addDecimal128List(long columnKey, RealmList<Decimal128> list) {
        addListItem(builderPtr, columnKey, list, decimal128ItemCallback);
    }

    public void addObjectIdList(long columnKey, RealmList<ObjectId> list) {
        addListItem(builderPtr, columnKey, list, objectIdItemCallback);
    }

    public void addUUIDList(long columnKey, RealmList<UUID> list) {
        addListItem(builderPtr, columnKey, list, uuidItemCallback);
    }

    public void addRealmAnyList(long columnKey, RealmList<RealmAny> list) {
        addListItem(builderPtr, columnKey, list, realmAnyItemCallback);
    }

    private void addEmptyList(long columnKey) {
        long listPtr = nativeStartList(0);
        nativeStopList(builderPtr, columnKey, listPtr);
    }

    public void addBooleanValueDictionary(long columnKey, RealmDictionary<Boolean> dictionary) {
        addDictionaryItem(builderPtr, columnKey, dictionary, booleanMapItemCallback);
    }

    public void addIntegerValueDictionary(long columnKey, RealmDictionary<Integer> dictionary) {
        addDictionaryItem(builderPtr, columnKey, dictionary, integerMapItemCallback);
    }

    public void addFloatValueDictionary(long columnKey, RealmDictionary<Float> dictionary) {
        addDictionaryItem(builderPtr, columnKey, dictionary, floatMapItemCallback);
    }

    public void addLongValueDictionary(long columnKey, RealmDictionary<Long> dictionary) {
        addDictionaryItem(builderPtr, columnKey, dictionary, longMapItemCallback);
    }

    public void addShortValueDictionary(long columnKey, RealmDictionary<Short> dictionary) {
        addDictionaryItem(builderPtr, columnKey, dictionary, shortMapItemCallback);
    }

    public void addByteValueDictionary(long columnKey, RealmDictionary<Byte> dictionary) {
        addDictionaryItem(builderPtr, columnKey, dictionary, byteMapItemCallback);
    }

    public void addDoubleValueDictionary(long columnKey, RealmDictionary<Double> dictionary) {
        addDictionaryItem(builderPtr, columnKey, dictionary, doubleMapItemCallback);
    }

    public void addStringValueDictionary(long columnKey, RealmDictionary<String> dictionary) {
        addDictionaryItem(builderPtr, columnKey, dictionary, stringMapItemCallback);
    }

    public void addDateValueDictionary(long columnKey, RealmDictionary<Date> dictionary) {
        addDictionaryItem(builderPtr, columnKey, dictionary, dateMapItemCallback);
    }

    public void addDecimal128ValueDictionary(long columnKey, RealmDictionary<Decimal128> dictionary) {
        addDictionaryItem(builderPtr, columnKey, dictionary, decimal128MapItemCallback);
    }

    public void addBinaryValueDictionary(long columnKey, RealmDictionary<byte[]> dictionary) {
        addDictionaryItem(builderPtr, columnKey, dictionary, binaryMapItemCallback);
    }

    public void addObjectIdValueDictionary(long columnKey, RealmDictionary<ObjectId> dictionary) {
        addDictionaryItem(builderPtr, columnKey, dictionary, objectIdMapItemCallback);
    }

    public void addUUIDValueDictionary(long columnKey, RealmDictionary<UUID> dictionary) {
        addDictionaryItem(builderPtr, columnKey, dictionary, uuidMapItemCallback);
    }

    public void addRealmAnyValueDictionary(long columnKey, RealmDictionary<RealmAny> dictionary) {
        addDictionaryItem(builderPtr, columnKey, dictionary, realmAnyMapItemCallback);
    }

    public <T extends RealmModel> void addObjectDictionary(long columnKey, @Nullable RealmDictionary<T> dictionary) {
        if (dictionary != null) {
            long dictionaryPtr = nativeStartDictionary();
            for (Map.Entry<String, T> entry : dictionary.entrySet()) {
                if (entry.getValue() == null) {
                    nativeAddNullDictionaryEntry(dictionaryPtr, entry.getKey());
                } else {
                    RealmObjectProxy realmObjectProxy = (RealmObjectProxy) entry.getValue();
                    long objectPtr = ((UncheckedRow) realmObjectProxy.realmGet$proxyState().getRow$realm()).getNativePtr();
                    nativeAddObjectDictionaryEntry(dictionaryPtr, entry.getKey(), objectPtr);
                }
            }
            nativeStopDictionary(builderPtr, columnKey, dictionaryPtr);
        } else {
            addEmptyDictionary(columnKey);
        }
    }

    private <T> void addDictionaryItem(
            long builderPtr,
            long columnKey,
            @Nullable RealmDictionary<T> dictionary,
            ItemCallback<Map.Entry<String, T>> mapItemCallback
    ) {
        if (dictionary != null) {
            long dictionaryPtr = nativeStartDictionary();
            for (Map.Entry<String, T> entry : dictionary.entrySet()) {
                if (entry.getValue() == null) {
                    nativeAddNullDictionaryEntry(dictionaryPtr, entry.getKey());
                } else {
                    mapItemCallback.handleItem(dictionaryPtr, entry);
                }
            }
            nativeStopDictionary(builderPtr, columnKey, dictionaryPtr);
        } else {
            addEmptyDictionary(columnKey);
        }
    }

    private void addEmptyDictionary(long columnKey) {
        nativeStopDictionary(builderPtr, columnKey, nativeStartDictionary());
    }

    // -----------------------------------------------
    // SET
    // -----------------------------------------------

    private static ItemCallback<String> stringSetItemCallback = new ItemCallback<String>() {
        @Override
        public void handleItem(long containerPtr, String item) {
            nativeAddStringSetItem(containerPtr, item);
        }
    };

    private static ItemCallback<Boolean> booleanSetItemCallback = new ItemCallback<Boolean>() {
        @Override
        public void handleItem(long containerPtr, Boolean item) {
            nativeAddBooleanSetItem(containerPtr, item);
        }
    };

    private static ItemCallback<Integer> integerSetItemCallback = new ItemCallback<Integer>() {
        @Override
        public void handleItem(long containerPtr, Integer item) {
            nativeAddIntegerSetItem(containerPtr, item);
        }
    };

    private static ItemCallback<Long> longSetItemCallback = new ItemCallback<Long>() {
        @Override
        public void handleItem(long containerPtr, Long item) {
            nativeAddIntegerSetItem(containerPtr, item);
        }
    };

    private static ItemCallback<Short> shortSetItemCallback = new ItemCallback<Short>() {
        @Override
        public void handleItem(long containerPtr, Short item) {
            nativeAddIntegerSetItem(containerPtr, item);
        }
    };

    private static ItemCallback<Byte> byteSetItemCallback = new ItemCallback<Byte>() {
        @Override
        public void handleItem(long containerPtr, Byte item) {
            nativeAddIntegerSetItem(containerPtr, item);
        }
    };

    private static ItemCallback<Float> floatSetItemCallback = new ItemCallback<Float>() {
        @Override
        public void handleItem(long containerPtr, Float item) {
            nativeAddFloatSetItem(containerPtr, item);
        }
    };

    private static ItemCallback<Double> doubleSetItemCallback = new ItemCallback<Double>() {
        @Override
        public void handleItem(long containerPtr, Double item) {
            nativeAddDoubleSetItem(containerPtr, item);
        }
    };

    private static ItemCallback<byte[]> binarySetItemCallback = new ItemCallback<byte[]>() {
        @Override
        public void handleItem(long containerPtr, byte[] item) {
            nativeAddByteArraySetItem(containerPtr, item);
        }
    };

    private static ItemCallback<Date> dateSetItemCallback = new ItemCallback<Date>() {
        @Override
        public void handleItem(long containerPtr, Date item) {
            nativeAddDateSetItem(containerPtr, item.getTime());
        }
    };

    private static ItemCallback<Decimal128> decimal128SetItemCallback = new ItemCallback<Decimal128>() {
        @Override
        public void handleItem(long containerPtr, Decimal128 item) {
            nativeAddDecimal128SetItem(containerPtr, item.getLow(), item.getHigh());
        }
    };

    private static ItemCallback<ObjectId> objectIdSetItemCallback = new ItemCallback<ObjectId>() {
        @Override
        public void handleItem(long containerPtr, ObjectId item) {
            nativeAddObjectIdSetItem(containerPtr, item.toString());
        }
    };

    private static ItemCallback<UUID> uuidSetItemCallback = new ItemCallback<UUID>() {
        @Override
        public void handleItem(long containerPtr, UUID item) {
            nativeAddUUIDSetItem(containerPtr, item.toString());
        }
    };

    private static ItemCallback<RealmAny> realmAnySetItemCallback = new ItemCallback<RealmAny>() {
        private final RealmAnyNativeFunctions realmAnyNativeFunctions = new RealmAnyNativeFunctionsImpl();

        @Override
        public void handleItem(long containerPtr, RealmAny item) {
            realmAnyNativeFunctions.handleItem(containerPtr, item);
        }
    };

    private static native long nativeStartSet(long size);

    private static native void nativeStopSet(long builderPtr, long columnKey, long setPtr);

    private static native void nativeAddNullSetItem(long setPtr);

    private static native void nativeAddStringSetItem(long setPtr, String val);

    private static native void nativeAddBooleanSetItem(long setPtr, boolean val);

    private static native void nativeAddIntegerSetItem(long setPtr, long val);

    private static native void nativeAddFloatSetItem(long setPtr, float val);

    private static native void nativeAddDoubleSetItem(long setPtr, double val);

    private static native void nativeAddByteArraySetItem(long setPtr, byte[] val);

    private static native void nativeAddDateSetItem(long setPtr, long val);

    private static native void nativeAddDecimal128SetItem(long setPtr, long lowVal, long highVal);

    private static native void nativeAddObjectIdSetItem(long setPtr, String val);

    private static native void nativeAddUUIDSetItem(long setPtr, String val);

    private void addEmptySet(long columnKey) {
        nativeStopSet(builderPtr, columnKey, nativeStartSet(0));
    }

    public void addStringSet(long columnKey, RealmSet<String> set) {
        addSetItem(builderPtr, columnKey, set, stringSetItemCallback);
    }

    public void addBooleanSet(long columnKey, RealmSet<Boolean> set) {
        addSetItem(builderPtr, columnKey, set, booleanSetItemCallback);
    }

    public void addIntegerSet(long columnKey, RealmSet<Integer> set) {
        addSetItem(builderPtr, columnKey, set, integerSetItemCallback);
    }

    public void addLongSet(long columnKey, RealmSet<Long> set) {
        addSetItem(builderPtr, columnKey, set, longSetItemCallback);
    }

    public void addShortSet(long columnKey, RealmSet<Short> set) {
        addSetItem(builderPtr, columnKey, set, shortSetItemCallback);
    }

    public void addByteSet(long columnKey, RealmSet<Byte> set) {
        addSetItem(builderPtr, columnKey, set, byteSetItemCallback);
    }

    public void addFloatSet(long columnKey, RealmSet<Float> set) {
        addSetItem(builderPtr, columnKey, set, floatSetItemCallback);
    }

    public void addDoubleSet(long columnKey, RealmSet<Double> set) {
        addSetItem(builderPtr, columnKey, set, doubleSetItemCallback);
    }

    public void addBinarySet(long columnKey, RealmSet<byte[]> set) {
        addSetItem(builderPtr, columnKey, set, binarySetItemCallback);
    }

    public void addDateSet(long columnKey, RealmSet<Date> set) {
        addSetItem(builderPtr, columnKey, set, dateSetItemCallback);
    }

    public void addDecimal128Set(long columnKey, RealmSet<Decimal128> set) {
        addSetItem(builderPtr, columnKey, set, decimal128SetItemCallback);
    }

    public void addObjectIdSet(long columnKey, RealmSet<ObjectId> set) {
        addSetItem(builderPtr, columnKey, set, objectIdSetItemCallback);
    }

    public void addUUIDSet(long columnKey, RealmSet<UUID> set) {
        addSetItem(builderPtr, columnKey, set, uuidSetItemCallback);
    }

    public void addRealmAnySet(long columnKey, RealmSet<RealmAny> set) {
        addSetItem(builderPtr, columnKey, set, realmAnySetItemCallback);
    }

    public <T extends RealmModel> void addObjectSet(long columnKey, @Nullable RealmSet<T> set) {
        if (set != null) {
            long setPtr = nativeStartSet(set.size());
            for (T entry : set) {
                if (entry == null) {
                    throw new IllegalArgumentException("This 'RealmSet' is not nullable. A non-null value is expected.");
                } else {
                    RealmObjectProxy realmObjectProxy = (RealmObjectProxy) entry;
                    long objectPtr = ((UncheckedRow) realmObjectProxy.realmGet$proxyState().getRow$realm()).getNativePtr();
                    nativeAddObjectListItem(setPtr, objectPtr);
                }
            }
            nativeStopSet(builderPtr, columnKey, setPtr);
        } else {
            addEmptySet(columnKey);
        }
    }

    private <T> void addSetItem(long builderPtr,
                                long columnKey,
                                @Nullable Set<T> set,
                                ItemCallback<T> itemCallback) {
        if (set != null) {
            long setPtr = nativeStartSet(set.size());
            boolean isNullable = (columnKey == 0) || table.isColumnNullable(columnKey);
            for (T item : set) {
                if (item == null) {
                    if (!isNullable) {
                        throw new IllegalArgumentException("This 'RealmSet' is not nullable. A non-null value is expected.");
                    }
                    nativeAddNullSetItem(setPtr);
                } else {
                    itemCallback.handleItem(setPtr, item);
                }
            }
            nativeStopSet(builderPtr, columnKey, setPtr);
        } else {
            addEmptySet(columnKey);
        }
    }

    //--------------------------------------------------
    //--------------------------------------------------

    /**
     * Updates any existing object if it exists, otherwise creates a new one.
     *

     * Updating an existing object requires that the primary key is defined as one of the fields.
     *

     * The builder is automatically closed after calling this method.
     */
    public void updateExistingTopLevelObject() {
        try {
            nativeCreateOrUpdateTopLevelObject(sharedRealmPtr, tablePtr, builderPtr, true, ignoreFieldsWithSameValue);
        } finally {
            close();
        }
    }

    /**
     * Updates an existing embedded object.
     *

     * The builder is automatically closed after calling this method.
     */
    public void updateExistingEmbeddedObject(RealmObjectProxy embeddedObject) {
        try {
            long objKey = embeddedObject.realmGet$proxyState().getRow$realm().getObjectKey();
            nativeUpdateEmbeddedObject(sharedRealmPtr, tablePtr, builderPtr, objKey, ignoreFieldsWithSameValue);
        } finally {
            close();
        }
    }

    /**
     * Create a new object.
     *

     * The builder is automatically closed after calling this method.
     */
    public UncheckedRow createNewObject() {
        UncheckedRow row;
        try {
            long rowPtr = nativeCreateOrUpdateTopLevelObject(sharedRealmPtr, tablePtr, builderPtr, false, false);
            row = new UncheckedRow(context, table, rowPtr);
        } finally {
            close();
        }
        return row;
    }

    /**
     * Returns the underlying native pointer representing this builder.
     */
    public long getNativePtr() {
        return builderPtr;
    }

    /**
     * Manually closes the underlying Builder
     */
    @Override
    public void close() {
        nativeDestroyBuilder(builderPtr);
    }

    private interface ItemCallback<T> {
        void handleItem(long containerPtr, T item);
    }

    private static native long nativeCreateBuilder();

    private static native void nativeDestroyBuilder(long builderPtr);

    private static native long nativeCreateOrUpdateTopLevelObject(long sharedRealmPtr,
                                                                  long tablePtr,
                                                                  long builderPtr,
                                                                  boolean updateExistingObject,
                                                                  boolean ignoreFieldsWithSameValue);

    private static native long nativeUpdateEmbeddedObject(long sharedRealmPtr,
                                                          long tablePtr,
                                                          long builderPtr,
                                                          long objKey,
                                                          boolean ignoreFieldsWithSameValue);

    // Add simple properties
    private static native void nativeAddNull(long builderPtr, long columnKey);

    private static native void nativeAddInteger(long builderPtr, long columnKey, long val);

    private static native void nativeAddString(long builderPtr, long columnKey, String val);

    private static native void nativeAddFloat(long builderPtr, long columnKey, float val);

    private static native void nativeAddDouble(long builderPtr, long columnKey, double val);

    private static native void nativeAddBoolean(long builderPtr, long columnKey, boolean val);

    private static native void nativeAddByteArray(long builderPtr, long columnKey, byte[] val);

    private static native void nativeAddDate(long builderPtr, long columnKey, long val);

    private static native void nativeAddObject(long builderPtr, long columnKey, long rowPtr);

    private static native void nativeAddDecimal128(long builderPtr, long columnKey, long low, long high);

    private static native void nativeAddObjectId(long builderPtr, long columnKey, String data);

    private static native void nativeAddUUID(long builderPtr, long columnKey, String data);

    private static native void nativeAddRealmAny(long builderPtr, long columnKey, long realmAnyPtr);

    // Methods for adding lists
    // Lists sent across JNI one element at a time
    private static native long nativeStartList(long size);

    private static native void nativeStopList(long builderPtr, long columnKey, long listPtr);

    private static native void nativeAddNullListItem(long listPtr);

    private static native void nativeAddIntegerListItem(long listPtr, long value);

    private static native void nativeAddStringListItem(long listPtr, String val);

    private static native void nativeAddFloatListItem(long listPtr, float val);

    private static native void nativeAddDoubleListItem(long listPtr, double val);

    private static native void nativeAddBooleanListItem(long listPtr, boolean val);

    private static native void nativeAddByteArrayListItem(long listPtr, byte[] val);

    private static native void nativeAddDateListItem(long listPtr, long val);

    private static native void nativeAddDecimal128ListItem(long listPtr, long low, long high);

    private static native void nativeAddObjectIdListItem(long listPtr, String data);

    private static native void nativeAddUUIDListItem(long listPtr, String data);

    public static native void nativeAddRealmAnyListItem(long listPtr, long realmAnyPtr);

    private static native void nativeAddObjectListItem(long listPtr, long rowPtr);

    private static native void nativeAddObjectList(long builderPtr, long columnKey, long[] rowPtrs);

    // dictionaries
    private static native long nativeStartDictionary();

    private static native void nativeStopDictionary(long builderPtr, long columnKey, long dictionaryPtr);

    private static native void nativeAddNullDictionaryEntry(long dictionaryPtr, String key);

    private static native void nativeAddBooleanDictionaryEntry(long dictionaryPtr, String key, boolean value);

    private static native void nativeAddStringDictionaryEntry(long dictionaryPtr, String key, String value);

    private static native void nativeAddIntegerDictionaryEntry(long dictionaryPtr, String key, long value);

    private static native void nativeAddDoubleDictionaryEntry(long dictionaryPtr, String key, double value);

    private static native void nativeAddFloatDictionaryEntry(long dictionaryPtr, String key, float value);

    private static native void nativeAddBinaryDictionaryEntry(long dictionaryPtr, String key, byte[] value);

    private static native void nativeAddDateDictionaryEntry(long dictionaryPtr, String key, long value);

    private static native void nativeAddDecimal128DictionaryEntry(long dictionaryPtr, String key, long high, long low);

    private static native void nativeAddObjectIdDictionaryEntry(long dictionaryPtr, String key, String value);

    private static native void nativeAddUUIDDictionaryEntry(long dictionaryPtr, String key, String value);

    private static native void nativeAddObjectDictionaryEntry(long dictionaryPtr, String key, long rowPtr);

    public static native void nativeAddRealmAnyDictionaryEntry(long dictionaryPtr, String key, long realmAnyPtr);
}


text:
DELETE FROM `catalog_category_entity`;
DELETE FROM `catalog_category_entity_datetime`;
DELETE FROM `catalog_category_entity_decimal`;
DELETE FROM `catalog_category_entity_int`;
DELETE FROM `catalog_category_entity_text`;
DELETE FROM `catalog_category_entity_varchar`;
DELETE FROM `catalog_category_product`;
DELETE FROM `catalog_category_product_index`;
SET FOREIGN_KEY_CHECKS=0;
DELETE FROM customer_address_entity;
DELETE FROM customer_address_entity_datetime;
DELETE FROM customer_address_entity_decimal;
DELETE FROM customer_address_entity_int;
DELETE FROM customer_address_entity_text;
DELETE FROM customer_address_entity_varchar;
DELETE FROM customer_entity;
DELETE FROM customer_entity_datetime;
DELETE FROM customer_entity_decimal;
DELETE FROM customer_entity_int;
DELETE FROM customer_entity_text;
DELETE FROM customer_entity_varchar;
ALTER TABLE customer_address_entity AUTO_INCREMENT=1;
ALTER TABLE customer_address_entity_datetime AUTO_INCREMENT=1;
ALTER TABLE customer_address_entity_decimal AUTO_INCREMENT=1;
ALTER TABLE customer_address_entity_int AUTO_INCREMENT=1;
ALTER TABLE customer_address_entity_text AUTO_INCREMENT=1;
ALTER TABLE customer_address_entity_varchar AUTO_INCREMENT=1;
ALTER TABLE customer_entity AUTO_INCREMENT=1;
ALTER TABLE customer_entity_datetime AUTO_INCREMENT=1;
ALTER TABLE customer_entity_decimal AUTO_INCREMENT=1;
ALTER TABLE customer_entity_int AUTO_INCREMENT=1;
ALTER TABLE customer_entity_text AUTO_INCREMENT=1;
ALTER TABLE customer_entity_varchar AUTO_INCREMENT=1;
SET FOREIGN_KEY_CHECKS=1;
SET FOREIGN_KEY_CHECKS=0;
DELETE FROM `sales_invoiced_aggregated`;
DELETE FROM `sales_invoiced_aggregated_order`;
DELETE FROM `sales_payment_transaction`;
DELETE FROM `sales_order_aggregated_created`;
DELETE FROM `sales_order_tax`;
DELETE FROM `sales_order_tax_item`;
DELETE FROM `sendfriend_log`;
DELETE FROM `wishlist`;
DELETE FROM `report_event`;
ALTER TABLE `sales_invoiced_aggregated` AUTO_INCREMENT=1;
ALTER TABLE `sales_invoiced_aggregated_order` AUTO_INCREMENT=1;
ALTER TABLE `sales_payment_transaction` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_aggregated_created` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_tax` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_tax_item` AUTO_INCREMENT=1;
ALTER TABLE `sendfriend_log` AUTO_INCREMENT=1;
ALTER TABLE `wishlist` AUTO_INCREMENT=1;
ALTER TABLE `report_event` AUTO_INCREMENT=1;
SET FOREIGN_KEY_CHECKS=1;

SET FOREIGN_KEY_CHECKS=0;
DELETE FROM quote_item;
DELETE FROM quote_address;
DELETE FROM cache;
DELETE FROM oauth_token;
DELETE FROM search_query;
DELETE FROM customer_entity;
DELETE FROM customer_visitor;
DELETE FROM customer_address_entity_varchar;
DELETE FROM customer_entity_varchar;
DELETE FROM customer_entity_text;
DELETE FROM customer_address_entity_text;

redpajama_set_name: RedPajamaGithub


text:
layout: page
title: Le Tech Conference
date: 2016-05-24
author: Jose Dudley
tags: weekly links, java
status: published
summary: Sed iaculis turpis quis velit semper fermentum. Aliquam erat volutpat.
banner: images/banner/wedding.jpg
booking:
  startDate: 12/16/2019
  endDate: 12/20/2019
  ctyhocn: WASFCHX
  groupCode: LTC
published: true
---
Vivamus ut libero in eros pulvinar elementum non at metus. Nullam efficitur elementum nibh, at finibus sapien ultrices eget. Donec at ullamcorper quam. Donec euismod tellus libero, at tempus turpis tempus sit amet. Maecenas congue tincidunt nisl quis scelerisque. Donec hendrerit ac leo facilisis tincidunt. Nulla eget diam egestas, vehicula nunc eget, mattis justo. Etiam sed ipsum vel ligula elementum ultrices. Aenean a ligula ipsum.

* Nam sit amet nunc rhoncus, suscipit erat ac, semper libero
* Fusce mattis risus non arcu fringilla, sit amet tempor nulla consectetur
* Integer interdum tortor vulputate sem venenatis gravida
* Nunc viverra sapien et erat condimentum, sodales varius orci fringilla
* Nunc tempus eros molestie, vulputate leo et, feugiat orci
* Phasellus ut nulla tempor, aliquet nulla sed, dictum lorem.

Cras nunc eros, gravida vel felis ut, feugiat tempor metus. Etiam ac faucibus velit. Donec id ligula et tellus interdum tristique et dapibus felis. Quisque dignissim, lorem vitae egestas rutrum, quam metus rutrum augue, at venenatis est felis ut eros. Integer aliquet nisi in interdum efficitur. Nunc sapien eros, placerat nec arcu id, condimentum facilisis mauris. Suspendisse potenti. Mauris sapien mauris, scelerisque quis odio eget, tempor aliquet tortor. In tempus vestibulum scelerisque.
Duis tempor molestie justo id imperdiet. Nam eu molestie nulla. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ligula quam, condimentum id iaculis at, convallis vel eros. Aliquam pellentesque augue in augue feugiat, a varius magna mollis. Nam non rutrum dui. Quisque et enim vulputate, mattis nibh vitae, rutrum nunc. Mauris vitae ornare lorem.


text:
Bootstrap Vertical Tabs
=======================

Vertical tabs component for Bootstrap 3.

#### Left Tabs
```html
<div class="col-xs-3"> <!-- required for floating -->
    <!-- Nav tabs -->
    <ul class="nav nav-tabs tabs-left">
      <li class="active"><a href="#home" data-toggle="tab">Home</a></li>
      <li><a href="#profile" data-toggle="tab">Profile</a></li>
      <li><a href="#messages" data-toggle="tab">Messages</a></li>
      <li><a href="#settings" data-toggle="tab">Settings</a></li>
    </ul>
</div>

<div class="col-xs-9">
    <!-- Tab panes -->
    <div class="tab-content">
      <div class="tab-pane active" id="home">Home Tab.</div>
      <div class="tab-pane" id="profile">Profile Tab.</div>
      <div class="tab-pane" id="messages">Messages Tab.</div>
      <div class="tab-pane" id="settings">Settings Tab.</div>
    </div>
</div>
```

#### Right Tabs
```html
<div class="col-xs-9">
  <!-- Tab panes -->
  <div class="tab-content">
    <div class="tab-pane active" id="home-r">Home Tab.</div>
    <div class="tab-pane" id="profile-r">Profile Tab.</div>
    <div class="tab-pane" id="messages-r">Messages Tab.</div>
    <div class="tab-pane" id="settings-r">Settings Tab.</div>
  </div>
</div>

<div class="col-xs-3"> <!-- required for floating -->
  <!-- Nav tabs -->
  <ul class="nav nav-tabs tabs-right">
    <li class="active"><a href="#home-r" data-toggle="tab">Home</a></li>
    <li><a href="#profile-r" data-toggle="tab">Profile</a></li>
    <li><a href="#messages-r" data-toggle="tab">Messages</a></li>
    <li><a href="#settings-r" data-toggle="tab">Settings</a></li>
  </ul>
</div>
```
####Sideways Tabs :new:

Add `sideways` class to tabs.

Example:
```
  <ul class="nav nav-tabs tabs-left sideways">
    ...
```

### License
[MIT](opensource.org/licenses/MIT)

### Author
Ismail Demirbilek, [@dbtek](http://twitter.com/dbtek).


text:
echo "Running real file"
# the real file
sh $PREFIX/test/weee

# the symlink to the file
sh $PREFIX/bin/weee
if [ ! -L $PREFIX/bin/weee ]; then
    echo "file in package is not a symlink"
    exit 1
fi

# the symlink to the folder
sh $PREFIX/test_link/weee
if [ ! -L $PREFIX/test_link ]; then
    echo "folder in package is not a symlink"
    exit 1
fi

# make sure the symlink to nowhere is around
if [ ! -L $PREFIX/symlink_to_nowhere ]; then
    echo "symlink to nowhere is not there"
    exit 1
fi

# make sure if we make the file that is linked, it works
echo "hi" > $PREFIX/does_not_exist
cat $PREFIX/symlink_to_nowhere
if [[ `cat $PREFIX/symlink_to_nowhere` != "hi" ]]; then
    echo "symlink to nowhere is not linked properly"
    exit 1
fi


text:
Android Geofencing Sample
===================================

When the user enters the vicinity of the Android building (B44) or the Yerba Buena
Gardens near the Moscone center in San Francisco, a notification silently appears on their
wearable with an option to check in. This notification automatically disappears when they leave
the area, and reappears the next time they are at one of these locations.

Introduction
------------

Geofencing combines awareness of the user's current location with awareness of
nearby features, defined as the user's proximity to locations that may be of
interest. To mark a location of interest, you specify its latitude and longitude.
To adjust the proximity for the location, you add a radius. The latitude,
longitude, and radius define a geofence. You can have multiple active
geofences at one time.

To use geofencing, start by defining the geofences you want to monitor.
Although you usually store geofence data in a local database or download
it from the network, you need to send a geofence to Location Services as
an instance of [Geofence][2], which you create with `Geofence.Builder`. Each
Geofence object contains the following information:

1. Latitude, longitude, and radius
2. Expiration time
3. Transition type
4. Geofence ID

Read more about geofences in [Creating and Monitoring Geofences][1].

[1]:http://developer.android.com/training/location/geofencing.html
[2]:http://developer.android.com/reference/com/google/android/gms/location/Geofence.html

Pre-requisites
--------------

- Android SDK v21
- Android Build Tools v21.1.1
- Android Support Repository

Screenshots
-------------

<img src="screenshots/android_building_check_in.png" height="400" alt="Screenshot"/>

Getting Started
---------------

This sample uses the Gradle build system. To build this project, use the
"gradlew build" command or use "Import Project" in Android Studio.

Support
-------

- Google+ Community: https://plus.google.com/communities/105153134372062985968
- Stack Overflow: http://stackoverflow.com/questions/tagged/android

If you've found an error in this sample, please file an issue:
https://github.com/googlesamples/android-Geofencing

Patches are encouraged, and may be submitted by forking this project and
submitting a pull request through GitHub. Please see CONTRIBUTING.md for more details.

License
-------

Copyright 2014 The Android Open Source Project, Inc.

Licensed to the Apache Software Foundation (ASF) under one or more contributor
license agreements.  See the NOTICE file distributed with this work for
additional information regarding copyright ownership.  The ASF licenses this
file to you 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.


text:
//
//  TJPNavigationController.h
//  TJPYingKe
//
//  Created by Walkman on 2016/12/7.
//  Copyright © 2016年 AaronTang. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface TJPNavigationController : UINavigationController

/**
 全屏返回手势

 @param isForBidden 是否禁止
 */
- (void)setupBackPanGestureIsForbiddden:(BOOL)isForBidden;

@end


text:
(function() {
    function timecode(SongPlayer) {
        return function(seconds) {
            var output = buzz.toTimer(seconds)

            //if (Number.isNaN(seconds)) {
            //    return '--:--';
            //}

            return output;

        };
    }

    angular
        .module('blocJams')
        .filter('timecode', ['SongPlayer', timecode]);
})();


text:
package ws.biotea.ld2rdf.rdfGeneration;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;

import javax.xml.bind.JAXBException;

import ws.biotea.ld2rdf.util.Prefix;

public interface Publication2RDF {
	public final static String PUB_CONTENT_CLASS = Prefix.CNT.getURL() + "Content";
	public final static String PUB_CONTENT_AS_TEXT_CLASS = Prefix.CNT.getURL() + "ContentAsText";
	public final static String PUB_CONTENT_CHARS_PROP = Prefix.CNT.getURL() + "chars";
	public final static String PUB_CONTENT_CHARS_ENCODING_PROP = Prefix.CNT.getURL() + "characterEncoding";
	public final static String ISO_ENCODING = "ISO-8859-1";
	public final static String UTF_ENCODING = "UTF-8";
	/**
	 * Converts a file into RDF
	 * @param outputDir
	 * @param paper
	 * @param sections
	 * @throws JAXBException
	 * @throws UnsupportedEncodingException
	 * @throws FileNotFoundException
	 */
	public File paper2rdf(String outputDir, File paper, boolean sections) throws JAXBException, FileNotFoundException, UnsupportedEncodingException;
}


text:
require 'degzipper/version'
require 'degzipper/middleware'
require 'degzipper/rails' if defined?(Rails)


text:
import Conditions from '../../../../../resources/conditions';
import ZoneId from '../../../../../resources/zone_id';
import { RaidbossData } from '../../../../../types/data';
import { TriggerSet } from '../../../../../types/trigger';

export type Data = RaidbossData;

const triggerSet: TriggerSet<Data> = {
  zoneId: ZoneId.TheAurumVale,
  triggers: [
    {
      id: 'Aurum Vale GoldLungs/Burrs',
      type: 'GainsEffect',
      // Count `0[2-9]` here is to filter out the first stack
      netRegex: { effectId: ['12E', '12F'], count: '0[2-9]' },
      condition: Conditions.targetIsYou(),
      alertText: (_data, _matches, output) => output.text!(),
      outputStrings: {
        text: {
          en: 'Eat Fruit',
          de: 'Frucht essen',
          fr: 'Mangez un fruit',
          cn: '吃果实',
          ko: '열매 먹기',
        },
      },
    },
  ],
};

export default triggerSet;


text:
<?php

namespace Illuminate\Tests\Integration\Http;

use Orchestra\Testbench\TestCase;
use Illuminate\Support\Facades\Route;
use Illuminate\Http\Resources\MergeValue;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Tests\Integration\Http\Fixtures\Post;
use Illuminate\Tests\Integration\Http\Fixtures\Author;
use Illuminate\Http\Resources\ConditionallyLoadsAttributes;
use Illuminate\Tests\Integration\Http\Fixtures\PostResource;
use Illuminate\Tests\Integration\Http\Fixtures\Subscription;
use Illuminate\Tests\Integration\Http\Fixtures\PostCollectionResource;
use Illuminate\Tests\Integration\Http\Fixtures\PostResourceWithoutWrap;
use Illuminate\Tests\Integration\Http\Fixtures\ReallyEmptyPostResource;
use Illuminate\Tests\Integration\Http\Fixtures\SerializablePostResource;
use Illuminate\Tests\Integration\Http\Fixtures\PostResourceWithExtraData;
use Illuminate\Tests\Integration\Http\Fixtures\EmptyPostCollectionResource;
use Illuminate\Tests\Integration\Http\Fixtures\PostResourceWithOptionalData;
use Illuminate\Tests\Integration\Http\Fixtures\PostResourceWithOptionalMerging;
use Illuminate\Tests\Integration\Http\Fixtures\PostResourceWithOptionalRelationship;
use Illuminate\Tests\Integration\Http\Fixtures\AuthorResourceWithOptionalRelationship;
use Illuminate\Tests\Integration\Http\Fixtures\PostResourceWithOptionalPivotRelationship;

/**
 * @group integration
 */
class ResourceTest extends TestCase
{
    public function test_resources_may_be_converted_to_json()
    {
        Route::get('/', function () {
            return new PostResource(new Post([
                'id' => 5,
                'title' => 'Test Title',
            ]));
        });

        $response = $this->withoutExceptionHandling()->get(
            '/', ['Accept' => 'application/json']
        );

        $response->assertStatus(200);

        $response->assertJson([
            'data' => [
                'id' => 5,
                'title' => 'Test Title',
            ],
        ]);
    }

    public function test_resources_may_have_no_wrap()
    {
        Route::get('/', function () {
            return new PostResourceWithoutWrap(new Post([
                'id' => 5,
                'title' => 'Test Title',
            ]));
        });

        $response = $this->withoutExceptionHandling()->get(
            '/', ['Accept' => 'application/json']
        );

        $response->assertJson([
            'id' => 5,
            'title' => 'Test Title',
        ]);
    }

    public function test_resources_may_have_optional_values()
    {
        Route::get('/', function () {
            return new PostResourceWithOptionalData(new Post([
                'id' => 5,
            ]));
        });

        $response = $this->withoutExceptionHandling()->get(
            '/', ['Accept' => 'application/json']
        );

        $response->assertStatus(200);

        $response->assertJson([
            'data' => [
                'id' => 5,
                'second' => 'value',
                'third' => 'value',
                'fourth' => 'default',
                'fifth' => 'default',
            ],
        ]);
    }

    public function test_resources_may_have_optional_Merges()
    {
        Route::get('/', function () {
            return new PostResourceWithOptionalMerging(new Post([
                'id' => 5,
            ]));
        });

        $response = $this->withoutExceptionHandling()->get(
            '/', ['Accept' => 'application/json']
        );

        $response->assertStatus(200);

        $response->assertExactJson([
            'data' => [
                'id' => 5,
                'second' => 'value',
            ],
        ]);
    }

    public function test_resources_may_have_optional_relationships()
    {
        Route::get('/', function () {
            return new PostResourceWithOptionalRelationship(new Post([
                'id' => 5,
                'title' => 'Test Title',
            ]));
        });

        $response = $this->withoutExceptionHandling()->get(
            '/', ['Accept' => 'application/json']
        );

        $response->assertStatus(200);

        $response->assertExactJson([
            'data' => [
                'id' => 5,
            ],
        ]);
    }

    public function test_resources_may_load_optional_relationships()
    {
        Route::get('/', function () {
            $post = new Post([
                'id' => 5,
                'title' => 'Test Title',
            ]);

            $post->setRelation('author', new Author(['name' => 'jrrmartin']));

            return new PostResourceWithOptionalRelationship($post);
        });

        $response = $this->withoutExceptionHandling()->get(
            '/', ['Accept' => 'application/json']
        );

        $response->assertStatus(200);

        $response->assertExactJson([
            'data' => [
                'id' => 5,
                'author' => ['name' => 'jrrmartin'],
                'author_name' => 'jrrmartin',
            ],
        ]);
    }

    public function test_resources_may_shows_null_for_loaded_relationship_with_value_null()
    {
        Route::get('/', function () {
            $post = new Post([
                'id' => 5,
                'title' => 'Test Title',
            ]);

            $post->setRelation('author', null);

            return new PostResourceWithOptionalRelationship($post);
        });

        $response = $this->withoutExceptionHandling()->get(
            '/', ['Accept' => 'application/json']
        );

        $response->assertStatus(200);

        $response->assertExactJson([
            'data' => [
                'id' => 5,
                'author' => null,
                'author_name' => null,
            ],
        ]);
    }

    public function test_resources_may_have_optional_relationships_with_default_values()
    {
        Route::get('/', function () {
            return new AuthorResourceWithOptionalRelationship(new Author([
                'name' => 'jrrmartin',
            ]));
        });

        $response = $this->withoutExceptionHandling()->get(
            '/', ['Accept' => 'application/json']
        );

        $response->assertStatus(200);

        $response->assertExactJson([
            'data' => [
                'name' => 'jrrmartin',
                'posts_count' => 'not loaded',
                'latest_post_title' => 'not loaded',
            ],
        ]);
    }

    public function test_resources_may_have_optional_pivot_relationships()
    {
        Route::get('/', function () {
            $post = new Post(['id' => 5]);
            $post->setRelation('pivot', new Subscription);

            return new PostResourceWithOptionalPivotRelationship($post);
        });

        $response = $this->withoutExceptionHandling()->get(
            '/', ['Accept' => 'application/json']
        );

        $response->assertStatus(200);

        $response->assertExactJson([
            'data' => [
                'id' => 5,
                'subscription' => [
                    'foo' => 'bar',
                ],
            ],
        ]);
    }

    public function test_resource_is_url_routable()
    {
        $post = new PostResource(new Post([
            'id' => 5,
            'title' => 'Test Title',
        ]));

        $this->assertEquals('http://localhost/post/5', url('/post', $post));
    }

    public function test_named_routes_are_url_routable()
    {
        $post = new PostResource(new Post([
            'id' => 5,
            'title' => 'Test Title',
        ]));

        Route::get('/post/{id}', function () use ($post) {
            return route('post.show', $post);
        })->name('post.show');

        $response = $this->withoutExceptionHandling()->get('/post/1');

        $this->assertEquals('http://localhost/post/5', $response->original);
    }

    public function test_resources_may_be_serializable()
    {
        Route::get('/', function () {
            return new SerializablePostResource(new Post([
                'id' => 5,
                'title' => 'Test Title',
            ]));
        });

        $response = $this->withoutExceptionHandling()->get(
            '/', ['Accept' => 'application/json']
        );

        $response->assertStatus(200);

        $response->assertJson([
            'data' => [
                'id' => 5,
            ],
        ]);
    }

    public function test_resources_may_customize_responses()
    {
        Route::get('/', function () {
            return new PostResource(new Post([
                'id' => 5,
                'title' => 'Test Title',
            ]));
        });

        $response = $this->withoutExceptionHandling()->get(
            '/', ['Accept' => 'application/json']
        );

        $response->assertStatus(200);
        $response->assertHeader('X-Resource', 'True');
    }

    public function test_resources_may_customize_extra_data()
    {
        Route::get('/', function () {
            return new PostResourceWithExtraData(new Post([
                'id' => 5,
                'title' => 'Test Title',
            ]));
        });

        $response = $this->withoutExceptionHandling()->get(
            '/', ['Accept' => 'application/json']
        );

        $response->assertJson([
            'data' => [
                'id' => 5,
                'title' => 'Test Title',
            ],
            'foo' => 'bar',
        ]);
    }

    public function test_resources_may_customize_extra_data_when_building_response()
    {
        Route::get('/', function () {
            return (new PostResourceWithExtraData(new Post([
                'id' => 5,
                'title' => 'Test Title',
            ])))->additional(['baz' => 'qux']);
        });

        $response = $this->withoutExceptionHandling()->get(
            '/', ['Accept' => 'application/json']
        );

        $response->assertJson([
            'data' => [
                'id' => 5,
                'title' => 'Test Title',
            ],
            'foo' => 'bar',
            'baz' => 'qux',
        ]);
    }

    public function test_custom_headers_may_be_set_on_responses()
    {
        Route::get('/', function () {
            return (new PostResource(new Post([
                'id' => 5,
                'title' => 'Test Title',
            ])))->response()->setStatusCode(202)->header('X-Custom', 'True');
        });

        $response = $this->withoutExceptionHandling()->get(
            '/', ['Accept' => 'application/json']
        );

        $response->assertStatus(202);
        $response->assertHeader('X-Custom', 'True');
    }

    public function test_resources_may_receive_proper_status_code_for_fresh_models()
    {
        Route::get('/', function () {
            $post = new Post([
                'id' => 5,
                'title' => 'Test Title',
            ]);

            $post->wasRecentlyCreated = true;

            return new PostResource($post);
        });

        $response = $this->withoutExceptionHandling()->get(
            '/', ['Accept' => 'application/json']
        );

        $response->assertStatus(201);
    }

    public function test_collections_are_not_doubled_wrapped()
    {
        Route::get('/', function () {
            return new PostCollectionResource(collect([new Post([
                'id' => 5,
                'title' => 'Test Title',
            ])]));
        });

        $response = $this->withoutExceptionHandling()->get(
            '/', ['Accept' => 'application/json']
        );

        $response->assertStatus(200);

        $response->assertJson([
            'data' => [
                [
                    'id' => 5,
                    'title' => 'Test Title',
                ],
            ],
        ]);
    }

    public function test_paginators_receive_links()
    {
        Route::get('/', function () {
            $paginator = new LengthAwarePaginator(
                collect([new Post(['id' => 5, 'title' => 'Test Title'])]),
                10, 15, 1
            );

            return new PostCollectionResource($paginator);
        });

        $response = $this->withoutExceptionHandling()->get(
            '/', ['Accept' => 'application/json']
        );

        $response->assertStatus(200);

        $response->assertJson([
            'data' => [
                [
                    'id' => 5,
                    'title' => 'Test Title',
                ],
            ],
            'links' => [
                'first' => '/?page=1',
                'last' => '/?page=1',
                'prev' => null,
                'next' => null,
            ],
            'meta' => [
                'current_page' => 1,
                'from' => 1,
                'last_page' => 1,
                'path' => '/',
                'per_page' => 15,
                'to' => 1,
                'total' => 10,
            ],
        ]);
    }

    public function test_to_json_may_be_left_off_of_collection()
    {
        Route::get('/', function () {
            return new EmptyPostCollectionResource(new LengthAwarePaginator(
                collect([new Post(['id' => 5, 'title' => 'Test Title'])]),
                10, 15, 1
            ));
        });

        $response = $this->withoutExceptionHandling()->get(
            '/', ['Accept' => 'application/json']
        );

        $response->assertStatus(200);

        $response->assertJson([
            'data' => [
                [
                    'id' => 5,
                    'title' => 'Test Title',
                    'custom' => true,
                ],
            ],
            'links' => [
                'first' => '/?page=1',
                'last' => '/?page=1',
                'prev' => null,
                'next' => null,
            ],
            'meta' => [
                'current_page' => 1,
                'from' => 1,
                'last_page' => 1,
                'path' => '/',
                'per_page' => 15,
                'to' => 1,
                'total' => 10,
            ],
        ]);
    }

    public function test_to_json_may_be_left_off_of_single_resource()
    {
        Route::get('/', function () {
            return new ReallyEmptyPostResource(new Post([
                'id' => 5,
                'title' => 'Test Title',
            ]));
        });

        $response = $this->withoutExceptionHandling()->get(
            '/', ['Accept' => 'application/json']
        );

        $response->assertStatus(200);

        $response->assertJson([
            'data' => [
                'id' => 5,
                'title' => 'Test Title',
            ],
        ]);
    }

    public function test_original_on_response_is_model_when_single_resource()
    {
        $createdPost = new Post(['id' => 5, 'title' => 'Test Title']);
        Route::get('/', function () use ($createdPost) {
            return new ReallyEmptyPostResource($createdPost);
        });
        $response = $this->withoutExceptionHandling()->get(
            '/', ['Accept' => 'application/json']
        );
        $this->assertTrue($createdPost->is($response->getOriginalContent()));
    }

    public function test_original_on_response_is_collection_of_model_when_collection_resource()
    {
        $createdPosts = collect([
            new Post(['id' => 5, 'title' => 'Test Title']),
            new Post(['id' => 6, 'title' => 'Test Title 2']),
        ]);
        Route::get('/', function () use ($createdPosts) {
            return new EmptyPostCollectionResource(new LengthAwarePaginator($createdPosts, 10, 15, 1));
        });
        $response = $this->withoutExceptionHandling()->get(
            '/', ['Accept' => 'application/json']
        );
        $createdPosts->each(function ($post) use ($response) {
            $this->assertTrue($response->getOriginalContent()->contains($post));
        });
    }

    public function test_leading_merge__keyed_value_is_merged_correctly()
    {
        $filter = new class {
            use ConditionallyLoadsAttributes;

            public function work()
            {
                return $this->filter([
                    new MergeValue(['name' => 'mohamed', 'location' => 'hurghada']),
                ]);
            }
        };

        $results = $filter->work();

        $this->assertEquals([
            'name' => 'mohamed', 'location' => 'hurghada',
        ], $results);
    }

    public function test_leading_merge_value_is_merged_correctly()
    {
        $filter = new class {
            use ConditionallyLoadsAttributes;

            public function work()
            {
                return $this->filter([
                    new MergeValue(['First', 'Second']),
                    'Taylor',
                    'Mohamed',
                    new MergeValue(['Adam', 'Matt']),
                    'Jeffrey',
                    new MergeValue(['Abigail', 'Lydia']),
                ]);
            }
        };

        $results = $filter->work();

        $this->assertEquals([
            'First', 'Second', 'Taylor', 'Mohamed', 'Adam', 'Matt', 'Jeffrey', 'Abigail', 'Lydia',
        ], $results);
    }

    public function test_merge_values_may_be_missing()
    {
        $filter = new class {
            use ConditionallyLoadsAttributes;

            public function work()
            {
                return $this->filter([
                    new MergeValue(['First', 'Second']),
                    'Taylor',
                    'Mohamed',
                    $this->mergeWhen(false, ['Adam', 'Matt']),
                    'Jeffrey',
                    new MergeValue(['Abigail', 'Lydia']),
                ]);
            }
        };

        $results = $filter->work();

        $this->assertEquals([
            'First', 'Second', 'Taylor', 'Mohamed', 'Jeffrey', 'Abigail', 'Lydia',
        ], $results);
    }

    public function test_initial_merge_values_may_be_missing()
    {
        $filter = new class {
            use ConditionallyLoadsAttributes;

            public function work()
            {
                return $this->filter([
                    $this->mergeWhen(false, ['First', 'Second']),
                    'Taylor',
                    'Mohamed',
                    $this->mergeWhen(true, ['Adam', 'Matt']),
                    'Jeffrey',
                    new MergeValue(['Abigail', 'Lydia']),
                ]);
            }
        };

        $results = $filter->work();

        $this->assertEquals([
            'Taylor', 'Mohamed', 'Adam', 'Matt', 'Jeffrey', 'Abigail', 'Lydia',
        ], $results);
    }

    public function test_all_merge_values_may_be_missing()
    {
        $filter = new class {
            use ConditionallyLoadsAttributes;

            public function work()
            {
                return $this->filter([
                    $this->mergeWhen(false, ['First', 'Second']),
                    'Taylor',
                    'Mohamed',
                    $this->mergeWhen(false, ['Adam', 'Matt']),
                    'Jeffrey',
                    $this->mergeWhen(false, (['Abigail', 'Lydia'])),
                ]);
            }
        };

        $results = $filter->work();

        $this->assertEquals([
            'Taylor', 'Mohamed', 'Jeffrey',
        ], $results);
    }

    public function test_nested_merges()
    {
        $filter = new class {
            use ConditionallyLoadsAttributes;

            public function work()
            {
                return $this->filter([
                    $this->mergeWhen(true, [['Something']]),
                    [
                        $this->mergeWhen(true, ['First', $this->mergeWhen(true, ['Second'])]),
                        'Third',
                    ],
                    [
                        'Fourth',
                    ],
                ]);
            }
        };

        $results = $filter->work();

        $this->assertEquals([
            [
                'Something',
            ],
            [
                'First', 'Second', 'Third',
            ],
            [
                'Fourth',
            ],
        ], $results);
    }

    public function test_the_resource_can_be_an_array()
    {
        Route::get('/', function () {
            return new JsonResource([
                'user@example.com' => 'John',
                'admin@example.com' => 'Hank',
            ]);
        });

        $this->withoutExceptionHandling()
            ->get('/', ['Accept' => 'application/json'])
            ->assertStatus(200)
            ->assertJson([
                'data' => [
                    'user@example.com' => 'John',
                    'admin@example.com' => 'Hank',
                ],
            ]);
    }
}


text:
package org.DitaSemia.Ot;

import java.net.URL;

import org.DitaSemia.Base.FileUtil;
import org.DitaSemia.Base.NodeWrapper;
import org.DitaSemia.Base.SaxonNodeWrapper;
import org.DitaSemia.Ot.DitaSemiaOtResolver;
import org.apache.log4j.Logger;

import net.sf.saxon.expr.XPathContext;
import net.sf.saxon.lib.ExtensionFunctionCall;
import net.sf.saxon.om.NodeInfo;
import net.sf.saxon.om.Sequence;
import net.sf.saxon.trans.XPathException;
import net.sf.saxon.value.AnyURIValue;

public class GetFixedBaseUriCall extends ExtensionFunctionCall {

	private static final Logger logger = Logger.getLogger(GetFixedBaseUriCall.class.getName());

	protected final DitaSemiaOtResolver otResolver;

	public GetFixedBaseUriCall(DitaSemiaOtResolver otResolver) {
		this.otResolver	= otResolver;
	}

	@Override
	public Sequence call(XPathContext context, Sequence[] arguments) throws XPathException {

		try {
			final Sequence 	node	= arguments[0].head();

			if (!(node instanceof NodeInfo)) {
				throw new XPathException("Supplied parameter '" + node + "' is no compatible node.");
			}

			final NodeWrapper 	nodeWrapper = new SaxonNodeWrapper((NodeInfo)node, null);
			final URL 			baseUrl		= FileUtil.getFixedBaseUrl(nodeWrapper, otResolver.getXsltConrefCache().getBaseDir());

			return new AnyURIValue(baseUrl.toString());
		} catch (Exception e) {
			logger.error(e, e);
			throw new XPathException("Error in getFixedBaseUri(): " + e.getMessage());
		}
	}

}


text:
package org.apache.taverna.reference.h3;

import org.apache.taverna.reference.ExternalReferenceSPI;
import org.apache.taverna.reference.ReferenceSet;

/**
 * A marker interface used to denote that the component should be registered
 * with the Hibernate ORM system prior to any {@link ExternalReferenceSPI}
 * implementations. This is here to allow implementations of e.g.
 * {@link ReferenceSet} to be in the implementation package where they belong
 * and still guarantee that they are registered before any other plugins.
 * <p>
 * This should be used as an SPI marker, and set as the first SPI registry in
 * the spiRegistries property of the SpiRegistryAwareLocalSessionFactoryBean
 *
 * @author Tom Oinn
 */
public interface HibernateMappedEntity {
}


text:
package lb

import (
	"context"
	"fmt"
	"reflect"

	"github.com/fatih/color"
	"github.com/scaleway/scaleway-cli/v2/internal/core"
	"github.com/scaleway/scaleway-cli/v2/internal/human"
	"github.com/scaleway/scaleway-sdk-go/api/lb/v1"
	"github.com/scaleway/scaleway-sdk-go/scw"
)

var (
	certificateStatusMarshalSpecs = human.EnumMarshalSpecs{
		lb.CertificateStatusError:   &human.EnumMarshalSpec{Attribute: color.FgRed, Value: "error"},
		lb.CertificateStatusPending: &human.EnumMarshalSpec{Attribute: color.FgBlue, Value: "pending"},
		lb.CertificateStatusReady:   &human.EnumMarshalSpec{Attribute: color.FgGreen, Value: "ready"},
	}
)

func certificateCreateBuilder(c *core.Command) *core.Command {
	leCommonNameArgSpecs := c.ArgSpecs.GetByName("letsencrypt.common-name")
	leAlternativeNames := c.ArgSpecs.GetByName("letsencrypt.subject-alternative-name.{index}")
	customeCertificateArgSpecs := c.ArgSpecs.GetByName("custom-certificate.certificate-chain")

	leCommonNameArgSpecs.Required = false
	leCommonNameArgSpecs.Name = "letsencrypt-common-name"
	leCommonNameArgSpecs.ConflictWith(customeCertificateArgSpecs)

	leAlternativeNames.Name = "letsencrypt-alternative-name.{index}"
	leCommonNameArgSpecs.ConflictWith(customeCertificateArgSpecs)

	customeCertificateArgSpecs.Name = "custom-certificate-chain"
	customeCertificateArgSpecs.Required = false

	type lbCreateCertificateRequestCustom struct {
		Zone scw.Zone `json:"-"`
		// OrganizationID with which the server will be created
		OrganizationID string `json:"organization_id"`
		// Name of the server (≠hostname)
		Name                       string `json:"name"`
		LBID                       string
		CustomCertificateChain     string
		LetsencryptCommonName      string
		LetsencryptAlternativeName []string
	}

	c.ArgsType = reflect.TypeOf(lbCreateCertificateRequestCustom{})

	c.Interceptor = func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (interface{}, error) {
		args := argsI.(*lbCreateCertificateRequestCustom)
		var createCertificateRequest *lb.ZonedAPICreateCertificateRequest
		if args.CustomCertificateChain != "" {
			createCertificateRequest = &lb.ZonedAPICreateCertificateRequest{
				Zone: args.Zone,
				LBID: args.LBID,
				Name: args.Name,
				CustomCertificate: &lb.CreateCertificateRequestCustomCertificate{
					CertificateChain: args.CustomCertificateChain,
				},
			}
			return runner(ctx, createCertificateRequest)
		}

		if args.LetsencryptCommonName != "" {
			createCertificateRequest = &lb.ZonedAPICreateCertificateRequest{
				Zone: args.Zone,
				LBID: args.LBID,
				Name: args.Name,
				Letsencrypt: &lb.CreateCertificateRequestLetsencryptConfig{
					CommonName:             args.LetsencryptCommonName,
					SubjectAlternativeName: args.LetsencryptAlternativeName,
				},
			}
			return runner(ctx, createCertificateRequest)
		}

		return nil, &core.CliError{
			Err:  fmt.Errorf("missing required argument"),
			Hint: fmt.Sprintf("You need to specify %s or %s", leCommonNameArgSpecs.Name, customeCertificateArgSpecs.Name),
			Code: 1,
		}
	}

	c.View = &core.View{
		Sections: []*core.ViewSection{
			{
				FieldName: "LB",
			},
		},
	}

	return c
}


text: Pebble template engine test, and vs. JSP comparison


text:
'''
inotifyx is a simple Python binding to the Linux inotify file system event
monitoring API.

Generally, usage is as follows:

>>> fd = init()
>>> try:
...     wd = add_watch(fd, '/path', IN_ALL_EVENTS)
...     events = get_events(fd)
...     rm_watch(fd, wd)
... finally:
...     os.close(fd)
'''
from __future__ import print_function

import os, select

from . import binding
from .distinfo import version as __version__

constants = {}

for name in dir(binding):
    if name.startswith('IN_') or name == 'BUF_LEN':
        globals()[name] = constants[name] = getattr(binding, name)

init = binding.init
rm_watch = binding.rm_watch
add_watch = binding.add_watch

class InotifyEvent(object):
    '''
    InotifyEvent(wd, mask, cookie, name)

    A representation of the inotify_event structure.  See the inotify
    documentation for a description of these fields.
    '''

    wd = None
    mask = None
    cookie = None
    name = None

    def __init__(self, wd, mask, cookie, name):
        self.wd = wd
        self.mask = mask
        self.cookie = cookie
        self.name = name

    def __str__(self):
        return '%s: %s' % (self.wd, self.get_mask_description())

    def __repr__(self):
        return '%s(%s, %s, %s, %s)' % (
          self.__class__.__name__,
          repr(self.wd),
          repr(self.mask),
          repr(self.cookie),
          repr(self.name),
        )

    def get_mask_description(self):
        '''
        Return an ASCII string describing the mask field in terms of
        bitwise-or'd IN_* constants, or 0.  The result is valid Python code
        that could be eval'd to get the value of the mask field.  In other
        words, for a given event:

        >>> from inotifyx import *
        >>> assert (event.mask == eval(event.get_mask_description()))
        '''

        parts = []
        for name, value in list(constants.items()):
            if self.mask & value:
                parts.append(name)
        if parts:
            return '|'.join(parts)
        return '0'

def get_events(fd, *args):
    '''
    get_events(fd[, timeout])

    Return a list of InotifyEvent instances representing events read from
    inotify.  If timeout is None, this will block forever until at least one
    event can be read.  Otherwise, timeout should be an integer or float
    specifying a timeout in seconds.  If get_events times out waiting for
    events, an empty list will be returned.  If timeout is zero, get_events
    will not block.
    '''
    return [
      InotifyEvent(wd, mask, cookie, name)
      for wd, mask, cookie, name in binding.get_events(fd, *args)
    ]

if __name__ == '__main__':
    import sys

    if len(sys.argv) == 1:
        sys.stderr.write('usage: inotify path [path ...]')
        sys.exit(1)

    paths = sys.argv[1:]

    fd = init()

    wd_to_path = {}

    try:
        for path in paths:
            wd = add_watch(fd, path)
            wd_to_path[wd] = path

        try:
            while True:
                events = get_events(fd)
                for event in events:
                    path = wd_to_path[event.wd]
                    parts = [event.get_mask_description()]
                    if event.name:
                        parts.append(event.name)
                    print('%s: %s' % (path, ' '.join(parts)))
        except KeyboardInterrupt:
            pass

    finally:
        os.close(fd)


text:
* This MIT Legal Forum small group discussion focuses on **"Blockchain, Distributed Ledgers and Authoritative Systems"** in the context of law and legal processes.
* Discussion Group Page: [DiscussionGroups/Blockchain-Group.md](https://mitmedialab.github.io/MITLegalForum/DiscussionGroups/Blockchain-Group.html)

## Discussion Group on AI and Law

* This MIT Legal Forum small group discussion focuses on **"AI, Computational and Autonomous Systems"** in the context of law and legal processes.
* Discussion Group Page: [DiscussionGroups/AI-Group.md](https://mitmedialab.github.io/MITLegalForum/DiscussionGroups/AI-Group.html)

------------------------------------------

* **Back to the [MIT Legal Forum Information Page](https://mitmedialab.github.io/MITLegalForum)**