text:
import {Injectable} from "@angular/core";
import {Observable} from "rxjs/Observable";
import {fromEvent} from "rxjs/observable/fromEvent";
import {filter, tap, share, flatMap, takeUntil, map, take} from "rxjs/operators";

type ExtendedMouseEvent = MouseEvent & {
    ctName?: string;
    ctData?: any;
};

@Injectable()
export class DomEventService {

    readonly ON_DRAG_ENTER_ZONE_EVENT = "onDragEnterZone";
    readonly ON_DRAG_LEAVE_ZONE_EVENT = "onDragLeaveZone";

    readonly ON_DRAG_ENTER_EVENT = "onDragEnter";
    readonly ON_DRAG_LEAVE_EVENT = "onDragLeave";
    readonly ON_DRAG_OVER_EVENT  = "onDragOver";

    readonly ON_DROP_SUCCESS_EVENT = "onDropSuccess";

    private registeredShortcuts = new Map<string[], Observable<KeyboardEvent>>();

    on(eventName: string, component?: Element, preventDefault = false) {

        return fromEvent(document, eventName).pipe(
            filter((ev: Event) => {
                if (component === undefined) {
                    return true;
                }

                return ev.srcElement === component || component.contains(ev.srcElement);
            }),
            tap((ev: Event) => {
                if (preventDefault) {
                    ev.preventDefault();
                }
            })
        );
    }

    /**
     * Create an observable of keyboard events based on a registered shortcut and a component that listens for them.
     * Examples:
     * - onShortcut("alt+1", document);
     * - onShortcut("cmdOrCtrl+w", document.findElementById("someEl"));
     *
     */
    onShortcut(shortcut: string, component?: Element): Observable<KeyboardEvent> {

        // Split up the key combination and sort it
        const normalized = shortcut.split("+").sort();

        // Check if we already have this combination registered and prevent the new shortcut in that case
        if (this.registeredShortcuts.has(normalized)) {
            return this.registeredShortcuts.get(normalized);
        }

        // Let's keep the status of all modifier keys here
        const modifierValues = {
            alt: false,
            meta: false,
            ctrl: false,
            shift: false,
        };

        // Take the names of all modifier keys
        const modifierNames = Object.keys(modifierValues);

        // Now we should find the first non-modifier key
        const mainKey = normalized.find(k => modifierNames.indexOf(k) === -1);

        // We won't allow modifier-only shortcuts
        if (!mainKey) {
            throw new Error(`Invalid shortcut "${shortcut}". It can't be made only of control characters.`);
        }

        // Switch on modifiers that we should listen for
        normalized.filter(k => modifierNames.indexOf(k) !== -1).forEach(mod => modifierValues[mod] = true);

        // Create a listener for this key combination
        const listener = this.on("keyup", component).pipe(
            filter((ev: KeyboardEvent) => {

                // Check if the main key is what we are listening for
                const isMainKey = String.fromCharCode(ev.keyCode) === mainKey;

                // Check if the modifiers are what we are listening for
                const modifiersMatch = modifierNames.reduce((outcome, mod) => {

                    if (outcome === false) {
                        return false;
                    }

                    return ev[mod + "Key"] === modifierValues[mod];
                }, true);

                return isMainKey && modifiersMatch;
            }),
            share()
        ) as Observable<KeyboardEvent>;

        this.registeredShortcuts.set(normalized, listener);

        return listener;
    }

    /**
     * Observes the dragging of an element.
     */
    onMove(element: Element, ctName = "", ctData = {}): Observable<ExtendedMouseEvent> {
        const down = fromEvent(element, "mousedown");
        const up   = fromEvent(document, "mouseup");
        const move = fromEvent(document, "mousemove");

        return down.pipe(
            flatMap(_ => move.pipe(
                takeUntil(up)
            )),
            map((ev: MouseEvent) => Object.assign(ev, {ctData}, {ctName}))
        );
    }

    onDrag(element: Element, ctName = "", ctData = {}): Observable<Observable<MouseEvent>> {

        const down = fromEvent(element, "mousedown").pipe(
            filter((ev: MouseEvent) => ev.button === 0),
            tap((ev: MouseEvent) => {
                if (ev.stopPropagation) {
                    ev.stopPropagation();
                }
                if (ev.preventDefault) {
                    ev.preventDefault();
                }
            })
        );

        const up   = fromEvent(document, "mouseup");
        const move = fromEvent(document, "mousemove");

        return down.pipe(
            map(ev => new Observable(obs => {

                const decorate = event => Object.assign(event, {ctData}, {ctName});

                obs.next(decorate(ev));

                const moveSub = move.subscribe(moveEv => obs.next(decorate(moveEv)));

                const upSub = up.pipe(
                    take(1)
                ).subscribe(upEvent => {
                    obs.next(decorate(upEvent));
                    obs.complete();
                });

                return () => {
                    moveSub.unsubscribe();
                    upSub.unsubscribe();
                };
            }))
        );
    }

    /**
     * Some browsers do not fire click events for mouse clicks other than a mouse left button click
     */
    onMouseClick(element: Element) {

        const down = fromEvent(element, "mousedown");
        const up   = fromEvent(document, "mouseup");

        return down.pipe(
            flatMap(() => up.pipe(
                take(1),
                filter((e: MouseEvent) => element.contains(e.target as Node))
            ))
        );
    }

    triggerCustomEventOnElements(elements: Element [], eventName: string, data?: any) {
        // FIXME: Should be added support for IE
        elements.forEach(element => {
            const event = new CustomEvent(eventName, {
                detail: {
                    data
                }
            });
            element.dispatchEvent(event);
        });
    }

    preventDropEventOnDocument() {
        document.addEventListener("dragover", function (event) {
            event.preventDefault();
            return false;
        });

        document.addEventListener("drop", function (event) {
            event.preventDefault();
            return false;
        });
    }
}


text:
package imagefile

import (
	"context"
	"fmt"
	"math"
	"path"
	"time"

	"github.com/GoogleCloudPlatform/compute-image-import/cli_tools/common/gcsfuse"
	"github.com/GoogleCloudPlatform/compute-image-import/cli_tools/common/utils/files"
	"github.com/GoogleCloudPlatform/compute-image-import/cli_tools/common/utils/storage"
	"github.com/cenkalti/backoff/v4"
)

const bytesPerGB = int64(1024 * 1024 * 1024)

// Metadata contains metadata about an image file.
type Metadata struct {
	// PhysicalSizeGB is the size of the file itself, rounded up to the nearest GB.
	PhysicalSizeGB int64

	// VirtualSizeGB is the size of the disk, after inflation. Rounded up to the nearest GB.
	VirtualSizeGB int64

	// FileFormat is the format used for encoding the VM disk.
	FileFormat string

	Checksum string
}

// Inspector returns metadata about image files.
type Inspector interface {
	// Inspect returns Metadata for the image file associated
	// with a reference. IO operations will be retried until the context is cancelled.
	Inspect(ctx context.Context, reference string) (Metadata, error)
}

// NewGCSInspector returns an inspector that inspects image
// files that are stored in the GCS bucket. The Inspect method expects
// a GCS URI to the file to be inspected.
func NewGCSInspector() Inspector {
	return gcsInspector{
		qemuClient: NewInfoClient(),
		fuseClient: gcsfuse.NewClient()}
}

// gcsInspector implements inspector using qemu-img gcsfuse.
type gcsInspector struct {
	qemuClient InfoClient
	fuseClient gcsfuse.Client
}

func (inspector gcsInspector) Inspect(ctx context.Context, gcsURI string) (metadata Metadata, err error) {
	operation := func() error {
		metadata, err = inspector.inspectOnce(ctx, gcsURI)
		return err
	}
	return metadata, backoff.Retry(operation,
		backoff.WithContext(backoff.NewConstantBackOff(50*time.Millisecond), ctx))
}

func (inspector gcsInspector) inspectOnce(ctx context.Context, gcsURI string) (metadata Metadata, err error) {
	bucket, object, err := storage.GetGCSObjectPathElements(gcsURI)
	if err != nil {
		return metadata, err
	}
	mountedDirectory, err := inspector.fuseClient.MountToTemp(ctx, bucket)
	defer inspector.fuseClient.Unmount(mountedDirectory)
	if err != nil {
		return metadata, err
	}
	absPath := path.Join(mountedDirectory, object)
	if !files.Exists(absPath) {
		return metadata, fmt.Errorf("the file %q was not found", gcsURI)
	}
	imageInfo, err := inspector.qemuClient.GetInfo(ctx, absPath)
	if err != nil {
		return metadata, err
	}
	return Metadata{
		PhysicalSizeGB: bytesToGB(imageInfo.ActualSizeBytes),
		VirtualSizeGB:  bytesToGB(imageInfo.VirtualSizeBytes),
		FileFormat:     imageInfo.Format,
		Checksum:       imageInfo.Checksum,
	}, nil
}

// bytesToGB rounds up to the nearest GB.
func bytesToGB(bytes int64) int64 {
	return int64(math.Ceil(float64(bytes) / float64(bytesPerGB)))
}

redpajama_set_name: RedPajamaGithub


text:
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using WebHookService.Services.Models;

namespace WebHookService.Services.Dispatchers.Local
{
    public class LoopbackInvocationDispatcher : IInvocationDispatcher
    {
        public async Task Dispatch(Invocation invocation)
        {
            var client = new HttpClient();

            // Add the headers to the client so they persist with every retry
            if(invocation.Headers != null)
            {
                foreach (var header in invocation.Headers)
                {
                    client.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
                }
            }

            var serializedContent = Newtonsoft.Json.JsonConvert.SerializeObject(invocation.Content);

            for(var i = invocation.TimeToLive; i > 0; i--)
            {
                try
                {
                    var response = await client.PostAsync(invocation.Endpoint, new StringContent(serializedContent, Encoding.UTF8, "application/json"));
                    if(response.StatusCode == HttpStatusCode.OK)
                    {
                        break;
                    }
                }
                catch (System.Exception)
                {
                    // keep on counting TTL down to death
                }
            }
        }
    }
}


text:
import path from 'path';
import { expect } from 'chai';
import jscodeshift from 'jscodeshift';
import transform from './transitions';
import readFile from '../util/readFile';

function read(fileName) {
  return readFile(path.join(__dirname, fileName));
}

describe('@mui/codemod', () => {
  describe('v5.0.0', () => {
    describe('transitions', () => {
      it('transforms transitions as needed', () => {
        const actual = transform(
          {
            source: read('./transitions.test/actual.js'),
            path: require.resolve('./transitions.test/actual.js'),
          },
          { jscodeshift },
          {},
        );

        const expected = read('./transitions.test/expected.js');
        expect(actual).to.equal(expected, 'The transformed version should be correct');
      });

      it('should be idempotent', () => {
        const actual = transform(
          {
            source: read('./transitions.test/expected.js'),
            path: require.resolve('./transitions.test/expected.js'),
          },
          { jscodeshift },
          {},
        );

        const expected = read('./transitions.test/expected.js');
        expect(actual).to.equal(expected, 'The transformed version should be correct');
      });
    });
  });
});


text:
"""
Linux Platform Module
"""
# Copyright (C) 2007 Invisigoth - See LICENSE file for details
import os
import sys
import signal
import struct
import logging
import binascii
import platform
import traceback

import envi.cli as e_cli
import envi.bits as e_bits
import envi.memory as e_mem

import vtrace
import vtrace.exc as v_exc

import vtrace.archs.arm as v_arm
import vtrace.archs.i386 as v_i386
import vtrace.archs.amd64 as v_amd64

import vtrace.platforms.base as v_base
import vtrace.platforms.posix as v_posix

from ctypes import *
import ctypes.util as cutil

logger = logging.getLogger(__name__)

if os.getenv('ANDROID_ROOT'):
    libc = CDLL('/system/lib/libc.so')
else:
    libc = CDLL(cutil.find_library("c"), use_errno=True)

libc.lseek64.restype = c_ulonglong
libc.lseek64.argtypes = [c_uint, c_ulonglong, c_uint]
libc.read.restype = c_long
libc.read.argtypes = [c_uint, c_void_p, c_long]
libc.write.restype = c_long
libc.write.argtypes = [c_uint, c_void_p, c_long]

O_RDWR = 2
O_LARGEFILE = 0x8000

MAP_ANONYMOUS = 0x20
MAP_PRIVATE = 0x02

# Linux specific ptrace extensions
PT_GETREGS = 12
PT_SETREGS = 13
PT_GETFPREGS = 14
PT_SETFPREGS = 15
PT_ATTACH = 16
PT_DETACH = 17
PT_GETFPXREGS = 18
PT_SETFPXREGS = 19
PT_SYSCALL = 24
PT_SETOPTIONS = 0x4200
PT_GETEVENTMSG = 0x4201
PT_GETSIGINFO = 0x4202
PT_SETSIGINFO = 0x4203
PT_GETREGSET = 0x4204
PT_SETREGSET = 0x4205
PT_SEIZE = 0x4206
PT_INTERRUPT = 0x4207
# PT set options stuff.  ONLY TRACESYSGOOD may be used in 2.4...
PT_O_TRACESYSGOOD   = 0x00000001 # add 0x80 to TRAP when generated by syscall
# For each of the options below, the stop signal is (TRAP | PT_EVENT_FOO << 8)
PT_O_TRACEFORK      = 0x00000002 # Cause a trap at fork
PT_O_TRACEVFORK     = 0x00000004 # Cause a trap at vfork
PT_O_TRACECLONE     = 0x00000008 # Cause a trap at clone
PT_O_TRACEEXEC      = 0x00000010 # Cause a trap at exec
PT_O_TRACEVFORKDONE = 0x00000020 # Cause a trap when vfork done
PT_O_TRACEEXIT      = 0x00000040 # Cause a trap on exit
PT_O_MASK           = 0x0000007f
# Ptrace event types (TRAP | PT_EVENT_FOO << 8) means that type
# when using GETEVENTMSG for most of these, the new pid is the data
PT_EVENT_FORK       = 1
PT_EVENT_VFORK      = 2
PT_EVENT_CLONE      = 3
PT_EVENT_EXEC       = 4
PT_EVENT_VFORK_DONE = 5
PT_EVENT_EXIT       = 6

# Reg sets for use in ptrace PT_GETREGSET
# typlically defined in /usr/include/elf.h
# for now, we only need the one, but we can add more on demand
NT_X86_XSTATE = 0x202  # x86 extended state using xsave

# Used to tell some of the additional events apart
SIG_LINUX_SYSCALL = signal.SIGTRAP | 0x80
SIG_LINUX_CLONE = signal.SIGTRAP | (PT_EVENT_CLONE << 8)
SIG_LINUX_EXIT = signal.SIGTRAP | (PT_EVENT_EXIT << 8)

#following from Pandaboard ES (OMAP4460) Armv7a (cortex-a9)
class user_regs_arm(Structure):
    _fields_ = (
            ("r0", c_ulong),
            ("r1", c_ulong),
            ("r2", c_ulong),
            ("r3", c_ulong),
            ("r4", c_ulong),
            ("r5", c_ulong),
            ("r6", c_ulong),
            ("r7", c_ulong),
            ("r8", c_ulong),
            ("r9", c_ulong),
            ("r10", c_ulong), #aka 'sl' ?
            ("r11", c_ulong),
            ("r12", c_ulong),
            ("sp", c_ulong),
            ("lr", c_ulong),
            ("pc", c_ulong),
            ("cpsr", c_ulong),
            ("orig_r0", c_ulong),
    )

class fp_reg_arm(Structure):
    _fields_ = (
            ("sign1", c_long, 1),
            ("unused", c_long, 15),
            ("sign2", c_long, 1),
            ("exponent", c_long, 14),
            ("j", c_long, 1),
            ("mantissa1", c_long, 31),
            ("mantissa0", c_long, 32),
    )

class user_fpregs_arm(Structure):
    _fields_ = (
            ("fpregs", fp_reg_arm*8),
            ("fpsr", c_ulong, 32),
            ("fpcr", c_ulong, 32),
            ("ftype", c_ubyte*8),
            ("init_flag", c_ulong),
    )

class USER_arm(Structure):
    _fields_ = (
        ("regs",       user_regs_arm),
        ("u_fpvalid",  c_long),
        ("u_tsize",    c_ulong),
        ("u_dsize",    c_ulong),
        ("u_ssize",    c_ulong),
        ("start_code", c_ulong),
        ("start_stack",c_ulong),
        ("signal",     c_long),
        ("reserved",   c_long),
        ("u_ar0",      c_void_p),
        ("magic",      c_ulong),
        ("u_comm",     c_char*32),
        ("u_debugreg", c_long*8),
        ("fpregs",     user_fpregs_arm),
        ("u_fp0",      c_void_p)
    )

class user_regs_i386(Structure):
    _fields_ = (
        ("ebx",  c_ulong),
        ("ecx",  c_ulong),
        ("edx",  c_ulong),
        ("esi",  c_ulong),
        ("edi",  c_ulong),
        ("ebp",  c_ulong),
        ("eax",  c_ulong),
        ("ds",   c_ushort),
        ("__ds", c_ushort),
        ("es",   c_ushort),
        ("__es", c_ushort),
        ("fs",   c_ushort),
        ("__fs", c_ushort),
        ("gs",   c_ushort),
        ("__gs", c_ushort),
        ("orig_eax", c_ulong),
        ("eip",  c_ulong),
        ("cs",   c_ushort),
        ("__cs", c_ushort),
        ("eflags", c_ulong),
        ("esp",  c_ulong),
        ("ss",   c_ushort),
        ("__ss", c_ushort),
    )

class iovec(Structure):
    _fields_ = [
        ('iov_base', c_void_p),
        ('iov_len', c_size_t),
    ]

class user_fpregs_i386(Structure):
    _fields_ = [
        ('cwd', c_long),
        ('swd', c_long),
        ('twd', c_long),
        ('fip', c_long),
        ('fcs', c_long),
        ('foo', c_long),
        ('fos', c_long),
        ('st_space', c_long * 20),
    ]

class user_fpxregs_i386(Structure):
    _fields_ = [
        ('cwd', c_ushort),
        ('swd', c_ushort),
        ('twd', c_ushort),
        ('fop', c_ushort),
        ('fip', c_long),
        ('fcs', c_long),
        ('foo', c_long),
        ('fos', c_long),
        ('mxcsr', c_long),
        ('reserved', c_long),
        ('st_space', c_long * 32),
        ('xmm_space', c_long * 32),
        ('padding', c_long * 56),
    ]

class USER_i386(Structure):
    _fields_ = (
        # NOTE: Expand out the user regs struct so
        #       we can make one call to _rctx_Import
        ("regs",       user_regs_i386),
        ("u_fpvalid",  c_ulong),
        ("u_tsize",    c_ulong),
        ("u_dsize",    c_ulong),
        ("u_ssize",    c_ulong),
        ("start_code", c_ulong),
        ("start_stack",c_ulong),
        ("signal",     c_ulong),
        ("reserved",   c_ulong),
        ("u_ar0",      c_void_p),
        ("u_fpstate",  c_void_p),
        ("magic",      c_ulong),
        ("u_comm",     c_char*32),
        ("debug0",     c_ulong),
        ("debug1",     c_ulong),
        ("debug2",     c_ulong),
        ("debug3",     c_ulong),
        ("debug4",     c_ulong),
        ("debug5",     c_ulong),
        ("debug6",     c_ulong),
        ("debug7",     c_ulong),
    )

class user_regs_amd64(Structure):
    _fields_ = [
        ('r15',      c_uint64),
        ('r14',      c_uint64),
        ('r13',      c_uint64),
        ('r12',      c_uint64),
        ('rbp',      c_uint64),
        ('rbx',      c_uint64),
        ('r11',      c_uint64),
        ('r10',      c_uint64),
        ('r9',       c_uint64),
        ('r8',       c_uint64),
        ('rax',      c_uint64),
        ('rcx',      c_uint64),
        ('rdx',      c_uint64),
        ('rsi',      c_uint64),
        ('rdi',      c_uint64),
        ('orig_rax', c_uint64),
        ('rip',      c_uint64),
        ('cs',       c_uint64),
        ('eflags',   c_uint64),
        ('rsp',      c_uint64),
        ('ss',       c_uint64),
        ('fs_base',  c_uint64),
        ('gs_base',  c_uint64),
        ('ds',       c_uint64),
        ('es',       c_uint64),
        ('fs',       c_uint64),
        ('gs',       c_uint64),
    ]

intel_dbgregs = (0,1,2,3,6,7)

class LinuxMixin(v_posix.PtraceMixin, v_posix.PosixMixin):
    """
    The mixin to take care of linux specific platform traits.
    (mostly proc)
    """

    def __init__(self):
        # Wrap reads from proc in our worker thread
        v_posix.PtraceMixin.__init__(self)
        v_posix.PosixMixin.__init__(self)
        self.memfd = None
        self._stopped_cache = {}
        self._stopped_hack = False

        self.fireTracerThread()
        self.setMeta('BadMaps', ['[vvar]', '[vsyscall]'])

        self.initMode("Syscall", False, "Break On Syscalls")

    def setupMemFile(self, offset):
        """
        A utility to open (if necessary) and seek the memfile
        """
        if self.memfd is None:
            self.memfd = libc.open(b"/proc/%d/mem" % self.pid, O_RDWR | O_LARGEFILE, 0o755)
            if self.memfd < 0:
                logger.warning('Failed to get proper file descriptor (errno: %d)', get_errno())

        retn = libc.lseek64(self.memfd, offset, 0)
        if retn < 0:
            logger.warning('lseek64 hit issue with error: %d' % get_errno())

    @v_base.threadwrap
    def platformReadMemory(self, address, size):
        """
        A *much* faster way of reading memory that the 4 bytes
        per syscall allowed by ptrace
        """
        self.setupMemFile(address)
        # Use ctypes cause python implementation is teh ghey
        buf = create_string_buffer(size)
        x = libc.read(self.memfd, addressof(buf), size)
        if x != size:
            # libc.perror('libc.read %d (size: %d)' % (x,size))
            raise Exception("reading from invalid memory %s (%d returned) (errno: %d) (fd: %d)" % (hex(address), x, get_errno(), self.memfd))
        # We have to slice cause ctypes "helps" us by adding a null byte...
        return buf.raw

    @v_base.threadwrap
    def whynot_platformWriteMemory(self, address, data):
        """
        A *much* faster way of writting memory that the 4 bytes
        per syscall allowed by ptrace
        """
        self.setupMemFile(address)
        buf = create_string_buffer(data)
        size = len(data)
        x = libc.write(self.memfd, addressof(buf), size)
        if x != size:
            libc.perror('write mem failed: 0x%.8x (%d)' % (address, size))
            raise Exception("write memory failed: %d" % x)
        return x

    def _findExe(self, pid):
        exe = os.readlink("/proc/%d/exe" % pid)
        if "(deleted)" in exe:
            if "#prelink#" in exe:
                exe = exe.split(".#prelink#")[0]
            elif ";" in exe:
                exe = exe.split(";")[0]
            else:
                exe = exe.split("(deleted)")[0].strip()
        return exe

    @v_base.threadwrap
    def platformExec(self, cmdline):
        # Very similar to posix, but not
        # quite close enough...
        self.execing = True
        cmdlist = e_cli.splitargs(cmdline)
        os.stat(cmdlist[0])
        pid = os.fork()

        if pid == 0:
            try:
                # Don't use PT_TRACEME -- on some linux (tested on ubuntu)
                # it will cause immediate asignment of ptrace slot to parent
                # without parent having PT_ATTACH'D.... MAKES SYNCHRONIZATION HARD
                # SIGSTOP ourself until parent continues us
                os.kill(os.getpid(), signal.SIGSTOP)
                os.execv(cmdlist[0], cmdlist)
            except Exception as e:
                logger.error(e)
            sys.exit(-1)

        # Attach to child. should cause SIGSTOP
        if 0 != v_posix.ptrace(PT_ATTACH, pid, 0, 0):
            raise Exception("PT_ATTACH failed! linux platformExec")

        # Eat all SIGSTOP (or other signal) and break from loop on SIGTRAP.
        # SIGTRAP triggered by execv while PTRACE_ATTACH'd
        while True:
            wpid, status = os.waitpid(pid, os.WUNTRACED)
            if wpid != pid:  # should never happen
                continue
            if os.WIFSTOPPED(status):
                cause = os.WSTOPSIG(status)
                if cause == signal.SIGTRAP:
                    break
                if v_posix.ptrace(v_posix.PT_CONTINUE, pid, 0, 0) != 0:
                    raise Exception("PT_CONTINUE failed! linux platformExec")

        # Do a single step, which will allow a new stop event for the
        # rest of vtrace to eat up.
        if v_posix.ptrace(v_posix.PT_STEP, pid, 0, 0) != 0:
            raise Exception("PT_CONTINUE failed! linux platformExec")

        self.pthreads = [pid]
        self.setMeta("ExeName", self._findExe(pid))
        return pid

    @v_base.threadwrap
    def platformAttach(self, pid):
        self.pthreads = [pid]
        self.setMeta("ThreadId", pid)
        if v_posix.ptrace(PT_ATTACH, pid, 0, 0) != 0:
            raise Exception("PT_ATTACH failed!")
        self.setMeta("ExeName", self._findExe(pid))

    def platformPs(self):
        pslist = []
        for dname in self.platformListDir('/proc'):
            try:
                if not dname.isdigit():
                    continue
                cmdline = self.platformReadFile('/proc/%s/cmdline' % dname)
                cmdline = cmdline.replace(b"\x00", b" ")
                if len(cmdline) > 0:
                    pslist.append((int(dname), cmdline.decode('utf-8')))
            except Exception as e:
                pass  # Permissions...  quick process... whatev.
        return pslist

    def _simpleCreateThreads(self):
        for tid in self.threadsForPid( self.pid ):
            if tid == self.pid:
                continue
            self.attachThread( tid )

    def attachThread(self, tid, attached=False):
        self.doAttachThread(tid, attached=attached)
        self.setMeta("ThreadId", tid)
        self.fireNotifiers(vtrace.NOTIFY_CREATE_THREAD)

    @v_base.threadwrap
    def detachThread(self, tid, ecode):

        self.setMeta('ThreadId', tid)
        self._fireExitThread(tid, ecode)

        if v_posix.ptrace(PT_DETACH, tid, 0, 0) != 0:
            raise Exception("ERROR ptrace detach failed for thread %d" % tid)

        self.pthreads.remove(tid)

    @v_base.threadwrap
    def platformWait(self):
        # Blocking wait once...
        pid, status = os.waitpid(-1, 0x40000002)
        self.setMeta("ThreadId", pid)
        # Stop the rest of the threads...
        # why is linux debugging so Ghetto?!?!
        if not self.stepping:  # If we're stepping, only do the one
            for tid in self.pthreads:
                if tid == pid:
                    continue
                try:
                    # We use SIGSTOP here because they can't mask it.
                    os.kill(tid, signal.SIGSTOP)
                    os.waitpid(tid, 0x40000002)
                except Exception as e:
                    logger.warning("WARNING TID is invalid %d %s", tid, e)
        return pid, status

    @v_base.threadwrap
    def platformContinue(self):
        cmd = v_posix.PT_CONTINUE
        if self.getMode("Syscall", False):
            cmd = PT_SYSCALL
        pid = self.getPid()
        sig = self.getCurrentSignal()
        if sig is None:
            sig = 0
        # Only deliver signals to the main thread
        if v_posix.ptrace(cmd, pid, 0, sig) != 0:
            libc.perror('ptrace PT_CONTINUE failed for pid %d' % pid)
            raise Exception("ERROR ptrace failed for pid %d" % pid)

        for tid in self.pthreads:
            if tid == pid:
                continue
            if v_posix.ptrace(cmd, tid, 0, 0) != 0:
                pass

    @v_base.threadwrap
    def platformStepi(self):
        self.stepping = True
        tid = self.getMeta("ThreadId", 0)
        if v_posix.ptrace(v_posix.PT_STEP, tid, 0, 0) != 0:
            raise Exception("ERROR ptrace failed!")

    @v_base.threadwrap
    def platformDetach(self):
        libc.close(self.memfd)
        for tid in self.pthreads:
            v_posix.ptrace(PT_DETACH, tid, 0, 0)

    @v_base.threadwrap
    def doAttachThread(self, tid, attached=False):
        """
        Do the work for attaching a thread.  This must be *under*
        attachThread() so callers in notifiers may call it (because
        it's also gotta be thread wrapped).
        """
        if not attached:
            if v_posix.ptrace(PT_ATTACH, tid, 0, 0) != 0:
                raise Exception("ERROR ptrace attach failed for thread %d" % tid)

        # We may have already revcieved the stop signal
        if not self._stopped_cache.pop(tid, None):
            os.waitpid(tid, 0x40000002)

        self.setupPtraceOptions(tid)
        self.pthreads.append(tid)

    @v_base.threadwrap
    def setupPtraceOptions(self, tid):
        """
        Called per pid/tid to setup proper options
        for ptrace.
        """
        opts = PT_O_TRACESYSGOOD
        ver = tuple(platform.release()[:3].split('.'))
        if (int(ver[0]), int(ver[1])) >= (2, 6):
            opts |= PT_O_TRACECLONE | PT_O_TRACEEXIT
        x = v_posix.ptrace(PT_SETOPTIONS, tid, 0, opts)
        if x != 0:
            libc.perror('ptrace PT_SETOPTION failed for thread %d' % tid)

    def threadsForPid(self, pid):
        ret = []
        tpath = "/proc/%s/task" % pid
        if os.path.exists(tpath):
            for pidstr in os.listdir(tpath):
                ret.append(int(pidstr))
        return ret

    def platformProcessEvent(self, event):
        # Skim some linux specific events before passing to posix
        tid, status = event
        if os.WIFSTOPPED(status):
            sig = status >> 8 # Cant use os.WSTOPSIG() here...
            # print('STOPPED: %d %d %.8x %d' % (self.pid, tid, status, sig))

            # Ok... this is a crazy little state engine that tries
            # to account for the discrepancies in how linux posts
            # signals to the debugger...

            # Thread Creation:
            # In each case below, the kernel may deliver
            # any of the 3 signals in any order...  ALSO
            # (and more importantly) *if* the kernel sends
            # SIGSTOP to the thread first, the debugger
            # will get a SIGSTOP *instead* of SIG_LINUX_CLONE
            # ( this will go back and forth on *ONE BOX* with
            #   the same kernel version... Finally squished it
            #   because it presents more frequently ( 1 in 10 )
            #   on my new ARM linux dev board. WTF?!1?!one?!? )
            #
            # Case 1 (SIG_LINUX_CLONE):
            #     debugger gets SIG_LINUX CLONE as expected
            #     and can then use ptrace(PT_GETEVENTMSG)
            #     to get new TID and attach as normal
            # Case 2 (SIGSTOP delivered to thread)
            #     Thread is already stoped and attached but
            #     parent debugger doesn't know yet.  We add
            #     the tid to the stopped_cache so when the
            #     kernel gets around to telling the debugger
            #     we don't wait on him again.
            # Case 3 (SIGSTOP delivered to debugger)
            #     In both case 2 and case 3, this will cause
            #     the SIG_LINUX_CLONE to be skipped.  Either
            #     way, we should head down into thread attach.
            #     ( The thread may be already stopped )
            if sig == SIG_LINUX_SYSCALL:
                self.fireNotifiers(vtrace.NOTIFY_SYSCALL)

            elif sig == SIG_LINUX_EXIT:

                ecode = self.getPtraceEvent() >> 8

                if tid == self.getPid():
                    self._fireExit( ecode )
                    self.platformDetach()

                else:
                    self.detachThread(tid, ecode)

            elif sig == SIG_LINUX_CLONE:
                # Handle a new thread here!
                newtid = self.getPtraceEvent()
                # print('CLONE (new tid: %d)' % newtid)
                self.attachThread(newtid, attached=True)

            elif sig == signal.SIGSTOP and tid != self.pid:
                #print('OMG IM THE NEW THREAD! %d' % tid)
                # We're not even a real event right now...
                self.runAgain()
                self._stopped_cache[tid] = True

            elif sig == signal.SIGSTOP:
                # If we are still 'exec()'ing, we havent hit the SIGTRAP
                # yet ( so our process info is still python, lets skip it )
                if self.execing:
                    self._stopped_hack = True
                    self.setupPtraceOptions(tid)
                    self.runAgain()

                elif self._stopped_hack:
                    newtid = self.getPtraceEvent(tid)
                    #print("WHY DID WE GET *ANOTHER* STOP?: %d" % tid)
                    #print('PTRACE EVENT: %d' % newtid)
                    self.attachThread(newtid, attached=True)

                else: # on first attach...
                    self._stopped_hack = True
                    self.setupPtraceOptions(tid)
                    self.handlePosixSignal(sig)

            #FIXME eventually implement child catching!
            else:
                self.handlePosixSignal(sig)

            return

        v_posix.PosixMixin.platformProcessEvent(self, event)

    @v_base.threadwrap
    def getPtraceEvent(self, tid=None):
        """
        This *thread wrapped* function will get any pending GETEVENTMSG
        msgs.
        """
        p = c_ulong(0)
        if tid is None:
            tid = self.getMeta("ThreadId", -1)
        if v_posix.ptrace(PT_GETEVENTMSG, tid, 0, addressof(p)) != 0:
            raise Exception('ptrace PT_GETEVENTMSG failed!')
        return p.value

    def platformGetThreads(self):
        ret = {}
        for tid in self.pthreads:
            ret[tid] = tid  # FIXME make this pthread struct or stackbase soon
        return ret

    def platformGetMaps(self):
        maps = []
        with open("/proc/%d/maps" % self.pid, 'r') as mapfile:
            for line in mapfile:

                perms = 0
                sline = line.split(" ")
                addrs = sline[0]
                permstr = sline[1]
                fname = sline[-1].strip()
                addrs = addrs.split("-")
                base = int(addrs[0],16)
                max = int(addrs[1],16)
                mlen = max-base

                if "r" in permstr:
                    perms |= e_mem.MM_READ
                if "w" in permstr:
                    perms |= e_mem.MM_WRITE
                if "x" in permstr:
                    perms |= e_mem.MM_EXEC
                #if "p" in permstr:
                    #pass

                maps.append((base,mlen,perms,fname))
        return maps

    def platformGetFds(self):
        fds = []
        for name in os.listdir("/proc/%d/fd/" % self.pid):
            try:
                fdnum = int(name)
                fdtype = vtrace.FD_UNKNOWN
                link = os.readlink("/proc/%d/fd/%s" % (self.pid, name))
                if "socket:" in link:
                    fdtype = vtrace.FD_SOCKET
                elif "pipe:" in link:
                    fdtype = vtrace.FD_PIPE
                elif "/" in link:
                    fdtype = vtrace.FD_FILE

                fds.append((fdnum, fdtype, link))
            except Exception:
                logger.error(traceback.format_exc())

        return fds

############################################################################
#
# NOTE: Both of these use class locals set by the i386/amd64 variants
#
    @v_base.threadwrap
    def platformGetRegCtx(self, tid):
        ctx = self.archGetRegCtx()
        u = self.user_reg_struct()
        if v_posix.ptrace(PT_GETREGS, tid, 0, addressof(u)) == -1:
            raise v_exc.PtraceException("PT_GETREGS")

        ctx._rctx_Import(u)
        return ctx

    @v_base.threadwrap
    def platformSetRegCtx(self, tid, ctx):
        u = self.user_reg_struct()
        # Populate the reg struct with the current values (to allow for
        # any regs in that struct that we don't track... *fs_base*ahem*
        if v_posix.ptrace(PT_GETREGS, tid, 0, addressof(u)) == -1:
            raise v_exc.PtraceException("PT_GETREGS")

        ctx._rctx_Export(u)
        if v_posix.ptrace(PT_SETREGS, tid, 0, addressof(u)) == -1:
            raise v_exc.PtraceException("PT_SETREGS")

class Linuxi386Trace(
        vtrace.Trace,
        LinuxMixin,
        v_i386.i386Mixin,
        v_posix.ElfMixin,
        v_base.TracerBase):

    user_reg_struct = user_regs_i386
    user_dbg_offset = 252
    reg_val_mask = 0xffffffff

    def __init__(self):
        vtrace.Trace.__init__(self)
        v_base.TracerBase.__init__(self)
        v_posix.ElfMixin.__init__(self)
        v_i386.i386Mixin.__init__(self)
        LinuxMixin.__init__(self)

        # Pre-calc the index of the debug regs
        self.dbgidx = self.archGetRegCtx().getRegisterIndex("debug0")

    @v_base.threadwrap
    def platformGetRegCtx(self, tid):
        ctx = LinuxMixin.platformGetRegCtx( self, tid )
        for i in intel_dbgregs:
            offset = self.user_dbg_offset + (self.psize * i)
            r = v_posix.ptrace(v_posix.PT_READ_U, tid, offset, 0)
            ctx.setRegister(self.dbgidx+i, r & self.reg_val_mask)
        return ctx

    @v_base.threadwrap
    def platformSetRegCtx(self, tid, ctx):
        LinuxMixin.platformSetRegCtx( self, tid, ctx )
        for i in intel_dbgregs:
            val = ctx.getRegister(self.dbgidx + i)
            offset = self.user_dbg_offset + (self.psize * i)
            if v_posix.ptrace(v_posix.PT_WRITE_U, tid, offset, val) != 0:
                libc.perror('PT_WRITE_U failed for debug%d' % i)

    @v_base.threadwrap
    def platformAllocateMemory(self, size, perms=e_mem.MM_RWX, suggestaddr=0):
        sp = self.getStackCounter()
        pc = self.getProgramCounter()

        # Xlate perms (mmap is backward)
        realperm = 0
        if perms & e_mem.MM_READ:
            realperm |= 1
        if perms & e_mem.MM_WRITE:
            realperm |= 2
        if perms & e_mem.MM_EXEC:
            realperm |= 4

        #mma is struct of mmap args for linux syscall
        mma = struct.pack("<6L", suggestaddr, size, realperm, MAP_ANONYMOUS|MAP_PRIVATE, 0, 0)

        regsave = self.getRegisters()

        stacksave = self.readMemory(sp, len(mma))
        ipsave = self.readMemory(pc, 2)

        SYS_mmap = 90

        self.writeMemory(sp, mma)
        self.writeMemory(pc, b"\xcd\x80")
        self.setRegisterByName("eax", SYS_mmap)
        self.setRegisterByName("ebx", sp)
        self._syncRegs()

        try:
            # Step over our syscall instruction
            tid = self.getMeta("ThreadId", 0)
            self.platformStepi()
            os.waitpid(tid, 0)
            eax = self.getRegisterByName("eax")
            if eax & 0x80000000:
                raise Exception("Linux mmap syscall error: %d" % eax)
            return eax

        finally:
            # Clean up all our fux0ring
            self.writeMemory(sp, stacksave)
            self.writeMemory(pc, ipsave)
            self.setRegisters(regsave)

class LinuxAmd64Trace(
        vtrace.Trace,
        LinuxMixin,
        v_amd64.Amd64Mixin,
        v_posix.ElfMixin,
        v_base.TracerBase):

    user_reg_struct = user_regs_amd64
    user_dbg_offset = 848
    reg_val_mask = 0xffffffffffffffff

    def __init__(self):
        vtrace.Trace.__init__(self)
        v_base.TracerBase.__init__(self)
        v_posix.ElfMixin.__init__(self)
        v_amd64.Amd64Mixin.__init__(self)
        LinuxMixin.__init__(self)
        self.dbgidx = self.archGetRegCtx().getRegisterIndex("debug0")

    @v_base.threadwrap
    def platformGetRegCtx(self, tid):
        ctx = LinuxMixin.platformGetRegCtx( self, tid )
        for i in intel_dbgregs:
            offset = self.user_dbg_offset + (self.psize * i)
            r = v_posix.ptrace(v_posix.PT_READ_U, tid, offset, 0)
            ctx.setRegister(self.dbgidx+i, r & self.reg_val_mask)

        self.platformGetExtendedRegs(tid, ctx)
        return ctx

    @v_base.threadwrap
    def platformSetRegCtx(self, tid, ctx):
        LinuxMixin.platformSetRegCtx( self, tid, ctx )
        for i in intel_dbgregs:
            val = ctx.getRegister(self.dbgidx + i)
            offset = self.user_dbg_offset + (self.psize * i)
            if v_posix.ptrace(v_posix.PT_WRITE_U, tid, offset, val) != 0:
                libc.perror('PT_WRITE_U failed for debug%d' % i)

    def parseXSave(self, ctx, iovec):
        '''
        PT_GETREGSET basically just dumps the xsave memory region, so we need to parse that out
        '''
        # There are other registers that are saved in here, but for now, fuck 'em
        simd_regs = [0 for i in range(16)]
        fpu_off = 32
        fpu_len = 8
        # yes you could get this by various other PTRACE calls, but since we already have to call into NT_X86_XSTATE,
        # might as well grab these while we're here
        regidx = self.archGetRegCtx().getRegisterIndex("st0")
        mask = 0xFFFFFFFFFFFFFFFFFFFF  # 80 bit mask for floating points regs
        for i in range(fpu_len):
            offset = fpu_off + i * 16
            # the upper 48 bits of the st/mm registers are marked as reserved
            valu = e_bits.parsebytes(bytes(iovec[offset:offset+10]), 0, 10)
            ctx.setRegister(regidx+i, valu)

        xmm_off = 160

        # these are just the lower bits of the simd registers (just the xmm portion)
        for i in range(len(simd_regs)):
            offset = xmm_off + i * 16
            simd_regs[i] = e_bits.parsebytes(bytes(iovec[offset:offset+16]), 0, 16)

        xstate_bv = e_bits.parsebytes(bytes(iovec[512:520]), 0, 8)
        has_avx = xstate_bv & 0x4
        # XXX: Sooooo....we're gonna cheat a bit here. Technically what we're supposed to do
        # is check CPUID.(EAX=0x0D, ECX=i) for every feature and se how many bytes it takes up, but
        # right now the goal is just to get the upper YMM registers, and we know exactly how
        # many bytes those take up, and they're literally the first state component in the extended
        # xsave region (standard or compacted), so let's parse us some bytes if the has_avx bit is set.
        # (we're also doing it this way because I don't feel like figuring out how to directly call
        # the cpuid asm instruction from python)
        if has_avx:
            ymm_offset = 576
            for i in range(len(simd_regs)):
                offset = ymm_offset + i*16
                valu = e_bits.parsebytes(bytes(iovec[offset:offset+16]), 0, 16)
                simd_regs[i] |= valu << 128

        regidx = self.archGetRegCtx().getRegisterIndex("ymm0")
        for i, valu in enumerate(simd_regs):
            ctx.setRegister(regidx+i, valu)

    def platformGetExtendedRegs(self, tid, ctx):
        '''
        for now, the only real way to get access to things like YMM and ZMM registers
        '''
        buflen = 2048  # Guess. Actual length will be set by kernel
        buffer = (c_uint8 * buflen)()
        vec = iovec(cast(buffer, c_void_p), buflen)

        if v_posix.ptrace(PT_GETREGSET, tid, NT_X86_XSTATE, addressof(vec)) != 0:
            raise v_exc.PtraceException("PT_GETREGSET(NT_X86_XSTATE)")

        self.parseXSave(ctx, buffer)

arm_break_be = binascii.unhexlify('e7f001f0')
arm_break_le = binascii.unhexlify('f001f0e7')

class LinuxArmTrace(
        vtrace.Trace,
        LinuxMixin,
        v_arm.ArmMixin,
        v_posix.ElfMixin,
        v_base.TracerBase):

    user_reg_struct = user_regs_arm
    reg_val_mask = 0xffffffff

    def __init__(self):
        vtrace.Trace.__init__(self)
        v_base.TracerBase.__init__(self)
        v_posix.ElfMixin.__init__(self)
        v_arm.ArmMixin.__init__(self)
        LinuxMixin.__init__(self)

        self._break_after_bp = False
        self._step_cleanup = []

    def _fireStep(self):
        # See notes below about insanity...
        if self._step_cleanup is not None:
            [ self.writeMemory( bva, bytes ) for (bva,bytes) in self._step_cleanup ]
            self._step_cleanup = None
        return v_base.TracerBase._fireStep( self )

    def archGetBreakInstr(self):
        return arm_break_le

    @v_base.threadwrap
    def platformStepi(self):
        # This is a total rediculous hack to account
        # for the fact that the arm platform couldn't
        # be bothered to implement single stepping in
        # the stupid hardware...

        self.stepping = True

        pc = self.getProgramCounter()
        op = self.parseOpcode( pc )

        branches = op.getBranches( self )
        if not branches:
            raise Exception('''
                    The branches for the instruction %r were not decoded correctly.  This means that
                    we cant properly predict the possible next instruction executions in a way that allows us
                    to account for the STUPID INSANE FACT THAT THERE IS NO HARDWARE SINGLE STEP CAPABILITY ON
                    ARM (non-realtime or JTAG anyway).  We *would* have written invalid instructions to each
                    of those locations and cleaned them up before you ever knew anything was amiss... which is
                    how we pretend arm can single step... even though IT CANT. (please tell visi...)
            ''' % op)

        # Save the memory at the branches for later
        # restoration in the _fireStep callback.

        self._step_cleanup = []
        for bva,bflags in op.getBranches( self ):
            self._step_cleanup.append( (bva, self.readMemory( bva, 4 )) )
            self.writeMemory( bva, arm_break_le )

        tid = self.getMeta('ThreadId')

        if v_posix.ptrace(v_posix.PT_CONTINUE, tid, 0, 0) != 0:
            raise Exception("ERROR ptrace failed for tid %d" % tid)


text:
require 'open-uri'
require 'nokogiri'
require 'fileutils'
require 'html5slides2pdf/version'

class Html5slides2pdfError < StandardError; end

class Html5slides2pdf
  attr_accessor :work_dir, :output, :options

  DEFAULT_OPTIONS = [
    '--page-size A4',
    '--orientation landscape',
    '--margin-top 0',
    '--margin-left 0',
    '--margin-right 0',
    '--margin-bottom 0'
  ]

  def initialize(output='_slide.pdf', work_dir='./work', options=nil)
    @output = output
    @work_dir = work_dir
    @options = options || DEFAULT_OPTIONS
  end

  def convert(url)
    doc = Nokogiri::HTML(open(url))
    unless slide?(doc)
      raise Html5slides2pdfError, 'not html5slides'
    end
    Dir.mkdir(@work_dir) unless File.exists?(@work_dir)
    preprocess_for_image(url, doc)
    htmls = make_html_per_page(doc)
    make_pdf(doc, htmls)
  end

  def slide?(doc)
    section_tag = doc.at('section')
    article_tag = doc.at('article')
    slides_js = doc.search('script').any? {|e|
      e[:src] && File.basename(e[:src]) == 'slides.js'
    }
    (section_tag && article_tag && slides_js) ? true : false
  end

  def preprocess_for_image(url, doc)
    doc.search('img').each {|e|
      src = URI.parse(e[:src])
      if src.relative?
        from = URI.join(url, src).to_s
        to = '%s/%s' % [@work_dir, src]
      else
        from = src.to_s
        to = '%s/%s' % [@work_dir, s - url]
      end
      FileUtils.mkdir_p(File.dirname(to))
      download_image(from, to)
    }
  end

  def download_image(from, to)
    open(to, 'wb') {|w|
      open(from) {|r|
        w.write(r.read)
      }
    }
  end

  def make_html_per_page(doc)
    files = []
    doc.search('article').each_with_index {|article, i|
      html = template % {:article => article}
      filename = '%s/%s.html' % [@work_dir, i]
      open(filename, 'w') {|f| f.write(html) }
      files << filename
    }
    files
  end

  def template
    css = load_css.gsub(/%/, '%%')
    <<-EOS
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<style>
#{css}
</style>
</head>
<body>
%<article>s
</body>
</html>
    EOS
  end

  def load_css
    path = File.join(File.dirname(File.expand_path(__FILE__)), 'styles.css')
    File.readlines(path).reject {|line|
      line.index('letter-spacing')
    }.join
  end

  def make_pdf(doc, htmls)
    cmd = 'wkhtmltopdf %s %s %s' % [@options.join(' '),
                                    htmls.join(' '),
                                    @output]
    system cmd
  end
end


text:
package com.huawei.esdk.fusionmanager.local.impl.resources.net;

//import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.huawei.esdk.fusionmanager.local.impl.SDKClient;
import com.huawei.esdk.fusionmanager.local.impl.constant.ESDKURL;
import com.huawei.esdk.fusionmanager.local.impl.constant.NativeConstant;
import com.huawei.esdk.fusionmanager.local.impl.utils.ClientProvider;
import com.huawei.esdk.fusionmanager.local.impl.utils.URLUtils;
import com.huawei.esdk.fusionmanager.local.model.ClientProviderBean;
import com.huawei.esdk.fusionmanager.local.model.net.QueryPublicIPPoolResp;
import com.huawei.esdk.fusionmanager.local.resources.net.PublicIPPoolResource;

public class PublicIPPoolResourceImpl implements PublicIPPoolResource
{
    //private static final Logger LOGGER = Logger.getLogger(PublicIPPoolResourceImpl.class);

    private static PublicIPPoolResourceImpl instance = null;

    private Gson gson = new GsonBuilder().serializeNulls().create();

    private SDKClient sdkRestClient;

    private ClientProviderBean bean;

    public static synchronized PublicIPPoolResourceImpl getInstance(ClientProviderBean bean)
    {
        if (null == instance)
        {
            instance = new PublicIPPoolResourceImpl();
        }

        instance.init(bean);
        return instance;
    }

    private PublicIPPoolResourceImpl()
    {
    }

    private void init(ClientProviderBean bean)
    {
        sdkRestClient = (SDKClient)ClientProvider.getClient(bean);
        this.bean = bean;
    }

    @Override
    public QueryPublicIPPoolResp query(String vdcId, String cloudInfraId, String vpcId)
    {
        //LOGGER.info("query() start");
        String json = null;
        QueryPublicIPPoolResp response = null;

        try
        {
            json =
                sdkRestClient.get(URLUtils.makeUrl(bean, ESDKURL.PUBLICIPPOOLRESOURCE_QUERY, new String[] {vdcId,
                    cloudInfraId, vpcId}),
                    "PublicIPPoolResource#Query");
            response = gson.fromJson(json, QueryPublicIPPoolResp.class);
        }
        catch (JsonSyntaxException e)
        {
            //LOGGER.error("query() JsonSyntaxException", e);
            response = new QueryPublicIPPoolResp();
            response.setCode(NativeConstant.SERVER_EXCEPTION);
        }
        catch (Exception e)
        {
            //LOGGER.error("query() error", e);
            response = new QueryPublicIPPoolResp();
            response.setCode(NativeConstant.NATIVE_EXCEPTION);
        }
        //LOGGER.info("query() resp:" + gson.toJson(response));
        //LOGGER.info("query() end");
        return response;
    }

}


text:
package com.payalabs.scalajs.react.bridge

import japgolly.scalajs.react.vdom.{VdomElement, VdomNode}

import scala.scalajs.js

import scala.language.implicitConversions

class WithPropsAndTagsMods(jsComponent: JsComponentType, jsProps: js.Object, tagModChildren: List[VdomNode]) {
  def apply(children: VdomNode*): VdomElement = {
    new WithPropsAndTagModsAndChildren(jsComponent, jsProps, tagModChildren ++ children).apply
  }
}

object WithPropsAndTagsMods {
  implicit def toVdomNode(wp: WithPropsAndTagsMods): VdomNode = wp.apply()
}


text:
package com.thoughtworks.go.config;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

public class BuildArtifactConfigTest {
    @Test
    public void validate_shouldFailIfSourceIsEmpty() {
        BuildArtifactConfig artifactPlan = new BuildArtifactConfig(null, "bar");
        artifactPlan.validate(ConfigSaveValidationContext.forChain(new JobConfig("jobname")));
        assertThat(artifactPlan.errors().on(BuiltinArtifactConfig.SRC), is("Job 'jobname' has an artifact with an empty source"));
    }

    @Test
    public void validate_shouldFailIfDestDoesNotMatchAFilePattern() {
        BuildArtifactConfig artifactPlan = new BuildArtifactConfig("foo/bar", "..");
        artifactPlan.validate(null);
        assertThat(artifactPlan.errors().on(BuiltinArtifactConfig.DEST), is("Invalid destination path. Destination path should match the pattern (([.]\\/)?[.][^. ]+)|([^. ].+[^. ])|([^. ][^. ])|([^. ])"));
    }

    @Test
    public void validate_shouldNotFailWhenDestinationIsNotSet() {
        BuildArtifactConfig artifactPlan = new BuildArtifactConfig(null, null);
        artifactPlan.setSource("source");
        artifactPlan.validate(null);
        assertThat(artifactPlan.errors().isEmpty(), is(true));
    }

    @Test
    public void shouldErrorOutWhenDuplicateArtifactConfigsExists() {
        List<ArtifactTypeConfig> plans = new ArrayList<>();
        BuildArtifactConfig existingPlan = new BuildArtifactConfig("src", "dest");
        plans.add(existingPlan);
        BuildArtifactConfig artifactPlan = new BuildArtifactConfig("src", "dest");

        artifactPlan.validateUniqueness(plans);

        assertThat(artifactPlan.errors().isEmpty(), is(false));
        assertThat(artifactPlan.errors().on(BuiltinArtifactConfig.SRC), is("Duplicate artifacts defined."));
        assertThat(artifactPlan.errors().on(BuiltinArtifactConfig.DEST), is("Duplicate artifacts defined."));
        assertThat(existingPlan.errors().isEmpty(), is(false));
        assertThat(existingPlan.errors().on(BuiltinArtifactConfig.SRC), is("Duplicate artifacts defined."));
        assertThat(existingPlan.errors().on(BuiltinArtifactConfig.DEST), is("Duplicate artifacts defined."));
    }

    @Test
    public void validate_shouldNotFailWhenComparingBuildAndTestArtifacts() {
        List<ArtifactTypeConfig> plans = new ArrayList<>();
        TestArtifactConfig testArtifactConfig = new TestArtifactConfig("src", "dest");
        plans.add(testArtifactConfig);
        BuildArtifactConfig buildArtifactConfig = new BuildArtifactConfig("src", "dest");

        buildArtifactConfig.validateUniqueness(plans);

        assertThat(buildArtifactConfig.errors().isEmpty(), is(true));
    }

    @Test
    public void shouldAllowOverridingDefaultArtifactDestination() {
        BuildArtifactConfig artifactConfig = new BuildArtifactConfig("src", "dest");
        assertThat(artifactConfig.getDestination(), is("dest"));

        TestArtifactConfig testArtifactConfig = new TestArtifactConfig("src", "destination");
        assertThat(testArtifactConfig.getDestination(), is("destination"));
    }

    @Test
    public void shouldNotOverrideDefaultArtifactDestinationWhenNotSpecified() {
        BuildArtifactConfig artifactConfig = new BuildArtifactConfig("src", null);
        assertThat(artifactConfig.getDestination(), is(""));

        TestArtifactConfig testArtifactConfig = new TestArtifactConfig("src", null);
        assertThat(testArtifactConfig.getDestination(), is("testoutput"));
    }
}


text:
<?php

namespace Plank\Mediable\Tests\Integration;

use Illuminate\Support\Facades\DB;
use Plank\Mediable\Media;
use Plank\Mediable\MediableCollection;
use Plank\Mediable\Tests\Mocks\SampleMediable;
use Plank\Mediable\Tests\Mocks\SampleMediableSoftDelete;
use Plank\Mediable\Tests\TestCase;

class MediableTest extends TestCase
{
    public function setUp(): void
    {
        parent::setUp();
        $this->useDatabase();
    }

    public function test_it_can_attach_and_retrieve_media_by_a_tag()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media1 = factory(Media::class)->create(['id' => 2]);

        $mediable->attachMedia($media1, 'foo');
        $result = $mediable->getMedia('foo');

        $this->assertInstanceOf(\Illuminate\Database\Eloquent\Collection::class, $result);
        $this->assertEquals([2], $result->pluck('id')->toArray());
    }

    public function test_it_can_attach_to_numeric_tags()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media1 = factory(Media::class)->create(['id' => 2]);

        $mediable->attachMedia($media1, (string)2018);
        $result = $mediable->getMedia((string)2018);

        $this->assertInstanceOf(\Illuminate\Database\Eloquent\Collection::class, $result);
        $this->assertEquals([2], $result->pluck('id')->toArray());
    }

    public function test_it_can_attach_one_media_to_multiple_tags()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media1 = factory(Media::class)->create(['id' => 2]);

        $mediable->attachMedia($media1, 'bar');
        $mediable->attachMedia($media1, 'foo');

        $this->assertEquals([2], $mediable->getMedia('foo')->pluck('id')->toArray());
        $this->assertEquals([2], $mediable->getMedia('bar')->pluck('id')->toArray());
        $this->assertEquals(
            0,
            $mediable->getMedia('baz')->count(),
            'Found media for non-existent tag'
        );
    }

    public function test_it_can_attach_multiple_media_to_multiple_tags_simultaneously()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media1 = factory(Media::class)->create();
        $media2 = factory(Media::class)->create();

        $mediable->attachMedia([$media1->id, $media2->id], ['foo', 'bar']);

        $this->assertCount(2, $mediable->getMedia('foo'));
        $this->assertCount(2, $mediable->getMedia('bar'));
    }

    public function test_it_can_find_the_first_media()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media1 = factory(Media::class)->create(['id' => 1]);
        $media2 = factory(Media::class)->create(['id' => 2]);

        $mediable->attachMedia($media1, 'foo');
        $mediable->attachMedia($media2, 'foo');

        $this->assertEquals(1, $mediable->firstMedia('foo')->id);
    }

    public function test_it_can_find_the_last_media()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media1 = factory(Media::class)->create(['id' => 1]);
        $media2 = factory(Media::class)->create(['id' => 2]);

        $mediable->attachMedia($media1, 'foo');
        $mediable->attachMedia($media2, 'foo');

        $this->assertEquals(2, $mediable->lastMedia('foo')->id);
    }

    public function test_it_can_find_media_matching_any_tags()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media1 = factory(Media::class)->create(['id' => 1]);
        $media2 = factory(Media::class)->create(['id' => 2]);
        $media3 = factory(Media::class)->create(['id' => 3]);

        $mediable->attachMedia($media1, 'foo');
        $mediable->attachMedia($media1, 'bar');
        $mediable->attachMedia($media2, 'bar');
        $mediable->attachMedia($media3, 'baz');

        $this->assertEquals(
            [1, 2],
            $mediable->getMedia(['foo', 'bar'], false)->pluck(
                'id'
            )->toArray()
        );
    }

    public function test_it_can_find_media_matching_multiple_tags()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media1 = factory(Media::class)->create(['id' => 1]);
        $media2 = factory(Media::class)->create(['id' => 2]);
        $media3 = factory(Media::class)->create(['id' => 3]);

        $mediable->attachMedia($media1, 'foo');
        $mediable->attachMedia($media1, 'bar');
        $mediable->attachMedia($media2, 'bar');
        $mediable->attachMedia($media3, 'baz');

        $this->assertEquals(
            [1],
            $mediable->getMedia(['foo', 'bar'], true)->pluck(
                'id'
            )->toArray()
        );
        $this->assertEquals(0, $mediable->getMedia(['foo', 'bat'], true)->count());
    }

    public function test_it_can_check_presence_of_attached_media()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media1 = factory(Media::class)->create(['id' => 1]);
        $media2 = factory(Media::class)->create(['id' => 2]);

        $mediable->attachMedia($media1, 'foo');
        $mediable->attachMedia($media2, 'foo');
        $mediable->attachMedia($media2, 'bar');

        $this->assertTrue($mediable->hasMedia('foo'));
        $this->assertTrue($mediable->hasMedia('bar'));
        $this->assertFalse($mediable->hasMedia('baz'));
        $this->assertTrue(
            $mediable->hasMedia(['bar', 'baz'], false),
            'Failed to find model matching one of many tag'
        );
        $this->assertFalse(
            $mediable->hasMedia(['bar', 'baz'], true),
            'Failed to match all tags'
        );
    }

    public function test_it_can_list_media_by_tag()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media1 = factory(Media::class)->create(['id' => 1]);
        $media2 = factory(Media::class)->create(['id' => 2]);

        $mediable->attachMedia($media1, 'foo');
        $mediable->attachMedia($media2, 'bar');

        $result = $mediable->getAllMediaByTag();
        $this->assertEquals(['foo', 'bar'], $result->keys()->toArray());
        $this->assertEquals([1], $result['foo']->pluck('id')->toArray());
        $this->assertEquals([2], $result['bar']->pluck('id')->toArray());
    }

    public function test_it_can_detach_media_by_tag()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media = factory(Media::class)->create();
        $mediable->attachMedia($media, 'foo');
        $mediable->detachMedia($media, 'foo');

        $this->assertEquals(0, $mediable->getMedia('foo')->count());
    }

    public function test_it_can_detach_media_of_multiple_tags()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media = factory(Media::class)->create(['id' => 1]);
        $mediable->attachMedia($media, 'foo');
        $mediable->attachMedia($media, 'bar');

        $mediable->detachMedia($media, ['foo', 'bar']);

        $this->assertEquals(0, $mediable->getMedia('foo')->count());
        $this->assertEquals(0, $mediable->getMedia('bar')->count());
    }

    public function test_it_can_sync_media_by_tag()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media1 = factory(Media::class)->create(['id' => 2]);
        $media2 = factory(Media::class)->create(['id' => 3]);

        $mediable->attachMedia([$media1->id, $media2->id], 'foo');
        $mediable->attachMedia($media2, 'bar');
        $mediable->syncMedia($media1, 'foo');

        $this->assertEquals(1, $mediable->getMedia('foo')->count());
        $this->assertEquals(
            [3],
            $mediable->getMedia('bar')->pluck('id')->toArray(),
            'Modified other tags'
        );
    }

    public function test_it_can_sync_media_to_multiple_tags()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media1 = factory(Media::class)->create(['id' => 1]);
        $media2 = factory(Media::class)->create(['id' => 2]);
        $media3 = factory(Media::class)->create(['id' => 3]);

        $mediable->attachMedia($media1, 'foo');
        $mediable->attachMedia($media1, 'bar');

        $mediable->syncMedia([$media2->id, $media3->id], ['bar', 'baz']);

        $this->assertEquals([1], $mediable->getMedia('foo')->pluck('id')->toArray());
        $this->assertEquals([2, 3], $mediable->getMedia('bar')->pluck('id')->toArray());
        $this->assertEquals([2, 3], $mediable->getMedia('baz')->pluck('id')->toArray());
    }

    public function test_it_can_be_queried_by_any_media()
    {
        $mediable = factory(SampleMediable::class)->create();
        $mediable2 = factory(SampleMediable::class)->create();
        $media = factory(Media::class)->create();
        $mediable->attachMedia($media, 'foo');

        $result = SampleMediable::whereHasMedia([], false)->get();
        $this->assertEquals([$mediable->getKey()], $result->modelKeys());
    }

    public function test_it_can_be_queried_by_tag()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media = factory(Media::class)->create();
        $mediable->attachMedia($media, 'foo');

        $this->assertEquals(1, SampleMediable::whereHasMedia('foo', false)->count());
        $this->assertEquals(
            0,
            SampleMediable::whereHasMedia('bar', false)->count(),
            'Queriable by non-existent group'
        );
    }

    public function test_it_can_be_queried_by_tag_matching_all()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media1 = factory(Media::class)->create(['id' => 1]);
        $media2 = factory(Media::class)->create(['id' => 2]);

        $mediable->attachMedia($media1, ['foo', 'bar']);
        $mediable->attachMedia($media2, ['foo']);

        $this->assertEquals(
            [1],
            SampleMediable::whereHasMediaMatchAll(['foo', 'bar'])->get()->pluck(
                'id'
            )->toArray()
        );
        $this->assertEquals(
            [1],
            SampleMediable::whereHasMedia(['foo', 'bar'], true)->get()->pluck(
                'id'
            )->toArray()
        );
    }

    public function test_it_can_list_the_tags_a_media_is_attached_to()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media = factory(Media::class)->create();

        $mediable->attachMedia($media, 'foo');
        $mediable->attachMedia($media, 'bar');

        $this->assertContains('foo', $mediable->getTagsForMedia($media));
        $this->assertContains('bar', $mediable->getTagsForMedia($media));
    }

    public function test_it_can_disable_automatic_rehydration()
    {
        $mediable = factory(SampleMediable::class)->create();
        $mediable->rehydrates_media = false;
        $media = factory(Media::class)->create();

        $mediable->media;
        $mediable->attachMedia($media, 'foo');
        $this->assertEquals(0, $mediable->getMedia('foo')->count());
    }

    public function test_it_can_eager_load_media()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media = factory(Media::class)->create();
        $mediable->attachMedia($media, 'foo');

        $result = SampleMediable::withMedia()->first();
        $this->assertTrue($result->relationLoaded('media'));
        $this->assertFalse($result->media[0]->relationLoaded('originalMedia'));
        $this->assertFalse($result->media[0]->relationLoaded('variants'));
    }

    public function test_it_can_eager_load_media_by_tag()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media1 = factory(Media::class)->create(['id' => 1]);
        $media2 = factory(Media::class)->create(['id' => 2]);
        $mediable->attachMedia($media1, 'foo');
        $mediable->attachMedia($media2, 'bar');

        $result = SampleMediable::withMedia(['bar'])->first();

        $this->assertTrue($result->relationLoaded('media'));
        $this->assertEquals([2], $result->media->pluck('id')->toArray());
        $this->assertFalse($result->media[0]->relationLoaded('originalMedia'));
        $this->assertFalse($result->media[0]->relationLoaded('variants'));
    }

    public function test_it_can_eager_load_media_by_tag_matching_all()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media1 = factory(Media::class)->create(['id' => 1]);
        $media2 = factory(Media::class)->create(['id' => 2]);
        $mediable->attachMedia($media1, 'foo');
        $mediable->attachMedia($media2, ['bar', 'foo', 'baz']);

        $result = SampleMediable::withMedia(['bar', 'foo'], true)->first();
        $this->assertTrue($result->relationLoaded('media'));
        $this->assertEquals([2, 2], $result->media->pluck('id')->toArray());
        $this->assertFalse($result->media[0]->relationLoaded('originalMedia'));
        $this->assertFalse($result->media[0]->relationLoaded('variants'));

        $result = SampleMediable::withMediaMatchAll(['bar', 'foo'])->first();
        $this->assertTrue($result->relationLoaded('media'));
        $this->assertEquals([2, 2], $result->media->pluck('id')->toArray());
        $this->assertFalse($result->media[0]->relationLoaded('originalMedia'));
        $this->assertFalse($result->media[0]->relationLoaded('variants'));
    }

    public function test_it_can_eager_load_media_with_variants()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media = factory(Media::class)->create();
        $mediable->attachMedia($media, 'foo');

        $result = SampleMediable::withMedia([], false, true)->first();
        $this->assertTrue($result->relationLoaded('media'));
        $this->assertTrue($result->media[0]->relationLoaded('originalMedia'));
        $this->assertTrue($result->media[0]->relationLoaded('variants'));

        $result = SampleMediable::withMediaAndVariants()->first();
        $this->assertTrue($result->relationLoaded('media'));
        $this->assertTrue($result->media[0]->relationLoaded('originalMedia'));
        $this->assertTrue($result->media[0]->relationLoaded('variants'));
    }

    public function test_it_can_eager_load_media_with_variants_by_tag()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media1 = factory(Media::class)->create(['id' => 1]);
        $media2 = factory(Media::class)->create(['id' => 2]);
        $mediable->attachMedia($media1, 'foo');
        $mediable->attachMedia($media2, 'bar');

        $result = SampleMediable::withMedia(['bar'], false, true)->first();
        $this->assertTrue($result->relationLoaded('media'));
        $this->assertEquals([2], $result->media->pluck('id')->toArray());
        $this->assertTrue($result->media[0]->relationLoaded('originalMedia'));
        $this->assertTrue($result->media[0]->relationLoaded('variants'));

        $result = SampleMediable::withMediaAndVariants(['bar'])->first();
        $this->assertTrue($result->relationLoaded('media'));
        $this->assertEquals([2], $result->media->pluck('id')->toArray());
        $this->assertTrue($result->media[0]->relationLoaded('originalMedia'));
        $this->assertTrue($result->media[0]->relationLoaded('variants'));
    }

    public function test_it_can_eager_load_media_with_variants_by_tag_matching_all()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media1 = factory(Media::class)->create(['id' => 1]);
        $media2 = factory(Media::class)->create(['id' => 2]);
        $mediable->attachMedia($media1, 'foo');
        $mediable->attachMedia($media2, ['bar', 'foo', 'baz']);

        $result = SampleMediable::withMedia(['bar', 'foo'], true, true)->first();
        $this->assertTrue($result->relationLoaded('media'));
        $this->assertEquals([2, 2], $result->media->pluck('id')->toArray());
        $this->assertTrue($result->media[0]->relationLoaded('originalMedia'));
        $this->assertTrue($result->media[0]->relationLoaded('variants'));

        $result = SampleMediable::withMediaAndVariants(['bar', 'foo'], true)->first();
        $this->assertTrue($result->relationLoaded('media'));
        $this->assertEquals([2, 2], $result->media->pluck('id')->toArray());
        $this->assertTrue($result->media[0]->relationLoaded('originalMedia'));
        $this->assertTrue($result->media[0]->relationLoaded('variants'));

        $result = SampleMediable::withMediaMatchAll(['bar', 'foo'], true)->first();
        $this->assertTrue($result->relationLoaded('media'));
        $this->assertEquals([2, 2], $result->media->pluck('id')->toArray());
        $this->assertTrue($result->media[0]->relationLoaded('originalMedia'));
        $this->assertTrue($result->media[0]->relationLoaded('variants'));

        $result = SampleMediable::withMediaAndVariantsMatchAll(['bar', 'foo'])->first();
        $this->assertTrue($result->relationLoaded('media'));
        $this->assertEquals([2, 2], $result->media->pluck('id')->toArray());
        $this->assertTrue($result->media[0]->relationLoaded('originalMedia'));
        $this->assertTrue($result->media[0]->relationLoaded('variants'));
    }

    public function test_it_can_lazy_eager_load_media()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media = factory(Media::class)->create();
        $mediable->attachMedia($media, 'foo');

        $result = SampleMediable::first();
        $this->assertSame($result, $result->loadMedia());
        $this->assertTrue($result->relationLoaded('media'));
        $this->assertFalse($result->media[0]->relationLoaded('originalMedia'));
        $this->assertFalse($result->media[0]->relationLoaded('variants'));
    }

    public function test_it_can_lazy_eager_load_media_by_tag()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media1 = factory(Media::class)->create(['id' => 1]);
        $media2 = factory(Media::class)->create(['id' => 2]);
        $mediable->attachMedia($media1, 'foo');
        $mediable->attachMedia($media2, 'bar');

        $result = SampleMediable::first();
        $this->assertSame($result, $result->loadMedia(['bar']));
        $this->assertTrue($result->relationLoaded('media'));
        $this->assertEquals([2], $result->media->pluck('id')->toArray());
        $this->assertFalse($result->media[0]->relationLoaded('originalMedia'));
        $this->assertFalse($result->media[0]->relationLoaded('variants'));
    }

    public function test_it_can_lazy_eager_load_media_by_tag_matching_all()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media1 = factory(Media::class)->create(['id' => 1]);
        $media2 = factory(Media::class)->create(['id' => 2]);
        $mediable->attachMedia($media1, 'foo');
        $mediable->attachMedia($media2, ['bar', 'foo', 'baz']);

        $result = SampleMediable::first();
        $this->assertSame($result, $result->loadMedia(['bar', 'foo'], true));
        $this->assertTrue($result->relationLoaded('media'));
        $this->assertEquals([2, 2], $result->media->pluck('id')->toArray());
        $this->assertFalse($result->media[0]->relationLoaded('originalMedia'));
        $this->assertFalse($result->media[0]->relationLoaded('variants'));

        $result = SampleMediable::first();
        $this->assertSame($result, $result->loadMediaMatchAll(['bar', 'foo']));
        $this->assertTrue($result->relationLoaded('media'));
        $this->assertEquals([2, 2], $result->media->pluck('id')->toArray());
        $this->assertFalse($result->media[0]->relationLoaded('originalMedia'));
        $this->assertFalse($result->media[0]->relationLoaded('variants'));
    }

    public function test_it_can_lazy_eager_load_media_with_variants()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media = factory(Media::class)->create();
        $mediable->attachMedia($media, 'foo');

        $result = SampleMediable::first();
        $this->assertSame($result, $result->loadMedia([], false, true));
        $this->assertTrue($result->relationLoaded('media'));
        $this->assertTrue($result->media[0]->relationLoaded('originalMedia'));
        $this->assertTrue($result->media[0]->relationLoaded('variants'));

        $result = SampleMediable::first();
        $this->assertSame($result, $result->loadMediaWithVariants());
        $this->assertTrue($result->relationLoaded('media'));
        $this->assertTrue($result->media[0]->relationLoaded('originalMedia'));
        $this->assertTrue($result->media[0]->relationLoaded('variants'));
    }

    public function test_it_can_lazy_eager_load_media_with_variants_by_tag()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media1 = factory(Media::class)->create(['id' => 1]);
        $media2 = factory(Media::class)->create(['id' => 2]);
        $mediable->attachMedia($media1, 'foo');
        $mediable->attachMedia($media2, 'bar');

        $result = SampleMediable::first();
        $this->assertSame($result, $result->loadMedia(['bar'], false, true));
        $this->assertTrue($result->relationLoaded('media'));
        $this->assertEquals([2], $result->media->pluck('id')->toArray());
        $this->assertTrue($result->media[0]->relationLoaded('originalMedia'));
        $this->assertTrue($result->media[0]->relationLoaded('variants'));

        $result = SampleMediable::first();
        $this->assertSame($result, $result->loadMediaWithVariants(['bar']));
        $this->assertTrue($result->relationLoaded('media'));
        $this->assertEquals([2], $result->media->pluck('id')->toArray());
        $this->assertTrue($result->media[0]->relationLoaded('originalMedia'));
        $this->assertTrue($result->media[0]->relationLoaded('variants'));
    }

    public function test_it_can_lazy_eager_load_media_with_variants_by_tag_matching_all()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media1 = factory(Media::class)->create(['id' => 1]);
        $media2 = factory(Media::class)->create(['id' => 2]);
        $mediable->attachMedia($media1, 'foo');
        $mediable->attachMedia($media2, ['bar', 'foo', 'baz']);

        $result = SampleMediable::first();
        $this->assertSame($result, $result->loadMedia(['bar', 'foo'], true, true));
        $this->assertTrue($result->relationLoaded('media'));
        $this->assertEquals([2, 2], $result->media->pluck('id')->toArray());
        $this->assertTrue($result->media[0]->relationLoaded('originalMedia'));
        $this->assertTrue($result->media[0]->relationLoaded('variants'));

        $result = SampleMediable::first();
        $this->assertSame($result, $result->loadMediaWithVariants(['bar', 'foo'], true));
        $this->assertTrue($result->relationLoaded('media'));
        $this->assertEquals([2, 2], $result->media->pluck('id')->toArray());
        $this->assertTrue($result->media[0]->relationLoaded('originalMedia'));
        $this->assertTrue($result->media[0]->relationLoaded('variants'));

        $result = SampleMediable::first();
        $this->assertSame($result, $result->loadMediaMatchAll(['bar', 'foo'], true));
        $this->assertTrue($result->relationLoaded('media'));
        $this->assertEquals([2, 2], $result->media->pluck('id')->toArray());
        $this->assertTrue($result->media[0]->relationLoaded('originalMedia'));
        $this->assertTrue($result->media[0]->relationLoaded('variants'));

        $result = SampleMediable::first();
        $this->assertSame($result, $result->loadMediaWithVariantsMatchAll(['bar', 'foo']));
        $this->assertTrue($result->relationLoaded('media'));
        $this->assertEquals([2, 2], $result->media->pluck('id')->toArray());
        $this->assertTrue($result->media[0]->relationLoaded('originalMedia'));
        $this->assertTrue($result->media[0]->relationLoaded('variants'));
    }

    public function test_it_uses_custom_collection()
    {
        $mediable = factory(SampleMediable::class)->make();
        $this->assertInstanceOf(MediableCollection::class, $mediable->newCollection([]));
    }

    public function test_it_cascades_relationship_on_delete()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media = factory(Media::class)->create();
        $mediable->attachMedia($media, 'foo');

        $mediable->delete();
        $this->assertEquals(0, $mediable->getMedia('foo')->count());
    }

    public function test_it_doesnt_cascade_relationship_on_soft_delete()
    {
        $mediable = factory(SampleMediableSoftDelete::class)->create();
        $media = factory(Media::class)->create();
        $mediable->attachMedia($media, 'foo');

        $mediable->delete();
        $this->assertEquals(1, $mediable->getMedia('foo')->count());
    }

    public function test_it_cascades_relationships_on_soft_delete_with_config()
    {
        $mediable = factory(SampleMediableSoftDelete::class)->create();
        $media = factory(Media::class)->create();
        $mediable->attachMedia($media, 'foo');

        config()->set('mediable.detach_on_soft_delete', true);

        $mediable->delete();
        $this->assertEquals(0, $mediable->getMedia('foo')->count());
    }

    public function test_it_cascades_relationship_on_force_delete()
    {
        $mediable = factory(SampleMediableSoftDelete::class)->create();
        $media = factory(Media::class)->create();
        $mediable->attachMedia($media, 'foo');

        $mediable->forceDelete();
        $this->assertEquals(0, $mediable->getMedia('foo')->count());
    }

    public function test_it_reads_highest_order()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media = factory(Media::class)->create(['id' => 1]);
        $method = $this->getPrivateMethod($mediable, 'getOrderValueForTags');

        $this->assertEquals(['foo' => 0], $method->invoke($mediable, 'foo'));
        $mediable->attachMedia($media, 'foo');
        $this->assertEquals(['foo' => 1], $method->invoke($mediable, 'foo'));
    }

    public function test_it_increments_order()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media1 = factory(Media::class)->create(['id' => 1]);
        $media2 = factory(Media::class)->create(['id' => 2]);
        $media3 = factory(Media::class)->create(['id' => 3]);

        $mediable->attachMedia($media2, 'foo');
        $mediable->attachMedia($media3, 'foo');
        $mediable->attachMedia($media1, 'bar');
        $mediable->attachMedia($media1, 'foo');

        $this->assertEquals(
            [2 => 1, 3 => 2, 1 => 3],
            $mediable->getMedia('foo')->pluck('pivot.order', 'id')->toArray()
        );
        $this->assertEquals(
            [1 => 1],
            $mediable->getMedia('bar')->pluck(
                'pivot.order',
                'id'
            )->toArray()
        );
    }

    public function test_it_increments_order_when_attaching_multiple()
    {
        $mediable = factory(SampleMediable::class)->create();
        $media1 = factory(Media::class)->create(['id' => 1]);
        $media2 = factory(Media::class)->create(['id' => 2]);
        $media3 = factory(Media::class)->create(['id' => 3]);

        $mediable->attachMedia([2, 3, 1], 'foo');

        $this->assertEquals(
            [2 => 1, 3 => 2, 1 => 3],
            $mediable->getMedia('foo')->pluck('pivot.order', 'id')->toArray()
        );
    }

    public function test_it_can_unset_order()
    {
        $mediable = factory(SampleMediable::class)->make();

        $query = $mediable->media()->unordered()->toSql();

        $this->assertEquals(0, preg_match('/order by `order`/i', $query));
    }

    public function test_it_can_create_mediables_on_custom_table()
    {
        config()->set('mediable.mediables_table', 'prefixed_mediables');

        $media = factory(Media::class)->create();
        $mediable = factory(SampleMediable::class)->create();
        $mediable->attachMedia($media, 'foo');

        $this->assertEmpty(DB::table('mediables')->get());
        $this->assertCount(1, DB::table('prefixed_mediables')->get());
    }
}


text:
package play.learn.java.design.abstract_document;

import java.util.Map;

public class Part extends AbstractDocument implements HasType, HasModel, HasPrice {
	public Part(Map<String, Object> properties) {
		super(properties);
	}
}


text:
from conftest import rvo_output, rvo_err
from click.testing import CliRunner
from rvo import cli

def test_edit():
    options = ['edit', '569e5eed6815b47ce7bdb584']
    output = ['Document "just broke my leg" updated.']
    rvo_output(options,output)

def test_edit_shortid():
    options = ['edit', '2']
    output = ['Document "just broke my leg" updated.']
    rvo_output(options,output)

def test_edit_encrypt():
    runner = CliRunner()
    result = runner.invoke(cli.cli, ['edit', '-p', 'test123', '5'])
    assert not result.exception
    assert result.output.strip().endswith('Document "pynacl is just greatTEST" updated.')

def test_edit_encrypt_wrong_pw():
    runner = CliRunner()
    result = runner.invoke(cli.cli, ['edit', '-p', 'wrongpw', '5'])
    assert result.output.strip().endswith('Invalid Password')
    assert result.exception

def test_edit_encrypt_by_input():
    runner = CliRunner()
    result = runner.invoke(cli.cli, ['edit', '5'], input="test123\n")
    assert result.output.strip().endswith('Document "pynacl is just greatTEST" updated.')
    assert not result.exception

def test_edit_encrypt_by_input_wrong_pw():
    runner = CliRunner()
    result = runner.invoke(cli.cli, ['edit', '5'], input="wrongpw\n")
    assert result.output.strip().endswith('Invalid Password')
    assert result.exception


text:
package info.korzeniowski.rcontroller;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceFragmentCompat;
import android.widget.NumberPicker;

import info.korzeniowski.rcontroller.communicator.CarCommunicator;
import info.korzeniowski.rcontroller.communicator.CarCommunicatorFactory;
import info.korzeniowski.rcontroller.view.NumberPickerPreference;
import info.korzeniowski.rcontroller.view.NumberPickerPreferenceDialogFragment;

public class SettingsActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getSupportFragmentManager()
                .beginTransaction()
                .add(CarCommunicatorFactory.getCommunicator(), CarCommunicator.TAG)
                .replace(android.R.id.content, new SettingsFragment())
                .commit();
    }

    public static class SettingsFragment extends PreferenceFragmentCompat {
        private static final String DIALOG_FRAGMENT_TAG = "android.support.v7.preference.PreferenceFragment.DIALOG";

        private CarCommunicator carCommunicator;

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
        }

        @Override
        public void onPause() {
            super.onPause();
            if (carCommunicator != null) {
                carCommunicator.disconnect();
            }
        }

        @Override
        public void onCreatePreferences(Bundle bundle, String s) {
            addPreferencesFromResource(R.xml.settings);
        }

        @Override
        public void onDisplayPreferenceDialog(Preference preference) {
            if (preference instanceof NumberPickerPreference) {
                NumberPickerPreferenceDialogFragment fragment = NumberPickerPreferenceDialogFragment.newInstance(preference);

                fragment.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
                    @Override
                    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                        ControlData controlData = new ControlData(
                                new ControlData.Engine(ControlData.Direction.FORWARD, 0),
                                new ControlData.SteeringWheel(ControlData.Side.RIGHT, 0),
                                newVal);
                        carCommunicator.write(controlData);
                    }
                });

                fragment.setTargetFragment(SettingsFragment.this, 0);
                fragment.show(getFragmentManager(), DIALOG_FRAGMENT_TAG);

                carCommunicator = (CarCommunicator) getActivity().getSupportFragmentManager().findFragmentByTag(CarCommunicator.TAG);
                carCommunicator.connect();
            } else {
                super.onDisplayPreferenceDialog(preference);
            }
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycologia 90(2): 303 (1998)

#### Original name
Orbilia junci Kohlm., Baral & Volkm.-Kohlm.

### Remarks
null


text:
<?php

namespace Bakery\Exceptions;

class SystemIOExceptions extends \Bakery\Exceptions\Exception{

	public function __construct($message){

		$this->message = "$message\n";

		parent::__construct($message);

	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta content="IE=edge" http-equiv="X-UA-Compatible"></meta>

  <link href="../images/vl_blue.ico" type="image/x-icon" rel="icon"></link>
  <link href="../images/vl_blue.ico" type="image/x-icon" rel="shortcut icon"></link>

  <title>VLFeat - Tutorials</title>

  <link href="../vlfeat.css" type="text/css" rel="stylesheet"></link>
  <link href="../pygmentize.css" type="text/css" rel="stylesheet"></link>

        <gcse:searchbox-only autoCompleteMaxCompletions="5" autoCompleteMatchType="any" resultsUrl="http://www.vlfeat.org/search.html"></gcse:searchbox-only>

VLFeat.org

Home

About

License

Download

Using from MATLAB

Using from Octave

Using from the command line

Using from C

Xcode

Visual C++

g++

Compiling

Compiling on UNIX-like platforms

Compiling on Windows

Tutorials

Local feature frames

Covariant feature detectors

HOG features

SIFT detector and descriptor

Dense SIFT

LIOP local descriptor

MSER feature detector

Distance transform

Fisher Vector and VLAD

Gaussian Mixture Models

K-means clustering

Agglomerative Infromation Bottleneck

Quick shift superpixels

SLIC superpixels

Support Vector Machines (SVMs)

KD-trees and forests

Plotting AP and ROC curves

Miscellaneous utilities

Integer K-means

Hierarchical integer k-means

Applications

Documentation

MATLAB API

C API

Man pages

      Tutorials

Table of Contents

Visual features

Statistical methods

Obsolete tutorials

This section features a number of tutorials illustrating some of
the algorithms implemented in VLFeat, roughly divided
into visual features such
as SIFT and Fisher vectors and
statistical methods, such as
K-means, GMMs, KDTrees, and SVMs.

Visual features

Local features: the concept
  of frames (keypoints). An overview of the concept of feature
  frame used as geometric reference in feature detection.

Covariant detectors. An
  introduction to computing co-variant features like Harris-Affine.

Histogram of Oriented Gradients
  (HOG). Getting started with this ubiquitous representation for
  object recognition and detection.

Scale Invariant Feature Transform
  (SIFT). An introduction to SIFT keypoint and descriptor
  extraction and matching.

Dense SIFT (DSIFT) and
  PHOW. Extracting dense SIFT features for image
  classification.

Local Intensity Order Pattern
  (LIOP). Getting started with the LIOP descriptor as an
  alternative to SIFT in keypoint matching.

Maximally Stable Extremal Regions
  (MSER). Extracting MSERs from an image as an alternative
  covariant feature detector.

Image distance transform.
  Compute the image distance transform for fast part models and edge
  matching.

Fisher vector and VLAD
  encodings. Compute global image encodings by pooling local image
  features with Fisher vectors and VLAD.

Statistical methods

GMM. Learn Gaussian Mixture
  Models using the Expectation Maximization algorithm.

k-means. Cluster
    features with k-means.

Agglomerative Information Bottleneck
  (AIB). Cluster discrete data based on the mutual information
  between the data and class labels.

Quick shift.  An introduction
  which shows how to create superpixels using this quick mode seeking
  method.

SLIC. An introduction to SLIC
  superpixels.

Support Vector Machine (SVM).
  Learn a binary classifier and check its convergence by plotting
  various statistical information.

Forests of kd-trees.
  Approximate nearest neighbour queries in high dimensions using an
  optimized forest of kd-trees.

Plotting functions for rank
  evaluation.  Learn how to plot ROC, DET, and precision-recall
  curves.

MATLAB Utilities. A list of
  useful MATLAB functions bundled with VLFeat.

Obsolete tutorials

Integer optimized k-means
  (IKM). VLFeat integeger-otpimized k-means
  implementation (obsolete).

Hierarchical k-means
  (HIKM). Create a fast k-means tree for integer
  data (obsolete).

      © 2007-13 The authors of VLFeat


text:
// Copyright (c) "Neo4j"
// Neo4j Sweden AB [http://neo4j.com]
//
// This file is part of Neo4j.
//
// 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.Linq;
using System.Runtime.InteropServices;
using Neo4j.Driver.Internal;
using Xunit;

namespace Neo4j.Driver.Tests.TestUtil
{

    public class MonoFactAttribute : FactAttribute
    {

        public MonoFactAttribute()
        {
            var shouldSkip = Type.GetType("Mono.Runtime") == null;

            if (shouldSkip)
            {
                Skip = $"Test is supposed to be run only on mono runtimes";
            }
        }

    }

    public class MonoTheoryAttribute : TheoryAttribute
    {

        public MonoTheoryAttribute()
        {
            var shouldSkip = Type.GetType("Mono.Runtime") == null;

            if (shouldSkip)
            {
                Skip = $"Test is supposed to be run only on mono runtimes";
            }
        }

    }

    public class DotnetCoreFactAttribute : FactAttribute
    {

        public DotnetCoreFactAttribute()
        {
            var shouldSkip =
                RuntimeInformation.FrameworkDescription.StartsWith(".NET Core", StringComparison.OrdinalIgnoreCase) ==
                false;

            if (shouldSkip)
            {
                Skip = $"Test is supposed to be run only on .net core runtimes";
            }
        }

    }

    public class DotnetCoreTheoryAttribute : TheoryAttribute
    {

        public DotnetCoreTheoryAttribute()
        {
            var shouldSkip =
                RuntimeInformation.FrameworkDescription.StartsWith(".NET Core", StringComparison.OrdinalIgnoreCase) ==
                false;

            if (shouldSkip)
            {
                Skip = $"Test is supposed to be run only on .net core runtimes";
            }
        }

    }
}


text:
'use strict';
// example components, not including mandrill in this package.json
let mandrillLib = require('mandrill-api/mandrill');

exports = module.exports = function (config) {
  let mandrill = new mandrillLib.Mandrill(config.Mandrill.KEY);

  return mandrill;
};
exports['@singleton'] = true;
exports['@require'] = ['config'];


text:
from .data import sfr
from asmgenerator import Asm
from syntaxitems import DataField, Module, PredefinedFunction

def Constants():
	return {'sfr': SFRModule(), 'compilerservices': CompilerServicesModule()}

def CompilerServicesModule():
	functions = []

	functions.append(PredefinedFunction('compilerservices', 0, 'reti', (
			Asm('RETI'),
		), 0))

	functions.append(PredefinedFunction('compilerservices', 0, 'reset', (
			Asm('MOV direct,#data', 'SP', 'stack'),
			Asm('LJMP addr16', 'startcode'),
		), 0))

	return Module('compilerservices', 0, 'compilerservices', [], functions)

def SFRModule():
	datafields = []

	fakeLine = 0
	for sfrName in sfr.RegisterMapping:
		fakeLine += 1

		if sfr.RegisterMapping[sfrName][0] != 0:
			continue

		datafield = DataField('sfr', fakeLine, 'byte', sfrName)
		datafield.address = sfr.RegisterMapping[sfrName][1]
		datafield.location = 'internal'
		datafield.predefined = True
		datafields.append(datafield)

	return Module('sfr', 0, 'sfr', datafields, [])


text:
module Haste.Foreign (
    -- * Conversion to/from JSAny
    ToAny (..), FromAny (..), JSAny,
    Opaque, toOpaque, fromOpaque,
    nullValue, toObject, has, get, index,

    -- * Importing and exporting JavaScript functions
    FFI, JSFunc,
    ffi, constant, export
  ) where
import Haste.Prim.Foreign


text:
=========================
salt.modules.saltcloudmod
=========================

.. automodule:: salt.modules.saltcloudmod
    :members: