text:
package functional

import (
	"bytes"
	"context"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"github.com/Microsoft/hcsshim/internal/cmd"
	"github.com/Microsoft/hcsshim/internal/cow"
	"github.com/Microsoft/hcsshim/internal/hcsoci"
	"github.com/Microsoft/hcsshim/internal/lcow"
	"github.com/Microsoft/hcsshim/internal/resources"
	"github.com/Microsoft/hcsshim/internal/uvm"
	"github.com/Microsoft/hcsshim/osversion"
	testutilities "github.com/Microsoft/hcsshim/test/functional/utilities"
)

// TestLCOWUVMNoSCSINoVPMemInitrd starts an LCOW utility VM without a SCSI controller and
// no VPMem device. Uses initrd.
func TestLCOWUVMNoSCSINoVPMemInitrd(t *testing.T) {
	opts := uvm.NewDefaultOptionsLCOW(t.Name(), "")
	opts.SCSIControllerCount = 0
	opts.VPMemDeviceCount = 0
	opts.PreferredRootFSType = uvm.PreferredRootFSTypeInitRd
	opts.RootFSFile = uvm.InitrdFile

	testLCOWUVMNoSCSISingleVPMem(t, opts, fmt.Sprintf("Command line: initrd=/%s", opts.RootFSFile))
}

// TestLCOWUVMNoSCSISingleVPMemVHD starts an LCOW utility VM without a SCSI controller and
// only a single VPMem device. Uses VPMEM VHD
func TestLCOWUVMNoSCSISingleVPMemVHD(t *testing.T) {
	opts := uvm.NewDefaultOptionsLCOW(t.Name(), "")
	opts.SCSIControllerCount = 0
	opts.VPMemDeviceCount = 1
	opts.PreferredRootFSType = uvm.PreferredRootFSTypeVHD
	opts.RootFSFile = uvm.VhdFile

	testLCOWUVMNoSCSISingleVPMem(t, opts, `Command line: root=/dev/pmem0 init=/init`)
}

func testLCOWUVMNoSCSISingleVPMem(t *testing.T, opts *uvm.OptionsLCOW, expected string) {
	testutilities.RequiresBuild(t, osversion.RS5)
	lcowUVM := testutilities.CreateLCOWUVMFromOpts(context.Background(), t, opts)
	defer lcowUVM.Close()
	out, err := exec.Command(`hcsdiag`, `exec`, `-uvm`, lcowUVM.ID(), `dmesg`).Output() // TODO: Move the CreateProcess.
	if err != nil {
		t.Fatal(string(err.(*exec.ExitError).Stderr))
	}
	if !strings.Contains(string(out), expected) {
		t.Fatalf("Expected dmesg output to have %q: %s", expected, string(out))
	}
}

// TestLCOWTimeUVMStartVHD starts/terminates a utility VM booting from VPMem-
// attached root filesystem a number of times.
func TestLCOWTimeUVMStartVHD(t *testing.T) {
	testutilities.RequiresBuild(t, osversion.RS5)

	testLCOWTimeUVMStart(t, false, uvm.PreferredRootFSTypeVHD)
}

// TestLCOWUVMStart_KernelDirect_VHD starts/terminates a utility VM booting from
// VPMem- attached root filesystem a number of times starting from the Linux
// Kernel directly and skipping EFI.
func TestLCOWUVMStart_KernelDirect_VHD(t *testing.T) {
	testutilities.RequiresBuild(t, 18286)

	testLCOWTimeUVMStart(t, true, uvm.PreferredRootFSTypeVHD)
}

// TestLCOWTimeUVMStartInitRD starts/terminates a utility VM booting from initrd-
// attached root file system a number of times.
func TestLCOWTimeUVMStartInitRD(t *testing.T) {
	testutilities.RequiresBuild(t, osversion.RS5)

	testLCOWTimeUVMStart(t, false, uvm.PreferredRootFSTypeInitRd)
}

// TestLCOWUVMStart_KernelDirect_InitRd starts/terminates a utility VM booting
// from initrd- attached root file system a number of times starting from the
// Linux Kernel directly and skipping EFI.
func TestLCOWUVMStart_KernelDirect_InitRd(t *testing.T) {
	testutilities.RequiresBuild(t, 18286)

	testLCOWTimeUVMStart(t, true, uvm.PreferredRootFSTypeInitRd)
}

func testLCOWTimeUVMStart(t *testing.T, kernelDirect bool, rfsType uvm.PreferredRootFSType) {
	for i := 0; i < 3; i++ {
		opts := uvm.NewDefaultOptionsLCOW(t.Name(), "")
		opts.KernelDirect = kernelDirect
		opts.VPMemDeviceCount = 32
		opts.PreferredRootFSType = rfsType
		switch opts.PreferredRootFSType {
		case uvm.PreferredRootFSTypeInitRd:
			opts.RootFSFile = uvm.InitrdFile
		case uvm.PreferredRootFSTypeVHD:
			opts.RootFSFile = uvm.VhdFile
		}

		lcowUVM := testutilities.CreateLCOWUVMFromOpts(context.Background(), t, opts)
		lcowUVM.Close()
	}
}

func TestLCOWSimplePodScenario(t *testing.T) {
	t.Skip("Doesn't work quite yet")
	testutilities.RequiresBuild(t, osversion.RS5)
	alpineLayers := testutilities.LayerFolders(t, "alpine")

	cacheDir := testutilities.CreateTempDir(t)
	defer os.RemoveAll(cacheDir)
	cacheFile := filepath.Join(cacheDir, "cache.vhdx")

	// This is what gets mounted into /tmp/scratch
	uvmScratchDir := testutilities.CreateTempDir(t)
	defer os.RemoveAll(uvmScratchDir)
	uvmScratchFile := filepath.Join(uvmScratchDir, "uvmscratch.vhdx")

	// Scratch for the first container
	c1ScratchDir := testutilities.CreateTempDir(t)
	defer os.RemoveAll(c1ScratchDir)
	c1ScratchFile := filepath.Join(c1ScratchDir, "sandbox.vhdx")

	// Scratch for the second container
	c2ScratchDir := testutilities.CreateTempDir(t)
	defer os.RemoveAll(c2ScratchDir)
	c2ScratchFile := filepath.Join(c2ScratchDir, "sandbox.vhdx")

	lcowUVM := testutilities.CreateLCOWUVM(context.Background(), t, "uvm")
	defer lcowUVM.Close()

	// Populate the cache and generate the scratch file for /tmp/scratch
	if err := lcow.CreateScratch(context.Background(), lcowUVM, uvmScratchFile, lcow.DefaultScratchSizeGB, cacheFile); err != nil {
		t.Fatal(err)
	}

	var options []string
	if _, err := lcowUVM.AddSCSI(context.Background(), uvmScratchFile, `/tmp/scratch`, false, false, options, uvm.VMAccessTypeIndividual); err != nil {
		t.Fatal(err)
	}

	// Now create the first containers sandbox, populate a spec
	if err := lcow.CreateScratch(context.Background(), lcowUVM, c1ScratchFile, lcow.DefaultScratchSizeGB, cacheFile); err != nil {
		t.Fatal(err)
	}
	c1Spec := testutilities.GetDefaultLinuxSpec(t)
	c1Folders := append(alpineLayers, c1ScratchDir)
	c1Spec.Windows.LayerFolders = c1Folders
	c1Spec.Process.Args = []string{"echo", "hello", "lcow", "container", "one"}
	c1Opts := &hcsoci.CreateOptions{
		Spec:          c1Spec,
		HostingSystem: lcowUVM,
	}

	// Now create the second containers sandbox, populate a spec
	if err := lcow.CreateScratch(context.Background(), lcowUVM, c2ScratchFile, lcow.DefaultScratchSizeGB, cacheFile); err != nil {
		t.Fatal(err)
	}
	c2Spec := testutilities.GetDefaultLinuxSpec(t)
	c2Folders := append(alpineLayers, c2ScratchDir)
	c2Spec.Windows.LayerFolders = c2Folders
	c2Spec.Process.Args = []string{"echo", "hello", "lcow", "container", "two"}
	c2Opts := &hcsoci.CreateOptions{
		Spec:          c2Spec,
		HostingSystem: lcowUVM,
	}

	// Create the two containers
	c1hcsSystem, c1Resources, err := CreateContainerTestWrapper(context.Background(), c1Opts)
	if err != nil {
		t.Fatal(err)
	}
	c2hcsSystem, c2Resources, err := CreateContainerTestWrapper(context.Background(), c2Opts)
	if err != nil {
		t.Fatal(err)
	}

	// Start them. In the UVM, they'll be in the created state from runc's perspective after this.eg
	/// # runc list
	//ID                                     PID         STATUS      BUNDLE         CREATED                        OWNER
	//3a724c2b-f389-5c71-0555-ebc6f5379b30   138         running     /run/gcs/c/1   2018-06-04T21:23:39.1253911Z   root
	//7a8229a0-eb60-b515-55e7-d2dd63ffae75   158         created     /run/gcs/c/2   2018-06-04T21:23:39.4249048Z   root
	if err := c1hcsSystem.Start(context.Background()); err != nil {
		t.Fatal(err)
	}
	defer resources.ReleaseResources(context.Background(), c1Resources, lcowUVM, true)

	if err := c2hcsSystem.Start(context.Background()); err != nil {
		t.Fatal(err)
	}
	defer resources.ReleaseResources(context.Background(), c2Resources, lcowUVM, true)

	// Start the init process in each container and grab it's stdout comparing to expected
	runInitProcess(t, c1hcsSystem, "hello lcow container one")
	runInitProcess(t, c2hcsSystem, "hello lcow container two")

}

// Helper to run the init process in an LCOW container; verify it exits with exit
// code 0; verify stderr is empty; check output is as expected.
func runInitProcess(t *testing.T, s cow.Container, expected string) {
	var errB bytes.Buffer
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	cmd := &cmd.Cmd{
		Host:    s,
		Stderr:  &errB,
		Context: ctx,
	}
	outb, err := cmd.Output()
	if err != nil {
		t.Fatalf("stderr: %s", err)
	}
	out := string(outb)
	if strings.TrimSpace(out) != expected {
		t.Fatalf("got %q expecting %q", string(out), expected)
	}
}


text:
// Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
// Original code is licensed as follows:

#include "BC_PDF417DecodedBitStreamParser.h"

#include <stdlib.h>

#include "xfa/src/fxbarcode/BC_DecoderResult.h"
#include "xfa/src/fxbarcode/barcode.h"
#include "xfa/src/fxbarcode/common/BC_CommonDecoderResult.h"
#include "BC_PDF417ResultMetadata.h"
#include "third_party/bigint/BigIntegerLibrary.hh"

#define TEXT_COMPACTION_MODE_LATCH 900
#define BYTE_COMPACTION_MODE_LATCH 901
#define NUMERIC_COMPACTION_MODE_LATCH 902
#define BYTE_COMPACTION_MODE_LATCH_6 924
#define BEGIN_MACRO_PDF417_CONTROL_BLOCK 928
#define BEGIN_MACRO_PDF417_OPTIONAL_FIELD 923
#define MACRO_PDF417_TERMINATOR 922
#define MODE_SHIFT_TO_BYTE_COMPACTION_MODE 913

int32_t CBC_DecodedBitStreamPaser::MAX_NUMERIC_CODEWORDS = 15;
int32_t CBC_DecodedBitStreamPaser::NUMBER_OF_SEQUENCE_CODEWORDS = 2;
int32_t CBC_DecodedBitStreamPaser::PL = 25;
int32_t CBC_DecodedBitStreamPaser::LL = 27;
int32_t CBC_DecodedBitStreamPaser::AS = 27;
int32_t CBC_DecodedBitStreamPaser::ML = 28;
int32_t CBC_DecodedBitStreamPaser::AL = 28;
int32_t CBC_DecodedBitStreamPaser::PS = 29;
int32_t CBC_DecodedBitStreamPaser::PAL = 29;
FX_CHAR CBC_DecodedBitStreamPaser::PUNCT_CHARS[29] = {
    ';', '<',  '>',  '@', '[', '\\', '}', '_', '`', '~',
    '!', '\r', '\t', ',', ':', '\n', '-', '.', '$', '/',
    '"', '|',  '*',  '(', ')', '?',  '{', '}', '\''};
FX_CHAR CBC_DecodedBitStreamPaser::MIXED_CHARS[30] = {
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '&', '\r', '\t',
    ',', ':', '#', '-', '.', '$', '/', '+', '%', '*', '=', '^'};
void CBC_DecodedBitStreamPaser::Initialize() {}
void CBC_DecodedBitStreamPaser::Finalize() {}
CBC_DecodedBitStreamPaser::CBC_DecodedBitStreamPaser() {}
CBC_DecodedBitStreamPaser::~CBC_DecodedBitStreamPaser() {}
CBC_CommonDecoderResult* CBC_DecodedBitStreamPaser::decode(
    CFX_Int32Array& codewords,
    CFX_ByteString ecLevel,
    int32_t& e) {
  CFX_ByteString result;
  int32_t codeIndex = 1;
  int32_t code = codewords.GetAt(codeIndex);
  codeIndex++;
  CBC_PDF417ResultMetadata* resultMetadata = new CBC_PDF417ResultMetadata;
  while (codeIndex < codewords[0]) {
    switch (code) {
      case TEXT_COMPACTION_MODE_LATCH:
        codeIndex = textCompaction(codewords, codeIndex, result);
        break;
      case BYTE_COMPACTION_MODE_LATCH:
        codeIndex = byteCompaction(code, codewords, codeIndex, result);
        break;
      case NUMERIC_COMPACTION_MODE_LATCH:
        codeIndex = numericCompaction(codewords, codeIndex, result, e);
        BC_EXCEPTION_CHECK_ReturnValue(e, NULL);
        break;
      case MODE_SHIFT_TO_BYTE_COMPACTION_MODE:
        codeIndex = byteCompaction(code, codewords, codeIndex, result);
        break;
      case BYTE_COMPACTION_MODE_LATCH_6:
        codeIndex = byteCompaction(code, codewords, codeIndex, result);
        break;
      case BEGIN_MACRO_PDF417_CONTROL_BLOCK:
        codeIndex = decodeMacroBlock(codewords, codeIndex, resultMetadata, e);
        if (e != BCExceptionNO) {
          delete resultMetadata;
          return NULL;
        }
        break;
      default:
        codeIndex--;
        codeIndex = textCompaction(codewords, codeIndex, result);
        break;
    }
    if (codeIndex < codewords.GetSize()) {
      code = codewords[codeIndex++];
    } else {
      e = BCExceptionFormatInstance;
      delete resultMetadata;
      return NULL;
    }
  }
  if (result.GetLength() == 0) {
    e = BCExceptionFormatInstance;
    delete resultMetadata;
    return NULL;
  }
  CFX_ByteArray rawBytes;
  CFX_PtrArray byteSegments;
  CBC_CommonDecoderResult* tempCd = new CBC_CommonDecoderResult();
  tempCd->Init(rawBytes, result, byteSegments, ecLevel, e);
  if (e != BCExceptionNO) {
    delete resultMetadata;
    return NULL;
  }
  tempCd->setOther(resultMetadata);
  return tempCd;
}
int32_t CBC_DecodedBitStreamPaser::decodeMacroBlock(
    CFX_Int32Array& codewords,
    int32_t codeIndex,
    CBC_PDF417ResultMetadata* resultMetadata,
    int32_t& e) {
  if (codeIndex + NUMBER_OF_SEQUENCE_CODEWORDS > codewords[0]) {
    e = BCExceptionFormatInstance;
    return -1;
  }
  CFX_Int32Array segmentIndexArray;
  segmentIndexArray.SetSize(NUMBER_OF_SEQUENCE_CODEWORDS);
  for (int32_t i = 0; i < NUMBER_OF_SEQUENCE_CODEWORDS; i++, codeIndex++) {
    segmentIndexArray.SetAt(i, codewords[codeIndex]);
  }
  CFX_ByteString str =
      decodeBase900toBase10(segmentIndexArray, NUMBER_OF_SEQUENCE_CODEWORDS, e);
  BC_EXCEPTION_CHECK_ReturnValue(e, -1);
  resultMetadata->setSegmentIndex(atoi(str.GetBuffer(str.GetLength())));
  CFX_ByteString fileId;
  codeIndex = textCompaction(codewords, codeIndex, fileId);
  resultMetadata->setFileId(fileId);
  if (codewords[codeIndex] == BEGIN_MACRO_PDF417_OPTIONAL_FIELD) {
    codeIndex++;
    CFX_Int32Array additionalOptionCodeWords;
    additionalOptionCodeWords.SetSize(codewords[0] - codeIndex);
    int32_t additionalOptionCodeWordsIndex = 0;
    FX_BOOL end = FALSE;
    while ((codeIndex < codewords[0]) && !end) {
      int32_t code = codewords[codeIndex++];
      if (code < TEXT_COMPACTION_MODE_LATCH) {
        additionalOptionCodeWords[additionalOptionCodeWordsIndex++] = code;
      } else {
        switch (code) {
          case MACRO_PDF417_TERMINATOR:
            resultMetadata->setLastSegment(TRUE);
            codeIndex++;
            end = TRUE;
            break;
          default:
            e = BCExceptionFormatInstance;
            return -1;
        }
      }
    }
    CFX_Int32Array array;
    array.SetSize(additionalOptionCodeWordsIndex);
    array.Copy(additionalOptionCodeWords);
    resultMetadata->setOptionalData(array);
  } else if (codewords[codeIndex] == MACRO_PDF417_TERMINATOR) {
    resultMetadata->setLastSegment(TRUE);
    codeIndex++;
  }
  return codeIndex;
}
int32_t CBC_DecodedBitStreamPaser::textCompaction(CFX_Int32Array& codewords,
                                                  int32_t codeIndex,
                                                  CFX_ByteString& result) {
  CFX_Int32Array textCompactionData;
  textCompactionData.SetSize((codewords[0] - codeIndex) << 1);
  CFX_Int32Array byteCompactionData;
  byteCompactionData.SetSize((codewords[0] - codeIndex) << 1);
  int32_t index = 0;
  FX_BOOL end = FALSE;
  while ((codeIndex < codewords[0]) && !end) {
    int32_t code = codewords[codeIndex++];
    if (code < TEXT_COMPACTION_MODE_LATCH) {
      textCompactionData[index] = code / 30;
      textCompactionData[index + 1] = code % 30;
      index += 2;
    } else {
      switch (code) {
        case TEXT_COMPACTION_MODE_LATCH:
          textCompactionData[index++] = TEXT_COMPACTION_MODE_LATCH;
          break;
        case BYTE_COMPACTION_MODE_LATCH:
          codeIndex--;
          end = TRUE;
          break;
        case NUMERIC_COMPACTION_MODE_LATCH:
          codeIndex--;
          end = TRUE;
          break;
        case BEGIN_MACRO_PDF417_CONTROL_BLOCK:
          codeIndex--;
          end = TRUE;
          break;
        case BEGIN_MACRO_PDF417_OPTIONAL_FIELD:
          codeIndex--;
          end = TRUE;
          break;
        case MACRO_PDF417_TERMINATOR:
          codeIndex--;
          end = TRUE;
          break;
        case MODE_SHIFT_TO_BYTE_COMPACTION_MODE:
          textCompactionData[index] = MODE_SHIFT_TO_BYTE_COMPACTION_MODE;
          code = codewords[codeIndex++];
          byteCompactionData[index] = code;
          index++;
          break;
        case BYTE_COMPACTION_MODE_LATCH_6:
          codeIndex--;
          end = TRUE;
          break;
      }
    }
  }
  decodeTextCompaction(textCompactionData, byteCompactionData, index, result);
  return codeIndex;
}
void CBC_DecodedBitStreamPaser::decodeTextCompaction(
    CFX_Int32Array& textCompactionData,
    CFX_Int32Array& byteCompactionData,
    int32_t length,
    CFX_ByteString& result) {
  Mode subMode = ALPHA;
  Mode priorToShiftMode = ALPHA;
  int32_t i = 0;
  while (i < length) {
    int32_t subModeCh = textCompactionData[i];
    FX_CHAR ch = 0;
    switch (subMode) {
      case ALPHA:
        if (subModeCh < 26) {
          ch = (FX_CHAR)('A' + subModeCh);
        } else {
          if (subModeCh == 26) {
            ch = ' ';
          } else if (subModeCh == LL) {
            subMode = LOWER;
          } else if (subModeCh == ML) {
            subMode = MIXED;
          } else if (subModeCh == PS) {
            priorToShiftMode = subMode;
            subMode = PUNCT_SHIFT;
          } else if (subModeCh == MODE_SHIFT_TO_BYTE_COMPACTION_MODE) {
            result += (FX_CHAR)byteCompactionData[i];
          } else if (subModeCh == TEXT_COMPACTION_MODE_LATCH) {
            subMode = ALPHA;
          }
        }
        break;
      case LOWER:
        if (subModeCh < 26) {
          ch = (FX_CHAR)('a' + subModeCh);
        } else {
          if (subModeCh == 26) {
            ch = ' ';
          } else if (subModeCh == AS) {
            priorToShiftMode = subMode;
            subMode = ALPHA_SHIFT;
          } else if (subModeCh == ML) {
            subMode = MIXED;
          } else if (subModeCh == PS) {
            priorToShiftMode = subMode;
            subMode = PUNCT_SHIFT;
          } else if (subModeCh == MODE_SHIFT_TO_BYTE_COMPACTION_MODE) {
            result += (FX_CHAR)byteCompactionData[i];
          } else if (subModeCh == TEXT_COMPACTION_MODE_LATCH) {
            subMode = ALPHA;
          }
        }
        break;
      case MIXED:
        if (subModeCh < PL) {
          ch = MIXED_CHARS[subModeCh];
        } else {
          if (subModeCh == PL) {
            subMode = PUNCT;
          } else if (subModeCh == 26) {
            ch = ' ';
          } else if (subModeCh == LL) {
            subMode = LOWER;
          } else if (subModeCh == AL) {
            subMode = ALPHA;
          } else if (subModeCh == PS) {
            priorToShiftMode = subMode;
            subMode = PUNCT_SHIFT;
          } else if (subModeCh == MODE_SHIFT_TO_BYTE_COMPACTION_MODE) {
            result += (FX_CHAR)byteCompactionData[i];
          } else if (subModeCh == TEXT_COMPACTION_MODE_LATCH) {
            subMode = ALPHA;
          }
        }
        break;
      case PUNCT:
        if (subModeCh < PAL) {
          ch = PUNCT_CHARS[subModeCh];
        } else {
          if (subModeCh == PAL) {
            subMode = ALPHA;
          } else if (subModeCh == MODE_SHIFT_TO_BYTE_COMPACTION_MODE) {
            result += (FX_CHAR)byteCompactionData[i];
          } else if (subModeCh == TEXT_COMPACTION_MODE_LATCH) {
            subMode = ALPHA;
          }
        }
        break;
      case ALPHA_SHIFT:
        subMode = priorToShiftMode;
        if (subModeCh < 26) {
          ch = (FX_CHAR)('A' + subModeCh);
        } else {
          if (subModeCh == 26) {
            ch = ' ';
          } else if (subModeCh == TEXT_COMPACTION_MODE_LATCH) {
            subMode = ALPHA;
          }
        }
        break;
      case PUNCT_SHIFT:
        subMode = priorToShiftMode;
        if (subModeCh < PAL) {
          ch = PUNCT_CHARS[subModeCh];
        } else {
          if (subModeCh == PAL) {
            subMode = ALPHA;
          } else if (subModeCh == MODE_SHIFT_TO_BYTE_COMPACTION_MODE) {
            result += (FX_CHAR)byteCompactionData[i];
          } else if (subModeCh == TEXT_COMPACTION_MODE_LATCH) {
            subMode = ALPHA;
          }
        }
        break;
    }
    if (ch != 0) {
      result += ch;
    }
    i++;
  }
}
int32_t CBC_DecodedBitStreamPaser::byteCompaction(int32_t mode,
                                                  CFX_Int32Array& codewords,
                                                  int32_t codeIndex,
                                                  CFX_ByteString& result) {
  if (mode == BYTE_COMPACTION_MODE_LATCH) {
    int32_t count = 0;
    int64_t value = 0;
    FX_WORD* decodedData = FX_Alloc(FX_WORD, 6);
    CFX_Int32Array byteCompactedCodewords;
    byteCompactedCodewords.SetSize(6);
    FX_BOOL end = FALSE;
    int32_t nextCode = codewords[codeIndex++];
    while ((codeIndex < codewords[0]) && !end) {
      byteCompactedCodewords[count++] = nextCode;
      value = 900 * value + nextCode;
      nextCode = codewords[codeIndex++];
      if (nextCode == TEXT_COMPACTION_MODE_LATCH ||
          nextCode == BYTE_COMPACTION_MODE_LATCH ||
          nextCode == NUMERIC_COMPACTION_MODE_LATCH ||
          nextCode == BYTE_COMPACTION_MODE_LATCH_6 ||
          nextCode == BEGIN_MACRO_PDF417_CONTROL_BLOCK ||
          nextCode == BEGIN_MACRO_PDF417_OPTIONAL_FIELD ||
          nextCode == MACRO_PDF417_TERMINATOR) {
        codeIndex--;
        end = TRUE;
      } else {
        if ((count % 5 == 0) && (count > 0)) {
          int32_t j = 0;
          for (; j < 6; ++j) {
            decodedData[5 - j] = (FX_WORD)(value % 256);
            value >>= 8;
          }
          for (j = 0; j < 6; ++j) {
            result += (FX_CHAR)decodedData[j];
          }
          count = 0;
        }
      }
    }
    FX_Free(decodedData);
    if (codeIndex == codewords[0] && nextCode < TEXT_COMPACTION_MODE_LATCH) {
      byteCompactedCodewords[count++] = nextCode;
    }
    for (int32_t i = 0; i < count; i++) {
      result += (FX_CHAR)(FX_WORD)byteCompactedCodewords[i];
    }
  } else if (mode == BYTE_COMPACTION_MODE_LATCH_6) {
    int32_t count = 0;
    int64_t value = 0;
    FX_BOOL end = FALSE;
    while (codeIndex < codewords[0] && !end) {
      int32_t code = codewords[codeIndex++];
      if (code < TEXT_COMPACTION_MODE_LATCH) {
        count++;
        value = 900 * value + code;
      } else {
        if (code == TEXT_COMPACTION_MODE_LATCH ||
            code == BYTE_COMPACTION_MODE_LATCH ||
            code == NUMERIC_COMPACTION_MODE_LATCH ||
            code == BYTE_COMPACTION_MODE_LATCH_6 ||
            code == BEGIN_MACRO_PDF417_CONTROL_BLOCK ||
            code == BEGIN_MACRO_PDF417_OPTIONAL_FIELD ||
            code == MACRO_PDF417_TERMINATOR) {
          codeIndex--;
          end = TRUE;
        }
      }
      if ((count % 5 == 0) && (count > 0)) {
        FX_WORD* decodedData = FX_Alloc(FX_WORD, 6);
        int32_t j = 0;
        for (; j < 6; ++j) {
          decodedData[5 - j] = (FX_WORD)(value & 0xFF);
          value >>= 8;
        }
        for (j = 0; j < 6; ++j) {
          result += (FX_CHAR)decodedData[j];
        }
        count = 0;
        FX_Free(decodedData);
      }
    }
  }
  return codeIndex;
}
int32_t CBC_DecodedBitStreamPaser::numericCompaction(CFX_Int32Array& codewords,
                                                     int32_t codeIndex,
                                                     CFX_ByteString& result,
                                                     int32_t& e) {
  int32_t count = 0;
  FX_BOOL end = FALSE;
  CFX_Int32Array numericCodewords;
  numericCodewords.SetSize(MAX_NUMERIC_CODEWORDS);
  while (codeIndex < codewords[0] && !end) {
    int32_t code = codewords[codeIndex++];
    if (codeIndex == codewords[0]) {
      end = TRUE;
    }
    if (code < TEXT_COMPACTION_MODE_LATCH) {
      numericCodewords[count] = code;
      count++;
    } else {
      if (code == TEXT_COMPACTION_MODE_LATCH ||
          code == BYTE_COMPACTION_MODE_LATCH ||
          code == BYTE_COMPACTION_MODE_LATCH_6 ||
          code == BEGIN_MACRO_PDF417_CONTROL_BLOCK ||
          code == BEGIN_MACRO_PDF417_OPTIONAL_FIELD ||
          code == MACRO_PDF417_TERMINATOR) {
        codeIndex--;
        end = TRUE;
      }
    }
    if (count % MAX_NUMERIC_CODEWORDS == 0 ||
        code == NUMERIC_COMPACTION_MODE_LATCH || end) {
      CFX_ByteString s = decodeBase900toBase10(numericCodewords, count, e);
      BC_EXCEPTION_CHECK_ReturnValue(e, -1);
      result += s;
      count = 0;
    }
  }
  return codeIndex;
}
CFX_ByteString CBC_DecodedBitStreamPaser::decodeBase900toBase10(
    CFX_Int32Array& codewords,
    int32_t count,
    int32_t& e) {
  BigInteger result = 0;
  BigInteger nineHundred(900);
  for (int32_t i = 0; i < count; i++) {
    result = result * nineHundred + BigInteger(codewords[i]);
  }
  CFX_ByteString resultString(bigIntegerToString(result).c_str());
  if (resultString.GetAt(0) != '1') {
    e = BCExceptionFormatInstance;
    return ' ';
  }
  return resultString.Mid(1, resultString.GetLength() - 1);
}

redpajama_set_name: RedPajamaGithub


text:
namespace java.security.cert
{
	[global::MonoJavaBridge.JavaClass()]
	public partial class PKIXCertPathValidatorResult : java.lang.Object, CertPathValidatorResult
	{
		internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
		protected PKIXCertPathValidatorResult(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
		{
		}
		private static global::MonoJavaBridge.MethodId _m0;
		public override global::java.lang.String toString()
		{
			return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.security.cert.PKIXCertPathValidatorResult.staticClass, "toString", "()Ljava/lang/String;", ref global::java.security.cert.PKIXCertPathValidatorResult._m0) as java.lang.String;
		}
		private static global::MonoJavaBridge.MethodId _m1;
		public virtual global::java.lang.Object clone()
		{
			return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.security.cert.PKIXCertPathValidatorResult.staticClass, "clone", "()Ljava/lang/Object;", ref global::java.security.cert.PKIXCertPathValidatorResult._m1) as java.lang.Object;
		}
		public new global::java.security.PublicKey PublicKey
		{
			get
			{
				return getPublicKey();
			}
		}
		private static global::MonoJavaBridge.MethodId _m2;
		public virtual global::java.security.PublicKey getPublicKey()
		{
			return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.security.PublicKey>(this, global::java.security.cert.PKIXCertPathValidatorResult.staticClass, "getPublicKey", "()Ljava/security/PublicKey;", ref global::java.security.cert.PKIXCertPathValidatorResult._m2) as java.security.PublicKey;
		}
		public new global::java.security.cert.TrustAnchor TrustAnchor
		{
			get
			{
				return getTrustAnchor();
			}
		}
		private static global::MonoJavaBridge.MethodId _m3;
		public virtual global::java.security.cert.TrustAnchor getTrustAnchor()
		{
			return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.security.cert.PKIXCertPathValidatorResult.staticClass, "getTrustAnchor", "()Ljava/security/cert/TrustAnchor;", ref global::java.security.cert.PKIXCertPathValidatorResult._m3) as java.security.cert.TrustAnchor;
		}
		public new global::java.security.cert.PolicyNode PolicyTree
		{
			get
			{
				return getPolicyTree();
			}
		}
		private static global::MonoJavaBridge.MethodId _m4;
		public virtual global::java.security.cert.PolicyNode getPolicyTree()
		{
			return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.security.cert.PolicyNode>(this, global::java.security.cert.PKIXCertPathValidatorResult.staticClass, "getPolicyTree", "()Ljava/security/cert/PolicyNode;", ref global::java.security.cert.PKIXCertPathValidatorResult._m4) as java.security.cert.PolicyNode;
		}
		private static global::MonoJavaBridge.MethodId _m5;
		public PKIXCertPathValidatorResult(java.security.cert.TrustAnchor arg0, java.security.cert.PolicyNode arg1, java.security.PublicKey arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (global::java.security.cert.PKIXCertPathValidatorResult._m5.native == global::System.IntPtr.Zero)
				global::java.security.cert.PKIXCertPathValidatorResult._m5 = @__env.GetMethodIDNoThrow(global::java.security.cert.PKIXCertPathValidatorResult.staticClass, "<init>", "(Ljava/security/cert/TrustAnchor;Ljava/security/cert/PolicyNode;Ljava/security/PublicKey;)V");
			global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.security.cert.PKIXCertPathValidatorResult.staticClass, global::java.security.cert.PKIXCertPathValidatorResult._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
			Init(@__env, handle);
		}
		static PKIXCertPathValidatorResult()
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			global::java.security.cert.PKIXCertPathValidatorResult.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/security/cert/PKIXCertPathValidatorResult"));
		}
	}
}


text:
require 'spec_helper'

describe Goose::Config do

  it 'has on <li> as the default wrapper tag' do
    subject.wrapper_tag.should == :li
  end

  it 'applies a class attribute by default when active' do
    subject.active_options.should == {:class => 'active'}
  end

  it 'applies no inactive attributes by default when inactive' do
    subject.inactive_options.should == {}
  end

  it 'calls link_to by default to create breadcrumbs' do
    view = double(link_to: :linked)
    view.should_receive(:link_to).with(1, 2, 3)
    subject.breadcrumb_linker.(view, 1, 2, 3)
  end

end


text:
package annis.model;

/**
 *
 * @author thomas
 */
public class AnnisConstants
{

  public static final String ANNIS_NS = "annis";

  /**
   * Comma-sperated list of matched node Salt-IDs. Feature is applied to
   * {@link SDocument}.
   */
  public static final String FEAT_MATCHEDIDS = "matchedids";

  /**
   * Comma-sperated list of matched annotations.
   * If the node itself and not an annotation was matched the string is empty.
   *
   * Feature is applied to {@link SDocument}.
   */
  public static final String FEAT_MATCHEDANNOS = "matchedannos";

  /**
   * The number of the query node if matched. Feature is applied to
   * {@link SNode} and {@link SAnnotation}.
   */
  public static final String FEAT_MATCHEDNODE = "matchednode";

  /**
   * A number of relANNIS specific node values encoded as {@link RelannisNodeFeature}.   *
   */
  public static final String FEAT_RELANNIS_NODE = "relannis_node";

  /**
   * A number of relANNIS specific edge values encoded as {@link RelannisEdgeFeature}.   *
   */
  public static final String FEAT_RELANNIS_EDGE = "relannis_edge";

  /**
   * A marker feature for the first node of a segmentation chain. The value is the name of the segmentation.
   */
  public static final String FEAT_FIRST_NODE_SEGMENTATION_CHAIN = "first_node_segmentation_chain";

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace Hacon.Motash.Service
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new MotashService()
            };
            ServiceBase.Run(ServicesToRun);
        }
    }
}


text:
module.exports = {
  staticFileGlobs: [
    '/index.html',
    '/manifest.json',
    '/bower_components/webcomponentsjs/webcomponents-lite.min.js',
    '/images/*'
  ],
  navigateFallback: '/index.html',
  navigateFallbackWhitelist: [/^(?!.*\.html$|\/data\/).*/]
};


text:
package com.ibm.si.qradar.offenseviz.api;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.servlet.ServletContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.api.client.util.Lists;
import com.ibm.si.qradar.offenseviz.conf.QRadarConfig;
import com.ibm.si.qradar.offenseviz.dao.OffenseDao;
import com.ibm.si.qradar.offenseviz.jpa.Offense;
import com.ibm.si.qradar.offenseviz.model.OffenseBucket;
import com.ibm.si.qradar.offenseviz.util.PersistenceUtil;

@Path("/offenses")
public class OffenseResource {

	@Resource ServletContext servletContext;
    private static final Logger logger = LoggerFactory.getLogger(OffenseResource.class);
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

	@GET
	@Produces( MediaType.APPLICATION_JSON )
	public Response getOffenses(@QueryParam("buckets") Integer bucketCount) {
		List<OffenseBucket> buckets = buildOffenseBuckets(bucketCount);

		GenericEntity<List<OffenseBucket>> entity = new GenericEntity<List<OffenseBucket>>(
				Lists.newArrayList(buckets)) {
		};

		Response response = Response.ok().entity(entity).build();

		return response;
	}

	private List<OffenseBucket> buildOffenseBuckets(int bucketCount) {
		EntityManager em = PersistenceUtil.getEntityManagerFactory().createEntityManager();
		OffenseDao offenseDao = new OffenseDao(em);

		Long mostRecentBucketMillis = getLastBucketTime();
		Timestamp mostRecentTimestamp = new Timestamp(mostRecentBucketMillis);
		Timestamp oldestLastSeenTimestamp = calculateAge(bucketCount, mostRecentBucketMillis);

		List<Offense> offensesInTimeRange = offenseDao.findByTimestamp(oldestLastSeenTimestamp, mostRecentTimestamp);
		em.close();

		Date now = new Date(mostRecentTimestamp.getTime());
		Date then = new Date(oldestLastSeenTimestamp.getTime());

		logger.debug(String.format("We found %s offenses in between %s and %s",
				offensesInTimeRange.size(),
				dateFormat.format(then),
				dateFormat.format(now)));

		List<OffenseBucket> buckets = new ArrayList<OffenseBucket>();
		for(int i = 0; i < bucketCount; i++) {
			Timestamp bucketTime = calculateAge(i, mostRecentTimestamp.getTime());
			OffenseBucket bucket = new OffenseBucket(bucketTime, offensesInTimeRange);
			buckets.add(bucket);
		}

		return buckets;
	}

	private Long getLastBucketTime() {
		Long startupTime = QRadarConfig.getInstance().getStartupTime();
		Long interval = Long.valueOf(QRadarConfig.getInstance().getUpdateInterval() * 1000);
		Long now = Calendar.getInstance().getTimeInMillis();
		Long delta = now - startupTime;
		Long modulo = delta % interval;
		Long maxBucketTime = now - modulo;

		return maxBucketTime;
	}

	private Timestamp calculateAge(int bucketCount, long nowMillis) {
		int interval = QRadarConfig.getInstance().getUpdateInterval();
		int seconds = interval * bucketCount;

		Timestamp original = new Timestamp(nowMillis);
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(original.getTime());
        cal.add(Calendar.SECOND, -seconds);
        Timestamp maxAge = new Timestamp(cal.getTimeInMillis());

        return maxAge;
	}

}


text:
namespace WebApiTemplate.Data.Contracts
{
    using System.Data.Entity;
    using WebApiTemplate.Models;
    using System.Data.Entity.Infrastructure;

    public interface IWebApiTemplateDbContext
    {

        IDbSet<SampleClass> SampleClasses { get; set; }

        DbSet<TEntity> Set<TEntity>() where TEntity : class;

        DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;

        void Dispose();

        int SaveChanges();
    }
}


text:
var program = require('commander');
var commands = require('../lib/wrappedCommands');

program
  .version('0.0.1')
  .option('-d, --database <dbname>', 'database name')
  .option('-p, --port <portnumber>', 'port number');

program
  .command('generate [name]')
  .description('generates a new migration')
  .action(commands.generate);

program
  .command('up')
  .description('migrates up to the latest migration')
  .action(commands.up);

program
  .command('down [migration]')
  .description('migrates down the last migration')
  .action(commands.down);

program
  .command('status')
  .description('returns the current migration status')
  .action(commands.status);

program.parse(process.argv);

// Check the program.args obj
var NO_COMMAND_SPECIFIED = program.args.length === 0;

// Handle it however you like
if (NO_COMMAND_SPECIFIED) {
  // e.g. display usage
  program.help();
}


text:
algorithms
==========

A study of commonly used algorithms and data structures, and some algorithmic problems.


text:
using System;
using System.Runtime.CompilerServices;

// This test is a reduced repro case for DevDiv VSO bug 278365.
// The failure mode is that the RyuJIT/x86 backend changed call to ROUND intrinsic
// with double return type to ROUND intrinsic with int return type, that is not supported.

internal class Program
{
    [MethodImpl(MethodImplOptions.NoInlining)]
    public static int Bar()
    {
        int sum = 0;
        for (int i = 0; i < 100; ++i)
        {
            int v = (int)Math.Round(4.4 + i);
            sum += v;
        }
        sum -= 4 * 100;
        if (sum != 100 * 99 / 2)
        {
            return 0;
        }
        else
        {
            return 100;
        }
    }

    private static int Main(string[] args)
    {
        try
        {
            if (Bar() != 100)
                return 0;
        }
        catch (Exception)
        {
        }

        Console.WriteLine("Pass");
        return 100;
    }
}


text:
import { Section } from "eightbittr";

import { FullScreenPokemon } from "../../FullScreenPokemon";
import { Character, Actor } from "../Actors";

/**
 * Hops characters down ledges.
 */
export class Ledges extends Section<FullScreenPokemon> {
    /**
     * Starts a Character hopping over a ledge.
     *
     * @param actor   A Character hopping over a ledge.
     * @param other   The ledge the Character is hopping over.
     */
    public startLedgeHop(actor: Character, other: Actor): void {
        const ticksPerBlock: number = this.game.equations.walkingTicksPerBlock(actor);

        actor.nocollide = true;
        actor.wantsToWalk = true;
        actor.ledge = other;

        this.addHopOffset(actor);
        this.addHopShadow(actor);

        this.game.timeHandler.addEvent((): void => this.endLedgeHop(actor), ticksPerBlock * 2);
    }

    /**
     * Finishes a Character hopping over a ledge.
     *
     * @param actor   A Character done hopping over a ledge.
     * @param other   The ledge the Character is done hopping over.
     */
    public endLedgeHop(actor: Character): void {
        this.game.death.kill(actor.shadow!);
        actor.nocollide = false;
        actor.wantsToWalk = false;
        actor.ledge = undefined;
        actor.shadow = undefined;
    }

    /**
     * Adds a visual "hop" to a hopping Character.
     *
     * @param actor   A Character hopping over a ledge.
     */
    protected addHopOffset(actor: Character): void {
        const ticksPerBlock: number = this.game.equations.walkingTicksPerBlock(actor);
        let dy = -2;

        this.game.timeHandler.addEventInterval((): void => {
            dy *= -1;
        }, ticksPerBlock + 1);

        this.game.timeHandler.addEventInterval(
            (): void => {
                actor.offsetY += dy;
            },
            1,
            ticksPerBlock * 2
        );
    }

    /**
     * Adds a visual shadow to a hopping Character.
     *
     * @param actor   A Character hopping over a ledge.
     */
    protected addHopShadow(actor: Character): void {
        actor.shadow = this.game.actors.add(this.game.actors.names.shadow);

        this.game.timeHandler.addEventInterval(
            (): boolean => this.updateShadowPosition(actor),
            1,
            Infinity
        );
    }

    /**
     * Updates a hopping Character's shadow.
     *
     * @param actor   A Character hopping over a ledge.
     * @param other   The ledge the Character is hopping over.
     */
    protected updateShadowPosition(actor: Character): boolean {
        if (!actor.shadow) {
            return true;
        }

        this.game.physics.setMidXObj(actor.shadow, actor);
        this.game.physics.setBottom(actor.shadow, actor.bottom);
        return false;
    }
}


text:
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
    /// <summary>
    /// Controller class for Sys_Municipio
    /// </summary>
    [System.ComponentModel.DataObject]
    public partial class SysMunicipioController
    {
        // Preload our schema..
        SysMunicipio thisSchemaLoad = new SysMunicipio();
        private string userName = String.Empty;
        protected string UserName
        {
            get
            {
				if (userName.Length == 0)
				{
    				if (System.Web.HttpContext.Current != null)
    				{
						userName=System.Web.HttpContext.Current.User.Identity.Name;
					}
					else
					{
						userName=System.Threading.Thread.CurrentPrincipal.Identity.Name;
					}
				}
				return userName;
            }
        }
        [DataObjectMethod(DataObjectMethodType.Select, true)]
        public SysMunicipioCollection FetchAll()
        {
            SysMunicipioCollection coll = new SysMunicipioCollection();
            Query qry = new Query(SysMunicipio.Schema);
            coll.LoadAndCloseReader(qry.ExecuteReader());
            return coll;
        }
        [DataObjectMethod(DataObjectMethodType.Select, false)]
        public SysMunicipioCollection FetchByID(object IdMunicipio)
        {
            SysMunicipioCollection coll = new SysMunicipioCollection().Where("idMunicipio", IdMunicipio).Load();
            return coll;
        }

		[DataObjectMethod(DataObjectMethodType.Select, false)]
        public SysMunicipioCollection FetchByQuery(Query qry)
        {
            SysMunicipioCollection coll = new SysMunicipioCollection();
            coll.LoadAndCloseReader(qry.ExecuteReader());
            return coll;
        }
        [DataObjectMethod(DataObjectMethodType.Delete, true)]
        public bool Delete(object IdMunicipio)
        {
            return (SysMunicipio.Delete(IdMunicipio) == 1);
        }
        [DataObjectMethod(DataObjectMethodType.Delete, false)]
        public bool Destroy(object IdMunicipio)
        {
            return (SysMunicipio.Destroy(IdMunicipio) == 1);
        }

	    /// <summary>
	    /// Inserts a record, can be used with the Object Data Source
	    /// </summary>
        [DataObjectMethod(DataObjectMethodType.Insert, true)]
	    public void Insert(string Nombre)
	    {
		    SysMunicipio item = new SysMunicipio();

            item.Nombre = Nombre;

		    item.Save(UserName);
	    }

	    /// <summary>
	    /// Updates a record, can be used with the Object Data Source
	    /// </summary>
        [DataObjectMethod(DataObjectMethodType.Update, true)]
	    public void Update(int IdMunicipio,string Nombre)
	    {
		    SysMunicipio item = new SysMunicipio();
	        item.MarkOld();
	        item.IsLoaded = true;

			item.IdMunicipio = IdMunicipio;

			item.Nombre = Nombre;

	        item.Save(UserName);
	    }
    }
}


text:
title: "Webvideo-Channel für Jugendliche"
layout: angebot-detail
an_teaser: "Im Webvideo-Channel about:blank haben wir von Dezember 2017 - April 2018 wöchentlich gemeinsam mit unseren Partnern medialepfade.org und netzpolitik.org Sendungen zu digitalen, technologischen und gesellschaftlichen Themen produziert."
link: '/angebot/about-blank'
featured: true
hide_hero: true

---

	Gibt es ein Recht auf Internet? Wie kann ich sicher vor Überwachung kommunizieren? Und wozu brauchen wir eigentlich ein neutrales Netz? In unserem Webvideo-Channel about:blank gehen wir gemeinsam mit unseren Partnern medialepfade.org und netzpolitik.org diesen Fragen auf den Grund.

	In insgesamt 16 Folgen von Dezember 2017 bis April 2018 haben wir die wichtigsten digitalen, netzpolitischen und gesellschaftlichen Themen, die junge Menschen beschäftigen, aufgegriffen und jugendgerecht aufbereitet: Von Fake News und Safer Nudes bis Darknet und Überwachung!

Schaut doch mal rein

	Youtube

	Instagram

	Facebook


text:
CREATE VIEW view_form_legend AS
SELECT *
FROM view_form_element
WHERE LOWER(element_type_meta) = 'form_element_legend'
;


text:
class RedisKeystore(object):
    def get(self, id):
        pass

    def set(self, id, result):
        pass


text:
  Swie

    <app-top-speed></app-top-speed>

      Customer Admin

      Swie Account


text:
<?php header('content-type: text/javascript'); ?>
/////////////////
// FRAIS
/////////////////

// Ajax PHP script generating javscript code for adding a building to a project
<?php
require_once ("config.inc.php");
  $projectId=$_POST["projectId"];
  $buildingDesc=$_POST["desc"];
  $sql = "INSERT INTO haus(haus_id,projekt_id,beschreibung) VALUES (null,".$projectId.",'".$buildingDesc."')";

  $db = mysql_connect($CFG->dbhost, $CFG->dbuser, $CFG->dbpass)
      or die ("keine Verbindung m&ooml;glich");

	mysql_select_db ( $CFG->dbname , $db );

	$ergebnis = mysql_query ( $sql )
	  or die (mysql_error());

	if($ergebnis != 1){
		echo"alert(\"Haus konnte nicht hinzugefuegt werden!\");";
	}
	else{
		echo"alert(\"".$buildingDesc." wurde hinzugefuegt\");";
	}

?>
document.getElementById("addBuildingDescInput").value="";
FRAIS.getBuildingsForDelete();


text:
package com.jaquadro.minecraft.storagedrawers.capabilities;

import com.jaquadro.minecraft.storagedrawers.api.storage.IDrawerAttributes;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.common.capabilities.CapabilityToken;
import net.minecraftforge.common.capabilities.RegisterCapabilitiesEvent;

public class CapabilityDrawerAttributes
{
    public static Capability<IDrawerAttributes> DRAWER_ATTRIBUTES_CAPABILITY = CapabilityManager.get(new CapabilityToken<>(){});

    public static void register (RegisterCapabilitiesEvent event) {
        event.register(IDrawerAttributes.class);
    }
}


text:
/**
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 *
http://www.apache.org/licenses/LICENSE-2.0
 *
 *
Unless required by applicable law or agreed to in writing, software distributed under the
 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing permissions and
 * limitations under the License.
 */
package edu.berkeley.ground.common.model.core;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import edu.berkeley.ground.common.model.version.Item;
import edu.berkeley.ground.common.model.version.Tag;
import java.util.Map;

public class Edge extends Item {

  // the name of this Edge
  @JsonProperty("name")
  private final String name;

  // the id of the Node that this EdgeVersion originates from
  @JsonProperty("fromNodeId")
  private final long fromNodeId;

  // the id of the Node that this EdgeVersion points to
  @JsonProperty("toNodeId")
  private final long toNodeId;

  // the source key for this Edge
  @JsonProperty("sourceKey")
  private final String sourceKey;

  /**
   * Construct a new Edge.
   *
   * @param id the edge id
   * @param name the edge name
   * @param sourceKey the user-generated unique key for the edge
   * @param fromNodeId the source node of this edge
   * @param toNodeId the destination node of this edge
   * @param tags the tags associated with this edge
   */
  @JsonCreator
  public Edge(@JsonProperty("itemId") long id,
               @JsonProperty("name") String name,
               @JsonProperty("sourceKey") String sourceKey,
               @JsonProperty("fromNodeId") long fromNodeId,
               @JsonProperty("toNodeId") long toNodeId,
               @JsonProperty("tags") Map<String, Tag> tags) {

    super(id, tags);

    this.name = name;
    this.fromNodeId = fromNodeId;
    this.toNodeId = toNodeId;
    this.sourceKey = sourceKey;
  }

  public Edge(long id, Edge other) {
    super(id, other.getTags());

    this.name = other.name;
    this.fromNodeId = other.fromNodeId;
    this.toNodeId = other.toNodeId;
    this.sourceKey = other.sourceKey;
  }

  public String getName() {
    return this.name;
  }

  public long getFromNodeId() {
    return this.fromNodeId;
  }

  public long getToNodeId() {
    return this.toNodeId;
  }

  public String getSourceKey() {
    return this.sourceKey;
  }

  @Override
  public boolean equals(Object other) {
    if (!(other instanceof Edge)) {
      return false;
    }

    Edge otherEdge = (Edge) other;

    return this.name.equals(otherEdge.name)
             && this.sourceKey.equals(otherEdge.sourceKey)
             && this.getId() == otherEdge.getId()
             && this.fromNodeId == otherEdge.fromNodeId
             && this.toNodeId == otherEdge.toNodeId
             && this.getTags().equals(otherEdge.getTags());
  }
}


text:
package org.apache.kandula.context.impl;

import java.util.Map;

import javax.xml.namespace.QName;

import org.apache.axiom.om.OMElement;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.kandula.Constants;
import org.apache.kandula.context.CoordinationContext;
import org.apache.kandula.utility.EndpointReferenceFactory;
import org.oasis_open.docs.ws_tx.wscoor._2006._06.CoordinationContext_type0;

public class ADBCoordinationContext implements CoordinationContext {

	CoordinationContext_type0 context_type3;
	public ADBCoordinationContext(CoordinationContext_type0 context_type3) {
		super();
		this.context_type3 = context_type3;
	}
	public String getActivityID() {
		Map map = this.getRegistrationService().getAllReferenceParameters();
		OMElement element  = (OMElement)map.get(Constants.TRANSACTION_ID_PARAMETER);
		return element.getText();
	}
	public Object getCoordinationContextType() {
		return context_type3;
	}
	public String getCoordinationType() {
		return context_type3.getCoordinationType().getPath();
	}
	public long getExpires() {
		return context_type3.getExpires().getUnsignedInt().longValue();
	}
	public EndpointReference getRegistrationService() {
		return EndpointReferenceFactory
		.getEPR(context_type3.getRegistrationService());
	}
	public void setActivityID(String value) {
		// TODO Auto-generated method stub

	}
	public void setCoordinationType(String value) {
		// TODO Auto-generated method stub

	}
	public void setExpires(long value) {
		// TODO Auto-generated method stub

	}
	public void setRegistrationService(EndpointReference value) {
		// TODO Auto-generated method stub

	}
	public OMElement toOM() throws Exception {
		return context_type3.getOMElement(new QName(Constants.WS_COOR,"CoordinationContext"),
                org.apache.axiom.om.OMAbstractFactory.getOMFactory());
	}

}


text:
/**
 * @class Ext.draw.sprite.EllipticalArc
 * @extends Ext.draw.sprite.Ellipse
 *
 * A sprite that represents an elliptical arc.
 *
 *     @example preview miniphone
 *     var container = new Ext.draw.Container({
 *       items: [{
 *         type: 'ellipticalArc',
 *         cx: 100,
 *         cy: 100,
 *         rx: 40,
 *         ry: 25,
 *         fillStyle: 'blue',
 *         startAngle: 0,
 *         endAngle: Math.PI,
 *         anticlockwise: true
 *       }]
 *     });
 *     Ext.Viewport.setLayout('fit');
 *     Ext.Viewport.add(container);
 */
Ext.define("Ext.draw.sprite.EllipticalArc", {
    extend: "Ext.draw.sprite.Ellipse",
    alias: 'sprite.ellipticalArc',
    type: 'ellipticalArc',
    inheritableStatics: {
        def: {
            processors: {
                /**
                 * @cfg {Number} [startAngle=0] The beginning angle of the arc.
                 */
                startAngle: "number",

                /**
                 * @cfg {Number} [endAngle=Math.PI*2] The ending angle of the arc.
                 */
                endAngle: "number",

                /**
                 * @cfg {Boolean} [anticlockwise=false] Determines whether or not the arc is drawn clockwise.
                 */
                anticlockwise: "bool"
            },
            aliases: {
                from: "startAngle",
                to: "endAngle",
                start: "startAngle",
                end: "endAngle"
            },
            defaults: {
                startAngle: 0,
                endAngle: Math.PI * 2,
                anticlockwise: false
            },
            dirtyTriggers: {
                startAngle: 'path',
                endAngle: 'path',
                anticlockwise: 'path'
            }
        }
    },

    updatePath: function (path, attr) {
        path.ellipse(attr.cx, attr.cy, attr.rx, attr.ry, attr.axisRotation, attr.startAngle, attr.endAngle, attr.anticlockwise);
    }
});


text:
from __future__ import unicode_literals

from django.apps import AppConfig

class OrganizationConfig(AppConfig):
    name = 'organization'
    verbose_name = u"机构管理"


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>IntervalEstimator</title>
<meta name="date" content="2015-09-10">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

weka.classifiers

Interface IntervalEstimator

All Known Implementing Classes:

GaussianProcesses, RegressionByDiscretization

public interface IntervalEstimator

Interface for numeric prediction schemes that can output prediction
 intervals.

Version:

$Revision: 8034 $

Author:

Kurt Driessens (kurtd@cs.waikato.ac.nz)

Method Summary

Methods

Modifier and Type
Method and Description

double[][]
predictIntervals(Instance inst,
                double confidenceLevel)

Returns an N * 2 array, where N is the number of prediction
 intervals.

Method Detail

predictIntervals

double[][] predictIntervals(Instance inst,
                          double confidenceLevel)
                            throws java.lang.Exception

Returns an N * 2 array, where N is the number of prediction
 intervals. In each row, the first element contains the lower
 boundary of the corresponding prediction interval and the second
 element the upper boundary.

Parameters:

inst - the instance to make the prediction for.

confidenceLevel - the percentage of cases that the interval should cover.

Returns:

an array of prediction intervals

Throws:

java.lang.Exception - if the intervals can't be computed

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
int main() {
    using namespace std::chrono;

    // Create pipeline
    dai::Pipeline pipeline;

    // Define source and outputs
    auto camRgb = pipeline.create<dai::node::ColorCamera>();
    auto videoEnc = pipeline.create<dai::node::VideoEncoder>();
    auto xoutJpeg = pipeline.create<dai::node::XLinkOut>();
    auto xoutRgb = pipeline.create<dai::node::XLinkOut>();

    xoutJpeg->setStreamName("jpeg");
    xoutRgb->setStreamName("rgb");

    // Properties
    camRgb->setBoardSocket(dai::CameraBoardSocket::RGB);
    camRgb->setResolution(dai::ColorCameraProperties::SensorResolution::THE_4_K);
    videoEnc->setDefaultProfilePreset(camRgb->getFps(), dai::VideoEncoderProperties::Profile::MJPEG);

    // Linking
    camRgb->video.link(xoutRgb->input);
    camRgb->video.link(videoEnc->input);
    videoEnc->bitstream.link(xoutJpeg->input);

    // Connect to device and start pipeline
    dai::Device device(pipeline);

    // Queues
    auto qRgb = device.getOutputQueue("rgb", 30, false);
    auto qJpeg = device.getOutputQueue("jpeg", 30, true);

    std::string dirName = "rgb_data";
    createDirectory(dirName);

    while(true) {
        auto inRgb = qRgb->tryGet<dai::ImgFrame>();
        if(inRgb != NULL) {
            cv::imshow("rgb", inRgb->getCvFrame());
        }

        auto encFrames = qJpeg->tryGetAll<dai::ImgFrame>();
        for(const auto& encFrame : encFrames) {
            uint64_t time = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
            std::stringstream videoStr;
            videoStr << dirName << "/" << time << ".jpeg";
            auto videoFile = std::ofstream(videoStr.str(), std::ios::binary);
            videoFile.write((char*)encFrame->getData().data(), encFrame->getData().size());
        }

        int key = cv::waitKey(1);
        if(key == 'q' || key == 'Q') {
            return 0;
        }
    }
    return 0;
}


text:
from collections import deque
class UndoCommand(object):
    def __init__(self, name=None):
        self.name = name
        self.commands = deque()
    # end def

    def redo(self):
        for cmd in self.commands:
            cmd.redo()
    # end def

    def undo(self):
        for cmd in self.commands:
            cmd.undo()
    # end def

    def addCommand(self, cmd):
        self.commands.append(cmd)


text:
// Copyright (c) Samuel Cragg.
//
// Licensed under the MIT license. See LICENSE file in the project root for
// full license information.

namespace Crest.DataAccess
{
    using System.Collections.Generic;

    /// <summary>
    /// Provides methods to create <see cref="MappingInfo"/>s.
    /// </summary>
    public interface IMappingInfoFactory
    {
        /// <summary>
        /// Creates a sequence of mapping information.
        /// </summary>
        /// <returns>A sequence of mapping information.</returns>
        IEnumerable<MappingInfo> GetMappingInformation();
    }
}


text:
@implementation MessageAudio
- (id)initWithAudio:(NSString*)url duration:(int)duration {
    NSString *uuid = [[NSUUID UUID] UUIDString];
    NSNumber *d = [NSNumber numberWithInteger:duration];
    NSDictionary *dic = @{@"audio":@{@"url":url, @"duration":d}, @"uuid":uuid};
    self = [super initWithDictionary:dic];
    if (self) {

    }
    return self;
}

- (NSString*)url {
    return [[self.dict objectForKey:@"audio"] objectForKey:@"url"];
}

- (int)duration {
    return [[[self.dict objectForKey:@"audio"] objectForKey:@"duration"] intValue];
}

-(MessageAudioContent*)cloneWithURL:(NSString*)url {
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:self.dict];
    NSMutableDictionary *audio = [NSMutableDictionary dictionaryWithDictionary:[dict objectForKey:@"audio"]];
    [audio setObject:url forKey:@"url"];
    [dict setObject:audio forKey:@"audio"];
    MessageAudioContent *newContent = [[MessageAudioContent alloc] initWithDictionary:dict];
    return newContent;
}

-(int)type {
    return MESSAGE_AUDIO;
}
@end