text:
package io.perfmark.agent;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;

import com.google.common.truth.Truth;
import io.perfmark.PerfMark;
import io.perfmark.TaskCloseable;
import io.perfmark.impl.Mark;
import io.perfmark.impl.Storage;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class PerfMarkTransformerTest {

  @Test
  public void deriveFileName() {
    String file = PerfMarkTransformer.deriveFileName("io/perfmark/Clz");

    assertEquals("Clz.java", file);
  }

  @Test
  public void deriveFileName_innerClass() {
    String file = PerfMarkTransformer.deriveFileName("io/perfmark/Clz$Inner");

    assertEquals("Clz.java", file);
  }

  @Test
  @Ignore
  public void transform_autoAnnotate() throws Exception {
    // This test currently depends on the transformer treating this test class specially.
    PerfMark.setEnabled(true);
    Storage.clearLocalStorage();

    Class<?> clz = transformAndLoad(TransformerTestClasses.ClzAutoRecord.class);
    Constructor<?> ctor = clz.getConstructor();
    ctor.setAccessible(true);
    ctor.newInstance();
    List<Mark> marks = Storage.readForTest();
    assertThat(marks).hasSize(2);
  }

  @Test
  public void transform_record() throws Exception {
    PerfMark.setEnabled(true);
    Storage.clearLocalStorage();

    Class<?> clz = transformAndLoad(TransformerTestClasses.SomeRecord.class);
    Constructor<?> ctor = clz.getConstructor(int.class);
    ctor.setAccessible(true);
    ctor.newInstance(2);
    List<Mark> marks = Storage.readForTest();
    assertThat(marks).hasSize(4);
    assertEquals(marks.get(0).withTaskName("task"), marks.get(0));

    assertEquals(marks.get(1).getTagKey(), "PerfMark.startCallSite");
    Truth.assertThat(marks.get(1).getTagStringValue()).contains("TransformerTestClasses$SomeRecord");
    Truth.assertThat(marks.get(1).getTagStringValue()).contains("<init>");

    assertEquals(marks.get(2).getTagKey(), "PerfMark.stopCallSite");
    Truth.assertThat(marks.get(2).getTagStringValue()).contains("TransformerTestClasses$SomeRecord");
    Truth.assertThat(marks.get(2).getTagStringValue()).contains("<init>");

    assertEquals(marks.get(3).withTaskName("task"), marks.get(3));
  }

  @Test
  public void transform_lambda() throws Exception {
    PerfMark.setEnabled(true);
    Storage.clearLocalStorage();

    Class<?> clz = transformAndLoad(TransformerTestClasses.ClzCtorLambda.class);
    Constructor<?> ctor = clz.getConstructor();
    ctor.setAccessible(true);
    ctor.newInstance();
    List<Mark> marks = Storage.readForTest();
    assertThat(marks).hasSize(4);
    assertEquals(marks.get(0).withTaskName("task"), marks.get(0));

    assertEquals(marks.get(1).getTagKey(), "PerfMark.startCallSite");
    Truth.assertThat(marks.get(1).getTagStringValue()).contains("TransformerTestClasses$ClzCtorLambda");
    Truth.assertThat(marks.get(1).getTagStringValue()).contains("lambda");

    assertEquals(marks.get(2).getTagKey(), "PerfMark.stopCallSite");
    Truth.assertThat(marks.get(2).getTagStringValue()).contains("TransformerTestClasses$ClzCtorLambda");
    Truth.assertThat(marks.get(2).getTagStringValue()).contains("lambda");

    assertEquals(marks.get(3).withTaskName("task"), marks.get(3));
  }

  @Test
  public void transform_methodRef() throws Exception {
    PerfMark.setEnabled(true);
    Storage.clearLocalStorage();

    Class<?> clz = transformAndLoad(TransformerTestClasses.ClzWithMethodRefs.class);
    Constructor<?> ctor = clz.getConstructor();
    ctor.setAccessible(true);
    ctor.newInstance();
    List<Mark> marks = Storage.readForTest();
    assertThat(marks).hasSize(2);
    // I'm not sure what to do with methodrefs, so just leave it alone for now.
  }

  @Test
  public void transform_interface() throws Exception {
    PerfMark.setEnabled(true);
    Storage.clearLocalStorage();

    Class<?> clz =
        transformAndLoad(TransformerTestClasses.Bar.class, TransformerTestClasses.InterfaceWithDefaults.class);
    Constructor<?> ctor = clz.getConstructor();
    ctor.setAccessible(true);
    ctor.newInstance();

    List<Mark> marks = Storage.readForTest();
    assertThat(marks).hasSize(10);

    assertEquals(marks.get(0).withTaskName("task"), marks.get(0));

    assertEquals(marks.get(1).getTagKey(), "PerfMark.startCallSite");
    Truth.assertThat(marks.get(1).getTagStringValue()).contains("TransformerTestClasses$InterfaceWithDefaults");
    Truth.assertThat(marks.get(1).getTagStringValue()).contains("record");

    assertEquals(marks.get(2).getTagKey(), "PerfMark.stopCallSite");
    Truth.assertThat(marks.get(2).getTagStringValue()).contains("TransformerTestClasses$InterfaceWithDefaults");
    Truth.assertThat(marks.get(2).getTagStringValue()).contains("record");

    assertEquals(marks.get(3).withTaskName("task"), marks.get(3));

    assertEquals(marks.get(4).withTaskName("task"), marks.get(4));

    // Ignore the regular tag at 5

    assertEquals(marks.get(6).getTagKey(), "PerfMark.startCallSite");
    Truth.assertThat(marks.get(6).getTagStringValue()).contains("TransformerTestClasses$InterfaceWithDefaults");
    Truth.assertThat(marks.get(6).getTagStringValue()).contains("record");

    assertEquals(marks.get(7).getTagKey(), "PerfMark.stopCallSite");
    Truth.assertThat(marks.get(7).getTagStringValue()).contains("TransformerTestClasses$InterfaceWithDefaults");
    Truth.assertThat(marks.get(7).getTagStringValue()).contains("record");

    // Ignore the regular tag at 8

    assertEquals(marks.get(9).withTaskName("task"), marks.get(9));
  }

  @Test
  public void transform_link() throws Exception {
    PerfMark.setEnabled(true);
    Storage.clearLocalStorage();

    Class<?> clz = transformAndLoad(TransformerTestClasses.ClzWithLinks.class);
    Constructor<?> ctor = clz.getConstructor();
    ctor.setAccessible(true);
    ctor.newInstance();
    List<Mark> marks = Storage.readForTest();
    assertThat(marks).hasSize(6);

    assertEquals(marks.get(0).withTaskName("task"), marks.get(0));

    assertEquals(marks.get(1).getTagKey(), "PerfMark.startCallSite");
    Truth.assertThat(marks.get(1).getTagStringValue()).contains("TransformerTestClasses$ClzWithLinks");
    Truth.assertThat(marks.get(1).getTagStringValue()).contains("init");

    // assume links have not been modified

    assertEquals(marks.get(4).getTagKey(), "PerfMark.stopCallSite");
    Truth.assertThat(marks.get(4).getTagStringValue()).contains("TransformerTestClasses$ClzWithLinks");
    Truth.assertThat(marks.get(4).getTagStringValue()).contains("init");

    assertEquals(marks.get(5).withTaskName("task"), marks.get(5));
  }

  @Test
  public void transform_closeable() throws Exception {
    PerfMark.setEnabled(true);
    Storage.clearLocalStorage();

    Class<?> clz = transformAndLoad(TransformerTestClasses.ClzWithCloseable.class);
    Constructor<?> ctor = clz.getConstructor();
    ctor.setAccessible(true);
    ctor.newInstance();
    List<Mark> marks = Storage.readForTest();
    assertThat(marks).hasSize(4);

    assertEquals(marks.get(0).withTaskName("task"), marks.get(0));

    assertEquals(marks.get(1).getTagKey(), "PerfMark.startCallSite");
    Truth.assertThat(marks.get(1).getTagStringValue()).contains("TransformerTestClasses$ClzWithCloseable");
    Truth.assertThat(marks.get(1).getTagStringValue()).contains("init");

    assertEquals(marks.get(2).getTagKey(), "PerfMark.stopCallSite");
    Truth.assertThat(marks.get(2).getTagStringValue()).contains("TransformerTestClasses$ClzWithCloseable");
    Truth.assertThat(marks.get(2).getTagStringValue()).contains("init");

    assertEquals(Mark.Operation.TASK_END_N1S0, marks.get(3).getOperation());
  }

  @Test
  public void transform_wrongCloseable() throws Exception {
    // If the wrong static type is used, the agent won't be able to instrument it.  Add a test to document this
    // behavior.
    PerfMark.setEnabled(true);
    Storage.clearLocalStorage();

    Class<?> clz = transformAndLoad(TransformerTestClasses.ClzWithWrongCloseable.class);
    Constructor<?> ctor = clz.getConstructor();
    ctor.setAccessible(true);
    ctor.newInstance();
    List<Mark> marks = Storage.readForTest();
    assertThat(marks).hasSize(3);

    assertEquals(marks.get(0).withTaskName("task"), marks.get(0));

    assertEquals(marks.get(1).getTagKey(), "PerfMark.startCallSite");
    Truth.assertThat(marks.get(1).getTagStringValue()).contains("TransformerTestClasses$ClzWithWrongCloseable");
    Truth.assertThat(marks.get(1).getTagStringValue()).contains("init");

    assertEquals(Mark.Operation.TASK_END_N1S0, marks.get(2).getOperation());
  }

  @Test
  public void transform_wrongCloseable_autoCloseable() throws Exception {
    // If the wrong static type is used, the agent won't be able to instrument it.  Add a test to document this
    // behavior.
    PerfMark.setEnabled(true);
    Storage.clearLocalStorage();

    Class<? extends Closeable> clz = transformAndLoad(TaskCloseable.class).asSubclass(Closeable.class);
    Constructor<? extends Closeable> ctor = clz.getDeclaredConstructor();
    ctor.setAccessible(true);
    Closeable closeable = ctor.newInstance();
    closeable.close();
    List<Mark> marks = Storage.readForTest();
    assertThat(marks).hasSize(1);

    assertEquals(Mark.Operation.TASK_END_N1S0, marks.get(0).getOperation());
  }

  @Test
  public void transform_ctor() throws Exception {
    PerfMark.setEnabled(true);
    Storage.clearLocalStorage();

    Class<?> clz = transformAndLoad(TransformerTestClasses.ClzWithCtor.class);
    Constructor<?> ctor = clz.getConstructor();
    ctor.setAccessible(true);
    ctor.newInstance();
    List<Mark> marks = Storage.readForTest();
    assertThat(marks).hasSize(10);

    assertEquals(marks.get(0).withTaskName("task"), marks.get(0));

    assertEquals(marks.get(1).getTagKey(), "PerfMark.startCallSite");
    Truth.assertThat(marks.get(1).getTagStringValue()).contains("TransformerTestClasses$ClzWithCtor");
    Truth.assertThat(marks.get(1).getTagStringValue()).contains("init");

    assertEquals(marks.get(2).getTagKey(), "PerfMark.stopCallSite");
    Truth.assertThat(marks.get(2).getTagStringValue()).contains("TransformerTestClasses$ClzWithCtor");
    Truth.assertThat(marks.get(2).getTagStringValue()).contains("init");

    assertEquals(marks.get(3).withTaskName("task"), marks.get(3));

    assertEquals(marks.get(4).withTaskName("task"), marks.get(4));

    // Ignore the regular tag at 5

    assertEquals(marks.get(6).getTagKey(), "PerfMark.startCallSite");
    Truth.assertThat(marks.get(6).getTagStringValue()).contains("TransformerTestClasses$ClzWithCtor");
    Truth.assertThat(marks.get(6).getTagStringValue()).contains("init");

    assertEquals(marks.get(7).getTagKey(), "PerfMark.stopCallSite");
    Truth.assertThat(marks.get(7).getTagStringValue()).contains("TransformerTestClasses$ClzWithCtor");
    Truth.assertThat(marks.get(7).getTagStringValue()).contains("init");

    // Ignore the regular tag at 8

    assertEquals(marks.get(9).withTaskName("task"), marks.get(9));
  }

  @Test
  public void transform_init() throws Exception {
    PerfMark.setEnabled(true);
    Storage.clearLocalStorage();

    Class<?> clz = transformAndLoad(TransformerTestClasses.ClzWithInit.class);
    Constructor<?> ctor = clz.getDeclaredConstructor();
    ctor.setAccessible(true);
    ctor.newInstance();
    List<Mark> marks = Storage.readForTest();
    assertThat(marks).hasSize(10);

    assertEquals(marks.get(0).withTaskName("task"), marks.get(0));

    assertEquals(marks.get(1).getTagKey(), "PerfMark.startCallSite");
    Truth.assertThat(marks.get(1).getTagStringValue()).contains("TransformerTestClasses$ClzWithInit");
    Truth.assertThat(marks.get(1).getTagStringValue()).contains("init");

    assertEquals(marks.get(2).getTagKey(), "PerfMark.stopCallSite");
    Truth.assertThat(marks.get(2).getTagStringValue()).contains("TransformerTestClasses$ClzWithInit");
    Truth.assertThat(marks.get(2).getTagStringValue()).contains("init");

    assertEquals(marks.get(3).withTaskName("task"), marks.get(3));

    assertEquals(marks.get(4).withTaskName("task"), marks.get(4));

    // Ignore the regular tag at 5

    assertEquals(marks.get(6).getTagKey(), "PerfMark.startCallSite");
    Truth.assertThat(marks.get(6).getTagStringValue()).contains("TransformerTestClasses$ClzWithInit");
    Truth.assertThat(marks.get(6).getTagStringValue()).contains("init");

    assertEquals(marks.get(7).getTagKey(), "PerfMark.stopCallSite");
    Truth.assertThat(marks.get(7).getTagStringValue()).contains("TransformerTestClasses$ClzWithInit");
    Truth.assertThat(marks.get(7).getTagStringValue()).contains("init");

    // Ignore the regular tag at 8

    assertEquals(marks.get(9).withTaskName("task"), marks.get(9));
  }

  @Test
  public void transform_clinit() throws Exception {
    PerfMark.setEnabled(true);
    Storage.clearLocalStorage();

    Class<?> clz = transformAndLoad(TransformerTestClasses.ClzWithClinit.class);
    Constructor<?> ctor = clz.getDeclaredConstructor();
    ctor.setAccessible(true);
    ctor.newInstance();
    List<Mark> marks = Storage.readForTest();
    assertThat(marks).hasSize(10);

    assertEquals(marks.get(0).withTaskName("task"), marks.get(0));

    assertEquals(marks.get(1).getTagKey(), "PerfMark.startCallSite");
    Truth.assertThat(marks.get(1).getTagStringValue()).contains("TransformerTestClasses$ClzWithClinit");
    Truth.assertThat(marks.get(1).getTagStringValue()).contains("clinit");

    assertEquals(marks.get(2).getTagKey(), "PerfMark.stopCallSite");
    Truth.assertThat(marks.get(2).getTagStringValue()).contains("TransformerTestClasses$ClzWithClinit");
    Truth.assertThat(marks.get(2).getTagStringValue()).contains("clinit");

    assertEquals(marks.get(3).withTaskName("task"), marks.get(3));

    assertEquals(marks.get(4).withTaskName("task"), marks.get(4));

    // Ignore the regular tag at 5

    assertEquals(marks.get(6).getTagKey(), "PerfMark.startCallSite");
    Truth.assertThat(marks.get(6).getTagStringValue()).contains("TransformerTestClasses$ClzWithClinit");
    Truth.assertThat(marks.get(6).getTagStringValue()).contains("clinit");

    assertEquals(marks.get(7).getTagKey(), "PerfMark.stopCallSite");
    Truth.assertThat(marks.get(7).getTagStringValue()).contains("TransformerTestClasses$ClzWithClinit");
    Truth.assertThat(marks.get(7).getTagStringValue()).contains("clinit");

    // Ignore the regular tag at 8

    assertEquals(marks.get(9).withTaskName("task"), marks.get(9));
  }

  @Test
  public void transform_toplevel() throws Exception {
    PerfMark.setEnabled(true);
    Storage.clearLocalStorage();

    Class<?> clz = transformAndLoad(ClzFooter.class);
    Constructor<?> ctor = clz.getDeclaredConstructor();
    ctor.setAccessible(true);
    ctor.newInstance();
    List<Mark> marks = Storage.readForTest();
    assertThat(marks).hasSize(10);

    assertEquals(marks.get(0).withTaskName("task"), marks.get(0));

    assertEquals(marks.get(1).getTagKey(), "PerfMark.startCallSite");
    Truth.assertThat(marks.get(1).getTagStringValue()).contains("ClzFooter");
    Truth.assertThat(marks.get(1).getTagStringValue()).contains("init");

    assertEquals(marks.get(2).getTagKey(), "PerfMark.stopCallSite");
    Truth.assertThat(marks.get(2).getTagStringValue()).contains("ClzFooter");
    Truth.assertThat(marks.get(2).getTagStringValue()).contains("init");

    assertEquals(marks.get(3).withTaskName("task"), marks.get(3));

    assertEquals(marks.get(4).withTaskName("task"), marks.get(4));

    // Ignore the regular tag at 5

    assertEquals(marks.get(6).getTagKey(), "PerfMark.startCallSite");
    Truth.assertThat(marks.get(6).getTagStringValue()).contains("ClzFooter");
    Truth.assertThat(marks.get(6).getTagStringValue()).contains("init");

    assertEquals(marks.get(7).getTagKey(), "PerfMark.stopCallSite");
    Truth.assertThat(marks.get(7).getTagStringValue()).contains("ClzFooter");
    Truth.assertThat(marks.get(7).getTagStringValue()).contains("init");

    // Ignore the regular tag at 8

    assertEquals(marks.get(9).withTaskName("task"), marks.get(9));
  }

  @Test
  public void transform_anonymousClass() throws Exception {
    PerfMark.setEnabled(true);
    Storage.clearLocalStorage();

    Class<?> clz = transformAndLoad(new Runnable() {
      // avoid IntelliJ thinking this should be a lambda.
      public volatile int a;
      @Override
      public void run() {
        PerfMark.startTask("task");
        PerfMark.stopTask("task");
      }
    }.getClass());
    Constructor<?> ctor = clz.getDeclaredConstructor(PerfMarkTransformerTest.class);
    ctor.setAccessible(true);
    Runnable instance = (Runnable) ctor.newInstance(this);
    instance.run();
    List<Mark> marks = Storage.readForTest();
    assertThat(marks).hasSize(4);

    assertEquals(marks.get(0).withTaskName("task"), marks.get(0));

    assertEquals(marks.get(1).getTagKey(), "PerfMark.startCallSite");
    Truth.assertThat(marks.get(1).getTagStringValue()).contains("PerfMarkTransformerTest$");
    Truth.assertThat(marks.get(1).getTagStringValue()).contains("run");

    assertEquals(marks.get(2).getTagKey(), "PerfMark.stopCallSite");
    Truth.assertThat(marks.get(2).getTagStringValue()).contains("PerfMarkTransformerTest$");
    Truth.assertThat(marks.get(2).getTagStringValue()).contains("run");

    assertEquals(marks.get(3).withTaskName("task"), marks.get(3));
  }

  private static Class<?> transformAndLoad(Class<?> toLoad, Class<?> ...extra) throws IOException {
    Map<String, Class<?>> toTransform = new HashMap<>();
    for (Class<?>  clz : extra) {
      toTransform.put(clz.getName(), clz);
    }
    toTransform.put(toLoad.getName(), toLoad);
    try {
      return new ClassLoader(toLoad.getClassLoader()) {

        @Override
        protected Class<?> loadClass(String binaryClassName, boolean resolve) throws ClassNotFoundException {
          Class<?> existing = toTransform.get(binaryClassName);
          if (existing == null) {
            return super.loadClass(binaryClassName, resolve);
          }
          String internalFullyQualifiedClassName = binaryClassName.replace('.', '/');
          String resourceName = internalFullyQualifiedClassName + ".class";
          byte[] data;
          try (InputStream stream = getResourceAsStream(resourceName)) {
            data = stream.readAllBytes();
          } catch (IOException e) {
            throw new RuntimeException(e);
          }
          byte[] newClassBytes =
              new PerfMarkTransformer(null).transformInternal(
                  this, internalFullyQualifiedClassName, existing, null, data);
          if (newClassBytes == null) {
            newClassBytes = data;
          }
          Class<?> newClass = defineClass(binaryClassName, newClassBytes, 0, newClassBytes.length);
          if (resolve) {
            resolveClass(newClass);
          }
          return newClass;
        }
      }.loadClass(toLoad.getName());
    } catch (ClassNotFoundException e) {
      throw new RuntimeException(e);
    }
  }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Bidr. Känn. Finl. Nat. Folk 32: 243 (1879)

#### Original name
Helvella retiruga Bull., 1791

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML>

        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <title>Introduction | Summary</title>
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="generator" content="GitBook 2.6.5">

        <meta name="HandheldFriendly" content="true"/>
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="black">
        <link rel="apple-touch-icon-precomposed" sizes="152x152" href="gitbook/images/apple-touch-icon-precomposed-152.png">
        <link rel="shortcut icon" href="gitbook/images/favicon.ico" type="image/x-icon">

    <link rel="stylesheet" href="gitbook/style.css">

        <link rel="stylesheet" href="gitbook/plugins/gitbook-plugin-highlight/website.css">

        <link rel="stylesheet" href="gitbook/plugins/gitbook-plugin-search/search.css">

        <link rel="stylesheet" href="gitbook/plugins/gitbook-plugin-fontsettings/website.css">

        <link rel="stylesheet" href="./styles/website.css">

    <link rel="next" href="./vcr_-_an_introduction.html" />

                        Introduction

                            1.

                        VCR - An Introduction

                            2.

                        Getting Started

                            3.

                        Javascript API

                            3.1.

                        Instantiate new VCR

                            3.2.

                        API Functions

                    Published with GitBook

        Summary

Summary

Introduction

VCR - An Introduction

Getting Started

Javascript API

Instantiate new VCR

API Functions


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>

Loading...

  PacketAlignmentFactor
  RNDIS_Initialize_Complete_t

  Page
  HID_Usage_t

  Params
  SI_PIMA_Container_t

  Parent
  HID_CollectionPath_t

  ParityType

    USB_ClassInfo_CDC_Device_t::ParityType()
    USB_ClassInfo_CDC_Host_t::ParityType()

  PeripheralQualifier
  SCSI_Inquiry_Response_t

  PerPacketInfoLength
  RNDIS_Packet_Message_t

  PerPacketInfoOffset
  RNDIS_Packet_Message_t

  Physical
  HID_ReportItem_Attributes_t

  PollingIntervalMS
  USB_Descriptor_Endpoint_t

  PreviousValue
  HID_ReportItem_t

  PrevReportINBuffer
  USB_ClassInfo_HID_Device_t

  PrevReportINBufferSize
  USB_ClassInfo_HID_Device_t

  ProductID

    SCSI_Inquiry_Response_t::ProductID()
    USB_Descriptor_Device_t::ProductID()

  ProductStrIndex
  USB_Descriptor_Device_t

  Protocol

    USB_Descriptor_Device_t::Protocol()
    USB_Descriptor_Interface_t::Protocol()
    USB_Descriptor_Interface_Association_t::Protocol()

Searching...

No Matches


text:
using System;

namespace sly.parser.generator
{
    public class ParserConfigurationException : Exception
    {
        public ParserConfigurationException() : base("unable to configure parser")
        {
        }

        public ParserConfigurationException(string message) : base(message)
        {
        }
    }
}


text:
namespace Sunflower
{

// This is to disable 'this pointer in initializer list' warning
// It's okay to do this as the state that is used is defined
#pragma warning(push)
#pragma warning(disable: 4355)
Window::Window(Application& application, const WindowProperties& windowProperties)
    : windowProperties_(windowProperties),
      remove_(false),
      initialized_(false),
      application_(application),
      device_(application_.GetDevice(windowProperties_.adapter)),
      hWnd_(SetupWindow()),
      swapChain_(device_, *this)
{
    initialized_ = true;
}
#pragma warning(pop)

Window::HWNDLifetime Window::SetupWindow()
{
    // This goes here instead of constructor body as this is called first
    MEMBER_LOG_STRING_TAG(L"Window");

    DWORD windowStyle;
    int x = 0;
    int y = 0;

    Dimensions dimensions = windowProperties_.dimensions;

    if(windowProperties_.windowType == WindowType::WINDOWED)
    {
        // Create a normal window but without maximize
        windowStyle = WS_CAPTION | WS_SYSMENU | WS_MINIMIZE;
        x = y = CW_USEDEFAULT;
    }
    else
    {
        // Create a window without borders or title bar
        windowStyle = WS_POPUP;

        // Set window to show on proper monitor
        // TODO: Make this more robust
        auto outputInfo = windowProperties_.adapter.GetOutputs().at(windowProperties_.output).GetDescription();

        x = outputInfo.DesktopCoordinates.left;
        y = outputInfo.DesktopCoordinates.top;

        if(windowProperties_.windowType == WindowType::FULLSCREEN)
        {
            ShowCursor(FALSE);
            // Create a window that covers the entire requested monitor
            // This makes a nicer transition if the resolution is set lower than the desktop
            dimensions = Dimensions(outputInfo.DesktopCoordinates.right - x, outputInfo.DesktopCoordinates.bottom - y);
        }
    }

    MEMBER_LOG << L"Creating window: " << windowProperties_.name.c_str() << std::endl
        << L"Adapter: " << windowProperties_.adapter.GetDescription().DeviceId << L":" << windowProperties_.adapter.GetDescription().Description << std::endl
        << L"Output:" << windowProperties_.output << std::endl
        << L"Dimensions: " << dimensions.GetWidth() << L"x" << dimensions.GetHeight();

    HWND tempHWnd;
    tempHWnd = CreateWindow(application_.GetWindowClass().GetName().c_str(),
                         windowProperties_.name.c_str(),
                         windowStyle,
                         x, y,
                         dimensions.GetWidth(), dimensions.GetHeight(),
                         NULL, NULL,
                         application_.GetWindowClass().GetHInstance(),
                         this);

    if(!tempHWnd)
        e_throw_win_error(CreateWindowException(), "CreateWindow");

    ShowWindow(tempHWnd, application_.GetNCmdShow());
    UpdateWindow(tempHWnd);

    return HWNDLifetime(tempHWnd);
}

void Window::OnResize(const Dimensions& dimensions)
{
    windowProperties_.dimensions = dimensions;

    swapChain_.Resize(dimensions);
}

boost::optional<LRESULT> Window::WindowProcedure(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    if(remove_ || !initialized_)
        return boost::optional<LRESULT>();

    switch(msg)
    {
    case WM_DESTROY:
        MEMBER_LOG << L"WM_DESTROY called: " << windowProperties_.name;
        remove_ = true;
        return boost::optional<LRESULT>(0);
        break;

    case WM_SIZE:
        OnResize(Dimensions(LOWORD(lParam), HIWORD(lParam)));
        return boost::optional<LRESULT>(0);
        break;

    default:
        return boost::optional<LRESULT>();
    }
}

}


text:
import configureReducer from './configureReducer';
import configureMiddleware from './configureMiddleware';
import { applyMiddleware, createStore } from 'redux';

export default function configureStore(options) {
  const {
    initialState,
    platformDeps = {},
    platformMiddleware = [],
    platformReducers = {},
  } = options;

  const reducer = configureReducer(
    initialState,
    platformReducers
  );

  const middleware = configureMiddleware(
    initialState,
    platformDeps,
    platformMiddleware
  );

  const store = createStore(
    reducer,
    initialState,
    applyMiddleware(...middleware)
  );

  // Enable hot reload where available.
  if (module.hot) {
    const replaceReducer = configureReducer =>
      store.replaceReducer(configureReducer(initialState, platformReducers));

    if (initialState.device.isReactNative) {
      module.hot.accept(() => {
        replaceReducer(require('./configureReducer').default);
      });
    } else {
      module.hot.accept('./configureReducer', () => {
        replaceReducer(require('./configureReducer'));
      });
    }
  }

  return store;
}


text:
<?php

declare(strict_types=1);

namespace sad_spirit\pg_builder;

use sad_spirit\pg_builder\nodes\{
    CommonTableExpression,
    GenericNode,
    WithClause
};

/**
 * Base class for Nodes representing complete SQL statements
 *
 * @psalm-property WithClause $with
 *
 * @property WithClause|CommonTableExpression[] $with
 */
abstract class Statement extends GenericNode
{
    /** @var WithClause */
    protected $p_with;

    /**
     * Parser instance, used when adding nodes to a statement as SQL strings
     * @var Parser|null
     */
    private $parser;

    public function __construct()
    {
        $this->generatePropertyNames();

        $this->p_with = new WithClause();
        $this->p_with->parentNode = $this;
    }

    public function setWith(WithClause $with): void
    {
        $this->setRequiredProperty($this->p_with, $with);
    }

    /**
     * Sets the parser instance to use
     * @param Parser $parser
     */
    public function setParser(Parser $parser): void
    {
        $this->parser = $parser;
    }

    /**
     * Returns the parser
     * @return Parser|null
     */
    public function getParser(): ?Parser
    {
        if (
            null === $this->parser && null !== $this->parentNode
            && null !== ($parser = $this->parentNode->getParser())
        ) {
            $this->setParser($parser);
        }
        return $this->parser;
    }

    public function setParentNode(Node $parent = null): void
    {
        parent::setParentNode($parent);
        if (
            null === $this->parser && null !== $this->parentNode
            && null !== ($parser = $this->parentNode->getParser())
        ) {
            $this->setParser($parser);
        }
    }
}


text:
<a href="<?php echo $helpLink; ?>" target="_blank" rel="noopener noreferrer" class="wfhelp"><a href="<?php echo $helpLink; ?>" target="_blank" rel="noopener noreferrer"><?php echo $helpLabel; ?>

	<?php if (!wfConfig::get('firewallEnabled')) { ?>

Rate limiting rules and advanced blocking are disabled. You can enable it on the Wordfence Options page at the top.

	<?php } ?>

			IP address range

				<input type="text" id="ipRange" name="ipRange" class="wf-form-control" value="<?php
				if( isset( $_GET['wfBlockRange'] ) && preg_match('/^[\da-f\.\s\t\-:]+$/i', $_GET['wfBlockRange']) ){ echo wp_kses($_GET['wfBlockRange'], array()); }
				?>" onkeyup="WFAD.calcRangeTotal();">

				Examples: 192.168.200.200 - 192.168.200.220

			Hostname

				<input type="text" id="hostname" name="hostname" class="wf-form-control" value="<?php
				if( isset( $_GET['wfBlockHostname'] ) ){ echo esc_attr($_GET['wfBlockHostname']); }
				?>">
				Examples: *.amazonaws.com, *.linode.com
				Using this setting will make a DNS query per unique IP address (per visitor), and can add additional load. High traffic
 sites may not want to use this feature.

			User-Agent (browser) that matches

				<input type="text" id="uaRange" name="uaRange" class="wf-form-control">
				(Case insensitive)
				Examples: *badRobot*, AnotherBadRobot*, *someBrowserSuffix

			Referer (website visitor arrived from) that matches

				<input type="text" id="wfreferer" name="wfreferer" class="wf-form-control">
				(Case insensitive)
				Examples: *badWebsite*, AnotherBadWebsite*, *someWebsiteSuffix

			Enter a reason you're blocking this visitor pattern

				<input type="text" id="wfReason" name="wfReason" class="wf-form-control">
				(Case insensitive)
				Why a reason: The reason you specify above is for your own record keeping.

				Block Visitors Matching this Pattern

Current list of ranges and patterns you've blocked


text:
<?php

/**
 * Shade
 *
 * @package Shade
 * @version 1.0.0
 * @author  Denis Shapkin <i@denis-shapkin.ru>
 */

/* Routing */

/**
 * @var \ShadeApp\App $app
 */

$router = $app->getRouter();
if ($router instanceof \Shade\Router\Wildcard) {
    $router->addMapping('/', '\\Shade\\Controller\\Cli', 'indexAction');
    $router->addMapping('help', '\\Shade\\Controller\\Cli', 'helpAction');
    $router->addMapping('new', '\\Shade\\Controller\\Cli', 'newAction');
    $router->addMapping('run', '\\Shade\\Controller\\Cli', 'runAction');
}


text:
'''
Functions to check access to THREDDS datasets.

Created on 26 Sep 2011

@author: rwilkinson
'''
from dapbench.thredds.lib.catalog_parser import CatalogParser
from dapbench.thredds.lib.dataset_config import Access
import dapbench.thredds.lib.httpget as httpget
from dapbench.thredds.lib.results import Results
import dapbench.thredds.lib.url_util as url_util

SERVICE_TYPES_RETURNING_CATALOGS = ['Catalog', 'Resolver']
SERVICE_TYPES_NOT_TO_CHECK = ['QueryCapability']

def check_catalog(url, config):
    """Checks access to the contents of a THREDDS catalog specified by the URL of a catalog XML
    file.
    @param url - URL of catalog XML file
    @param config - configuration
    @return accumulated results of check
    """
    results = Results()
    _check_catalog(url, config, results)
    return results

def _check_catalog(url, config, results):
    """Checks access to the contents of a THREDDS catalog specified by the URL of a catalog XML
    file - may be called recursively.
    @param url - URL of catalog XML file
    @param config - configuration
    @param results - accumulated results of check
    """
    base_url = url_util.get_base_url(url)
    try:
        catalog_xml = httpget.fetch_from_url(url, config)
    except Exception, exc:
        print("### Could not retrieve catalog %s: %s" % (url, exc.__str__()))
        return
    cat = CatalogParser(catalog_xml)
    service_map = {}
    for s in cat.get_services(config.service_extensions, config.public_service_extensions,
                              config.forbidden_service_extensions):
        service_map[s.name] = s
        for c in s.children:
            service_map[c.name] = c

    for d in cat.get_datasets():
        service = service_map.get(d.service_name, None)
        if (not service
                or ((service.service_type not in SERVICE_TYPES_RETURNING_CATALOGS)
                    and (service.service_type not in SERVICE_TYPES_NOT_TO_CHECK))):
            if not config.quiet:
                print("Dataset: %s" % d.name)
            if not config.listonly:
                check_dataset(base_url, service_map, d, config, results)

    if config.recurse:
        for d in cat.get_datasets():
            service = service_map.get(d.service_name, None)
            if service and service.service_type in SERVICE_TYPES_RETURNING_CATALOGS:
                ref_url = url_util.make_url(base_url, d.url_path)
                if not config.quiet:
                    print("Dataset: %s  Catalog ref: %s" % (d.name, ref_url))
                _check_catalog(ref_url, config, results)

        for c in cat.get_catalog_refs(base_url):
            if not config.quiet:
                print("Catalog ref: %s" % c.url)
            _check_catalog(c.url, config, results)

def check_dataset(base_url, service_map, dataset, config, results):
    """Checks access to a THREDDS dataset by all configured access methods.
    @param base_url - base URL of the catalog
    @param service_map - map of service names to service configurations read from the catalog
    @param config - configuration
    @param results - accumulated results of check
    """
    dataset_results = Results()
    for access in dataset.get_accesses():
        check_access(base_url, service_map, access, config, dataset_results)

    if dataset_results.inconsistent_count:
        results.add_inconsistent()
    else:
        if dataset_results.access_allowed_count + dataset_results.access_denied_count > 0:
            if dataset_results.access_denied_count == 0:
                results.add_access_allowed()
            elif dataset_results.access_allowed_count == 0:
                results.add_access_denied()
            else:
                results.add_inconsistent()
    if dataset_results.untested_count:
        results.add_untested()
    for st in dataset_results.untested_service_types:
        results.add_untested_service_type(st)

def check_access(base_url, service_map, access, config, results):
    """Checks access to a THREDDS dataset with specified access details. If the service type is
    Compound, it calls this function recursively.
    @param base_url - base URL of the catalog
    @param service_map - map of service names to service configurations read from the catalog
    @param access - dataset access details
    @param config - configuration
    @param results - accumulated results of check
    """
    service_name = access.service_name
    if service_name in service_map:
        service = service_map[service_name]
        if service.service_type == 'Compound':
            for child_service in service.children:
                check_access(base_url, service_map, Access(access.url_path, child_service.name),
                             config, results)
        else:
            check_single_access(base_url, service, access, config, results)

def check_single_access(base_url, service, access, config, results):
    """Checks access to a THREDDS dataset with specified access details for a single service, i.e.,
    for a a service type that is not Compound.
    @param base_url - base URL of the catalog
    @param service_map - map of service names to service configurations read from the catalog
    @param access - dataset access details
    @param config - configuration
    @param results - accumulated results of check
    """
    if service.service_type not in config.services_to_test:
        results.add_untested()
        results.add_untested_service_type(service.service_type)
        if not config.quiet:
            print("### Service of type %s not tested." % service.service_type)
        return

    access_allowed_count = 0
    access_denied_count = 0
    inconsistent = False
    extensions = [''] if service.extensions is None else service.extensions
    url = url_util.make_url(base_url, service.base_url) + access.url_path + service.suffix
    for extension in extensions:
        extended_url = url + extension
        (rc, msg, success) = httpget.check_url(extended_url, config)
        if not config.quiet:
            print("  %d  [%s]  %s" % (rc, msg, extended_url))
        if service.is_public(extension):
            if not success:
                inconsistent = True
                if not config.quiet:
                    print("### Expected access allowed.")
        elif service.is_forbidden(extension):
            if success:
                inconsistent = True
                if not config.quiet:
                    print("### Expected access denied.")
        else:
            if success:
                access_allowed_count += 1
            else:
                access_denied_count += 1

    if access_allowed_count + access_denied_count > 0:
        if access_denied_count == 0:
            results.add_access_allowed()
        elif access_allowed_count == 0:
            results.add_access_denied()
        else:
            inconsistent = True
            if not config.quiet:
                print("### Expected accesses either all allowed or all denied (excluding public and forbidden).")
    if inconsistent:
        results.add_inconsistent()


text:
//
// $Id: ChromatogramListForm.cs 2322 2010-10-21 22:15:34Z chambm $
//
//
// Original author: Matt Chambers <matt.chambers .@. vanderbilt.edu>
//
// Copyright 2009 Vanderbilt University - Nashville, TN 37232
//
// 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.
//

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DigitalRune.Windows.Docking;
using pwiz.CLI.cv;
using pwiz.CLI.data;
using pwiz.CLI.msdata;
using pwiz.CLI.analysis;
using seems.Misc;

namespace seems
{
	public delegate void ChromatogramListCellClickHandler( object sender, ChromatogramListCellClickEventArgs e );
	public delegate void ChromatogramListCellDoubleClickHandler( object sender, ChromatogramListCellDoubleClickEventArgs e );
    public delegate void ChromatogramListFilterChangedHandler( object sender, ChromatogramListFilterChangedEventArgs e );

	public partial class ChromatogramListForm : DockableForm
	{
        Dictionary<int, Chromatogram> chromatogramList; // indexable by Chromatogram.Index

		public DataGridView GridView { get { return gridView; } }

		public event ChromatogramListCellClickHandler CellClick;
		public event ChromatogramListCellDoubleClickHandler CellDoubleClick;
        public event ChromatogramListFilterChangedHandler FilterChanged;

		protected void OnCellClick( DataGridViewCellMouseEventArgs e )
		{
			if( CellClick != null )
				CellClick( this, new ChromatogramListCellClickEventArgs( this, e ) );
		}

		protected void OnCellDoubleClick( DataGridViewCellMouseEventArgs e )
		{
			if( CellDoubleClick != null )
				CellDoubleClick( this, new ChromatogramListCellDoubleClickEventArgs( this, e ) );
		}

        protected void OnFilterChanged()
        {
            if( FilterChanged != null )
                FilterChanged( this, new ChromatogramListFilterChangedEventArgs( this, chromatogramDataSet ) );
        }

		public ChromatogramListForm()
		{
			InitializeComponent();

            initializeGridView();
		}

		private void initializeGridView()
		{
            // force handle creation
            IntPtr dummy = gridView.Handle;
            chromatogramList = new Dictionary<int, Chromatogram>();

            typeDataGridViewTextBoxColumn.ToolTipText = new CVTermInfo( CVID.MS_chromatogram_type ).def;
		}

        private void gridView_DataBindingComplete( object sender, DataGridViewBindingCompleteEventArgs e )
        {
            if( e.ListChangedType == ListChangedType.Reset )
                OnFilterChanged();
        }

        public void updateRow( ChromatogramDataSet.ChromatogramTableRow row, Chromatogram chromatogram )
        {
            chromatogramList[chromatogram.Index] = chromatogram;

            pwiz.CLI.msdata.Chromatogram c = chromatogram.Element;
            DataProcessing dp = chromatogram.DataProcessing;
            if( dp == null )
                dp = c.dataProcessing;

            row.Type = c.cvParamChild( CVID.MS_chromatogram_type ).name;
            row.DataPoints = c.defaultArrayLength;
            row.DpId = ( dp == null || dp.id.Length == 0 ? "unknown" : dp.id );
        }

        public void Add( Chromatogram chromatogram )
        {
            ChromatogramDataSet.ChromatogramTableRow row = chromatogramDataSet.ChromatogramTable.NewChromatogramTableRow();
            row.Id = chromatogram.Id;

            /*if( nativeIdFormat != CVID.CVID_Unknown )
            {
                gridView.Columns["Id"].Visible = false;

                string[] nameValuePairs = chromatogram.Id.Split( " ".ToCharArray() );
                foreach( string nvp in nameValuePairs )
                {
                    string[] nameValuePair = nvp.Split( "=".ToCharArray() );
                    row[nameValuePair[0]] = nameValuePair[1];
                }
            }*/

            row.Index = chromatogram.Index;
            updateRow( row, chromatogram );
            chromatogramDataSet.ChromatogramTable.AddChromatogramTableRow( row );

            //int rowIndex = gridView.Rows.Add();
            //gridView.Rows[rowIndex].Tag = chromatogram;
            chromatogram.Tag = this;

            //UpdateRow( rowIndex );
        }

        public int IndexOf( Chromatogram chromatogram )
        {
            return chromatogramBindingSource.Find( "Index", chromatogram.Index );
        }

        public Chromatogram GetChromatogram( int index )
        {
            return chromatogramList[(int) ( chromatogramBindingSource[index] as DataRowView )[1]];
        }

        public void UpdateAllRows()
        {
            for( int i = 0; i < gridView.RowCount; ++i )
                UpdateRow( i );
        }

        public void UpdateRow( int rowIndex )
        {
            UpdateRow( rowIndex, null );
        }

        public void UpdateRow( int rowIndex, ChromatogramList chromatogramList )
        {
            ChromatogramDataSet.ChromatogramTableRow row = ( chromatogramBindingSource[rowIndex] as DataRowView ).Row as ChromatogramDataSet.ChromatogramTableRow;

            if( chromatogramList != null )
            {
                this.chromatogramList[row.Index].ChromatogramList = chromatogramList;
                updateRow( row, this.chromatogramList[row.Index] );
                //dp = rowChromatogram.DataProcessing;
                //row.Tag = rowChromatogram = new Chromatogram( rowChromatogram, s );
                //rowChromatogram.DataProcessing = dp;
            } else
            {
                updateRow( row, this.chromatogramList[row.Index] );
                //s = rowChromatogram.Element;
                //dp = rowChromatogram.DataProcessing;
            }
        }

        private void gridView_CellMouseClick( object sender, DataGridViewCellMouseEventArgs e )
        {
            //if( e.RowIndex > -1 && gridView.Columns[e.ColumnIndex] is DataGridViewLinkColumn )
            //    gridView_ShowCellToolTip( gridView[e.ColumnIndex, e.RowIndex] );
            OnCellClick( e );
        }

        private void gridView_CellMouseDoubleClick( object sender, DataGridViewCellMouseEventArgs e )
        {
            OnCellDoubleClick( e );
        }

        private void selectColumnsToolStripMenuItem_Click( object sender, EventArgs e )
        {

        }

        private void gridView_ColumnHeaderMouseClick( object sender, DataGridViewCellMouseEventArgs e )
        {
            if( e.Button == MouseButtons.Right )
            {
                Rectangle cellRectangle = gridView.GetCellDisplayRectangle( e.ColumnIndex, e.RowIndex, true );
                Point cellLocation = new Point( cellRectangle.Left, cellRectangle.Top );
                cellLocation.Offset( e.Location );
                selectColumnsMenuStrip.Show( gridView, cellLocation );
            }
        }
	}

    public class ChromatogramListCellClickEventArgs : DataGridViewCellMouseEventArgs
	{
		private Chromatogram chromatogram;
		public Chromatogram Chromatogram { get { return chromatogram; } }

		internal ChromatogramListCellClickEventArgs( ChromatogramListForm sender, DataGridViewCellMouseEventArgs e )
            : base( e.ColumnIndex, e.RowIndex, e.X, e.Y, e )
		{
            if( e.RowIndex > -1 && e.RowIndex < sender.GridView.RowCount )
                chromatogram = sender.GetChromatogram( e.RowIndex );
		}
	}

    public class ChromatogramListCellDoubleClickEventArgs : DataGridViewCellMouseEventArgs
	{
		private Chromatogram chromatogram;
		public Chromatogram Chromatogram { get { return chromatogram; } }

		internal ChromatogramListCellDoubleClickEventArgs( ChromatogramListForm sender, DataGridViewCellMouseEventArgs e )
			: base( e.ColumnIndex, e.RowIndex, e.X, e.Y, e )
		{
            if( e.RowIndex > -1 && e.RowIndex < sender.GridView.RowCount )
                chromatogram = sender.GetChromatogram( e.RowIndex );
		}
	}

    public class ChromatogramListFilterChangedEventArgs : EventArgs
    {
        /// <summary>
        /// The number of spectra that matched the new filter.
        /// </summary>
        public int Matches { get { return matches; } }
        private int matches;

        /// <summary>
        /// The total number of spectra.
        /// </summary>
        public int Total { get { return total; } }
        private int total;

        internal ChromatogramListFilterChangedEventArgs( ChromatogramListForm sender, ChromatogramDataSet dataSet )
        {
            matches = sender.GridView.RowCount;
            total = dataSet.ChromatogramTable.Count;
        }
    }
}


text:
<!DOCTYPE html>

    <title>Rust Cookbook</title>
    <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../icons/css/fontello-embedded.css">
<link rel="stylesheet" href="../static/bulma-purified.css">
<link href="https://fonts.googleapis.com/css?family=Quicksand" rel="stylesheet">

The Cookbook

        <button id="burger" class="button is-primary navbar-burger">

         </button>

        General

Home

About

Search

Search Lite

        Recipies

Filesystem

Encoding

Caching

Text processing

Science

Rust patterns

OS

Filesystem

Crates for dealing with files and filesystems.

                        Read lines of strings from a file

Crates

                            crate
                            std

crates.io


text:
See [the documentation](http://amp.ampersandjs.com#amp-values) for more info.

Part of the [amp project](http://amp.ampersandjs.com#amp-values), initially created by [@HenrikJoreteg](http://twitter.com/henrikjoreteg).


text:
FACEBOOK API proof of concept
========================

this project was created just to check how to publish posts on Facebook on behalf of User i.e. for marketing purposes or to create famous 'facebook various'


text:
package org.openengsb.labs.paxexam.karaf.container.internal.runner;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.ops4j.io.Pipe;

public class InternalRunner {
    private Process m_frameworkProcess;
    private Thread m_shutdownHook;

    public synchronized void exec(CommandLineBuilder commandLine, final File workingDirectory,
            final String[] envOptions) {
        if (m_frameworkProcess != null)
        {
            throw new IllegalStateException("Platform already started");
        }

        try
        {
            m_frameworkProcess =
                Runtime.getRuntime().exec(commandLine.toArray(), createEnvironmentVars(envOptions),
                    workingDirectory);
        } catch (IOException e)
        {
            throw new IllegalStateException("Could not start up the process", e);
        }

        m_shutdownHook = createShutdownHook(m_frameworkProcess);
        Runtime.getRuntime().addShutdownHook(m_shutdownHook);

        waitForExit();
    }

    private String[] createEnvironmentVars(String[] envOptions)
    {
        List<String> env = new ArrayList<String>();
        Map<String, String> getenv = System.getenv();
        for (String key : getenv.keySet()) {
            env.add(key + "=" + getenv.get(key));
        }
        if (envOptions != null) {
            Collections.addAll(env, envOptions);
        }
        return env.toArray(new String[env.size()]);
    }

    /**
     * {@inheritDoc}
     */
    public void shutdown()
    {
        try {
            if (m_shutdownHook != null) {
                synchronized (m_shutdownHook) {
                    if (m_shutdownHook != null) {
                        Runtime.getRuntime().removeShutdownHook(m_shutdownHook);
                        m_frameworkProcess = null;
                        m_shutdownHook.run();
                        m_shutdownHook = null;
                    }
                }
            }
        } catch (IllegalStateException ignore)
        {
            // just ignore
        }
    }

    /**
     * Wait till the framework process exits.
     */
    public void waitForExit()
    {
        synchronized (m_frameworkProcess) {
            try
            {
                m_frameworkProcess.waitFor();
                shutdown();
            } catch (Throwable e)
            {
                shutdown();
            }
        }
    }

    /**
     * Create helper thread to safely shutdown the external framework process
     *
     * @param process framework process
     *
     * @return stream handler
     */
    private Thread createShutdownHook(final Process process)
    {
        final Pipe errPipe = new Pipe(process.getErrorStream(), System.err).start("Error pipe");
        final Pipe outPipe = new Pipe(process.getInputStream(), System.out).start("Out pipe");
        final Pipe inPipe = new Pipe(process.getOutputStream(), System.in).start("In pipe");

        return new Thread(
            new Runnable()
            {
                @Override
                public void run()
                {
                    inPipe.stop();
                    outPipe.stop();
                    errPipe.stop();

                    try
                    {
                        process.destroy();
                    }
                    catch (Exception e)
                    {
                        // ignore if already shutting down
                    }
                }
            },
            "Pax-Runner shutdown hook");
    }
}


text:
package com.google.android.exoplayer2.offline;

import android.net.Uri;
import com.google.android.exoplayer2.upstream.ParsingLoadable.Parser;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/** A manifest parser that includes only the tracks identified by the given track keys. */
public final class FilteringManifestParser<T extends FilterableManifest<T, K>, K>
    implements Parser<T> {

  private final Parser<T> parser;
  private final List<K> trackKeys;

  /**
   * @param parser A parser for the manifest that will be filtered.
   * @param trackKeys The track keys. If null or empty then filtering will not occur.
   */
  public FilteringManifestParser(Parser<T> parser, List<K> trackKeys) {
    this.parser = parser;
    this.trackKeys = trackKeys;
  }

  @Override
  public T parse(Uri uri, InputStream inputStream) throws IOException {
    T manifest = parser.parse(uri, inputStream);
    return trackKeys == null || trackKeys.isEmpty() ? manifest : manifest.copy(trackKeys);
  }
}


text:
package com.jeecms.cms.manager.assist.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeecms.cms.dao.assist.CmsFriendlinkCtgDao;
import com.jeecms.cms.entity.assist.CmsFriendlinkCtg;
import com.jeecms.cms.manager.assist.CmsFriendlinkCtgMng;
import com.jeecms.common.hibernate3.Updater;

@Service
@Transactional
public class CmsFriendlinkCtgMngImpl implements CmsFriendlinkCtgMng {
	@Transactional(readOnly = true)
	public List<CmsFriendlinkCtg> getList(Integer siteId) {
		return dao.getList(siteId);
	}

	public int countBySiteId(Integer siteId) {
		return dao.countBySiteId(siteId);
	}

	@Transactional(readOnly = true)
	public CmsFriendlinkCtg findById(Integer id) {
		CmsFriendlinkCtg entity = dao.findById(id);
		return entity;
	}

	public CmsFriendlinkCtg save(CmsFriendlinkCtg bean) {
		dao.save(bean);
		return bean;
	}

	public CmsFriendlinkCtg update(CmsFriendlinkCtg bean) {
		Updater<CmsFriendlinkCtg> updater = new Updater<CmsFriendlinkCtg>(bean);
		bean = dao.updateByUpdater(updater);
		return bean;
	}

	public void updateFriendlinkCtgs(Integer[] ids, String[] names,
			Integer[] priorities) {
		if (ids == null || ids.length == 0) {
			return;
		}
		CmsFriendlinkCtg ctg;
		for (int i = 0; i < ids.length; i++) {
			ctg = dao.findById(ids[i]);
			ctg.setName(names[i]);
			ctg.setPriority(priorities[i]);
		}
	}

	public CmsFriendlinkCtg deleteById(Integer id) {
		CmsFriendlinkCtg bean = dao.deleteById(id);
		return bean;
	}

	public CmsFriendlinkCtg[] deleteByIds(Integer[] ids) {
		CmsFriendlinkCtg[] beans = new CmsFriendlinkCtg[ids.length];
		for (int i = 0, len = ids.length; i < len; i++) {
			beans[i] = deleteById(ids[i]);
		}
		return beans;
	}

	private CmsFriendlinkCtgDao dao;

	@Autowired
	public void setDao(CmsFriendlinkCtgDao dao) {
		this.dao = dao;
	}
}


text:
package org.apache.geode.management.internal.cli.util;

import static org.apache.geode.internal.Assert.assertNotNull;

import java.io.FileNotFoundException;
import java.util.EmptyStackException;
import java.util.Stack;

import org.apache.geode.GemFireException;
import org.apache.geode.internal.lang.StringUtils;
import org.apache.geode.internal.lang.SystemUtils;
import org.apache.geode.internal.util.IOUtils;
import org.apache.geode.management.internal.cli.i18n.CliStrings;

public class JdkTool {
  protected static final String JAVA_HOME = System.getProperty("java.home");

  public static String getJVisualVMPathname() {
    if (SystemUtils.isMacOSX()) {
      try {
        return IOUtils.verifyPathnameExists(
            "/System/Library/Java/Support/VisualVM.bundle/Contents/Home/bin/jvisualvm");
      } catch (FileNotFoundException e) {
        throw new VisualVmNotFoundException(CliStrings.START_JVISUALVM__NOT_FOUND_ERROR_MESSAGE, e);
      }
    } else { // Linux, Solaris, Windows, etc...
      try {
        return getJdkToolPathname("jvisualvm" + getExecutableSuffix(),
            new VisualVmNotFoundException(CliStrings.START_JVISUALVM__NOT_FOUND_ERROR_MESSAGE));
      } catch (VisualVmNotFoundException e) {
        if (!SystemUtils.isJavaVersionAtLeast("1.6")) {
          throw new VisualVmNotFoundException(
              CliStrings.START_JVISUALVM__EXPECTED_JDK_VERSION_ERROR_MESSAGE);
        }

        throw e;
      }
    }
  }

  public static String getJConsolePathname() {
    return getJdkToolPathname("jconsole" + getExecutableSuffix(),
        new JConsoleNotFoundException(CliStrings.START_JCONSOLE__NOT_FOUND_ERROR_MESSAGE));
  }

  protected static String getJdkToolPathname(final String jdkToolExecutableName,
      final GemFireException throwable) {
    assertNotNull(jdkToolExecutableName, "The JDK tool executable name cannot be null!");
    assertNotNull(throwable, "The GemFireException cannot be null!");

    Stack<String> pathnames = new Stack<>();

    pathnames.push(jdkToolExecutableName);
    pathnames
        .push(IOUtils.appendToPath(System.getenv("JAVA_HOME"), "..", "bin", jdkToolExecutableName));
    pathnames.push(IOUtils.appendToPath(System.getenv("JAVA_HOME"), "bin", jdkToolExecutableName));
    pathnames.push(IOUtils.appendToPath(JAVA_HOME, "..", "bin", jdkToolExecutableName));
    pathnames.push(IOUtils.appendToPath(JAVA_HOME, "bin", jdkToolExecutableName));

    return getJdkToolPathname(pathnames, throwable);
  }

  protected static String getJdkToolPathname(final Stack<String> pathnames,
      final GemFireException throwable) {
    assertNotNull(pathnames, "The JDK tool executable pathnames cannot be null!");
    assertNotNull(throwable, "The GemFireException cannot be null!");

    try {
      // assume 'java.home' JVM System property refers to the JDK installation directory. note,
      // however, that the
      // 'java.home' JVM System property usually refers to the JRE used to launch this application
      return IOUtils.verifyPathnameExists(pathnames.pop());
    } catch (EmptyStackException ignore) {
      throw throwable;
    } catch (FileNotFoundException ignore) {
      return getJdkToolPathname(pathnames, throwable);
    }
  }

  protected static String getExecutableSuffix() {
    return SystemUtils.isWindows() ? ".exe" : StringUtils.EMPTY;
  }
}


text:
import zeeguu_core

from zeeguu_core.model.exercise_outcome import ExerciseOutcome
from zeeguu_core.model.exercise_source import ExerciseSource

db = zeeguu_core.db

class Exercise(db.Model):
    __table_args__ = {'mysql_collate': 'utf8_bin'}
    __tablename__ = 'exercise'

    id = db.Column(db.Integer, primary_key=True)
    outcome_id = db.Column(db.Integer, db.ForeignKey(ExerciseOutcome.id), nullable=False)
    outcome = db.relationship(ExerciseOutcome)
    source_id = db.Column(db.Integer, db.ForeignKey(ExerciseSource.id), nullable=False)
    source = db.relationship(ExerciseSource)
    solving_speed = db.Column(db.Integer)
    time = db.Column(db.DateTime, nullable=False)

    def __init__(self, outcome, source, solving_speed, time):
        self.outcome = outcome
        self.source = source
        self.solving_speed = solving_speed
        self.time = time

    def short_string_summary(self):
        return str(self.source.id) + self.outcome.outcome[0]

    def __str__(self):
        return f'{self.source.source} ' + str(self.time) + f' {self.outcome.outcome}'

    def __repr__(self):
        return self.__str__()

    @classmethod
    def find(cls,
             user_id=None):
        """
            Find all the exercises for a particular or for all users

            Parameters:
            user_id = user identifier

            return: list of exercises sorted by time in ascending order
        """
        from zeeguu_core.model.bookmark import Bookmark, bookmark_exercise_mapping

        query = cls.query
        if user_id is not None:
            query = query.join(bookmark_exercise_mapping).join(Bookmark).filter(Bookmark.user_id == user_id)
        query = query.order_by('time')

        return query.all()

    def find_user_id(self, db_session):
        """
            Finds related user_id corresponding to the exercise

            Parameters:
            db_session = database session

            returns: user_id or None when none is found
        """
        from zeeguu_core.model.bookmark import Bookmark, bookmark_exercise_mapping
        import sqlalchemy

        query = Bookmark.query.filter(Bookmark.exercise_log.any(id=self.id))

        try:
            corresponding_bookmark = query.one()
            return corresponding_bookmark.user_id
        except sqlalchemy.orm.exc.NoResultFound:
            return None

    def get_bookmark(self):
        from zeeguu_core.model.bookmark import Bookmark, bookmark_exercise_mapping

        q = (Bookmark.query.
             join(bookmark_exercise_mapping).
             join(Exercise).
             filter(Exercise.id == self.id))
        return q.one()

    def is_too_easy(self):
        return self.outcome.outcome == ExerciseOutcome.TOO_EASY

    def is_correct(self):
        return self.outcome.outcome == ExerciseOutcome.CORRECT


text:
layout: page
title: Low Cost, Encrypted S3 backups with Duplicity on Centos 7
order: 1
---

Duplicity is a flexible backup tool that compresses and encrypts backups and support multiple backend storage types. I want off site backup, so I'll use AWS S3 as my backend.

Duplicity has a lot of options, too many actually. Duply is a wrapper for duplicity that simplifies the backup/restore commands with profiles and configuration files. This enables simple one liners for cron without a lot of fuss.

## Step1: Install dependencies
Install duplicity, duply and keyring.

1. `yum install -y duplicity duply`
2. `pip install keyring`

## Step 2: Create a GPG key
1. Create a random passphrase `openssl rand -base64 20`. Save this for later.
2. Create a new GPG key pair `gpg --gen-key`. Use the passphrase from previous setup when prompted.
3. Export for safe keeping

  `gpg --armor --export duplicity`

  `gpg --armor --export-secret-key duplicity`

## Step 3: Setup S3 bucket

Create a new bucket and create a IAM policy restricting access to that bucket. You'll need to add this policy to the IAM user or role that duplicity is using.
```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["s3:ListBucket" ],
      "Resource": "arn:aws:s3:::my_bucket"
    },
    {
      "Effect": "Allow",
      "Action": [ "s3:PutObject", "s3:GetObject", "s3:DeleteObject"],
      "Resource": "arn:aws:s3:::my_bucket/*"
    }
  ]
}
```

## Step 4: (Optional) Create IAM user for duplicity
To limit duplicity access in AWS, create a user and attach the policy from the previous step. Save the AWS access key id and AWS secret access key for this user.

## Step 5: Store passwords in keyring
Don't hard code passwords. Use keyring instead. Keyring will prompt for the password after each command.

```bash
keyring set 'duplicity backup' AWS_ACCESS_KEY_ID
keyring set 'duplicity backup' AWS_SECRET_ACCESS_KEY
keyring set 'duplicity backup' GPG_PASSPHRASE
```

## Create duply profile
Create a new duply profile using `duply create profile_name`
`duply create s3-backup`.

## Update duply profile
SOURCE defines the folder location you want to backup. While TARGET is where you want to store the backups.

```shell
# ~/.duply/s3-backup/conf

SOURCE=/my/folder/to/backup
TARGET='s3://s3.amazonaws.com/my_bucket/_my_folder_to_backup_to'
```

Duplicity uses boto to interact with S3. Boto expects two environmental variables (AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY). Add these as export statements to the config file.
```shell
# ~/.duply/s3-backup/conf

export AWS_ACCESS_KEY_ID=`keyring get 'duplicity backup' AWS_ACCESS_KEY_ID`
export AWS_SECRET_ACCESS_KEY=`keyring get 'duplicity backup' AWS_SECRET_ACCESS_KEY`
```

Set your GPG passphrase from above.
```shell
# ~/.duply/s3-backup/conf

GPG_PW=`keyring get 'duplicity backup' GPG_PASSPHRASE`
```
Lastly add any duplicity options. Below I want to use the cheaper S3 infrequent access storage class and do a full backup every 6 months.
```shell
# ~/.duply/s3-backup/conf

DUPL_PARAMS="$DUPL_PARAMS --s3-use-ia --full-if-older-than 6M "
```

## Start backup
Start duply and sitback and wait.

`duply s3-backup backup`

Once finished, duplicity prints out statistics
```
--------------[ Backup Statistics ]--------------
StartTime 1540001358.94 (Fri Oct 19 22:09:18 2018)
EndTime 1540044391.82 (Sat Oct 20 10:06:31 2018)
ElapsedTime 43032.88 (11 hours 57 minutes 12.88 seconds)
SourceFiles 28029
SourceFileSize 55294520907 (51.5 GB)
NewFiles 28029
NewFileSize 55294520907 (51.5 GB)
DeletedFiles 0
ChangedFiles 0
ChangedFileSize 0 (0 bytes)
ChangedDeltaSize 0 (0 bytes)
DeltaEntries 28029
RawDeltaSize 55292189166 (51.5 GB)
TotalDestinationSizeChange 51002426457 (47.5 GB)
Errors 1
-------------------------------------------------
```


text:
package components.textfields;

import javax.swing.JTextField;

import components.GamesLibrarian.WindowBuilderMask;
import components.Librarian;
import components.commons.BundleManager;
import components.commons.interfaces.Translatable;

/**
 * @author Naeregwen
 *
 */
public class TranslatableTextField extends JTextField implements Translatable {

	/**
	 *
	 */
	private static final long serialVersionUID = 2889747520227466865L;

	WindowBuilderMask me;
	Librarian librarian;

	String toolTipKey;

	/**
	 * @param me the WindowBuilderMask to use for creating/managing this instance
	 * @param toolTipKey the toolTipKey to use for in translate process
	 */
	public TranslatableTextField(WindowBuilderMask me, String toolTipKey) {
		this.me = me;
		this.toolTipKey = toolTipKey;
		this.librarian = me != null ? me.getLibrarian() : null; // WindowBuilder
		if (librarian != null) // WindowBuilder
			librarian.addTranslatable(this);
		translate();
	}

	/* (non-Javadoc)
	 * @see components.commons.interfaces.Translatable#translate()
	 */
	@Override
	public void translate() {
		setToolTipText(BundleManager.getUITexts(me, toolTipKey));
	}

}


text:
<?php

namespace Zephir\Statements\Let;

use Zephir\CompilationContext;
use Zephir\CompiledExpression;
use Zephir\Exception\CompilerException;
use Zephir\Expression;
use Zephir\Variable as ZephirVariable;

/**
 * ObjectPropertyArrayIndexAppend.
 *
 * Updates object properties dynamically
 */
class ObjectPropertyArrayIndexAppend extends ArrayIndex
{
    /**
     * Compiles x->y[z][] = foo.
     *
     * @param string             $variable
     * @param ZephirVariable     $symbolVariable
     * @param CompiledExpression $resolvedExpr
     * @param CompilationContext $compilationContext,
     * @param array              $statement
     */
    public function assign($variable, ZephirVariable $symbolVariable, CompiledExpression $resolvedExpr, CompilationContext $compilationContext, $statement)
    {
        if (!$symbolVariable->isInitialized()) {
            throw new CompilerException("Cannot mutate variable '".$variable."' because it is not initialized", $statement);
        }

        if (!$symbolVariable->isVariable()) {
            throw new CompilerException('Attempt to use variable type: '.$symbolVariable->getType().' as object', $statement);
        }

        $this->_assignPropertyArrayMultipleIndex($variable, $symbolVariable, $resolvedExpr, $compilationContext, $statement);
    }

    /**
     * Compiles x->y[a][b][] = {expr} (multiple offset assignment).
     *
     * @param string             $variable
     * @param ZephirVariable     $symbolVariable
     * @param CompiledExpression $resolvedExpr
     * @param CompilationContext $compilationContext
     * @param array              $statement
     *
     * @throws CompilerException
     */
    protected function _assignPropertyArrayMultipleIndex($variable, ZephirVariable $symbolVariable, CompiledExpression $resolvedExpr, CompilationContext $compilationContext, array $statement)
    {
        $property = $statement['property'];
        $compilationContext->headersManager->add('kernel/object');

        /**
         * Create a temporal zval (if needed).
         */
        $variableExpr = $this->_getResolvedArrayItem($resolvedExpr, $compilationContext);

        if (\count($statement['index-expr']) > 16) {
            throw new CompilerException('Too many array indexes', $statement);
        }

        /**
         * Only string/variable/int.
         */
        $offsetExprs = [];
        foreach ($statement['index-expr'] as $indexExpr) {
            $indexExpression = new Expression($indexExpr);

            $resolvedIndex = $indexExpression->compile($compilationContext);
            switch ($resolvedIndex->getType()) {
                case 'string':
                case 'int':
                case 'uint':
                case 'ulong':
                case 'long':
                case 'variable':
                    break;
                default:
                    throw new CompilerException('Expression: '.$resolvedIndex->getType().' cannot be used as index without cast', $statement);
            }

            $offsetExprs[] = $resolvedIndex;
        }

        /*
         * Check if the property to update is defined
         */
        if ('this' == $symbolVariable->getRealName()) {
            $classDefinition = $compilationContext->classDefinition;
            if (!$classDefinition->hasProperty($property)) {
                throw new CompilerException("Class '".$classDefinition->getCompleteName()."' does not have a property called: '".$property."'", $statement);
            }
        } else {
            /*
             * If we know the class related to a variable we could check if the property
             * is defined on that class
             */
            if ($symbolVariable->hasAnyDynamicType('object')) {
                $classType = current($symbolVariable->getClassTypes());
                $compiler = $compilationContext->compiler;

                if ($compiler->isClass($classType)) {
                    $classDefinition = $compiler->getClassDefinition($classType);
                    if (!$classDefinition) {
                        throw new CompilerException('Cannot locate class definition for class: '.$classType, $statement);
                    }

                    if (!$classDefinition->hasProperty($property)) {
                        throw new CompilerException("Class '".$classType."' does not have a property called: '".$property."'", $statement);
                    }
                }
            }
        }

        $offsetExprs[] = 'a';
        $compilationContext->backend->assignPropertyArrayMulti($symbolVariable, $variableExpr, $property, $offsetExprs, $compilationContext);
    }
}


text:
/*
  Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/property.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/constitute.h"
#include "MagickCore/delegate.h"
#include "MagickCore/draw.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/geometry.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/profile.h"
#include "MagickCore/resource_.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/module.h"
#include "MagickCore/token.h"
#include "MagickCore/transform.h"
#include "MagickCore/utility.h"

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   R e a d X P S I m a g e                                                   %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  ReadXPSImage() reads a Printer Control Language image file and returns it.
%  It allocates the memory necessary for the new Image structure and returns a
%  pointer to the new image.
%
%  The format of the ReadXPSImage method is:
%
%      Image *ReadXPSImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
%  A description of each parameter follows:
%
%    o image_info: the image info.
%
%    o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadXPSImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define CropBox  "CropBox"
#define DeviceCMYK  "DeviceCMYK"
#define MediaBox  "MediaBox"
#define RenderXPSText  "  Rendering XPS...  "

  char
    command[MaxTextExtent],
    density[MaxTextExtent],
    filename[MaxTextExtent],
    geometry[MaxTextExtent],
    options[MaxTextExtent],
    input_filename[MaxTextExtent];

  const char
    *option;

  const DelegateInfo
    *delegate_info;

  Image
    *image,
    *next_image;

  ImageInfo
    *read_info;

  MagickBooleanType
    cmyk,
    status;

  PointInfo
    delta;

  RectangleInfo
    bounding_box,
    page;

  register char
    *p;

  register ssize_t
    c;

  SegmentInfo
    bounds;

  size_t
    height,
    width;

  ssize_t
    count;

  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickSignature);
  /*
    Open image file.
  */
  image=AcquireImage(image_info,exception);
  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
  if (status == MagickFalse)
    {
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  status=AcquireUniqueSymbolicLink(image_info->filename,input_filename);
  if (status == MagickFalse)
    {
      ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile",
        image_info->filename);
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  /*
    Set the page density.
  */
  delta.x=DefaultResolution;
  delta.y=DefaultResolution;
  if ((image->resolution.x == 0.0) || (image->resolution.y == 0.0))
    {
      GeometryInfo
        geometry_info;

      MagickStatusType
        flags;

      flags=ParseGeometry(PSDensityGeometry,&geometry_info);
      image->resolution.x=geometry_info.rho;
      image->resolution.y=geometry_info.sigma;
      if ((flags & SigmaValue) == 0)
        image->resolution.y=image->resolution.x;
    }
  (void) FormatLocaleString(density,MaxTextExtent,"%gx%g",
    image->resolution.x,image->resolution.y);
  /*
    Determine page geometry from the XPS media box.
  */
  cmyk=image->colorspace == CMYKColorspace ? MagickTrue : MagickFalse;
  count=0;
  (void) ResetMagickMemory(&bounding_box,0,sizeof(bounding_box));
  (void) ResetMagickMemory(&bounds,0,sizeof(bounds));
  (void) ResetMagickMemory(&page,0,sizeof(page));
  (void) ResetMagickMemory(command,0,sizeof(command));
  p=command;
  for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))
  {
    if (image_info->page != (char *) NULL)
      continue;
    /*
      Note XPS elements.
    */
    *p++=(char) c;
    if ((c != (int) '/') && (c != '\n') &&
        ((size_t) (p-command) < (MaxTextExtent-1)))
      continue;
    *p='\0';
    p=command;
    /*
      Is this a CMYK document?
    */
    if (LocaleNCompare(DeviceCMYK,command,strlen(DeviceCMYK)) == 0)
      cmyk=MagickTrue;
    if (LocaleNCompare(CropBox,command,strlen(CropBox)) == 0)
      {
        /*
          Note region defined by crop box.
        */
        count=(ssize_t) sscanf(command,"CropBox [%lf %lf %lf %lf",
          &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
        if (count != 4)
          count=(ssize_t) sscanf(command,"CropBox[%lf %lf %lf %lf",
            &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
      }
    if (LocaleNCompare(MediaBox,command,strlen(MediaBox)) == 0)
      {
        /*
          Note region defined by media box.
        */
        count=(ssize_t) sscanf(command,"MediaBox [%lf %lf %lf %lf",
          &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
        if (count != 4)
          count=(ssize_t) sscanf(command,"MediaBox[%lf %lf %lf %lf",
            &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
      }
    if (count != 4)
      continue;
    /*
      Set XPS render geometry.
    */
    width=(size_t) (floor(bounds.x2+0.5)-ceil(bounds.x1-0.5));
    height=(size_t) (floor(bounds.y2+0.5)-ceil(bounds.y1-0.5));
    if (width > page.width)
      page.width=width;
    if (height > page.height)
      page.height=height;
  }
  (void) CloseBlob(image);
  /*
    Render XPS with the GhostXPS delegate.
  */
  if ((page.width == 0) || (page.height == 0))
    (void) ParseAbsoluteGeometry(PSPageGeometry,&page);
  if (image_info->page != (char *) NULL)
    (void) ParseAbsoluteGeometry(image_info->page,&page);
  (void) FormatLocaleString(geometry,MaxTextExtent,"%.20gx%.20g",(double)
    page.width,(double) page.height);
  if (image_info->monochrome != MagickFalse)
    delegate_info=GetDelegateInfo("xps:mono",(char *) NULL,exception);
  else
     if (cmyk != MagickFalse)
       delegate_info=GetDelegateInfo("xps:cmyk",(char *) NULL,exception);
     else
       delegate_info=GetDelegateInfo("xps:color",(char *) NULL,exception);
  if (delegate_info == (const DelegateInfo *) NULL)
    return((Image *) NULL);
  *options='\0';
  if ((page.width == 0) || (page.height == 0))
    (void) ParseAbsoluteGeometry(PSPageGeometry,&page);
  if (image_info->page != (char *) NULL)
    (void) ParseAbsoluteGeometry(image_info->page,&page);
  page.width=(size_t) floor(page.width*image->resolution.y/delta.x+0.5);
  page.height=(size_t) floor(page.height*image->resolution.y/delta.y+0.5);
  (void) FormatLocaleString(options,MaxTextExtent,"-g%.20gx%.20g ",(double)
    page.width,(double) page.height);
  image=DestroyImage(image);
  read_info=CloneImageInfo(image_info);
  *read_info->magick='\0';
  if (read_info->number_scenes != 0)
    {
      if (read_info->number_scenes != 1)
        (void) FormatLocaleString(options,MaxTextExtent,"-dLastPage=%.20g",
          (double) (read_info->scene+read_info->number_scenes));
      else
        (void) FormatLocaleString(options,MaxTextExtent,
          "-dFirstPage=%.20g -dLastPage=%.20g",(double) read_info->scene+1,
          (double) (read_info->scene+read_info->number_scenes));
      read_info->number_scenes=0;
      if (read_info->scenes != (char *) NULL)
        *read_info->scenes='\0';
    }
  option=GetImageOption(read_info,"authenticate");
  if (option != (const char *) NULL)
    (void) FormatLocaleString(options+strlen(options),MaxTextExtent,
      " -sPCLPassword=%s",option);
  (void) CopyMagickString(filename,read_info->filename,MaxTextExtent);
  (void) AcquireUniqueFilename(read_info->filename);
  (void) FormatLocaleString(command,MaxTextExtent,
    GetDelegateCommands(delegate_info),
    read_info->antialias != MagickFalse ? 4 : 1,
    read_info->antialias != MagickFalse ? 4 : 1,density,options,
    read_info->filename,input_filename);
  status=SystemCommand(MagickFalse,read_info->verbose,command,exception) != 0 ?
    MagickTrue : MagickFalse;
  image=ReadImage(read_info,exception);
  (void) RelinquishUniqueFileResource(read_info->filename);
  (void) RelinquishUniqueFileResource(input_filename);
  read_info=DestroyImageInfo(read_info);
  if (image == (Image *) NULL)
    ThrowReaderException(DelegateError,"XPSDelegateFailed");
  if (LocaleCompare(image->magick,"BMP") == 0)
    {
      Image
        *cmyk_image;

      cmyk_image=ConsolidateCMYKImages(image,exception);
      if (cmyk_image != (Image *) NULL)
        {
          image=DestroyImageList(image);
          image=cmyk_image;
        }
    }
  do
  {
    (void) CopyMagickString(image->filename,filename,MaxTextExtent);
    image->page=page;
    next_image=SyncNextImageInList(image);
    if (next_image != (Image *) NULL)
      image=next_image;
  } while (next_image != (Image *) NULL);
  return(GetFirstImageInList(image));
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   R e g i s t e r X P S I m a g e                                           %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  RegisterXPSImage() adds attributes for the Microsoft XML Paper Specification
%  format to the list of supported formats.  The attributes include the image
%  format tag, a method to read and/or write the format, whether the format
%  supports the saving of more than one frame to the same file or blob,
%  whether the format supports native in-memory I/O, and a brief
%  description of the format.
%
%  The format of the RegisterXPSImage method is:
%
%      size_t RegisterXPSImage(void)
%
*/
ModuleExport size_t RegisterXPSImage(void)
{
  MagickInfo
    *entry;

  entry=SetMagickInfo("XPS");
  entry->decoder=(DecodeImageHandler *) ReadXPSImage;
  entry->adjoin=MagickFalse;
  entry->blob_support=MagickFalse;
  entry->seekable_stream=MagickTrue;
  entry->thread_support=EncoderThreadSupport;
  entry->description=ConstantString("Microsoft XML Paper Specification");
  entry->module=ConstantString("XPS");
  (void) RegisterMagickInfo(entry);
  return(MagickImageCoderSignature);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   U n r e g i s t e r X P S I m a g e                                       %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  UnregisterXPSImage() removes format registrations made by the XPS module
%  from the list of supported formats.
%
%  The format of the UnregisterXPSImage method is:
%
%      UnregisterXPSImage(void)
%
*/
ModuleExport void UnregisterXPSImage(void)
{
  (void) UnregisterMagickInfo("XPS");
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Bayesian Modelling of Globular Cluster Systems in Wide-Field Imaging</title>
  <meta name="description" content="Hi! I'm Zach, an astronomy PhD student in Santa Cruz, CA. Welcome to my website!">

  <meta name="author" content="Zachary Jennings">
  <meta name="copyright" content="© Zachary Jennings 2016">

  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.5/styles/monokai_sublime.min.css">
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/lightbox2/2.7.1/css/lightbox.css">

  <link rel="shortcut icon" href="/assets/icons/favicon.ico" type="image/x-icon">
  <link rel="icon" href="/assets/icons/favicon.ico" type="image/x-icon">
  <link rel="apple-touch-icon" sizes="57x57" href="/assets/icons/apple-icon-57x57.png">
  <link rel="apple-touch-icon" sizes="60x60" href="/assets/icons/apple-icon-60x60.png">
  <link rel="apple-touch-icon" sizes="72x72" href="/assets/icons/apple-icon-72x72.png">
  <link rel="apple-touch-icon" sizes="76x76" href="/assets/icons/apple-icon-76x76.png">
  <link rel="apple-touch-icon" sizes="114x114" href="/assets/icons/apple-icon-114x114.png">
  <link rel="apple-touch-icon" sizes="120x120" href="/assets/icons/apple-icon-120x120.png">
  <link rel="apple-touch-icon" sizes="144x144" href="/assets/icons/apple-icon-144x144.png">
  <link rel="apple-touch-icon" sizes="152x152" href="/assets/icons/apple-icon-152x152.png">
  <link rel="apple-touch-icon" sizes="180x180" href="/assets/icons/apple-icon-180x180.png">
  <link rel="icon" type="image/png" sizes="192x192"  href="/assets/icons/android-icon-192x192.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/assets/icons/favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="96x96" href="/assets/icons/favicon-96x96.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/assets/icons/favicon-16x16.png">
  <link rel="manifest" href="/assets/icons/manifest.json">
  <meta name="msapplication-TileColor" content="#ffffff">
  <meta name="msapplication-TileImage" content="/assets/icons/ms-icon-144x144.png">
  <meta name="theme-color" content="#ffffff">

  <meta property="og:description" content="Hi! I'm Zach, an astronomy PhD student in Santa Cruz, CA. Welcome to my website!" />
  <meta property="og:url" content="http://zachjennings.github.io/" />
  <meta property="og:site_name" content="Zachary Jennings" />
  <meta property="og:title" content="Bayesian Modelling of Globular Cluster Systems in Wide-Field Imaging" />
  <meta property="og:type" content="website" />
  <meta property="og:image" content="http://zachjennings.github.io//assets/logo.png" />
  <meta property="og:image:type" content="image/png" />
  <meta property="og:image:width" content="612" />
  <meta property="og:image:height" content="605" />

  <meta name="twitter:card" content="summary">
  <meta name="twitter:title" content="Bayesian Modelling of Globular Cluster Systems in Wide-Field Imaging">
  <meta name="twitter:description" content="Hi! I'm Zach, an astronomy PhD student in Santa Cruz, CA. Welcome to my website!">
  <meta name="twitter:image" content="http://zachjennings.github.io//assets/logo.png">
  <meta name="twitter:url" content="http://zachjennings.github.io/">

  <link rel="stylesheet" href="/css/main.css">
  <link rel="canonical" href="http://zachjennings.github.io//research/gc_selection.html">

      Zachary Jennings

Research

About Me

Resume

Stats Refs

Bayesian Modelling of Globular Cluster Systems in Wide-Field Imaging

Basic questions of interest about globular cluster systems include how many globular clusters there are, what are the relative fractions
of different types of globular clusters, and how are they distributed around their host galaxies. Ideally, these questions
could be answered trivially by taking an image of the galaxy, selecting those sources which are globular clusters,
and performing our measurements on that subsample. Unfortunately, typical datasets are much messier than this.
In a globular cluster dataset, we are dealing with a sample that is both incomplete (globular clusters may exist below the detection
threshold of our imaging data) and contaminated (globular clusters in images are easily confused both with foreground
stars in the Milky Way and distant galaxies far behind the galaxy of interest). Current approaches to globular cluster selection have use somewhat
ad-hoc selection rules to attempt a selection with minimal contamination, but unquantified
selection errors muddle inferences from such a method.

I am developing a fully Bayesian framework for modelling the globular cluster populations of nearby galaxies.
My method simultaneously models all sources in the image as a mixture model composed
of both contaminants and genuine globular clusters, each with their own distributions. I model
the contaminants using kernel density estimates trained on control images taken far
away from galaxies, then use parametric models for the distribution of globular clusters mixed in with these contaminants.
This allows me to easily fold
in all measured data from sources in our imaging; while most methods just select globular clusters based
on their measured colors, I can easily fold in information about their spatial and luminosity
distributions into the selection methodology.

The advantages of these methods are two-fold: first, I get a better sample of likely globular clusters.
Rather than simply selecting a sample using ad-hoc criteria, I calculate a probability
for every source in the image of how likely it is to be a globular cluster. Any studies requiring a
clean sample of clusters will have a clear quantification of their contamination, and follow-up
spectroscopic studies with different telescopes will be able to better optimize their target selection.
Second, the parameters of the distributions used to model the globular clusters are themselves very interesting
astrophysical quantities. Bayesian methods give us full PDFs for quantities like the total
number of globular clusters or the relative fractions of red and blue globular clusters, completely folding in any
uncertainties introduced by the selection process. The estimates of such parameters with
reliable uncertainties attached will offer a useful discriminant between competing models
of globular cluster formation which currently exist in the literature.

Zachary Jennings

Site Map

Research

About Me

Useful Stats Refs

Resume

Contact

            zach.jennings@gmail.com

              Zachary Jennings

Hi! I'm Zach, an astronomy PhD student in Santa Cruz, CA. Welcome to my website!

 Based on the
		  Centrarium theme for Jekyll 		by Ben Centra