text:
/*
 * board.c
 * Ce fichier regroupe l'ensemble des fonctions
 * qui gèrent le plateau de jeu.
 *
 * Le plateau de jeu se présente comme une matrice de caractères de 15 lignes
 * par 19 colonnes (constantes ROWS et COLS).
 * Cette matrice est créée à partir d'un fichier map composé de caractères
 * correspondant à un certain type de case.
 *
 * Objectifs :
 *     -    Extraire les entités de la map
 *     -    Afficher le panel et le plateau
 */

#include "../lib/setup.h"

/**
 * Extrait les entités de la map.
 * @param board Le plateau de jeu
 * @param entityList La liste des entités extraites
 */
void extractEntities(char board[ROWS][COLS], Entity* entityList[ENTITY_MAX]) {
    unsigned short x, y;
    int count;
    Entity* entity = NULL;

    count = -1;

    for (x = 0; x < ROWS; x++) {
        for (y = 0; y < COLS; y++) {
            entity = NULL;

            switch (board[x][y]) {
                case ENEMY_CHAR:
                    if (board[x + 1][y] != THIN_CHAR && board[x - 1][y] != THIN_CHAR)
                        entity = createEnemy(x, y, RIGHT);
                    else
                        entity = createEnemy(x, y, UP);
                    count++;
                    break;
                case MOWER_CHAR:
                    entity = createMower(x, y);
                    count++;
                    break;
            }

            if (entity != NULL)
                entityList[count] = entity;
        }
    }
}

/**
 * Affiche les informations du jeu.
 * @param game L'état actuel du jeu
 */
void drawToolbar(const GameState* game) {
    goToXY(INFOPANEL_X, 0);
    printf("Niveau %2u\n", game->level);
    goToXY(INFOPANEL_X, 1);
    printf("Score %3u\n", game->score + game->levelScore);
}

/**
 * Affiche le temps de jeu.
 * @param game L'état du jeu
 */
void drawTime(GameState* game) {
    goToXY(INFOPANEL_X, 2);
    printf("Temps %3.0f\n", game->timePlayed + game->timeTmp);
}

/**
 * Affiche la légende du jeu.
 */
static void drawPanel() {
    setColor(GRAY_COLOR);

    goToXY(INFOPANEL_X, 4);
    setColor(getCaseColor(HERO_CHAR));
    printf("%c", convertCase(HERO_CHAR));
    setColor(GRAY_COLOR);
    printf(" %s\n", "Personnage");

    goToXY(INFOPANEL_X, 5);
    setColor(getCaseColor(WALL_CHAR));
    printf("%c", convertCase(WALL_CHAR));
    setColor(GRAY_COLOR);
    printf(" %s\n", "Mur");

    goToXY(INFOPANEL_X, 6);
    setColor(getCaseColor(DOOR_CHAR));
    printf("%c", convertCase(DOOR_CHAR));
    setColor(GRAY_COLOR);
    printf(" %s\n", "Porte de sortie");

    goToXY(INFOPANEL_X, 7);
    setColor(getCaseColor(THIN_CHAR));
    printf("%c", convertCase(THIN_CHAR));
    setColor(GRAY_COLOR);
    printf(" %s\n", "Glace fine");

    goToXY(INFOPANEL_X, 8);
    setColor(getCaseColor(THICK_CHAR));
    printf("%c", convertCase(THICK_CHAR));
    setColor(GRAY_COLOR);
    printf(" %s\n", "Glace epaisse");

    goToXY(INFOPANEL_X, 9);
    setColor(getCaseColor(SLIP_CHAR));
    printf("%c", convertCase(SLIP_CHAR));
    setColor(GRAY_COLOR);
    printf(" %s\n", "Glace glissante");

    goToXY(INFOPANEL_X, 10);
    setColor(getCaseColor(MELT_CHAR));
    printf("%c", convertCase(MELT_CHAR));
    setColor(GRAY_COLOR);
    printf(" %s\n", "Eau");

    goToXY(INFOPANEL_X, 11);
    setColor(getCaseColor(LIGHTNESS_POTION_CHAR));
    printf("%c", convertCase(LIGHTNESS_POTION_CHAR));
    setColor(GRAY_COLOR);
    printf(" %s\n", "Potion de legerete");

    goToXY(INFOPANEL_X, 12);
    setColor(getCaseColor(SCORE_BONUS_CHAR));
    printf("%c", convertCase(SCORE_BONUS_CHAR));
    setColor(GRAY_COLOR);
    printf(" %s\n", "Bonus de score");

    goToXY(INFOPANEL_X, 13);
    setColor(getCaseColor(TUNNEL_CHAR));
    printf("%c", convertCase(TUNNEL_CHAR));
    setColor(GRAY_COLOR);
    printf(" %s\n", "Tunnel");

    goToXY(INFOPANEL_X, 14);
    setColor(getCaseColor(MOWER_CHAR));
    printf("%c", convertCase(MOWER_CHAR));
    setColor(GRAY_COLOR);
    printf(" %s\n", "Tondeuse");

    goToXY(INFOPANEL_X, 15);
    setColor(getCaseColor(HOLE_CHAR));
    printf("%c", convertCase(HOLE_CHAR));
    setColor(GRAY_COLOR);
    printf(" %s\n", "Trou");

    goToXY(INFOPANEL_X, 16);
    setColor(getCaseColor(ENEMY_CHAR));
    printf("%c", convertCase(ENEMY_CHAR));
    setColor(GRAY_COLOR);
    printf(" %s\n", "Ennemi");

    goToXY(INFOPANEL_X, 18);
    printf("%s %4s\n", "(p)", "Pause");
    goToXY(INFOPANEL_X, 19);
    printf("%s %4s\n", "(r)", "Recommencer le niveau");
    goToXY(INFOPANEL_X, 20);
    printf("%s %2s\n", "(q)", "Quitter");

    resetColor();
}

/**
 * Dessine le plateau de jeu.
 * @param map Le fichier correspondant à la map
 * @param game L'état du jeu
 * @param board Le plateau à afficher
 */
void drawBoard(FILE* map, const GameState* game, char board[ROWS][COLS]) {
    unsigned short x, y;

    for (x = 0; x < ROWS; x++) {
        for (y = 0; y <= COLS; y++) {
            board[x][y] = fgetc(map);

            setColor(getCaseColor(board[x][y]));
            putchar(convertCase(board[x][y]));
        }
    }

    resetColor();

    drawToolbar(game);
    drawPanel();

    printf("\n");

    closeMap(map);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.cyrus.zhihudaily.activity.FavoriteActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar_favorite"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary"
        app:theme="@style/ToolbarStyle"
        app:title="收藏"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_favorite_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/toolbar_favorite"/>

    <TextView
        android:id="@+id/tv_tip"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/toolbar_favorite"
        android:gravity="center"
        android:text="@string/favorite_tip"
        android:textSize="20sp"
        android:visibility="gone"/>
</RelativeLayout>

redpajama_set_name: RedPajamaGithub


text: export function configureStaticApi(apiServerCreator: Function, port: number): void;


text:
import React, { Component, PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Splash.scss';
import {Button, Icon} from 'react-materialize';
import SVGIcon from '../../SVGIcon';

class Splash extends Component {

  scrollDown() {
    var n = $(window).height();
    $('html, body').animate({ scrollTop: n }, 800, 'easeInExpo');
  }

  render() {
    return (

            <Icon className={s.logo} large>invert_colors</Icon>

J.V. Estolas

Full Stack Web Developer

            <Button>AVAILABLE FOR HIRE</Button>

            Learn more about what I do

              <SVGIcon size="3.0rem" icon="keyboard-arrow-down" className={s.arrowIcon} fillColor="white" />

    );
  }

}

export default withStyles(Splash, s);


text:
package com.google.cloud.bigtable.hbase.tools;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.eq;

import com.google.cloud.bigtable.hbase.tools.ClusterSchemaDefinition.TableSchemaDefinition;
import com.google.cloud.bigtable.hbase.tools.HBaseSchemaTranslator.BigtableSchemaWriter;
import com.google.cloud.bigtable.hbase.tools.HBaseSchemaTranslator.FileBasedSchemaReader;
import com.google.cloud.bigtable.hbase.tools.HBaseSchemaTranslator.FileBasedSchemaWriter;
import com.google.cloud.bigtable.hbase.tools.HBaseSchemaTranslator.HBaseSchemaReader;
import com.google.cloud.bigtable.hbase.tools.HBaseSchemaTranslator.JsonBasedSchemaTransformer;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.exceptions.DeserializationException;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;

@RunWith(JUnit4.class)
public class HBaseSchemaTranslatorTest {

  @Mock private Admin btAdmin;

  @Mock private Admin hbaseAdmin;

  @Rule public MockitoRule initRule = MockitoJUnit.rule();

  @Rule public TemporaryFolder tempFolder = new TemporaryFolder();

  private final ClusterSchemaDefinition schemaDefinition;

  public HBaseSchemaTranslatorTest() {
    schemaDefinition = new ClusterSchemaDefinition();
    TableSchemaDefinition tableSchemaDefinition = new TableSchemaDefinition();
    tableSchemaDefinition.name = "test-table1";
    tableSchemaDefinition.splits = new byte[3][];
    tableSchemaDefinition.splits[0] = HConstants.EMPTY_BYTE_ARRAY;
    tableSchemaDefinition.splits[1] = "first-split".getBytes();
    tableSchemaDefinition.splits[2] = "second-split".getBytes();
    HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf("test-table1"));
    HColumnDescriptor columnDescriptor = new HColumnDescriptor("cf");
    columnDescriptor.setMaxVersions(2).setTimeToLive(1000);
    tableDescriptor.addFamily(columnDescriptor);
    tableSchemaDefinition.tableDescriptor = tableDescriptor.toByteArray();
    schemaDefinition.tableSchemaDefinitions.add(tableSchemaDefinition);

    TableSchemaDefinition tableSchemaDefinition2 = new TableSchemaDefinition();
    tableSchemaDefinition2.name = "test-table2";
    HTableDescriptor tableDescriptor2 = new HTableDescriptor(TableName.valueOf("test-table2"));
    HColumnDescriptor columnDescriptor2 = new HColumnDescriptor("cf");
    tableDescriptor2.addFamily(columnDescriptor2);
    tableSchemaDefinition2.splits = new byte[0][];
    tableSchemaDefinition2.tableDescriptor = tableDescriptor2.toByteArray();
    schemaDefinition.tableSchemaDefinitions.add(tableSchemaDefinition2);
  }

  private List<HRegionInfo> getRegions(int tableIndex) {
    List<HRegionInfo> regions = new ArrayList<>();

    TableSchemaDefinition tableSchemaDefinition =
        schemaDefinition.tableSchemaDefinitions.get(tableIndex);

    if (tableSchemaDefinition.splits == null || tableSchemaDefinition.splits.length == 0) {
      return regions;
    }

    TableName tableName =
        TableName.valueOf(schemaDefinition.tableSchemaDefinitions.get(tableIndex).name);
    byte[][] splits = schemaDefinition.tableSchemaDefinitions.get(tableIndex).splits;
    byte[] currentStart = splits[0];
    for (int i = 1; i < splits.length; i++) {
      byte[] currentEnd = splits[i];
      HRegionInfo regionInfo = new HRegionInfo(tableName, currentStart, currentEnd);
      regions.add(regionInfo);
      currentStart = currentEnd;
    }
    regions.add(new HRegionInfo(tableName, currentStart, HConstants.EMPTY_END_ROW));
    return regions;
  }

  private HTableDescriptor[] getTables() throws DeserializationException, IOException {
    HTableDescriptor[] tables =
        new HTableDescriptor[schemaDefinition.tableSchemaDefinitions.size()];
    for (int i = 0; i < schemaDefinition.tableSchemaDefinitions.size(); i++) {
      tables[i] = schemaDefinition.tableSchemaDefinitions.get(i).getHbaseTableDescriptor();
    }
    System.out.println("Created tables " + Arrays.asList(tables));
    return tables;
  }

  @After
  public void tearDown() throws Exception {
    Mockito.validateMockitoUsage();
    Mockito.reset(btAdmin, hbaseAdmin);
  }

  ///////////////////////////////////// Happy Cases ///////////////////////////////////////////////

  // These tests only validates that the object received from HBase is passed to Bigtable client.
  // The actual translation is performed by Bigtable HBase client and hence not validated here.
  @Test
  public void testTranslateFromHBaseToBigtable() throws IOException, DeserializationException {
    // Setup
    Mockito.when(hbaseAdmin.listTables(eq(".*"))).thenReturn(getTables());
    Mockito.when(hbaseAdmin.getTableRegions(eq(TableName.valueOf("test-table1"))))
        .thenReturn(getRegions(0));
    Mockito.when(hbaseAdmin.getTableRegions(eq(TableName.valueOf("test-table2"))))
        .thenReturn(getRegions(1));

    HBaseSchemaTranslator translator =
        new HBaseSchemaTranslator(
            new HBaseSchemaReader(hbaseAdmin, ".*"), new BigtableSchemaWriter(btAdmin));

    // Call
    translator.translate();

    // Verify
    Mockito.verify(btAdmin)
        .createTable(
            eq(schemaDefinition.tableSchemaDefinitions.get(0).getHbaseTableDescriptor()),
            // First split is EMPTY_BYTE_ARRAY which gets filtered as CBT does not support empty
            // splits.
            eq(Arrays.copyOfRange(schemaDefinition.tableSchemaDefinitions.get(0).splits, 1, 3)));
    Mockito.verify(btAdmin)
        .createTable(
            eq(schemaDefinition.tableSchemaDefinitions.get(1).getHbaseTableDescriptor()),
            eq(schemaDefinition.tableSchemaDefinitions.get(1).splits));
    Mockito.verify(hbaseAdmin).listTables(".*");
    Mockito.verify(hbaseAdmin).getTableRegions(TableName.valueOf("test-table1"));
    Mockito.verify(hbaseAdmin).getTableRegions(TableName.valueOf("test-table2"));
  }

  @Test
  public void testTranslateFromHBaseToBigtableWithTransformation()
      throws IOException, DeserializationException {
    // Setup
    Mockito.when(hbaseAdmin.listTables(eq("test.*"))).thenReturn(getTables());
    Mockito.when(hbaseAdmin.getTableRegions(eq(TableName.valueOf("test-table1"))))
        .thenReturn(getRegions(0));
    Mockito.when(hbaseAdmin.getTableRegions(eq(TableName.valueOf("test-table2"))))
        .thenReturn(getRegions(1));
    ArgumentCaptor<HTableDescriptor> tableCaptor = ArgumentCaptor.forClass(HTableDescriptor.class);

    Map<String, String> schemaMapping = new HashMap<>();
    schemaMapping.put("test-table1", "new-test-table1");
    // NO Op renaming
    schemaMapping.put("test-table2", "test-table2");
    // Not found in the schema, should get discarded.
    schemaMapping.put("test", "new-test");

    HBaseSchemaTranslator translator =
        new HBaseSchemaTranslator(
            new HBaseSchemaReader(hbaseAdmin, "test.*"),
            new BigtableSchemaWriter(btAdmin),
            new JsonBasedSchemaTransformer(schemaMapping));

    // Call
    translator.translate();

    // Verify
    Mockito.verify(btAdmin)
        .createTable(
            tableCaptor.capture(),
            // First split is EMPTY_BYTE_ARRAY which gets filtered as CBT does not support empty
            // splits.
            eq(Arrays.copyOfRange(schemaDefinition.tableSchemaDefinitions.get(0).splits, 1, 3)));
    Mockito.verify(btAdmin)
        .createTable(
            tableCaptor.capture(), eq(schemaDefinition.tableSchemaDefinitions.get(1).splits));
    HTableDescriptor transformedTable = tableCaptor.getAllValues().get(0);
    assertEquals("new-test-table1", transformedTable.getNameAsString());
    assertEquals("cf", transformedTable.getColumnFamilies()[0].getNameAsString());
    // Cloud Bigtable only uses the GC policies from HColumnFamily object
    assertEquals(2, transformedTable.getColumnFamilies()[0].getMaxVersions());
    assertEquals(1000, transformedTable.getColumnFamilies()[0].getTimeToLive());
    assertEquals(
        schemaDefinition.tableSchemaDefinitions.get(1).getHbaseTableDescriptor(),
        tableCaptor.getAllValues().get(1));

    Mockito.verify(hbaseAdmin).listTables("test.*");
    Mockito.verify(hbaseAdmin).getTableRegions(TableName.valueOf("test-table1"));
    Mockito.verify(hbaseAdmin).getTableRegions(TableName.valueOf("test-table2"));
  }

  @Test
  public void testTranslateHBaseToBigtableViaFile() throws IOException, DeserializationException {
    // Setup
    Mockito.when(hbaseAdmin.listTables(eq(".*"))).thenReturn(getTables());
    Mockito.when(hbaseAdmin.getTableRegions(eq(TableName.valueOf("test-table1"))))
        .thenReturn(getRegions(0));
    Mockito.when(hbaseAdmin.getTableRegions(eq(TableName.valueOf("test-table2"))))
        .thenReturn(getRegions(1));

    File schemaFile = tempFolder.newFile("schema.json");
    HBaseSchemaTranslator translator1 =
        new HBaseSchemaTranslator(
            new HBaseSchemaReader(hbaseAdmin, ".*"),
            new FileBasedSchemaWriter(schemaFile.getPath()));

    // call
    translator1.translate();

    HBaseSchemaTranslator translator2 =
        new HBaseSchemaTranslator(
            new FileBasedSchemaReader(schemaFile.getPath()), new BigtableSchemaWriter(btAdmin));

    translator2.translate();

    // Verify
    Mockito.verify(btAdmin)
        .createTable(
            eq(schemaDefinition.tableSchemaDefinitions.get(0).getHbaseTableDescriptor()),
            // First split is EMPTY_BYTE_ARRAY which gets filtered as CBT does not support empty
            // splits.
            eq(Arrays.copyOfRange(schemaDefinition.tableSchemaDefinitions.get(0).splits, 1, 3)));
    Mockito.verify(btAdmin)
        .createTable(
            eq(schemaDefinition.tableSchemaDefinitions.get(1).getHbaseTableDescriptor()),
            eq(schemaDefinition.tableSchemaDefinitions.get(1).splits));
    Mockito.verify(hbaseAdmin).listTables(".*");
    Mockito.verify(hbaseAdmin).getTableRegions(TableName.valueOf("test-table1"));
    Mockito.verify(hbaseAdmin).getTableRegions(TableName.valueOf("test-table2"));
  }

  ///////////////////////////////////// Exception Tests ///////////////////////////////////////////

  @Test
  public void testHBaseListTableFails() throws IOException {
    // Setup
    Mockito.when(hbaseAdmin.listTables(eq(".*"))).thenThrow(new IOException("List table failed"));

    HBaseSchemaTranslator translator =
        new HBaseSchemaTranslator(
            new HBaseSchemaReader(hbaseAdmin, ".*"), new BigtableSchemaWriter(btAdmin));

    // Call
    try {
      translator.translate();
      fail("Expected IOException here.");
    } catch (IOException e) {
      // Expected.
      e.printStackTrace();
    } catch (Exception e) {
      fail("Expected IOException but found: " + e.toString());
    } finally {
      // Verify
      Mockito.verify(hbaseAdmin).listTables(".*");
    }
  }

  @Test
  public void testHBaseGetTableRegionFails() throws IOException, DeserializationException {
    // Setup
    Mockito.when(hbaseAdmin.listTables(eq(".*"))).thenReturn(getTables());
    Mockito.when(hbaseAdmin.getTableRegions(eq(TableName.valueOf("test-table1"))))
        .thenThrow(new IOException("getTableRegions failed."));

    // Create a translator;
    HBaseSchemaTranslator translator =
        new HBaseSchemaTranslator(
            new HBaseSchemaReader(hbaseAdmin, ".*"), new BigtableSchemaWriter(btAdmin));
    // Call
    try {
      translator.translate();
      fail("Expected IOException here.");
    } catch (IOException e) {
      // Expected.
      e.printStackTrace();
    } catch (Exception e) {
      fail("Expected IOException but found: " + e.toString());
    } finally {
      // Verify
      Mockito.verify(hbaseAdmin).listTables(".*");
      Mockito.verify(hbaseAdmin).getTableRegions(TableName.valueOf("test-table1"));
    }
  }

  @Test
  public void testBigtableCreateTableFails() throws IOException, DeserializationException {
    // Setup
    Mockito.when(hbaseAdmin.listTables(eq(".*"))).thenReturn(getTables());
    Mockito.when(hbaseAdmin.getTableRegions(eq(TableName.valueOf("test-table1"))))
        .thenReturn(getRegions(0));
    Mockito.when(hbaseAdmin.getTableRegions(eq(TableName.valueOf("test-table2"))))
        .thenReturn(getRegions(1));

    Mockito.doThrow(new IOException("CBT create table failed."))
        .when(btAdmin)
        .createTable(
            eq(schemaDefinition.tableSchemaDefinitions.get(0).getHbaseTableDescriptor()),
            // First split is EMPTY_BYTE_ARRAY which gets filtered as CBT does not support empty
            // splits.
            eq(Arrays.copyOfRange(schemaDefinition.tableSchemaDefinitions.get(0).splits, 1, 3)));

    HBaseSchemaTranslator translator =
        new HBaseSchemaTranslator(
            new HBaseSchemaReader(hbaseAdmin, ".*"), new BigtableSchemaWriter(btAdmin));

    // Call
    try {
      translator.translate();
      fail("Expected IOException here.");
    } catch (RuntimeException e) {
      // Expected.
      e.printStackTrace();
    } catch (Exception e) {
      fail("Expected IOException but found: " + e.toString());
    } finally {
      // Verify
      Mockito.verify(btAdmin)
          .createTable(
              eq(schemaDefinition.tableSchemaDefinitions.get(0).getHbaseTableDescriptor()),
              // First split is EMPTY_BYTE_ARRAY which gets filtered as CBT does not support empty
              // splits.
              eq(Arrays.copyOfRange(schemaDefinition.tableSchemaDefinitions.get(0).splits, 1, 3)));
      // Validate that translator calls createTable for  test-table-2 even after creation of
      // test-table1 failed.
      Mockito.verify(btAdmin)
          .createTable(
              eq(schemaDefinition.tableSchemaDefinitions.get(1).getHbaseTableDescriptor()),
              eq(schemaDefinition.tableSchemaDefinitions.get(1).splits));
      Mockito.verify(hbaseAdmin).listTables(".*");
      Mockito.verify(hbaseAdmin).getTableRegions(TableName.valueOf("test-table1"));
      Mockito.verify(hbaseAdmin).getTableRegions(TableName.valueOf("test-table2"));
    }
  }

  @Test
  public void testHBaseSchemaTranslatorCreationFails()
      throws IOException, DeserializationException {
    // Setup
    File schemaFile = tempFolder.newFile("schema.json");
    FileWriter fileWriter = new FileWriter(schemaFile.getPath());
    fileWriter.write("{This is invalid JSON}");

    // Try creating the schema translator with invalid JSON, expect it to fail.
    try {
      HBaseSchemaTranslator translator =
          new HBaseSchemaTranslator(
              new HBaseSchemaReader(hbaseAdmin, ".*"),
              new BigtableSchemaWriter(btAdmin),
              JsonBasedSchemaTransformer.newSchemaTransformerFromJsonFile(schemaFile.getPath()));
      fail("Expected IOException here.");
    } catch (IllegalStateException e) {
      // Expected.
    } catch (Exception e) {
      fail("Expected DeserializationException but found: " + e.toString());
    }
  }
}


text:
test_cases = gets.chomp.to_i
test_cases.times do |test|
  slices = gets.chomp.to_i
  horizontal_slices = slices / 2
  vertical_slices = slices - horizontal_slices
  puts vertical_slices * horizontal_slices
end


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:bottom="20dp">
		<shape android:shape="rectangle">
		    <corners android:radius="2dp" />
		    <solid android:color="#3000" />
		    <size
		        android:width="25dp"
		        android:height="5dp" />
		</shape>
    </item>

    <item android:top="10dp" android:bottom="10dp">
        <shape android:shape="rectangle">
            <corners android:radius="2dp" />
            <solid android:color="#3000" />
            <size
                android:width="25dp"
                android:height="5dp" />
        </shape>
    </item>

    <item android:top="20dp">
        <shape android:shape="rectangle">
            <corners android:radius="2dp" />
            <solid android:color="#3000" />
            <size
                android:width="25dp"
                android:height="5dp" />
        </shape>
    </item>
</layer-list>


text:
function Get-DbaUserPermission {
    <#
    .SYNOPSIS
        Displays detailed permissions information for the server and database roles and securables.

    .DESCRIPTION
        This command will display all server logins, server level securables, database logins and database securables.

        DISA STIG implementators will find this command useful as it uses Permissions.sql provided by DISA.

        Note that if you Ctrl-C out of this command and end it prematurely, it will leave behind a STIG schema in tempdb.

    .PARAMETER SqlInstance
        The target SQL Server instance or instances.

    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).

        Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.

        For MFA support, please use Connect-DbaInstance.

    .PARAMETER Database
        The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
        The database(s) to exclude - this list is auto-populated from the server

    .PARAMETER ExcludeSystemDatabase
        Allows you to suppress output on system databases

    .PARAMETER IncludePublicGuest
        Allows you to include output for public and guest grants.

    .PARAMETER IncludeSystemObjects
        Allows you to include output on sys schema objects.

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Discovery, Permissions, Security
        Author: Brandon Abshire, netnerds.net

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Get-DbaUserPermission

    .EXAMPLE
        PS C:\> Get-DbaUserPermission -SqlInstance sql2008, sqlserver2012

        Check server and database permissions for servers sql2008 and sqlserver2012.

    .EXAMPLE
        PS C:\> Get-DbaUserPermission -SqlInstance sql2008 -Database TestDB

        Check server and database permissions on server sql2008 for only the TestDB database

    .EXAMPLE
        PS C:\> Get-DbaUserPermission -SqlInstance sql2008 -Database TestDB -IncludePublicGuest -IncludeSystemObjects

        Check server and database permissions on server sql2008 for only the TestDB database,
        including public and guest grants, and sys schema objects.

    #>
    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$ExcludeSystemDatabase,
        [switch]$IncludePublicGuest,
        [switch]$IncludeSystemObjects,
        [switch]$EnableException
    )

    begin {
        $endSQL = "	   BEGIN TRY DROP FUNCTION STIG.server_effective_permissions END TRY BEGIN CATCH END CATCH;
                       GO
                       BEGIN TRY DROP VIEW STIG.server_permissions END TRY BEGIN CATCH END CATCH;
                       GO
                       BEGIN TRY DROP FUNCTION STIG.members_of_server_role END TRY BEGIN CATCH END CATCH;
                       GO
                       BEGIN TRY DROP FUNCTION STIG.server_roles_of END TRY BEGIN CATCH END CATCH;
                       GO
                       BEGIN TRY DROP VIEW STIG.server_role_members END TRY BEGIN CATCH END CATCH;
                       GO
                       BEGIN TRY DROP FUNCTION STIG.database_effective_permissions END TRY BEGIN CATCH END CATCH;
                       GO
                       BEGIN TRY DROP VIEW STIG.database_permissions END TRY BEGIN CATCH END CATCH;
                       GO
                       BEGIN TRY DROP FUNCTION STIG.members_of_db_role END TRY BEGIN CATCH END CATCH;
                       GO
                       BEGIN TRY DROP FUNCTION STIG.database_roles_of END TRY BEGIN CATCH END CATCH;
                       GO
                       BEGIN TRY DROP VIEW STIG.database_role_members END TRY BEGIN CATCH END CATCH;
                       GO
                       BEGIN TRY DROP SCHEMA STIG END TRY BEGIN CATCH END CATCH;
                       GO"

        $serverSQL = "SELECT  'SERVER LOGINS' AS Type ,
                                    sl.name AS Member ,
                                    ISNULL(srm.Role, 'None') AS [Role/Securable/Class] ,
                                    ' ' AS [Schema/Owner] ,
                                    ' ' AS [Securable] ,
                                    ' ' AS [Grantee Type] ,
                                    ' ' AS [Grantee] ,
                                    ' ' AS [Permission] ,
                                    ' ' AS [State] ,
                                    ' ' AS [Grantor] ,
                                    ' ' AS [Grantor Type] ,
                                    ' ' AS [Source View]
                            FROM    master.sys.syslogins sl
                                    LEFT JOIN tempdb.[STIG].[server_role_members] srm ON sl.name = srm.Member
                            WHERE   sl.name NOT LIKE 'NT %'
                                    AND sl.name NOT LIKE '##%'
                            UNION
                            SELECT  'SERVER SECURABLES' AS Type ,
                                    sl.name ,
                                    sp.[Securable Class] COLLATE SQL_Latin1_General_CP1_CI_AS ,
                                    ' ' ,
                                    sp.[Securable] ,
                                    sp.[Grantee Type] COLLATE SQL_Latin1_General_CP1_CI_AS ,
                                    sp.Grantee ,
                                    sp.Permission COLLATE SQL_Latin1_General_CP1_CI_AS ,
                                    sp.State COLLATE SQL_Latin1_General_CP1_CI_AS ,
                                    sp.Grantor ,
                                    sp.[Grantor Type] COLLATE SQL_Latin1_General_CP1_CI_AS ,
                                    sp.[Source View]
                            FROM    master.sys.syslogins sl
                                    LEFT JOIN tempdb.[STIG].[server_permissions] sp ON sl.name = sp.Grantee
                            WHERE   sl.name NOT LIKE 'NT %'
                                    AND sl.name NOT LIKE '##%';"

        $dbSQL = "SELECT  'DB ROLE MEMBERS' AS type ,
                                Member ,
                                ISNULL(Role, 'None') AS [Role/Securable/Class],
                                ' ' AS [Schema/Owner] ,
                                ' ' AS [Securable] ,
                                ' ' AS [Grantee Type] ,
                                ' ' AS [Grantee] ,
                                ' ' AS [Permission] ,
                                ' ' AS [State] ,
                                ' ' AS [Grantor] ,
                                ' ' AS [Grantor Type] ,
                                ' ' AS [Source View]
                        FROM    tempdb.[STIG].[database_role_members]
                        UNION
                        SELECT DISTINCT
                                'DB SECURABLES' AS Type ,
                                ISNULL(drm.member, 'None') AS [Role/Securable/Class] ,
                                dp.[Securable Type or Class] COLLATE SQL_Latin1_General_CP1_CI_AS ,
                                dp.[Schema/Owner] ,
                                dp.Securable ,
                                dp.[Grantee Type] COLLATE SQL_Latin1_General_CP1_CI_AS ,
                                dp.Grantee ,
                                dp.Permission COLLATE SQL_Latin1_General_CP1_CI_AS ,
                                dp.State COLLATE SQL_Latin1_General_CP1_CI_AS ,
                                dp.Grantor ,
                                dp.[Grantor Type] COLLATE SQL_Latin1_General_CP1_CI_AS ,
                                dp.[Source View]
                        FROM    tempdb.[STIG].[database_role_members] drm
                                FULL JOIN tempdb.[STIG].[database_permissions] dp ON ( drm.Member = dp.Grantee
                                                                                OR drm.Role = dp.Grantee
                                                                                )
                        WHERE	dp.Grantor IS NOT NULL
                                AND dp.Grantee NOT IN ('public', 'guest')
                                AND [Schema/Owner] <> 'sys'"

        if ($IncludePublicGuest) { $dbSQL = $dbSQL.Replace("AND dp.Grantee NOT IN ('public', 'guest')", "") }
        if ($IncludeSystemObjects) { $dbSQL = $dbSQL.Replace("AND [Schema/Owner] <> 'sys'", "") }

    }

    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-DbaInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 10 -AzureUnsupported
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $dbs = $server.Databases
            $tempdb = $server.Databases['tempdb']

            if ($Database) {
                $dbs = $dbs | Where-Object { $Database -contains $_.Name }
            }

            if ($ExcludeDatabase) {
                $dbs = $dbs | Where-Object Name -NotIn $ExcludeDatabase
            }

            if ($ExcludeSystemDatabase) {
                $dbs = $dbs | Where-Object IsSystemObject -eq $false
            }

            #reset $serverDT
            $serverDT = $null

            foreach ($db in $dbs) {
                Write-Message -Level Verbose -Message "Processing $db on $instance"

                $db.ExecuteNonQuery($endSQL)

                if ($db.IsAccessible -eq $false) {
                    Stop-Function -Message "The database $db is not accessible" -Continue
                }

                $sqlFile = Join-Path -Path $script:PSModuleRoot -ChildPath "bin\stig.sql"
                $sql = [System.IO.File]::ReadAllText("$sqlFile")
                $sql = $sql.Replace("<TARGETDB>", $db.Name)

                #Create objects in active database
                Write-Message -Level Verbose -Message "Creating objects"
                try {
                    $db.ExecuteNonQuery($sql)
                } catch {
                    # here to avoid an empty catch
                    $null = 1
                } # sometimes it complains about not being able to drop the stig schema if the person Ctrl-C'd before.

                #Grab permissions data
                if (-not $serverDT) {
                    Write-Message -Level Verbose -Message "Building data table for server objects"

                    try {
                        $serverDT = $db.Query($serverSQL)
                    } catch {
                        # here to avoid an empty catch
                        $null = 1
                    }

                    foreach ($row in $serverDT) {
                        [PSCustomObject]@{
                            ComputerName       = $server.ComputerName
                            InstanceName       = $server.ServiceName
                            SqlInstance        = $server.DomainInstanceName
                            Object             = 'SERVER'
                            Type               = $row.Type
                            Member             = $row.Member
                            RoleSecurableClass = $row.'Role/Securable/Class'
                            SchemaOwner        = $row.'Schema/Owner'
                            Securable          = $row.Securable
                            GranteeType        = $row.'Grantee Type'
                            Grantee            = $row.Grantee
                            Permission         = $row.Permission
                            State              = $row.State
                            Grantor            = $row.Grantor
                            GrantorType        = $row.'Grantor Type'
                            SourceView         = $row.'Source View'
                        }
                    }
                }

                Write-Message -Level Verbose -Message "Building data table for $db objects"
                try {
                    $dbDT = $db.Query($dbSQL)
                } catch {
                    # here to avoid an empty catch
                    $null = 1
                }

                foreach ($row in $dbDT) {
                    [PSCustomObject]@{
                        ComputerName       = $server.ComputerName
                        InstanceName       = $server.ServiceName
                        SqlInstance        = $server.DomainInstanceName
                        Object             = $db.Name
                        Type               = $row.Type
                        Member             = $row.Member
                        RoleSecurableClass = $row.'Role/Securable/Class'
                        SchemaOwner        = $row.'Schema/Owner'
                        Securable          = $row.Securable
                        GranteeType        = $row.'Grantee Type'
                        Grantee            = $row.Grantee
                        Permission         = $row.Permission
                        State              = $row.State
                        Grantor            = $row.Grantor
                        GrantorType        = $row.'Grantor Type'
                        SourceView         = $row.'Source View'
                    }
                }

                #Delete objects
                Write-Message -Level Verbose -Message "Deleting objects"
                try {
                    $tempdb.ExecuteNonQuery($endSQL)
                } catch {
                    # here to avoid an empty catch
                    $null = 1
                }
                #Sashay Away
            }
        }
    }
}


text: int internal_api(int, void*, char*);


text:
The Configuration Engine
========================

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

In the previous versions of ASP .NET, any configuration setting or parameter you needed was added in `web.config` [(complete description of the old `web.config` file)](http://www.codeproject.com/Articles/301726/Web-config-File-ASP-NET), or added in a separate XML file and referenced in `web.config` (for scenarios like database connection strings, or storing APIs access tokens).

The new configuration system provides support for JSON, XML and INI, while also allowing you to [create your custom configuration provider](https://docs.asp.net/en/latest/fundamentals/configuration.html#custom-config-providers) and for in-memory configuration.

> For a detailed view of ASP .NET Core Configuration system, read the [Official ASP .NET Documentation](https://docs.asp.net/en/latest/fundamentals/configuration.html).

[In the tutorial about Routing](https://radu-matei.github.io/blog/aspnet-core-routing/), we created a very simple web application that used the Routing service to respond to some requests, but they were hardcoded and if we wanted to change the response message, we would have had to recompile the entire application.
> For more information about Routing, check the [ASP .NET Core Routing Tutorial](https://radu-matei.github.io/blog/aspnet-core-routing/).

Let's assume that in our application we want the response messages not to be hardcoded in `Startup` anymore, but stored in a configuration file so we don't have to stop, modify or recompile our application every time the messages or the routes change.

More clearly, we want to map the keys from the JSON file below as routes and the values as the responses we want our application to give, so when a user browses in our application to `/some-route`, if `some-route` is present in the JSON configuration file, then the response will be the value from the file, if else to display a default message.

```
{
    "hi": "Hi!",
    "hello": "Hello!",
    "bye": "Goodbye!",
    "default": "This is default!"
}
```

Also, if we modify the configuration file while the application is running, our application should be able to use the latest configuration. (We don't actually do much here, it's just a constructor parameter we set to `true` or `false`).

There can be any number of defined paths in our configuration file and they can change with any frequency (so that hard-coding them in our application is not an option).

Using the ASP .NET Core JSON Configuration Provider
----------------------------------------------------

As we said earlier, the new ASP .NET implements a JSON configuration provider that allows us to read and use configurations from JSON files (and not only), and we can have strong typing (where we define classes for our configuration settings) or we can access them using directly their key.

> For a complete article on creating [Strongly Typed Configuration Settings in ASP .NET Core, see this article by Rick Strahl](https://weblog.west-wind.com/posts/2016/May/23/Strongly-Typed-Configuration-Settings-in-ASPNET-Core).

To use configuration settings in ASP .NET Core, simply instantiate a `Configuration` object (using a `ConfigurationBuilder`)  and indicate the source of the JSON file.

> At its simplest, `Configuration` is just a collection of sources, which provide the ability to read and write name/value pairs. If a name/value pair is written to Configuration, it is not persisted. This means that the written value will be lost when the sources are read again.

> Developers are not limited to using a single configuration source. In fact several may be set up together such that a default configuration is overridden by settings from another source if they are present.

> [The Official ASP .NET Core Documentation](https://docs.asp.net/en/latest/fundamentals/configuration.html#using-the-built-in-sources)

Because at the time when we write the application we can't know the exact paths, we will not create stronyly-typed configurations but we will take the path from our application an check to see wether that path exists in our configuration file.

Building the configurable Greeting service
------------------------------------------

First of all, [follow all the steps in order to create an ASP .NET Core application with a `Startup` class from this tutorial](https://radu-matei.github.io/blog/aspnet-core-startup/), that means:

- create new app using `dotnet new`
- add the ` "Microsoft.AspNetCore.Server.Kestrel": "1.0.1"` NuGet package
- add an empty `Startup` class

Then, we create a new file, `greetings.json` in the same folder as our `Program.cs`, `Startup.cs` and `project.json` files, where we add our custom routes and messages we want our application to respond with.

```
{
    "hi": "Hi!",
    "hello": "Hello!",
    "bye": "Goodbye!",
    "default": "This is default!"
}
```
Now we need to add another NuGet package, `"Microsoft.Extensions.Configuration.Json": "1.0.1"` that will contain the necessary methods for using JSON files as configuration.

In `Startup` we create a property of type `IConfiguration` where we will keep our configuration files: `public IConfiguration Configuration { get;set; }`

Then, we add a constructor for the `Startup` class that will instantiate a `ConfigurationBuilder` that will actually get the configuration information in our `Configuration` property.

```
    public Startup(IHostingEnvironment env)
    {
        var configurationBuilder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("greetings.json", optional: false, reloadOnChange: true);

        Configuration = configurationBuilder.Build();
    }
```

> The constructor has an `IHostingEnvironment` parameter that is used to establish the directory of the `json` configuration file. Since we placed it in the same folder as the other files, we can simply get the current directory: `Directory.GetCurrentDirectory()`.

After we instantiate the `ConfigurationBuilder` we chain two method calls - one for establishing the directory of the configuration file, the other for determing the actual name of the file.

The `.AddJsonFile()` method takes three arguments in this case:

- the name of the file - in our case `greetings.json`
- a `bool` that determines wether this configuration file is optional or not, used to determine the order in which the system searches the files (if there are multiple files) if the same configuration name exists in multiple files.
- a `bool` that specifies what happens if the configuration file is modified while the application is running - `reloadOnChange`
After this, we set our `Configuration` property to what the `configurationBuilder` "builds".

The next step is to add the "`Microsoft.AspNetCore.Routing": "1.0.0"` package in `project.json`, create the `Configure` method in `Startup` and add the routing service.

```
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRouting();
    }
```

> As you write code in Visual Studio or Visual Studio Code, you can press Ctrl + . (period) to show suggestions for errors (like adding `using` statements for you).

Then, we create the `Configure` method where we will hook up incoming requests and map them with the routes from our configuration file.

```
    public void Configure(IApplicationBuilder app)
    {
        var routeBuilder = new RouteBuilder(app);

        routeBuilder.MapGet("{route}", context =>
        {
            var routeMessage = Configuration.AsEnumerable()
                .FirstOrDefault(r => r.Key == context.GetRouteValue("route")
                .ToString())
                .Value;

            var defaultMessage = Configuration.AsEnumerable()
                .FirstOrDefault(r => r.Key == "default")
                .Value;

            var response = (routeMessage != null) ? routeMessage : defaultMessage;

            return context.Response.WriteAsync(response);
        });

        app.UseRouter(routeBuilder.Build());
    }
```

We create a new `RouteBuilder` and map a new GET `route` in [the same way as in this article](https://radu-matei.github.io/blog/aspnet-core-routing/).

```
            var routeMessage = Configuration.AsEnumerable()
                .FirstOrDefault(r => r.Key == context.GetRouteValue("route")
                .ToString())
                .Value;
```

We know that our configuration is now accessible through the `Configuration` property that we populated in the `Startup` constructor, and the configuration settings are an `IEnumerable<KeyValuePair<string, string>>`, that is a collection of key-value pairs of strings, so we can use Linq to search for the key-value pair in our file that has the same key as our path and take the value from that pair.

> For some examples of using Linq with lambdas [check this article from Code Magazine](http://www.codemag.com/article/1001051).

We also search for the default message in our JSON so that if the path does not exist in the file, we have a standard respone.

```
            var defaultMessage = Configuration.AsEnumerable()
                .FirstOrDefault(r => r.Key == "default")
                .Value;
```

Then, depending on wether the route actually exists in our configuration file or not, we return either the message of that specific route, or the default message.

If we run the application and open a browser, we can check if our routing works:

```
http://localhost:5000/hello - This should display Hello!
http://localhost:5000/hi - This should display Hi!
http://localhost:5000/bye - This should display Goodbye!
http://localhost:5000/default or http://localhost:5000/anything-else - This should display This is default!
```

Without closing the application, go to `greeting.json` and either add a new key-value pair, or modify an existing one's value, save the file and navigate to that path.

Normally, you should see that our application was able to load the configuration file without restarting or recompiling.

> Our application works, but there is a lot of logic code in `Startup`, a place for configuration.
> [In the next article, we will use the dependency injection engine and extract the code from startup, make a service out of it and inject it in our application.](configuration-dependency-injection.md)


text:
package com.cnnranderson.yotzy.injection.components;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

import javax.inject.Scope;

@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface PerActivity {
}


text:
@interface GRMustacheFilterTestSupport: NSObject<GRMustacheFilter>
@end

@implementation GRMustacheFilterTestSupport

- (id)transformedValue:(id)object
{
    return object;
}

- (NSString *)test
{
    return @"failure";
}

@end

@interface GRMustacheFilterTest : GRMustachePublicAPITest
@end

@implementation GRMustacheFilterTest

- (void)testFilterCanChain
{
    id data = @{
        @"name" : @"Name",
        @"uppercase": [GRMustacheFilter filterWithBlock:^id(id value) {
            return [[value description] uppercaseString];
        }],
        @"prefix": [GRMustacheFilter filterWithBlock:^id(id value) {
            return [NSString stringWithFormat:@"prefix%@", [value description]];
        }],
    };

    NSString *templateString = @"<{{name}}> <{{prefix(name)}}> <{{uppercase(name)}}> <{{prefix(uppercase(name))}}> <{{uppercase(prefix(name))}}>";
    NSString *rendering = [[GRMustacheTemplate templateFromString:templateString error:NULL] renderObject:data error:NULL];
    XCTAssertEqualObjects(rendering, @"<Name> <prefixName> <NAME> <prefixNAME> <PREFIXNAME>");
}

- (void)testScopedValueAreExtractedOutOfAFilterExpression
{
    NSString *templateString = @"<{{f(object).name}}> {{#f(object)}}<{{name}}>{{/f(object)}}";
    GRMustacheTemplate *template = [GRMustacheTemplate templateFromString:templateString error:NULL];

    {
        id data = @{
            @"object" : @{
                @"name": @"objectName",
            },
            @"name": @"rootName",
            @"f": [GRMustacheFilter filterWithBlock:^id(id value) {
                return value;
            }],
        };
        NSString *rendering = [template renderObject:data error:NULL];
        XCTAssertEqualObjects(rendering, @"<objectName> <objectName>");
    }

    {
        id data = @{
            @"object" : @{
                @"name": @"objectName",
            },
            @"name": @"rootName",
            @"f": [GRMustacheFilter filterWithBlock:^id(id value) {
                return @{ @"name": @"filterName" };
            }],
        };
        NSString *rendering = [template renderObject:data error:NULL];
        XCTAssertEqualObjects(rendering, @"<filterName> <filterName>");
    }

    {
        id data = @{
            @"object" : @{
                @"name": @"objectName",
            },
            @"name": @"rootName",
            @"f": [GRMustacheFilter filterWithBlock:^id(id value) {
                return @{};
            }],
        };
        NSString *rendering = [template renderObject:data error:NULL];
        XCTAssertEqualObjects(rendering, @"<> <rootName>");
    }
}

- (void)testFilteredSectionClosingTagCanHaveDifferentWhiteSpaceThanSectionOpeningTag
{
    NSString *templateString = @"{{#a(b)}}{{/ \t\na \t\n( \t\nb \t\n) \t\n}}";
    GRMustacheTemplate *template = [GRMustacheTemplate templateFromString:templateString error:NULL];
    XCTAssertNotNil(template);
}

- (void)testFilteredSectionClosingTagCanBeBlank
{
    NSString *templateString = @"<{{#uppercase(.)}}{{.}}{{/}}> <{{#uppercase(.)}}{{.}}{{/ }}>";
    GRMustacheTemplate *template = [GRMustacheTemplate templateFromString:templateString error:NULL];
    XCTAssertNotNil(template);
    NSString *rendering = [template renderObject:@"foo" error:NULL];
    XCTAssertEqualObjects(rendering, @"<FOO> <FOO>");
}

- (void)testFilteredSectionClosingTagCanNotBeInvalid
{
    NSString *templateString = @"<{{#uppercase(.)}}{{.}}{{/uppercase(.}}>";
    NSError *error;
    XCTAssertNil([GRMustacheTemplate templateFromString:templateString error:&error]);
    XCTAssertEqual(error.code, (NSInteger)GRMustacheErrorCodeParseError);
}

- (void)testFilterArgumentsDoNotEnterSectionContextStack
{
    id data = @{
        @"test": @"success",
        @"filtered": @{
            @"test": @"failure",
        },
        @"filter": [GRMustacheFilter filterWithBlock:^id(id value) {
            return @"filter";
        }],
    };
    NSString *templateString = @"{{#filter(filtered)}}<{{test}} instead of {{#filtered}}{{test}}{{/filtered}}>{{/filter(filtered)}}";
    NSString *rendering = [[GRMustacheTemplate templateFromString:templateString error:NULL] renderObject:data error:NULL];
    XCTAssertEqualObjects(rendering, @"<success instead of failure>");
}

- (void)testFilterNameSpace
{
    id data = @{
        @"x": @(0.5),
        @"math": @{
            @"double": [GRMustacheFilter filterWithBlock:^id(id value) {
                return @(2 * [(NSNumber *)value doubleValue]);
            }],
        },
    };
    NSString *rendering = [[GRMustacheTemplate templateFromString:@"{{ math.double(x) }}" error:NULL] renderObject:data error:NULL];
    XCTAssertEqualObjects(rendering, @"1");
}

- (void)testFiltersCanReturnFilters
{
    id data = @{
        @"prefix": @"prefix",
        @"value": @"value",
        @"f": [GRMustacheFilter filterWithBlock:^id(id value1) {
            return [GRMustacheFilter filterWithBlock:^id(id value2) {
                return [NSString stringWithFormat:@"%@%@", value1, value2];
            }];
        }],
    };
    NSString *rendering = [[GRMustacheTemplate templateFromString:@"{{f(prefix)(value)}}" error:NULL] renderObject:data error:NULL];
    XCTAssertEqualObjects(rendering, @"prefixvalue", @"");
}

- (void)testImplicitIteratorCanReturnFilter
{
    {
        id data = [GRMustacheFilter filterWithBlock:^id(id value) { return @"filter"; }];
        NSString *rendering = [[GRMustacheTemplate templateFromString:@"{{.(a)}}" error:NULL] renderObject:data error:NULL];
        XCTAssertEqualObjects(rendering, @"filter", @"");
    }
    {
        id data = @{ @"f": [GRMustacheFilter filterWithBlock:^id(id value) { return @"filter"; }] };
        NSString *rendering = [[GRMustacheTemplate templateFromString:@"{{.f(a)}}" error:NULL] renderObject:data error:NULL];
        XCTAssertEqualObjects(rendering, @"filter", @"");
    }
}

- (void)testImplicitIteratorCanBeVariadicFilterArgument
{
    id data = @{
        @"f": [GRMustacheFilter variadicFilterWithBlock:^id(NSArray *arguments) {
            NSMutableString *buffer = [NSMutableString string];
            for (NSDictionary *dictionary in arguments) {
                [buffer appendFormat:@"%d", (int)[dictionary count]];
            }
            return buffer;
        }],
        @"foo": @{ @"a":@"a", @"b":@"b", @"c":@"c" },
    };
    NSString *rendering = [[GRMustacheTemplate templateFromString:@"{{f(foo,.)}} {{f(.,foo)}}" error:NULL] renderObject:data error:NULL];
    XCTAssertEqualObjects(rendering, @"32 23", @"");
}

- (void)testMissingFilterError
{
    id data = @{
                @"name": @"Name",
                @"replace": [GRMustacheFilter filterWithBlock:^id(id value) {
                    return @"replace";
                }],
                };

    {
        GRMustacheTemplate *template = [GRMustacheTemplate templateFromString:@"<{{missing(missing)}}>" error:NULL];
        XCTAssertNotNil(template, @"");
        NSError *error;
        NSString *rendering = [template renderObject:data error:&error];
        XCTAssertNil(rendering, @"WTF");
        XCTAssertEqualObjects(error.domain, GRMustacheErrorDomain, @"");
        XCTAssertEqual(error.code, GRMustacheErrorCodeRenderingError, @"");
    }
    {
        GRMustacheTemplate *template = [GRMustacheTemplate templateFromString:@"<{{missing(name)}}>" error:NULL];
        XCTAssertNotNil(template, @"");
        NSError *error;
        NSString *rendering = [template renderObject:data error:&error];
        XCTAssertNil(rendering, @"WTF");
        XCTAssertEqualObjects(error.domain, GRMustacheErrorDomain, @"");
        XCTAssertEqual(error.code, GRMustacheErrorCodeRenderingError, @"");
    }
    {
        GRMustacheTemplate *template = [GRMustacheTemplate templateFromString:@"<{{replace(missing(name))}}>" error:NULL];
        XCTAssertNotNil(template, @"");
        NSError *error;
        NSString *rendering = [template renderObject:data error:&error];
        XCTAssertNil(rendering, @"WTF");
        XCTAssertEqualObjects(error.domain, GRMustacheErrorDomain, @"");
        XCTAssertEqual(error.code, GRMustacheErrorCodeRenderingError, @"");
    }
    {
        GRMustacheTemplate *template = [GRMustacheTemplate templateFromString:@"<{{missing(replace(name))}}>" error:NULL];
        XCTAssertNotNil(template, @"");
        NSError *error;
        NSString *rendering = [template renderObject:data error:&error];
        XCTAssertNil(rendering, @"WTF");
        XCTAssertEqualObjects(error.domain, GRMustacheErrorDomain, @"");
        XCTAssertEqual(error.code, GRMustacheErrorCodeRenderingError, @"");
    }
}

- (void)testNotAFilterError
{
    id data = @{
                @"name": @"Name",
                @"filter": @"filter",
                };

    GRMustacheTemplate *template = [GRMustacheTemplate templateFromString:@"<{{filter(name)}}>" error:NULL];
    XCTAssertNotNil(template, @"");
    NSError *error;
    NSString *rendering = [template renderObject:data error:&error];
    XCTAssertNil(rendering, @"WTF");
    XCTAssertEqualObjects(error.domain, GRMustacheErrorDomain, @"");
    XCTAssertEqual(error.code, GRMustacheErrorCodeRenderingError, @"");
}

@end


text:
main(WScript.Arguments, WScript.Arguments.Count());

/////////////////////////////////////////////////////////////////////////////
// Global Declarations

var objSession;

/////////////////////////////////////////////////////////////////////////////
// Description: Parses the command line parameters and validates the usage.
//
function main(args, cArgs)
{
  // Validate the command line arguments
  if (0 > cArgs || cArgs > 2)
    return Syntax();

  // Get the specified behavior type
  var strBehavior = (2 == cArgs) ? args(1) : "Default";

  // Create the utility object
  var objUtil = new ActiveXObject("TCUtil");

  // Create the Session Information object
  //var objInfo = new ActiveXObject("Pigs.SessionInfo");
  //objInfo.ApplicationName = WScript.ScriptFullName;

  // Connect to the Pig Server on the specified machine
  objSession = objUtil.CreateObject("Pigs.Session", args(0));
  //objSession.SessionInfo = objInfo;

  // Create a single pig
  WScript.Echo("Creating a pig with the '" + strBehavior + "' behavior...");
  var objPig = objSession.CreatePig(strBehavior);

  WScript.Echo("1 pig named \"" + objPig + "\" created.");
}

/////////////////////////////////////////////////////////////////////////////
// Displays the usage syntax of this script
//
function Syntax()
{
  var str  = "\nUsage:\n\n";
      str +=   "  RemCreatePig computer [behavior]";
  WScript.Echo(str);
}


text:
layout: post
date: 2016-04-01
title: "Jovani Multi Print Two-Piece A-line Prom Dress 34034 Sleeveless Floor-Length Aline/Princess"
category: Jovani
tags: [Jovani ,Jovani,Aline/Princess ,Halter,Floor-Length,Sleeveless]
---
### Jovani Multi Print Two-Piece A-line Prom Dress 34034
Just **$421.98**
###   Sleeveless Floor-Length Aline/Princess

BRANDS	Jovani

Silhouette	Aline/Princess

Neckline	Halter

Hemline/Train	Floor-Length

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/jovani-/39138-jovani-multi-print-two-piece-a-line-prom-dress-34034.html](https://www.readybrides.com/en/jovani-/39138-jovani-multi-print-two-piece-a-line-prom-dress-34034.html)


text:
<template name="appLayout">
  {{> yield}}
</template>


text:
namespace eosio {
namespace blockvault {

postgres_backend::postgres_backend(const std::string& options)
    : conn(options) {

   try {
      pqxx::work w(conn);
      w.exec("CREATE TABLE IF NOT EXISTS BlockData (watermark_bn bigint, watermark_ts bigint, lib bigint, block_num bigint, "
            "block_id bytea UNIQUE, previous_block_id bytea, block oid, block_size bigint);"
            "CREATE TABLE IF NOT EXISTS SnapshotData (watermark_bn bigint, watermark_ts bigint, snapshot oid);");
      w.commit();
   }
   catch (const pqxx::integrity_constraint_violation&) {
      // this would happen when multiple clients try to create the tables at the same time. The first one client should succeed, just ignore it.
   }

   conn.prepare("serialize_transaction", "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;");

   conn.prepare(
       "insert_constructed_block",
       "INSERT INTO BlockData (watermark_bn, watermark_ts, lib, block_num, block_id, previous_block_id, block, block_size) "
       "SELECT $1, $2, $3, $1, $4, $5, $6, $7  WHERE NOT "
       "EXISTS (SELECT * FROM BlockData WHERE (watermark_bn >= $1) OR (watermark_ts >= $2) OR (lib > $3))");

   conn.prepare(
       "insert_external_block",
       "INSERT INTO BlockData (watermark_bn, watermark_ts, lib, block_num, block_id, previous_block_id, block, block_size) SELECT "
       "COALESCE((SELECT MAX(watermark_bn) FROM BlockData),0), COALESCE((SELECT MAX(watermark_ts) FROM "
       "BlockData),0), $2, $1, $3, $4, $5, $6 WHERE NOT "
       "EXISTS (SELECT * FROM BlockData WHERE lib >= $1)");

   conn.prepare("get_block_insertion_result", "SELECT block from BlockData WHERE block=$1");

   conn.prepare("insert_snapshot",
                "INSERT INTO SnapshotData (watermark_bn, watermark_ts, snapshot) SELECT $1, $2, $3 WHERE NOT EXISTS "
                "(SELECT * FROM SnapshotData WHERE watermark_bn >= $1 OR watermark_ts >= $2)");

   conn.prepare("get_snapshot_insertion_result", "SELECT snapshot from SnapshotData WHERE snapshot=$1");

   conn.prepare("get_sync_watermark", "SELECT watermark_bn, watermark_ts FROM BlockData WHERE "
                                      "previous_block_id = $1 ORDER BY watermark_bn, watermark_ts LIMIT 1");

   conn.prepare("get_latest_snapshot", "SELECT snapshot FROM SnapshotData "
                                       "ORDER BY watermark_bn DESC, watermark_ts DESC LIMIT 1");

   conn.prepare("get_blocks_since_watermark", "SELECT block, block_size FROM BlockData WHERE "
                                              "watermark_bn >= $1 AND watermark_ts >= $2"
                                              "ORDER BY block_num");

   conn.prepare("get_all_blocks", "SELECT block, block_size FROM BlockData");

   conn.prepare("delete_outdated_block_lo",
                "SELECT lo_unlink(r.block) FROM BlockData r WHERE watermark_bn <= $1 OR watermark_ts <= $2;");
   conn.prepare("delete_outdated_block_data", "DELETE FROM BlockData WHERE watermark_bn <= $1 OR watermark_ts <= $2;");
   conn.prepare("delete_outdated_snapshot_lo",
                "SELECT lo_unlink(r.snapshot) FROM SnapshotData r WHERE watermark_bn < $1 OR watermark_ts < $2;");
   conn.prepare("delete_outdated_snapshot_data",
                "DELETE FROM SnapshotData WHERE watermark_bn < $1 OR watermark_ts < $2;");

   conn.prepare("has_block", "SELECT COUNT(*) FROM BlockData WHERE block_id = $1");
} // namespace blockvault

bool postgres_backend::propose_constructed_block(std::pair<uint32_t, uint32_t> watermark, uint32_t lib,
                                                 const std::vector<char>& block_content, std::string_view block_id,
                                                 std::string_view previous_block_id) {
   try {
      pqxx::work w(conn);
      w.exec_prepared0("serialize_transaction");
      pqxx::largeobjectaccess obj(w);

      obj.write(nullptr, 0);
      pqxx::binarystring      block_id_blob(block_id.data(), block_id.size());
      pqxx::binarystring      previous_block_id_blob(previous_block_id.data(), previous_block_id.size());
      w.exec_prepared0("insert_constructed_block", watermark.first, watermark.second, lib, block_id_blob,
                       previous_block_id_blob, obj.id(), block_content.size());
      auto r = w.exec_prepared("get_block_insertion_result", obj.id());
      if (!r.empty()) {
         obj.write(block_content.data(), block_content.size());
         w.commit();
         return true;
      }
   } catch (const pqxx::sql_error&) {
   }

   return false;
}

bool postgres_backend::append_external_block(uint32_t block_num, uint32_t lib, const std::vector<char>& block_content,
                                             std::string_view block_id, std::string_view previous_block_id) {
   try {
      pqxx::work w(conn);
      w.exec_prepared0("serialize_transaction");
      pqxx::largeobjectaccess obj(w);
      obj.write(nullptr, 0);
      pqxx::binarystring      block_id_blob(block_id.data(), block_id.size());
      pqxx::binarystring      previous_block_id_blob(previous_block_id.data(), previous_block_id.size());
      w.exec_prepared0("insert_external_block", block_num, lib, block_id_blob, previous_block_id_blob, obj.id(),
                       block_content.size());
      auto r = w.exec_prepared("get_block_insertion_result", obj.id());
      if (!r.empty()) {
         obj.write(block_content.data(), block_content.size());
         w.commit();
         return true;
      }
   } catch (const pqxx::sql_error&) {
   }
   return false;
}

bool postgres_backend::propose_snapshot(std::pair<uint32_t, uint32_t> watermark, const char* snapshot_filename) {

   try {
      std::filebuf infile;

      infile.open(snapshot_filename, std::ios::in);

      pqxx::work              w(conn);
      w.exec_prepared0("serialize_transaction");
      pqxx::largeobjectaccess obj(w);
      obj.write(nullptr, 0);

      w.exec_prepared0("insert_snapshot", watermark.first, watermark.second, obj.id());
      auto r = w.exec_prepared("get_snapshot_insertion_result", obj.id());

      if (!r.empty()) {

         const int chunk_size = 4096;
         char      chunk[chunk_size];

         auto sz = chunk_size;
         while (sz == chunk_size) {
            sz = infile.sgetn(chunk, chunk_size);
            obj.write(chunk, sz);
         };

         w.exec_prepared("delete_outdated_block_lo", watermark.first, watermark.second);
         w.exec_prepared("delete_outdated_block_data", watermark.first, watermark.second);
         w.exec_prepared("delete_outdated_snapshot_lo", watermark.first, watermark.second);
         w.exec_prepared("delete_outdated_snapshot_data", watermark.first, watermark.second);
      }

      w.commit();
      return !r.empty();

   } catch (const pqxx::transaction_rollback&) {
   }

   return false;
}

void retrieve_blocks(backend::sync_callback& callback, pqxx::work& trx, pqxx::result r) {
   std::vector<char> block_data;

   for (const auto& x : r) {
      pqxx::oid               block_oid  = x[0].as<pqxx::oid>();
      uint64_t                block_size = x[1].as<uint64_t>();
      pqxx::largeobjectaccess obj(trx, block_oid, std::ios::in | std::ios::binary);
      block_data.resize(block_size);
      obj.read(block_data.data(), block_size);
      callback.on_block(std::string_view{block_data.data(), block_data.size()});
   }

   trx.commit();
}

void postgres_backend::sync(std::string_view previous_block_id, backend::sync_callback& callback) {
   pqxx::work trx(conn);

   if (previous_block_id.size()) {
      pqxx::binarystring blob(previous_block_id.data(), previous_block_id.size());
      auto               r = trx.exec_prepared("get_sync_watermark", blob);

      if (!r.empty()) {
         retrieve_blocks(
             callback, trx,
             trx.exec_prepared("get_blocks_since_watermark", r[0][0].as<uint32_t>(), r[0][1].as<uint32_t>()));
         return;
      }

      auto row = trx.exec_prepared1("has_block", blob);
      if (row[0].as<int>() != 0)
         // in this case, the client is up-to-date, nothing to sync.
         return;
   }

   auto r = trx.exec_prepared("get_latest_snapshot");

   if (!r.empty()) {
      pqxx::largeobject snapshot_obj(r[0][0].as<pqxx::oid>());

      fc::temp_file temp_file;
      std::string   fname = temp_file.path().string();

      snapshot_obj.to_file(trx, fname.c_str());
      callback.on_snapshot(fname.c_str());
   }

   retrieve_blocks(callback, trx, trx.exec_prepared("get_all_blocks"));
}

} // namespace blockvault
} // namespace eosio


text:
    <title>Download</title>

About ProxyToys version numbers...

Stable Version: 1.0

proxytoys.jar only

Complete distribution

Source distribution

Latest Snapshot

Below are builds of the latest version of ProxyToys from the Subversion repository.

Complete distributions

ProxyToys.jar only

Previous Releases

Previous releases of ProxyToys are also available. However, use of the latest stable version is recommended.

Previous 0.x releases

Optional Dependencies

cglib-nodep-2.2.jar (recommended for improved functionality and performance)


text:
namespace DotSpatial.Symbology.Forms
{
    public partial class Size2DDialog
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Size2DDialog));
            this.dialogButtons1 = new DotSpatial.Symbology.Forms.DialogButtons();
            this.dbxHeight = new DotSpatial.Symbology.Forms.DoubleBox();
            this.dbxWidth = new DotSpatial.Symbology.Forms.DoubleBox();
            this.SuspendLayout();
            //
            // dialogButtons1
            //
            resources.ApplyResources(this.dialogButtons1, "dialogButtons1");
            this.dialogButtons1.Name = "dialogButtons1";
            //
            // dbxHeight
            //
            resources.ApplyResources(this.dbxHeight, "dbxHeight");
            this.dbxHeight.BackColorInvalid = System.Drawing.Color.Salmon;
            this.dbxHeight.BackColorRegular = System.Drawing.Color.Empty;
            this.dbxHeight.InvalidHelp = "The value entered could not be correctly parsed into a valid double precision floating point value.";
            this.dbxHeight.IsValid = true;
            this.dbxHeight.Name = "dbxHeight";
            this.dbxHeight.NumberFormat = null;
            this.dbxHeight.RegularHelp = "Enter a double precision floating point value.";
            this.dbxHeight.Value = 0D;
            this.dbxHeight.TextChanged += new System.EventHandler(this.DbxHeightTextChanged);
            //
            // dbxWidth
            //
            resources.ApplyResources(this.dbxWidth, "dbxWidth");
            this.dbxWidth.BackColorInvalid = System.Drawing.Color.Salmon;
            this.dbxWidth.BackColorRegular = System.Drawing.Color.Empty;
            this.dbxWidth.InvalidHelp = "The value entered could not be correctly parsed into a valid double precision floating point value.";
            this.dbxWidth.IsValid = true;
            this.dbxWidth.Name = "dbxWidth";
            this.dbxWidth.NumberFormat = null;
            this.dbxWidth.RegularHelp = "Enter a double precision floating point value.";
            this.dbxWidth.Value = 0D;
            this.dbxWidth.TextChanged += new System.EventHandler(this.DbxWidthTextChanged);
            //
            // Size2DDialog
            //
            resources.ApplyResources(this, "$this");
            this.Controls.Add(this.dialogButtons1);
            this.Controls.Add(this.dbxHeight);
            this.Controls.Add(this.dbxWidth);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.HelpButton = true;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "Size2DDialog";
            this.ShowIcon = false;
            this.ShowInTaskbar = false;
            this.ResumeLayout(false);
        }

        #endregion

        private DoubleBox dbxHeight;
        private DoubleBox dbxWidth;
        private DialogButtons dialogButtons1;
    }
}


text:
package storage

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"path"
	"strings"

	"github.com/pachyderm/pachyderm/src/traffic"
	"github.com/stretchr/testify/require"
)

var (
	fakeTestingTInstance = &fakeTestingT{}
)

func RunWorkload(t require.TestingT, url string, w traffic.Workload) {
	if t == nil {
		t = fakeTestingTInstance
	}
	for _, o := range w {
		runOp(t, url, o)
	}
}

func checkAndCloseHTTPResponseBody(t require.TestingT, response *http.Response, expected string) {
	data, err := ioutil.ReadAll(response.Body)
	require.NoError(t, response.Body.Close())
	require.NoError(t, err)
	require.Equal(t, http.StatusOK, response.StatusCode, string(data))
	require.Equal(t, expected, string(data))
}

func checkWriteFile(t require.TestingT, url, name, branch, data string) {
	response, err := http.Post(url+path.Join("/file", name)+"?branch="+branch, "application/text", strings.NewReader(data))
	require.NoError(t, err)
	checkAndCloseHTTPResponseBody(t, response, "")
}

func checkFile(t require.TestingT, url, name, commit, data string) {
	response, err := http.Get(url + path.Join("/file", name) + "?commit=" + commit)
	require.NoError(t, err)
	checkAndCloseHTTPResponseBody(t, response, data)
}

func checkNoFile(t require.TestingT, url, name, commit string) {
	response, err := http.Get(url + path.Join("/file", name) + "?commit=" + commit)
	require.NoError(t, err)
	require.Equal(t, http.StatusNotFound, response.Status)
}

func commit(t require.TestingT, url, commit, branch string) {
	_url := fmt.Sprintf("%s/commit?branch=%s&commit=%s", url, branch, commit)
	response, err := http.Post(_url, "", nil)
	require.NoError(t, err)
	checkAndCloseHTTPResponseBody(t, response, fmt.Sprintf("%s\n", commit))
}

func branch(t require.TestingT, url, commit, branch string) {
	_url := fmt.Sprintf("%s/branch?branch=%s&commit=%s", url, branch, commit)
	response, err := http.Post(_url, "", nil)
	require.NoError(t, err)
	checkAndCloseHTTPResponseBody(t, response, fmt.Sprintf("%s\n", branch))
}

func runOp(t require.TestingT, url string, o traffic.Op) {
	switch {
	case o.Object == traffic.File && o.RW == traffic.W:
		checkWriteFile(t, url, o.Path, o.Branch, o.Data)
	case o.Object == traffic.File && o.RW == traffic.R:
		checkFile(t, url, o.Path, o.Commit, o.Data)
	case o.Object == traffic.Commit:
		commit(t, url, o.Commit, o.Branch)
	case o.Object == traffic.Branch:
		branch(t, url, o.Commit, o.Branch)
	default:
		require.FailNow(t, "Unrecognized op.")
	}
}

// TODO(pedge): remove when testing.T is removed from these methods, we need to keep
// this around because of the dependency in router which passes a nil value
type fakeTestingT struct{}

func (f *fakeTestingT) Errorf(format string, args ...interface{}) {
	log.Printf(format, args...)
}

func (f *fakeTestingT) FailNow() {
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.zte.oes.im</groupId>
        <artifactId>im</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>im-server</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <createDependencyReducedPom>false</createDependencyReducedPom>
                    <filters>
                        <filter>
                            <artifact>*:*</artifact>
                            <excludes>
                                <exclude>META-INF/*.SF</exclude>
                                <exclude>META-INF/*.DSA</exclude>
                                <exclude>META-INF/*.RSA</exclude>
                            </excludes>
                        </filter>
                    </filters>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.zte.oes.im.echo.server.EchoServer</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
/* eslint-disable no-undef */
const chai = require('chai');
const assert = chai.assert;
const {getRandomNumber, getRandomString, snakeCase, overridden} =
  require('../../src/utils/app');

describe('utils/app.js', function() {
  describe('getRandomNumber()', function() {
    const testCases = [
      [undefined, undefined],
      [undefined, undefined, {returnInteger: true}],
      [undefined, 10, undefined],
      [undefined, 10, {returnInteger: true}],
      [10, undefined, undefined],
      [10, undefined, {returnInteger: true}],
      [1, 10, undefined],
      [1, 10, {returnInteger: true}],
    ];
    testCases.forEach(function(testCase) {
      const [low, high, options] = testCase;
      const result = getRandomNumber(low, high, options);
      if (options && options.returnInteger) {
        it('should return an integer', function() {
          assert.isNumber(result);
        });
      }
      if (low) {
        it('should return an number greater than low', function() {
          assert.isAtLeast(result, low);
        });
      }
      if (high) {
        it('should return an number smaller than high', function() {
          assert.isAtMost(result, high);
        });
      }
    });
  });

  describe('getRandomString()', function() {
    it('should return a random string of given length', function() {
      const lengthOfString =
        Math.abs(getRandomNumber(1, 100, {returnInteger: true}));
      const result = getRandomString(lengthOfString);
      assert.lengthOf(result, lengthOfString);
    });
  });

  describe('snakeCase()', function() {
    it('should return string in snakecase style', function() {
      assert.equal(snakeCase('testsuite runner'), 'testsuite_runner');
    });
  });

  describe('overriden()', function() {
    const overrides = {
      'data': {
        'firstname': 'Abilash',
      },
    };
    it('should return true if the field is overriden', function() {
      assert.equal(overridden('$.data.firstname', overrides), true);
    });
    it('should return false if the field is not overriden', function() {
      assert.equal(overridden('$.data.lastname', overrides), false);
    });
  });
});


text:
  Se para usar ou não SSL para conectar-se ao servidor de SMTP. O padrão aponta para porta 465.

  Outras configurações avançadas podem ser feitas configurando as propriedades dos sistema.
  Veja
  esta documentação para possíveis valores e efeitos.


text:
@interface CreatNewMessageViewController ()
@property (strong, nonatomic) IBOutlet UILabel *headerLabel;

@end

@implementation CreatNewMessageViewController{
    NSIndexPath *indext;
    ThreadMessage *thread;
    NSMutableArray *listReng;
    NSMutableArray *listFilter;
    BOOL isFiltered;
    MutiSelectCell *cellTemp;
}
@synthesize mainView,footerButtom;
@synthesize selectContactTable,objAuthen,searchResults;
@synthesize chatDetail,isInviteNew,footerImage,footerLabel;
@synthesize listSelected = _listSelected;
@synthesize listContact = _listContact;
@synthesize threadId,xmppID,groupchatDetail;
@synthesize listContactSelected = _listContactSelected;
@synthesize chatViewController,rengData;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }

    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    objAuthen = [(AppDelegate *)[[UIApplication sharedApplication] delegate] objAuthen];
    [objAuthen.reengData addDelegate:self];
    [objAuthen.xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];

    _listSelected = [[NSMutableArray alloc] init];
    _listContact  = [[NSMutableArray alloc] init];
    _listContactSelected= [[NSMutableArray alloc] init];
    listReng = [[NSMutableArray alloc] initWithArray:objAuthen.reengData.listRengContacts];
//    UIFont *fon = [UIFont fontWithName:@"OpenSans" size:20];
//    self.headerLabel.font =fon;
    self.selectContactTable.bounces=YES;
    self.searchResults = [[NSMutableArray alloc]init];
    //    self.controller = [[UISearchDisplayController alloc]initWithSearchBar:self.searchBar contentsController:self];
    self.controller.searchResultsDataSource = self;
    self.controller.searchResultsDelegate = self;

    // scroll the search bar off-screen
    CGRect newBounds = self.selectContactTable.bounds;
    newBounds.origin.y = newBounds.origin.y + self.searchBar.bounds.size.height;
    self.selectContactTable.bounds = newBounds;

    [Util askContactsPermission];
    if (threadId !=-1) {
        thread = [DatabaseHelper getThreadById:threadId];
    }
    footerButtom.enabled = NO;
    [self setup];
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

-(void)onDidUpdateContact{
    [selectContactTable reloadData];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (isFiltered) {
        return [[searchResults objectAtIndex:section] count] ? [[[UILocalizedIndexedCollation currentCollation] sectionTitles] objectAtIndex:section] : nil;    }else{
       return [[_listContact objectAtIndex:section] count] ? [[[UILocalizedIndexedCollation currentCollation] sectionTitles] objectAtIndex:section] : nil;
    }

}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (isFiltered) {
       return [[searchResults objectAtIndex:section] count] ? tableView.sectionHeaderHeight : 0;
    }else{
       return [[_listContact objectAtIndex:section] count] ? tableView.sectionHeaderHeight : 0;
    }

}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (isFiltered) {
        return  [searchResults count];
    }else{
         return [_listContact count];
    }

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (isFiltered) {
        return [[searchResults objectAtIndex:section] count];
    }else{
        return [[_listContact objectAtIndex:section] count];
    }
}

#pragma mark tableView sectionIndexTitlesForTableView
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return nil;
    }else{
        return [[NSArray arrayWithObject:UITableViewIndexSearch] arrayByAddingObjectsFromArray:
                [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles]];
    }
}

#pragma mark tableView:sectionForSectionIndexTitle
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return 0;
    } else {
        if (title == UITableViewIndexSearch) {
            [tableView scrollRectToVisible:self.searchDisplayController.searchBar.frame animated:NO];
            return -1;
        } else {
            return [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index-1];
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	{
        static NSString *CellIdentifier = @"MutiSelectCell";

        MutiSelectCell *cell = (MutiSelectCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil)
        {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MutiSelectCell" owner:self options:nil];
            cell = [nib objectAtIndex:0];
        }

        Person*per;
        if (isFiltered) {
            per= [[searchResults objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];

        }else{
            per= [[_listContact objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
        }
        NSNumber *number = [NSNumber numberWithInt:per.idUserContact];

        if ([_listSelected containsObject:number]) {
            [cell.selectedImage setImage:[UIImage imageNamed:@"checkbox_3a.png"]];
        }else{
            [cell.selectedImage setImage:[UIImage imageNamed:@"checkbox_3b.png"]];
        }
        cell.nameLabel.text = per.fullName;
        if ([per.state isEqualToString:@"1"]||[per.state isEqualToString:@"3"]) {
            [cell.stateImage setImage:[UIImage imageNamed:@"ic_stat_offline.png"]];
        }else if ([per.state isEqualToString:@"2"]){
            [cell.stateImage setImage:[UIImage imageNamed:@"ic_stat_online.png"]];
        }else{
            [cell.stateImage setImage:nil];
        }
        if(per.usr_photoUri == nil || [per.usr_photoUri isEqualToString:@""]){
            if(per.imageAvatar == nil){
                per.imageAvatar = [UIImage imageNamed:@"ava-96.png"];
            }
            [cell.thumbnailImageView setImage:per.imageAvatar];
        }else{
            [cell.thumbnailImageView setImageWithURL:[NSURL URLWithString:per.usr_photoUri]placeholderImage:[UIImage imageNamed:@"ava-96.png"]];
        }
        return cell;
    }
}

-(void)setup{
    if (isInviteNew) {
        [footerImage setImage:[UIImage imageNamed:@"ic_invite_sms.png"]];
        self.headerLabel.text = @"Mời vào nhóm";
        [footerButtom setTitle:@"Mời" forState:UIControlStateNormal];
        listFilter = [[NSMutableArray alloc] initWithArray:[thread.numbers componentsSeparatedByString:@","]];
        _listContact =[[NSMutableArray alloc]initWithArray:objAuthen.reengData.listRengContacts];

        for (NSString *tmp in listFilter) {
            if ([self getPerson:tmp]!=nil) {
                [_listContact removeObject:[self getPerson:tmp]];
            }
        }

        _listContact = [Util sortContactBySector:_listContact];
    }else{
        _listContact = [Util sortContactBySector:objAuthen.reengData.listRengContacts];
        [footerImage setImage:[UIImage imageNamed:@"ic_menu_left_changepass.png"]];
        self.headerLabel.text = @"Gửi tin nhắn";
        [footerButtom setTitle:@"Tạo mới" forState:UIControlStateNormal];
    }
}

-(Person*)getPerson:(NSString*)number{
    for (Person * objecPer in _listContact) {
        for (PhoneNumber * objPhone in objecPer.listObjectPhone) {
            if([objPhone.phoneNumber isEqualToString:number]){
                return objecPer;
            }
        }
    }
    return nil;
}

-(void)invitePerson:(NSMutableArray*)listPerson :(NSString*)serverId {
    for (Person*person in listPerson) {
        NSString *intviteTo = ((PhoneNumber*)[person.listObjectPhone objectAtIndex:0]).phoneNumber;
        NSString* messageId = objAuthen.xmppStream.generateUUID;
        NSXMLElement *x = [NSXMLElement elementWithName:@"x"];
        [x addAttributeWithName:@"xmlns" stringValue:@"http://jabber.org/protocol/muc#user"];
        NSXMLElement *invite = [NSXMLElement elementWithName:@"invite"];
        [invite addAttributeWithName:@"to" stringValue:[NSString stringWithFormat:@"%@%@",intviteTo,@"@reeng/Smack"]];
        [x addChild:invite];
        XMPPMessage *message = [XMPPMessage elementWithName:@"message"];
        [message addAttributeWithName:@"id" stringValue:messageId];
        [message addAttributeWithName:@"to" stringValue:serverId];
        [message addChild:x];
        [objAuthen.xmppStream sendElement:message];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MutiSelectCell *cell = (MutiSelectCell*)[tableView cellForRowAtIndexPath:indexPath];
    Person*per;
    if (isFiltered) {
        per = [[searchResults objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    }else{
         per = [[_listContact objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    }

    NSMutableArray *numberOfContact = [[NSMutableArray alloc] init];
    for (PhoneNumber *number in per.listObjectPhone) {
        if (number.phoneIsReeng == 1) {
            [numberOfContact addObject:number];
        }
    }

   if (cell.selectedImage.image ==[UIImage imageNamed:@"checkbox_3b.png"]) {
        if ([numberOfContact count] >1) {
            indext = indexPath;
            UIActionSheet *notifySheet = [[UIActionSheet alloc]init];
            notifySheet.delegate = self;

            for (PhoneNumber *number in numberOfContact) {
                [notifySheet addButtonWithTitle: number.phoneNumber];
            }
            [notifySheet addButtonWithTitle: @"Cancel"];
            [notifySheet setCancelButtonIndex: [numberOfContact count]];
            [notifySheet showInView:self.view];
            cellTemp = cell;
        }else{
            [cell.selectedImage setImage:[UIImage imageNamed:@"checkbox_3a.png"]];
            NSNumber *perId = [NSNumber numberWithInt:per.idUserContact];
            [_listSelected addObject:perId];

            NSLog(@"%@",per.fullName);
            [_listContactSelected addObject:per];

        }
    }else{
        [cell.selectedImage setImage:[UIImage imageNamed:@"checkbox_3b.png"]];
        NSNumber *perId = [NSNumber numberWithInt:per.idUserContact];
        [_listSelected removeObject:perId];
        if ([numberOfContact count] >1) {
                NSLog(@"remove object==%d",per.idUserContact);
             [_listContactSelected removeObject:[self getPerSonForRemove:per]];

        }
        else{
            [_listContactSelected removeObject:per];
        }

    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [selectContactTable reloadData];
    if ([_listContactSelected count]>0) {
        footerButtom.enabled = YES;
    }else{
        footerButtom.enabled = NO;
    }
}
-(Person*)getPerSonForRemove:(Person*)per{
    for (Person *perSon in _listContactSelected) {
        if (perSon.idUserContact == per.idUserContact) {
            NSLog(@"====%d==",perSon.idUserContact);
            return perSon;
        }
    }
    return nil;
}

-(IBAction)creatNewMessageBackClick:(id)sender{
    if (isInviteNew) {
        [Util hideNextView:mainView.view :self.view];

    }else{

        [Util hideNextView:mainView.view :self.view];
        [mainView setGes:YES];
    }
}

-(void)instanListContact :(NSString*)number{

}

-(IBAction)creatNewMessageDetailClick:(id)sender{

    if ([_listContactSelected count]>0) {
        if (!isInviteNew) {
        chatDetail = [[ChatViewDetail alloc] init];
        chatDetail.mainView = mainView;
        NSMutableArray *listNumber = [[NSMutableArray alloc] init];
        for (Person*per in _listContactSelected) {
            [listNumber addObject:((PhoneNumber*)[per.listObjectPhone objectAtIndex:0]).phoneNumber];
        }
        chatDetail.chatWithUser =[NSMutableArray arrayWithArray:listNumber];
        PhoneNumber *num = [((Person*)[_listContactSelected objectAtIndex:0]).listObjectPhone objectAtIndex:0 ];

            NSString *my_number=[[NSUserDefaults standardUserDefaults] stringForKey:@"kXMPPmyJID"];
        if ([num.phoneNumber isEqualToString:my_number] ) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Bạn không thể nhắn tin cho chính mình !" delegate:self cancelButtonTitle:@"Đóng" otherButtonTitles:nil];
                [alert show];
        }else{

            chatDetail.thread_id =[Util checkExitThread:num.phoneNumber];
            chatDetail.thread_type = @"0";
            chatDetail.chatViewController = chatViewController;
            chatDetail.thread_name = [listNumber objectAtIndex:0];
            chatDetail.view.frame = mainView.view.frame;
            [UIView transitionWithView:mainView.view duration:0.5
                               options:UIViewAnimationOptionTransitionFlipFromRight //change to whatever animation you like
                            animations:^ { [mainView.view addSubview:chatDetail.view]; }
                            completion:nil];
            [self.view removeFromSuperview];
        }

        }else{
            [self invitePerson:_listContactSelected :thread.serverId];
            [groupchatDetail.view removeFromSuperview];
            [Util hideNextView:mainView.view :self.view];
            [chatDetail getListMember:objAuthen.xmppStream.generateUUID serverId:thread.serverId];
        }
    }else{
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil
		                                                    message:@"List selected can not empty"
		                                                   delegate:nil
		                                          cancelButtonTitle:@"OK"
		                                          otherButtonTitles:nil];
		[alertView show];

    }
}

-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{

    if([text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].length == 0){
        isFiltered = NO;
    }else{
        isFiltered = YES;
        NSLog(@"Text did change");
        searchResults = [[NSMutableArray alloc] init];
        for (Person*per in listReng) {
            NSString *tmp = per.fullName;
            NSRange nameRange = [tmp rangeOfString:[text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] options:NSCaseInsensitiveSearch];
            if(nameRange.location != NSNotFound && nameRange.length >0)
            {
                [searchResults addObject:per];
                NSLog(@"%@",tmp);
            }
        }
        if ([searchResults count]>0) {
            searchResults = [Util sortContactBySector:searchResults];
        }
    }
    [selectContactTable reloadData];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 55; // your dynamic height...
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSString *selected = [actionSheet buttonTitleAtIndex:buttonIndex];
    if (![@"Cancel" isEqualToString:selected]) {
        Person*per =[[Person alloc] init];
        per.listObjectPhone = [[NSMutableArray alloc]init ];
        Person *tmp ;
        if (isFiltered) {
            tmp = [[searchResults objectAtIndex:indext.section] objectAtIndex:indext.row];
        }else{
            tmp = [[_listContact objectAtIndex:indext.section] objectAtIndex:indext.row];
        }

        per.fullName = tmp.fullName;
        per.sectionNumber = tmp.sectionNumber;
        per.idUserContact = tmp.idUserContact;
        per.state = tmp.state;
        per.isOnline = tmp.isOnline;
        per.isFavorite = tmp.isFavorite;
        per.lastChangeAvatar = tmp.lastChangeAvatar;

        per.usr_photoUri = tmp.usr_photoUri;
        NSNumber *perId = [NSNumber numberWithInt:per.idUserContact];
        [_listSelected addObject:perId];
        for (PhoneNumber *phone in tmp.listObjectPhone) {
            if ([phone.phoneNumber isEqualToString:selected]) {
                [per.listObjectPhone addObject:phone];
            }
        }
        [_listContactSelected addObject:per];
        [cellTemp.selectedImage setImage:[UIImage imageNamed:@"checkbox_3a.png"]];
    }
    [selectContactTable reloadData];
    if ([_listContactSelected count]>0) {
        footerButtom.enabled = YES;
    }
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    isFiltered = NO;
    [searchBar resignFirstResponder];
    [selectContactTable reloadData];
}

@end