text:
interface(root).
interface(node).
interfaceAttribute(node, w).
interfaceAttribute(node, lineh).
interfaceAttribute(node, canvas).
interfaceAttribute(node, absy).
interfaceAttribute(node, rely).
interfaceAttribute(node, h).
interfaceAttribute(node, x).
interfaceAttribute(node, render).
class(top, root).
class(leaf, node).
class(hbox, node).
class(vbox, node).
class(wrapbox, node).
classChild(top, child, node).
classChild(hbox, childs, node).
classChild(vbox, childs, node).
classChild(wrapbox, childs, node).
classField(gensymattrib, gensymattrib) :- false.
classField(top, gensymattrib).
classField(leaf, gensymattrib).
classField(hbox, gensymattrib).
classField(vbox, gensymattrib).
classField(wrapbox, gensymattrib).
classField(wrapbox, width).
interfaceField(root, w).
interfaceField(root, display).
interfaceField(root, refname).
interfaceField(root, h).
interfaceField(node, display).
interfaceField(node, refname).
assignment(top, child, x, self, gensymattrib).
assignment(top, child, lineh, child, h).
assignment(top, child, canvas, child, w).
assignment(top, child, canvas, child, h).
assignment(top, child, absy, self, gensymattrib).
assignment(top, child, rely, self, gensymattrib).
assignment(leaf, self, render, self, w).
assignment(leaf, self, render, self, canvas).
assignment(leaf, self, render, self, absy).
assignment(leaf, self, render, self, h).
assignment(leaf, self, render, self, x).
assignment(leaf, self, w, self, gensymattrib).
assignment(leaf, self, h, self, gensymattrib).
assignment(hbox, self, render, self, w).
assignment(hbox, self, render, self, canvas).
assignment(hbox, self, render, self, absy).
assignment(hbox, self, render, self, h).
assignment(hbox, self, render, self, x).
assignment(hbox, self, numchilds_step, self, gensymattrib).
assignment(hbox, self, numchilds_last, self, numchilds_step).
assignment(hbox, self, numchilds, self, numchilds_step).
assignment(hbox, self, w_step, self, numchilds_last).
assignment(hbox, self, w_step, self, childs_w_step).
assignment(hbox, self, w_step, self, gensymattrib).
assignment(hbox, self, w_last, self, w_step).
assignment(hbox, self, w, self, w_step).
assignment(hbox, self, h_step, self, childs_h_step).
assignment(hbox, self, h_step, self, gensymattrib).
assignment(hbox, self, h_last, self, h_step).
assignment(hbox, self, h, self, h_step).
assignment(hbox, self, childs_rely_step, self, gensymattrib).
assignment(hbox, self, childs_rely_last, self, childs_rely_step).
assignment(hbox, childs, rely, self, childs_rely_step).
assignment(hbox, self, childs_absy_step, self, absy).
assignment(hbox, self, childs_absy_step, self, childs_rely_step).
assignment(hbox, self, childs_absy_step, self, gensymattrib).
assignment(hbox, self, childs_absy_last, self, childs_absy_step).
assignment(hbox, childs, absy, self, childs_absy_step).
assignment(hbox, self, childs_x_step, self, x).
assignment(hbox, self, childs_x_step, self, childs_w_step).
assignment(hbox, self, childs_x_step, self, gensymattrib).
assignment(hbox, self, childs_x_last, self, childs_x_step).
assignment(hbox, childs, x, self, childs_x_step).
assignment(hbox, self, childs_canvas_step, self, render).
assignment(hbox, self, childs_canvas_step, self, gensymattrib).
assignment(hbox, self, childs_canvas_last, self, childs_canvas_step).
assignment(hbox, childs, canvas, self, childs_canvas_step).
assignment(hbox, self, childs_lineh_step, self, gensymattrib).
assignment(hbox, self, childs_lineh_last, self, childs_lineh_step).
assignment(hbox, childs, lineh, self, childs_lineh_step).
assignment(hbox, self, childs_h_step, childs, h).
assignment(hbox, self, childs_w_step, childs, w).
assignment(vbox, self, render, self, w).
assignment(vbox, self, render, self, canvas).
assignment(vbox, self, render, self, absy).
assignment(vbox, self, render, self, h).
assignment(vbox, self, render, self, x).
assignment(vbox, self, numchilds_step, self, gensymattrib).
assignment(vbox, self, numchilds_last, self, numchilds_step).
assignment(vbox, self, numchilds, self, numchilds_step).
assignment(vbox, self, h_step, self, numchilds_last).
assignment(vbox, self, h_step, self, childs_h_step).
assignment(vbox, self, h_step, self, gensymattrib).
assignment(vbox, self, h_last, self, h_step).
assignment(vbox, self, h, self, h_step).
assignment(vbox, self, w_step, self, childs_w_step).
assignment(vbox, self, w_step, self, gensymattrib).
assignment(vbox, self, w_last, self, w_step).
assignment(vbox, self, w, self, w_step).
assignment(vbox, self, childs_x_step, self, x).
assignment(vbox, self, childs_x_step, self, gensymattrib).
assignment(vbox, self, childs_x_last, self, childs_x_step).
assignment(vbox, childs, x, self, childs_x_step).
assignment(vbox, self, childs_rely_step, self, childs_h_step).
assignment(vbox, self, childs_rely_step, self, gensymattrib).
assignment(vbox, self, childs_rely_last, self, childs_rely_step).
assignment(vbox, childs, rely, self, childs_rely_step).
assignment(vbox, self, childs_absy_step, self, absy).
assignment(vbox, self, childs_absy_step, self, childs_rely_step).
assignment(vbox, self, childs_absy_step, self, gensymattrib).
assignment(vbox, self, childs_absy_last, self, childs_absy_step).
assignment(vbox, childs, absy, self, childs_absy_step).
assignment(vbox, self, childs_canvas_step, self, render).
assignment(vbox, self, childs_canvas_step, self, gensymattrib).
assignment(vbox, self, childs_canvas_last, self, childs_canvas_step).
assignment(vbox, childs, canvas, self, childs_canvas_step).
assignment(vbox, self, childs_lineh_step, self, gensymattrib).
assignment(vbox, self, childs_lineh_last, self, childs_lineh_step).
assignment(vbox, childs, lineh, self, childs_lineh_step).
assignment(vbox, self, childs_h_step, childs, h).
assignment(vbox, self, childs_w_step, childs, w).
assignment(wrapbox, self, w, self, width).
assignment(wrapbox, self, render, self, w).
assignment(wrapbox, self, render, self, canvas).
assignment(wrapbox, self, render, self, absy).
assignment(wrapbox, self, render, self, h).
assignment(wrapbox, self, render, self, x).
assignment(wrapbox, self, childs_x_step, self, x).
assignment(wrapbox, self, childs_x_step, self, w).
assignment(wrapbox, self, childs_x_step, self, childs_w_step).
assignment(wrapbox, self, childs_x_step, self, childs_w_step).
assignment(wrapbox, self, childs_x_step, self, x).
assignment(wrapbox, self, childs_x_step, self, gensymattrib).
assignment(wrapbox, self, childs_x_last, self, childs_x_step).
assignment(wrapbox, childs, x, self, childs_x_step).
assignment(wrapbox, self, childs_lineh_step, self, childs_x_step).
assignment(wrapbox, self, childs_lineh_step, self, childs_h_step).
assignment(wrapbox, self, childs_lineh_step, self, x).
assignment(wrapbox, self, childs_lineh_step, self, gensymattrib).
assignment(wrapbox, self, childs_lineh_last, self, childs_lineh_step).
assignment(wrapbox, childs, lineh, self, childs_lineh_step).
assignment(wrapbox, self, childs_rely_step, self, childs_x_step).
assignment(wrapbox, self, childs_rely_step, self, childs_lineh_step).
assignment(wrapbox, self, childs_rely_step, self, x).
assignment(wrapbox, self, childs_rely_step, self, gensymattrib).
assignment(wrapbox, self, childs_rely_last, self, childs_rely_step).
assignment(wrapbox, childs, rely, self, childs_rely_step).
assignment(wrapbox, self, childs_absy_step, self, absy).
assignment(wrapbox, self, childs_absy_step, self, childs_rely_step).
assignment(wrapbox, self, childs_absy_step, self, gensymattrib).
assignment(wrapbox, self, childs_absy_last, self, childs_absy_step).
assignment(wrapbox, childs, absy, self, childs_absy_step).
assignment(wrapbox, self, childs_canvas_step, self, render).
assignment(wrapbox, self, childs_canvas_step, self, gensymattrib).
assignment(wrapbox, self, childs_canvas_last, self, childs_canvas_step).
assignment(wrapbox, childs, canvas, self, childs_canvas_step).
assignment(wrapbox, self, h_step, self, childs_lineh_step).
assignment(wrapbox, self, h_step, self, childs_rely_step).
assignment(wrapbox, self, h_step, self, gensymattrib).
assignment(wrapbox, self, h_last, self, h_step).
assignment(wrapbox, self, h, self, h_step).
assignment(wrapbox, self, childs_h_step, childs, h).
assignment(wrapbox, self, childs_w_step, childs, w).
classAttribute(hbox, numchilds).
classAttribute(hbox, childs_h_step).
classAttribute(hbox, childs_absy_step).
classAttribute(hbox, childs_canvas_step).
classAttribute(hbox, childs_w_step).
classAttribute(hbox, childs_x_step).
classAttribute(hbox, childs_rely_step).
classAttribute(hbox, childs_lineh_step).
classAttribute(hbox, childs_lineh_step).
classAttribute(hbox, childs_lineh_last).
classAttribute(hbox, childs_x_step).
classAttribute(hbox, childs_x_last).
classAttribute(hbox, childs_absy_step).
classAttribute(hbox, childs_absy_last).
classAttribute(hbox, childs_rely_step).
classAttribute(hbox, childs_rely_last).
classAttribute(hbox, h_step).
classAttribute(hbox, h_last).
classAttribute(hbox, childs_canvas_step).
classAttribute(hbox, childs_canvas_last).
classAttribute(hbox, numchilds_step).
classAttribute(hbox, numchilds_last).
classAttribute(hbox, w_step).
classAttribute(hbox, w_last).
classAttribute(vbox, numchilds).
classAttribute(vbox, childs_h_step).
classAttribute(vbox, childs_absy_step).
classAttribute(vbox, childs_canvas_step).
classAttribute(vbox, childs_w_step).
classAttribute(vbox, childs_x_step).
classAttribute(vbox, childs_rely_step).
classAttribute(vbox, childs_lineh_step).
classAttribute(vbox, childs_lineh_step).
classAttribute(vbox, childs_lineh_last).
classAttribute(vbox, childs_absy_step).
classAttribute(vbox, childs_absy_last).
classAttribute(vbox, childs_rely_step).
classAttribute(vbox, childs_rely_last).
classAttribute(vbox, childs_x_step).
classAttribute(vbox, childs_x_last).
classAttribute(vbox, h_step).
classAttribute(vbox, h_last).
classAttribute(vbox, childs_canvas_step).
classAttribute(vbox, childs_canvas_last).
classAttribute(vbox, numchilds_step).
classAttribute(vbox, numchilds_last).
classAttribute(vbox, w_step).
classAttribute(vbox, w_last).
classAttribute(wrapbox, childs_h_step).
classAttribute(wrapbox, childs_absy_step).
classAttribute(wrapbox, childs_canvas_step).
classAttribute(wrapbox, childs_w_step).
classAttribute(wrapbox, childs_x_step).
classAttribute(wrapbox, childs_lineh_step).
classAttribute(wrapbox, childs_rely_step).
classAttribute(wrapbox, childs_absy_step).
classAttribute(wrapbox, childs_absy_last).
classAttribute(wrapbox, childs_rely_step).
classAttribute(wrapbox, childs_rely_last).
classAttribute(wrapbox, childs_lineh_step).
classAttribute(wrapbox, childs_lineh_last).
classAttribute(wrapbox, childs_x_step).
classAttribute(wrapbox, childs_x_last).
classAttribute(wrapbox, h_step).
classAttribute(wrapbox, h_last).
classAttribute(wrapbox, childs_canvas_step).
classAttribute(wrapbox, childs_canvas_last).


text:
using System;

namespace SpecEasy
{
    public class DuplicateDescriptionException : InvalidOperationException
    {
        public override string StackTrace
        {
            get
            {
                return stackTrace;
            }
        }

        private readonly string stackTrace;

        internal DuplicateDescriptionException(string typeOfDuplicate, string description, string stackTrace)
            : base(string.Format("Failed to generate test cases; {0} description '{1}' has already been used", typeOfDuplicate, description))
        {
            this.stackTrace = stackTrace;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
/* eslint-disable react/jsx-pascal-case */
import {SearchIcon} from '@sanity/icons'
import {Flex, KBD, TextInput} from '@sanity/ui'
import React, {forwardRef, KeyboardEvent as ReactKeyboardEvent, Ref, useCallback} from 'react'
import styled from 'styled-components'
import {GLOBAL_SEARCH_KEY, GLOBAL_SEARCH_KEY_MODIFIER} from '../constants'
import {useSearchState} from '../contexts/search'

const KeyboardShortcutFlex = styled(Flex)`
  position: absolute;
  right: 0;
  top: 0;

  & > :first-child {
    margin-right: 1px;
  }
`

const PlaceholderSearchInputFlex = styled(Flex)`
  min-width: 253px;
  max-width: 350px;
  position: relative;
`

const PlaceholderTextInput = styled(TextInput)`
  padding-right: 60px;
`

export const PlaceholderSearchInput = forwardRef(function DummyInput(
  {onOpen}: {onOpen: () => void},
  ref: Ref<HTMLInputElement>
) {
  const {
    dispatch,
    state: {terms},
  } = useSearchState()

  const handleChange = useCallback(
    (event: ReactKeyboardEvent<HTMLInputElement>) => {
      dispatch({type: 'TERMS_QUERY_SET', query: event.currentTarget.value})
      onOpen()
    },
    [dispatch, onOpen]
  )

  const handleKeyDown = useCallback(
    (event: ReactKeyboardEvent<HTMLInputElement>) => {
      if (event.key === 'Enter') {
        onOpen()
      }
    },
    [onOpen]
  )

  return (
    <PlaceholderSearchInputFlex align="center">
      <PlaceholderTextInput
        radius={2}
        aria-autocomplete="list"
        aria-expanded="false"
        autoComplete="off"
        icon={SearchIcon}
        data-testid="studio-search"
        onChange={handleChange}
        onClick={onOpen}
        onKeyDown={handleKeyDown}
        placeholder="Search"
        ref={ref}
        role="combobox"
        value={terms.query}
      />
      <KeyboardShortcutFlex align="center" height="fill" marginRight={2}>
        {GLOBAL_SEARCH_KEY_MODIFIER.toUpperCase()}
        {GLOBAL_SEARCH_KEY.toUpperCase()}
      </KeyboardShortcutFlex>
    </PlaceholderSearchInputFlex>
  )
})


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>EARS: AssociationFramework.hpp File Reference</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Classes

Files

AssociationFramework.hpp File Reference
Association finding framework. More...

Go to the source code of this file.

Namespaces

namespace  	ears

Classes

class  	ears::AssociationFramework

 	Association finding framework.  More...

Detailed Description

Association finding framework.

Date:

2010-01-18

Version:

1.05

Definition in file AssociationFramework.hpp.

<address style="text-align: right;">Generated on Tue May 11 17:34:38 2010 for EARS by

 1.5.6 </address>


text:
use std::ffi::CStr;
use std::fmt;
use std::marker::PhantomData;
use std::os::raw::{c_char, c_int, c_uchar, c_void};
use std::ptr;
use std::slice;

use itertools::Itertools;

use crate::error::{Error, Result};
use crate::panic;

/// The result of a successful NAPTR lookup.
#[derive(Debug)]
pub struct NAPTRResults {
    naptr_reply: *mut c_ares_sys::ares_naptr_reply,
    phantom: PhantomData<c_ares_sys::ares_naptr_reply>,
}

/// The contents of a single NAPTR record.
#[derive(Clone, Copy)]
pub struct NAPTRResult<'a> {
    naptr_reply: &'a c_ares_sys::ares_naptr_reply,
}

impl NAPTRResults {
    /// Obtain a `NAPTRResults` from the response to a NAPTR lookup.
    pub fn parse_from(data: &[u8]) -> Result<NAPTRResults> {
        let mut naptr_reply: *mut c_ares_sys::ares_naptr_reply = ptr::null_mut();
        let parse_status = unsafe {
            c_ares_sys::ares_parse_naptr_reply(data.as_ptr(), data.len() as c_int, &mut naptr_reply)
        };
        if parse_status == c_ares_sys::ARES_SUCCESS {
            let naptr_result = NAPTRResults::new(naptr_reply);
            Ok(naptr_result)
        } else {
            Err(Error::from(parse_status))
        }
    }

    fn new(reply: *mut c_ares_sys::ares_naptr_reply) -> Self {
        NAPTRResults {
            naptr_reply: reply,
            phantom: PhantomData,
        }
    }

    /// Returns an iterator over the `NAPTRResult` values in this `NAPTRResults`.
    pub fn iter(&self) -> NAPTRResultsIter {
        NAPTRResultsIter {
            next: unsafe { self.naptr_reply.as_ref() },
        }
    }
}

impl fmt::Display for NAPTRResults {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        let results = self.iter().format("}, {");
        write!(fmt, "[{{{}}}]", results)
    }
}

/// Iterator of `NAPTRResult`s.
#[derive(Clone, Copy)]
pub struct NAPTRResultsIter<'a> {
    next: Option<&'a c_ares_sys::ares_naptr_reply>,
}

impl<'a> Iterator for NAPTRResultsIter<'a> {
    type Item = NAPTRResult<'a>;
    fn next(&mut self) -> Option<Self::Item> {
        let opt_reply = self.next;
        self.next = opt_reply.and_then(|reply| unsafe { reply.next.as_ref() });
        opt_reply.map(|reply| NAPTRResult { naptr_reply: reply })
    }
}

impl<'a> IntoIterator for &'a NAPTRResults {
    type Item = NAPTRResult<'a>;
    type IntoIter = NAPTRResultsIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl Drop for NAPTRResults {
    fn drop(&mut self) {
        unsafe { c_ares_sys::ares_free_data(self.naptr_reply as *mut c_void) }
    }
}

unsafe impl Send for NAPTRResults {}
unsafe impl Sync for NAPTRResults {}
unsafe impl<'a> Send for NAPTRResult<'a> {}
unsafe impl<'a> Sync for NAPTRResult<'a> {}
unsafe impl<'a> Send for NAPTRResultsIter<'a> {}
unsafe impl<'a> Sync for NAPTRResultsIter<'a> {}

impl<'a> NAPTRResult<'a> {
    /// Returns the flags in this `NAPTRResult`.
    ///
    /// In practice this is very likely to be a valid UTF-8 string, but the underlying `c-ares`
    /// library does not guarantee this - so we leave it to users to decide whether they prefer a
    /// fallible conversion, a lossy conversion, or something else altogether.
    pub fn flags(self) -> &'a CStr {
        unsafe { CStr::from_ptr(self.naptr_reply.flags as *const c_char) }
    }

    /// Returns the service name in this `NAPTRResult`.
    ///
    /// In practice this is very likely to be a valid UTF-8 string, but the underlying `c-ares`
    /// library does not guarantee this - so we leave it to users to decide whether they prefer a
    /// fallible conversion, a lossy conversion, or something else altogether.
    pub fn service_name(self) -> &'a CStr {
        unsafe { CStr::from_ptr(self.naptr_reply.service as *const c_char) }
    }

    /// Returns the regular expression in this `NAPTRResult`.
    ///
    /// In practice this is very likely to be a valid UTF-8 string, but the underlying `c-ares`
    /// library does not guarantee this - so we leave it to users to decide whether they prefer a
    /// fallible conversion, a lossy conversion, or something else altogether.
    pub fn reg_exp(self) -> &'a CStr {
        unsafe { CStr::from_ptr(self.naptr_reply.regexp as *const c_char) }
    }

    /// Returns the replacement pattern in this `NAPTRResult`.
    ///
    /// In practice this is very likely to be a valid UTF-8 string, but the underlying `c-ares`
    /// library does not guarantee this - so we leave it to users to decide whether they prefer a
    /// fallible conversion, a lossy conversion, or something else altogether.
    pub fn replacement_pattern(self) -> &'a CStr {
        unsafe { CStr::from_ptr(self.naptr_reply.replacement) }
    }

    /// Returns the order value in this `NAPTRResult`.
    pub fn order(self) -> u16 {
        self.naptr_reply.order
    }

    /// Returns the preference value in this `NAPTRResult`.
    pub fn preference(self) -> u16 {
        self.naptr_reply.preference
    }
}

impl<'a> fmt::Display for NAPTRResult<'a> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(
            fmt,
            "Flags: {}, ",
            self.flags().to_str().unwrap_or("<not utf8>")
        )?;
        write!(
            fmt,
            "Service name: {}, ",
            self.service_name().to_str().unwrap_or("<not utf8>")
        )?;
        write!(
            fmt,
            "Regular expression: {}, ",
            self.reg_exp().to_str().unwrap_or("<not utf8>")
        )?;
        write!(
            fmt,
            "Replacement pattern: {}, ",
            self.replacement_pattern().to_str().unwrap_or("<not utf8>")
        )?;
        write!(fmt, "Order: {}, ", self.order())?;
        write!(fmt, "Preference: {}", self.preference())
    }
}

pub(crate) unsafe extern "C" fn query_naptr_callback<F>(
    arg: *mut c_void,
    status: c_int,
    _timeouts: c_int,
    abuf: *mut c_uchar,
    alen: c_int,
) where
    F: FnOnce(Result<NAPTRResults>) + Send + 'static,
{
    ares_callback!(arg as *mut F, status, abuf, alen, NAPTRResults::parse_from);
}


text:
@implementation UIFont (LuckiestGuy)

+ (instancetype)luckiestGuyRegularFontOfSize:(CGFloat)size {
  static dispatch_once_t onceToken;
  [GFIFontLoader loadFontFile:@"LuckiestGuy"
                   fromBundle:@"LuckiestGuy"
                    onceToken:&onceToken];
  return [self fontWithName:@"LuckiestGuy-Regular" size:size];
}

@end


text:
FROM concourse/buildroot:base

# Put the binary into the container
# This is need with go only
COPY resource-template /

# Add tree - Not needed but illustrates how to add a command to build
COPY bin/tree /bin

# REQUIRED BY CONCROUSE RESOURCE
ADD /assets-go/check /opt/resource/check
#ADD /assets-bash/check /opt/resource/check
ADD /assets-go/in /opt/resource/in
#ADD /assets-bash/in /opt/resource/in
ADD /assets-go/out /opt/resource/out
#ADD /assets-bash/out /opt/resource/out

RUN chmod +x /opt/resource/*


text:
package org.bpmscript.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * customer.address[0].xxx = "20b" = { customer: { address[0]: { xxx: "20b" } address[1]: {  } } }
 * customer.address[0].yyy = "20b" = { customer: { address: [ { xxx: "20b", yyy: "20b"} ] } }
 * customer.address[1].houseNumber = "20b" { customer: { address: [ { xxx: "20b", yyy: "20b" } {
 * houseNumber: "20b" } ] } } customer.address.billing.houseNumber = "20b" customer.interest[]=
 * "hockey","fighting" customer.gender = "Male" customer.dob = "14/5/2008" customer.pin = "1234"
 * customer[0].address[0].xxx = "20b" customer[0][1].blah
 */
public class WebParamConverter {

    private static final Pattern p = Pattern.compile("^(.+?)\\[(\\d+)\\]$");

    private String getValue(String name, Map<String, String[]> params) {
        String[] values = params.get(name);
        if (values == null || values.length == 0) {
            return null;
        } else {
            return values[0];
        }
    }

    /**
     *
     * @param params
     * @return
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> convert(Map<String, String[]> params) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        Set<String> keySet = params.keySet();
        for (String name : keySet) {
            String[] names = name.split("\\.");
            Map current = result;
            for (int i = 0; i < names.length; i++) {
                String subname = names[i];
                if (i == names.length - 1) {
                    lastElement(params, current, name, subname);
                    break;
                } else {
                    Map next = (Map) current.get(subname);
                    if(next == null) {
                        next = new HashMap();
                        current.put(subname, next);
                    }
                    current = next;
                }
            }
        }
        convertArrays(result);
        return result;
    }

    @SuppressWarnings("unchecked")
    private void convertArrays(Map<String, Object> root) throws Exception {
        Set<String> keySet = new HashSet<String>(root.keySet());
        for (String key : keySet) {
            Object value = root.get(key);
            if(value instanceof Map) {
                convertArrays((Map<String, Object>) value);
                Matcher matcher = p.matcher(key);
                if(matcher.find()) {
                    String subname = matcher.group(1);
                    Integer index = Integer.parseInt(matcher.group(2));
                    Object object = root.get(subname);
                    if(object == null) {
                        object = new ArrayList();
                        root.put(subname, object);
                    }
                    if(object instanceof List) {
                        List list = (List) object;
                        if(list.size() < index + 1) {
                            for(int i = list.size(); i < index + 1; i++) {
                                list.add(null);
                            }
                        }
                        list.set(index, root.get(key));
                    } else {
                        throw new Exception(subname + " is already bound");
                    }
                    root.remove(key);
                }
            }
        }
    }

    /**
     * @param current
     * @param subname
     */
    @SuppressWarnings("unchecked")
    private void lastElement(Map<String, String[]> params, Map map, String name, String subname) {
        // if it's an array
        if (subname.endsWith("[]")) {
            String arraySubName = subname.substring(0, subname.length() - 2);
            map.put(arraySubName, params.get(name));
        } else
        // if it's a single value
        {
            map.put(subname, getValue(name, params));
        }
    }

}


text:
 /**
 *
 * @author Thomas Wuerthinger
 */

function colorize(property, regexp, color) {
    var f = new ColorFilter("");
    f.addRule(new ColorFilter.ColorRule(new MatcherSelector(new Properties.RegexpPropertyMatcher(property, regexp)), color));
    f.apply(graph);
}

function remove(property, regexp) {
    var f = new RemoveFilter("");
    f.addRule(new RemoveFilter.RemoveRule(new MatcherSelector(new Properties.RegexpPropertyMatcher(property, regexp)), false, false));
    f.apply(graph);
}

function split(property, regexp) {
    var f = new SplitFilter("", new MatcherSelector(new Properties.RegexpPropertyMatcher(property, regexp)));
    f.apply(graph);
}

function removeInputs(property, regexp, from, to) {
    var f = new RemoveInputsFilter("");
    if(from == undefined && to == undefined) {
        f.addRule(new RemoveInputsFilter.RemoveInputsRule(new MatcherSelector(new Properties.RegexpPropertyMatcher(property, regexp))));
    } else if(to == undefined) {
        f.addRule(new RemoveInputsFilter.RemoveInputsRule(new MatcherSelector(new Properties.RegexpPropertyMatcher(property, regexp)), from));
    } else {
        f.addRule(new RemoveInputsFilter.RemoveInputsRule(new MatcherSelector(new Properties.RegexpPropertyMatcher(property, regexp)), from, to));
    }
    f.apply(graph);
}

var black = Color.black;
var blue = Color.blue;
var cyan = Color.cyan;
var darkGray = Color.darkGray;
var gray = Color.gray;
var green = Color.green;
var lightGray = Color.lightGray;
var magenta = Color.magenta;
var orange = Color.orange;
var pink = Color.pink
var red = Color.red;
var yellow = Color.yellow;
var white = Color.white;


text:
<?php

class Pages_model extends CI_Model {

    public $name;
    public $details;
    private $table = "pages";

    public function __construct() {
        parent::__construct();
    }

    public function count($keyword = null) { /* function  นับจำนวน record ข้อมูล */
        $this->db->from($this->table);
        $this->db->like('name', $keyword);
        return $this->db->count_all_results();
    }

    public function all($keyword = null, $config = null) { /* function query ข้อมูล */
        $this->db->select('*');
        $this->db->from($this->table);
        if ($config != NULL) {
            $this->db->where("visible", $config);
        }
        $this->db->like('name', $keyword);
        return $this->db->get()->result();
    }

    public function entry_page($id) {
        $this->name = $this->input->post('name');
        $this->details = $this->input->post('details');
        if ($id == NULL) {
            $this->db->insert($this->table, $this);
        } else {
            $this->db->update($this->table, $this, array('id' => $id));
        }
    }

    public function save($id = null) {
        $post['name'] = $this->input->post("name");
        $post['details'] = $this->input->post('details');
        $post['visible'] = $this->input->post('visible');

        if ($id) {
            $this->db->where("id", $id);
            $this->db->update($this->table, $post);
            return $this->db->affected_rows();
        } else {
            $this->db->insert($this->table, $post);
            return $this->db->insert_id();
        }
    }

    public function read_page($id) {
        $this->db->where('id', $id);
        $query = $this->db->get($this->table);
        if ($query->num_rows() > 0) {
            return $query->row();
        }
        return FALSE;
    }

    public function remove_page($id) {
        $this->db->delete($this->table, array('id' => $id));
    }

    public function find($id) {
        $this->db->where("id", $id);
        $query = $this->db->get($this->table);
        return $query->num_rows() ? $query->row() : null;
    }

}


text:
#ifndef _SHADER2DNODE_H_
#define _SHADER2DNODE_H_

#include "cocos2d.h"
#include "ShaderNode.h"

USING_NS_CC;

class Shader2dNode : public ShaderNode
{
protected:
	Vec2 _center;
	Vec2 _resolution;

public:
	// Factory
	static Shader2dNode* create(const std::string &vert, const std::string &frag);

	// Override
	virtual void update(float dt);

	virtual void setPosition(const Vec2 &newPosition);

protected:
	Shader2dNode();
	virtual ~Shader2dNode();

	// Override
	virtual bool init(const std::string &vert, const std::string &frag);
	// Override
	virtual void onDraw(const Mat4 &transform, uint32_t flags);
};

#endif


text:
module ExampleLoaderHelper

  CLASS_EXAMPLES = {
  "2DShapes.ump" => ["Shape2D", "EllipticalShape", "EllipticalShape_generalization"],
  "AccessControl.ump" => ["FunctionalArea", "User", "umpleAssociation_5"],
  "AccessControl2.ump" => ["User", "umpleAssociation_11", "Door"],
  "Accidents.ump" => ["Accident", "umpleAssociation_2", "SeriousnessLevel"],
  "Accommodations.ump" => ["UnitBooking", "umpleAssociation_7", "ViewUnitStatus"],
  "AfghanRainDesign.ump" => ["SurveyObservation", "umpleAssociation_9", "Farm"],
  "AirlineExample.ump" => ["PersonRole", "PassengerRole_generalization", "umpleAssociation_7"],
  "BankingSystemA.ump" => ["Employee", "Client_generalization", "umpleAssociation_8"],
  "BankingSystemB.ump" => ["Bank", "BankAccount_generalization", "umpleAssociation_5"],
  "CanalSystem.ump" => ["SegEnd", "Bend_generalization", "umpleAssociation_8"],
  "Decisions.ump" => ["Person", "Comment_generalization", "umpleAssociation_21"],
  "OhHellWhist.ump" => ["Card", "Trick_generalization", "umpleAssociation_8"],
  "Claim.ump" => ["Claim", "Clamor", "umpleAssociation_0"],
  "CommunityAssociation.ump" => ["CommunityResidence", "Rink_generalization", "umpleAssociation_5"],
  "Compositions.ump" => ["Composition", "", ""],
  "CoOpSystem.ump" => ["Job", "Resume", "umpleAssociation_11"],
  "DMMOverview.ump" => ["SourceObject", "SourceRelationship_generalization", "umpleAssociation_6"],
  "DMMSourceObjectHierarchy.ump" => ["Contains", "SourceUnit_generalization", "umpleAssociation_7"],
  "DMMRelationshipHierarchy.ump" => ["SourceRelationship", "Uses_generalization", "TakesAddressOf"],
  "DMMExtensionCTF.ump" => ["Trace", "RoutineCallTrace_generalization", "umpleAssociation_10"],
  "ElectionSystem.ump" => ["Voter", "Candidate", "umpleAssociation_13"],
  "ElevatorSystemA.ump" => ["Bank", "Floor", "umpleAssociation_5"],
  "ElevatorSystemB.ump" => ["Button", "ConsoleCallButton_generalization", "umpleAssociation_8"],
  "GenealogyA.ump" => ["Person", "Union", "umpleAssociation_1"],
  "GenealogyB.ump" => ["Person", "Union", "umpleAssociation_2"],
  "GenealogyC.ump" => ["Person", "Adoption", "umpleAssociation_3"],
  "GeographicalInformationSystem.ump" => ["FeatureType", "RegionFeatureType_generalization", "umpleAssociation_5"],
  "Hospital.ump" => ["Shift", "Janitor_generalization", "umpleAssociation_5"],
  "Hotel.ump" => ["HotelCompany", "MeetingRoom_generalization", "umpleAssociation_6"],
  "Insurance.ump" => ["Transaction", "Renewal_generalization", "umpleAssociation_4"],
  "InventoryManagement.ump" => ["ProductSource", "ReceivedDelivery", "umpleAssociation_7"],
  "Library.ump" => ["Author", "IssueOfPeriodical_generalization", "umpleAssociation_5"],
  "MailOrderSystemClientOrder.ump" => ["Product", "Client", "umpleAssociation_7"],
  "ManufacturingPlantController.ump" => ["ProductRun", "Robot", "umpleAssociation_15"],
  "Pizza.ump" => ["Driver", "DrinkOrder_generalization", "umpleAssociation_5"],
  "PoliceSystem.ump" => ["CrimeOccurrence", "Victim_generalization", "umpleAssociation_10"],
  "PoliticalEntities.ump" => ["Territory", "Country_generalization", "umpleAssociation_2"],
  "realestate.ump" => ["Address", "Agent", "umpleAssociation_7"],
  "RoutesAndLocations.ump" => ["RoadSegment", "Intersection_generalization", "umpleAssociation_11"],
  "School.ump" => ["Person", "School", "umpleAssociation_0"],
  "TelephoneSystem.ump" => ["VoiceMailBox", "Telephone", "umpleAssociation_7"],
  "UniversitySystem.ump" => ["Topic", "MutualExclusionReason", "umpleAssociation_5"],
  "VendingMachineClassDiagram.ump" => ["ProductTransaction", "CoinType", "umpleAssociation_7"],
  "WarehouseSystem.ump" => ["MovementLocation", "SlotSet_generalization", "umpleAssociation_12"]
}

STATE_EXAMPLES = {
  "AgentsCommunication.ump" => ["clust2", "node12", "edge10"],
  "ApplicationProcessing.ump" => ["edge24", "node11"],
  "Booking.ump" => ["node6", "edge7"],
  "CanalLockStateMachine.ump" => ["node10", "edge17"],
  "CarTransmission.ump" => ["clust1", "edge16", "node9"],
  "ComplexStateMachine.ump" => ["clust3", "edge17", "node10"],
  "CourseSectionFlat.ump" => ["edge12", "node6"],
  "CourseSectionNested.ump" => ["clust1", "edge14", "node9"],
  "DigitalWatchNested.ump" => ["clust7", "edge47", "node25"],
  "DigitalWatchFlat.ump" => ["node20", "edge53"],
  "Elevator_State_Machine.ump" => ["clust4", "node14", "edge23"],
  "GarageDoor.ump" => ["node6", "edge8"],
  "LibraryLoanStateMachine.ump" => ["node7", "edge11"],
  "Lights.ump" => ["clust6", "edge29", "node21"],
  "MicrowaveOven2.ump" => ["edge13", "node7"],
  "Ovens.ump" => ["clust6", "edge19", "node20"],
  "ParliamentBill.ump" => ["clust2", "edge17", "node14"],
  "Phone.ump" => ["edge18", "node7"],
  "Runway.ump" => ["clust5", "edge18", "node12"],
  "SecurityLight.ump" => ["clust1", "edge8", "node6"],
  "SpecificFlight.ump" => ["clust1", "node11", "edge14"],
  "SpecificFlightFlat.ump" => ["edge18", "node10"],
  "TcpIpSimulation.ump" => ["node12", "edge18"],
  "TelephoneSystem2.ump" => ["clust3", "edge22", "node10"],
  "TicTacToe.ump" => ["edge7", "node5"],
  "TollBooth.ump" => ["clust2", "edge19", "node11"],
  "TrafficLightsA.ump" => ["edge10", "node6"],
  "TrafficLightsB.ump" => ["clust6", "node30", "edge24"],
  "HomeHeater.ump" => ["edge23", "node37"]
}

COMPOSITE_STRUCTURES_EXAMPLES = {
  "OBDCarSystem.ump" => ["svgCanvas"],
  "PingPong.ump" => ["svgCanvas"]
}

  def switch_to_class_examples
    select("Class Diagrams", :from => "inputExampleType")
  end

  def switch_to_state_examples
    select("State Machines", :from => "inputExampleType")
  end

  def switch_to_compound_structure_examples
    select("Composite Structure", :from => "inputExampleType")
  end

  def check_class_example(example_name)
    select_option_by_value("#inputExampleType", "cdModels")
    select_option_by_value("#inputExample", example_name)

    wait_for_loading

    #include is used here because the website adds the model delimiter to the
    #end of the code, which is not present in the source file for the diagram
    expect(evaluate_script("Page.getUmpleCode()"))
      .to include(get_example_contents(example_name))

    CLASS_EXAMPLES[example_name].each do |element|
      expect(find(:css, "#umpleCanvas")).to have_selector("##{element}")
    end
  end

  def check_state_example(example_name)
    select_option_by_value("#inputExampleType", "smModels")
    select_option_by_value("#inputExample2", example_name)

    wait_for_loading

    #include is used here because the website adds the model delimiter to the
    #end of the code, which is not present in the source file for the diagram
    expect(evaluate_script("Page.getUmpleCode()"))
      .to include(get_example_contents(example_name))

    STATE_EXAMPLES[example_name].each do |element|
      expect(find(:css, "#umpleCanvas")).to have_selector("##{element}")
    end
  end

  def check_comp_structure_example(example_name)
    select_option_by_value("#inputExampleType", "structureModels")
    select_option_by_value("#inputExample3", example_name)

    wait_for_loading
    expect(evaluate_script("Page.getUmpleCode()"))
      .to include(get_example_contents(example_name))

    COMPOSITE_STRUCTURES_EXAMPLES[example_name].each do |element|
      expect(find(:css, "#umpleCanvas")).to have_selector("##{element}")
    end
  end

  def get_example_contents(filename)
    return get_file_contents(filename, TestUtils::EXAMPLE_DIRECTORY)
  end
end


text:
require File.expand_path('../../../test_helper', __FILE__)

class Redmine::ApiTest::MembershipsTest < Redmine::ApiTest::Base
  fixtures :projects, :users, :roles, :members, :member_roles

  test "GET /projects/:project_id/memberships.xml should return memberships" do
    get '/projects/1/memberships.xml', {}, credentials('jsmith')

    assert_response :success
    assert_equal 'application/xml', @response.content_type
    assert_select 'memberships[type=array] membership id', :text => '2' do
      assert_select '~ user[id="3"][name="Dave Lopper"]'
      assert_select '~ roles role[id="2"][name=Developer]'
    end
  end

  test "GET /projects/:project_id/memberships.json should return memberships" do
    get '/projects/1/memberships.json', {}, credentials('jsmith')

    assert_response :success
    assert_equal 'application/json', @response.content_type
    json = ActiveSupport::JSON.decode(response.body)
    assert_equal({
      "memberships" =>
        [{"id"=>1,
          "project" => {"name"=>"eCookbook", "id"=>1},
          "roles" => [{"name"=>"Manager", "id"=>1}],
          "user" => {"name"=>"John Smith", "id"=>2}},
         {"id"=>2,
          "project" => {"name"=>"eCookbook", "id"=>1},
          "roles" => [{"name"=>"Developer", "id"=>2}],
          "user" => {"name"=>"Dave Lopper", "id"=>3}}],
     "limit" => 25,
     "total_count" => 2,
     "offset" => 0},
     json)
  end

  test "GET /projects/:project_id/memberships.xml should succeed for closed project" do
    project = Project.find(1)
    project.close
    assert !project.reload.active?
    get '/projects/1/memberships.json', {}, credentials('jsmith')
    assert_response :success
  end

  test "POST /projects/:project_id/memberships.xml should create the membership" do
    assert_difference 'Member.count' do
      post '/projects/1/memberships.xml', {:membership => {:user_id => 7, :role_ids => [2,3]}}, credentials('jsmith')

      assert_response :created
    end
  end

  test "POST /projects/:project_id/memberships.xml should create the group membership" do
    group = Group.find(11)

    assert_difference 'Member.count', 1 + group.users.count do
      post '/projects/1/memberships.xml', {:membership => {:user_id => 11, :role_ids => [2,3]}}, credentials('jsmith')

      assert_response :created
    end
  end

  test "POST /projects/:project_id/memberships.xml with invalid parameters should return errors" do
    assert_no_difference 'Member.count' do
      post '/projects/1/memberships.xml', {:membership => {:role_ids => [2,3]}}, credentials('jsmith')

      assert_response :unprocessable_entity
      assert_equal 'application/xml', @response.content_type
      assert_select 'errors error', :text => "Principal cannot be blank"
    end
  end

  test "GET /memberships/:id.xml should return the membership" do
    get '/memberships/2.xml', {}, credentials('jsmith')

    assert_response :success
    assert_equal 'application/xml', @response.content_type
    assert_select 'membership id', :text => '2' do
      assert_select '~ user[id="3"][name="Dave Lopper"]'
      assert_select '~ roles role[id="2"][name=Developer]'
    end
  end

  test "GET /memberships/:id.json should return the membership" do
    get '/memberships/2.json', {}, credentials('jsmith')

    assert_response :success
    assert_equal 'application/json', @response.content_type
    json = ActiveSupport::JSON.decode(response.body)
    assert_equal(
      {"membership" => {
        "id" => 2,
        "project" => {"name"=>"eCookbook", "id"=>1},
        "roles" => [{"name"=>"Developer", "id"=>2}],
        "user" => {"name"=>"Dave Lopper", "id"=>3}}
      },
      json)
  end

  test "PUT /memberships/:id.xml should update the membership" do
    assert_not_equal [1,2], Member.find(2).role_ids.sort
    assert_no_difference 'Member.count' do
      put '/memberships/2.xml', {:membership => {:user_id => 3, :role_ids => [1,2]}}, credentials('jsmith')

      assert_response :ok
      assert_equal '', @response.body
    end
    member = Member.find(2)
    assert_equal [1,2], member.role_ids.sort
  end

  test "PUT /memberships/:id.xml with invalid parameters should return errors" do
    put '/memberships/2.xml', {:membership => {:user_id => 3, :role_ids => [99]}}, credentials('jsmith')

    assert_response :unprocessable_entity
    assert_equal 'application/xml', @response.content_type
    assert_select 'errors error', :text => "Role cannot be empty"
  end

  test "DELETE /memberships/:id.xml should destroy the membership" do
    assert_difference 'Member.count', -1 do
      delete '/memberships/2.xml', {}, credentials('jsmith')

      assert_response :ok
      assert_equal '', @response.body
    end
    assert_nil Member.find_by_id(2)
  end

  test "DELETE /memberships/:id.xml should respond with 422 on failure" do
    assert_no_difference 'Member.count' do
      # A membership with an inherited role cannot be deleted
      Member.find(2).member_roles.first.update_attribute :inherited_from, 99
      delete '/memberships/2.xml', {}, credentials('jsmith')

      assert_response :unprocessable_entity
    end
  end
end


text:
@implementation NUINavigationBarRenderer

+ (void)render:(UINavigationBar*)bar withClass:(NSString*)className
{
    [NUISettings checkUnsupportedPropertiesForObject:bar withClass:className];

    if ([bar respondsToSelector:@selector(setBarTintColor:)]) {
        if ([NUISettings hasProperty:kBarTintColor withClass:className]) {
            [bar setBarTintColor:[NUISettings getColor:kBarTintColor withClass:className]];
        }
    }

    if ([NUISettings hasProperty:kBackgroundColor withClass:className]) {
        [bar setBackgroundColor:[NUISettings getColor:kBackgroundColor withClass:className]];
    }

    if ([NUISettings hasProperty:kBackgroundTintColor withClass:className]) {
        [bar setTintColor:[NUISettings getColor:kBackgroundTintColor withClass:className]];
    }

    if ([NUISettings hasProperty:kBackgroundImage withClass:className]) {
        [bar setBackgroundImage:[NUISettings getImage:kBackgroundImage withClass:className] forBarMetrics:UIBarMetricsDefault];
    }
    if ([NUISettings hasProperty:kShadowImage withClass:className]) {
        [bar setShadowImage:[NUISettings getImage:kShadowImage withClass:className]];
    }

    NSString *property = kTitleVerticalOffset;
    if ([NUISettings hasProperty:property withClass:className]) {
        float offset = [NUISettings getFloat:property withClass:className];
        [bar setTitleVerticalPositionAdjustment:offset forBarMetrics:UIBarMetricsDefault];
    }

    [self renderSizeDependentProperties:bar];

    NSDictionary *titleTextAttributes = [NUIUtilities titleTextAttributesForClass:className];

    if ([[titleTextAttributes allKeys] count] > 0) {
        bar.titleTextAttributes = titleTextAttributes;
    }
}

+ (void)sizeDidChange:(UINavigationBar*)bar
{
    [self renderSizeDependentProperties:bar];
}

+ (void)renderSizeDependentProperties:(UINavigationBar*)bar
{
    NSString *className = bar.nuiClass;

    if ([NUISettings hasProperty:kBackgroundColorTop withClass:className]) {
        CGRect frame = bar.bounds;
        UIImage *gradientImage = [NUIGraphics
                                  gradientImageWithTop:[NUISettings getColor:kBackgroundColorTop withClass:className]
                                  bottom:[NUISettings getColor:kBackgroundColorBottom withClass:className]
                                  frame:frame];
        [bar setBackgroundImage:gradientImage forBarMetrics:UIBarMetricsDefault];
    } else if ([NUISettings hasProperty:kBackgroundColor withClass:className]) {
        CGRect frame = bar.bounds;
        UIImage *colorImage = [NUIGraphics colorImage:[NUISettings getColor:kBackgroundColor withClass:className] withFrame:frame];
        [bar setBackgroundImage:colorImage forBarMetrics:UIBarMetricsDefault];
    }
}

@end


text: sample on using rust web framework nickel


text:
<?php

namespace Application\Sonata\UserBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * UserRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class UserRepository extends EntityRepository
{

    /**
     *
     * @return type
     */
    public function retrieveByGroup($groupId) {

        $qb = $this->createQueryBuilder('u')
                ->innerJoin('u.groups', 'g')
                ->where('g = :groupId')
                ->setParameter('groupId', $groupId)
                ->addOrderBy("u.lastname", "ASC")
                ->addOrderBy("u.firstname", "ASC")
                ->addOrderBy("u.username", "ASC");

        return $qb;
    }

    /**
     *
     * @return type
     */
    public function retrieveAll($params) {

         $qb = $this->createQueryBuilder('u')
                ->addOrderBy("u.firstname", "ASC")
                ->addOrderBy("u.lastname", "ASC")
                ->addOrderBy("u.username", "ASC");

        return $qb;
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Rebbound.Models
{
    public class RgbColor
    {
        public byte R { get; private set; }
        public byte G { get; private set; }
        public byte B { get; private set; }
        public string Name { get; private set; }

        public RgbColor(byte r, byte g, byte b)
            : this(r, g, b, string.Empty)
        {
        }

        public RgbColor(byte r, byte g, byte b, string name)
        {
            this.R = r;
            this.G = g;
            this.B = b;

            this.Name = name;
        }
    }
}


text:
define(function (require) {
  return function AggTypeFactory(Private) {
    var _ = require('lodash');
    var AggParams = Private(require('ui/agg_types/AggParams'));
    var fieldFormats = Private(require('ui/registry/field_formats'));

    /**
     * Generic AggType Constructor
     *
     * Used to create the values exposed by the agg_types module.
     *
     * @class AggType
     * @private
     * @param {object} config - used to set the properties of the AggType
     */
    function AggType(config) {

      /**
       * the unique, unchanging, name that we have assigned this aggType
       *
       * @property name
       * @type {string}
       */
      this.name = config.name;

      /**
       * the name of the elasticsearch aggregation that this aggType represents. Usually just this.name
       *
       * @property name
       * @type {string}
       */
      this.dslName = config.dslName || config.name;

      /**
       * the user friendly name that will be shown in the ui for this aggType
       *
       * @property title
       * @type {string}
       */
      this.title = config.title;

      /**
       * a function that will be called when this aggType is assigned to
       * an aggConfig, and that aggConfig is being rendered (in a form, chart, etc.).
       *
       * @method makeLabel
       * @param {AggConfig} aggConfig - an agg config of this type
       * @returns {string} - label that can be used in the ui to descripe the aggConfig
       */
      this.makeLabel = config.makeLabel || _.constant(this.name);

      /**
       * Describes if this aggType creates data that is ordered, and if that ordered data
       * is some sort of time series.
       *
       * If the aggType does not create ordered data, set this to something "falsey".
       *
       * If this does create orderedData, then the value should be an object.
       *
       * If the orderdata is some sort of time series, `this.ordered` should be an object
       * with the property `date: true`
       *
       * @property ordered
       * @type {object|undefined}
       */
      this.ordered = config.ordered;

      /**
       * Flag that prevents this aggregation from being included in the dsl. This is only
       * used by the count aggregation (currently) since it doesn't really exist and it's output
       * is available on every bucket.
       *
       * @type {Boolean}
       */
      this.hasNoDsl = !!config.hasNoDsl;

      /**
       * The method to create a filter representation of the bucket
       * @param {object} aggConfig The instance of the aggConfig
       * @param {mixed} key The key for the bucket
       * @returns {object} The filter
       */
      this.createFilter = config.createFilter;

      /**
       * An instance of {{#crossLink "AggParams"}}{{/crossLink}}.
       *
       * @property params
       * @type {AggParams}
       */
      this.params = config.params || [];
      if (!(this.params instanceof AggParams)) {
        // always append the raw JSON param
        this.params.push({
          name: 'json',
          type: 'json',
          advanced: true
        });
        // always append custom label

        if (config.customLabels !== false) {
          this.params.push({
            name: 'customLabel',
            type: 'string',
            write: _.noop
          });
        }

        this.params = new AggParams(this.params);
      }

      /**
       * Designed for multi-value metric aggs, this method can return a
       * set of AggConfigs that should replace this aggConfig in result sets
       * that walk the AggConfig set.
       *
       * @method getResponseAggs
       * @returns {array[AggConfig]|undefined} - an array of aggConfig objects
       *                                         that should replace this one,
       *                                         or undefined
       */
      this.getResponseAggs = config.getResponseAggs || _.noop;

      /**
       * A function that will be called each time an aggConfig of this type
       * is created, giving the agg type a chance to modify the agg config
       */
      this.decorateAggConfig = config.decorateAggConfig || null;

      if (config.getFormat) {
        this.getFormat = config.getFormat;
      }
    }

    /**
     * Pick a format for the values produced by this agg type,
     * overriden by several metrics that always output a simple
     * number
     *
     * @param  {agg} agg - the agg to pick a format for
     * @return {FieldFromat}
     */
    AggType.prototype.getFormat = function (agg) {
      var field = agg.field();
      return field ? field.format : fieldFormats.getDefaultInstance('string');
    };

    return AggType;
  };
});


text:
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import {
  Button,
  Tooltip,
  IconButton,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
} from '@material-ui/core'
import DeleteIcon from '@material-ui/icons/HighlightOff'
import styles from '../../styles/mapping'
import Dialog from '../Dialog'

class DeleteMappingButton extends Component {
  static propTypes = {
    deleteMapping: PropTypes.func.isRequired,
    name: PropTypes.string.isRequired,
  }

  state = {
    dialogVisible: false,
  }

  handleOk = () => {
    const { name, deleteMapping } = this.props
    this.setState({ dialogVisible: false })
    deleteMapping(name)
  }

  handleCancel = () => {
    this.setState({ dialogVisible: false })
  }

  handleDeleteClicked = ({ nativeEvent }) => {
    nativeEvent.stopPropagation()
    this.setState({ dialogVisible: true })
  }

  render() {
    const { dialogVisible } = this.state
    const { name } = this.props
    return (
      <div className={styles.removeIcon}>
        <Tooltip title="Delete mapping...">
          <IconButton onClick={this.handleDeleteClicked}>
            <DeleteIcon />
          </IconButton>
        </Tooltip>

        <Dialog
          open={dialogVisible}
          onClose={this.handleCancel}
        >
          <DialogTitle>Confirm</DialogTitle>
          <DialogContent>
            <DialogContentText style={{ minWidth: 300 }}>{`Sure to delete '${name}'?`}</DialogContentText>
          </DialogContent>
          <DialogActions>
            <Button onClick={this.handleOk}>Ok</Button>
            <Button
              onClick={this.handleCancel}
              variant="contained"
              color="primary"
              autoFocus
            >
              Cancel
            </Button>
          </DialogActions>
        </Dialog>
      </div>
    )
  }
}

export default DeleteMappingButton


text:
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.test;

import static com.google.devtools.build.lib.packages.Attribute.attr;
import static com.google.devtools.build.lib.packages.BuildType.LABEL_LIST;
import static com.google.devtools.build.lib.packages.Type.BOOLEAN;

import com.google.devtools.build.lib.analysis.BaseRuleClasses;
import com.google.devtools.build.lib.analysis.RuleDefinition;
import com.google.devtools.build.lib.analysis.RuleDefinitionEnvironment;
import com.google.devtools.build.lib.analysis.test.TestConfiguration;
import com.google.devtools.build.lib.packages.ConfigurationFragmentPolicy.MissingFragmentPolicy;
import com.google.devtools.build.lib.packages.RuleClass;

/** Rule object implementing "test_suite". */
public final class TestSuiteRule implements RuleDefinition {
  @Override
  public RuleClass build(RuleClass.Builder builder, RuleDefinitionEnvironment env) {
    return builder
        // Technically, test_suite does not use TestConfiguration. But the tests it depends on
        // will always depend on TestConfiguration, so requiring it here simply acknowledges that
        // and prevents pruning by --trim_test_configuration.
        .requiresConfigurationFragments(TestConfiguration.class)
        .setMissingFragmentPolicy(TestConfiguration.class, MissingFragmentPolicy.IGNORE)
        .override(
            attr("testonly", BOOLEAN)
                .value(true)
                .nonconfigurable("policy decision: should be consistent across configurations"))
        /*
        List of text tags such as "small" or "database" or "-flaky". Tags may be any valid string.

          Tags which begin with a "-" character are considered negative tags. The
          preceding "-" character is not considered part of the tag, so a suite tag
          of "-small" matches a test's "small" size. All other tags are considered
          positive tags.

          Optionally, to make positive tags more explicit, tags may also begin with the
          "+" character, which will not be evaluated as part of the text of the tag. It
          merely makes the positive and negative distinction easier to read.

          Only test rules that match all of the positive tags and none of the negative
          tags will be included in the test suite. Note that this does not mean that error checking
          for dependencies on tests that are filtered out is skipped; the dependencies on skipped
          tests still need to be legal (e.g. not blocked by visibility constraints).

          The manual tag keyword is treated specially. It marks the
          test_suite target as "manual" so that it will be ignored by the wildcard
          expansion and automated testing facilities. It does not work as a filter on the set
          of tests in the suite. So when the manual tag is used on a test_suite, test
          rules do not have to be tagged as manual to be included in the test suite.

          Note that a test's size is considered a tag for the purpose of filtering.

          If you need a test_suite that contains tests with mutually exclusive tags
          (e.g. all small and medium tests), you'll have to create three test_suite
          rules: one for all small tests, one for all medium tests, and one that includes the
          previous two.

         */

        /*
        A list of test suites and test targets of any language.

          Any *_test is accepted here, independent of the language. No
          *_binary targets are accepted however, even if they happen to run a test.
          Filtering by the specified tags is only done for tests listed directly in
          this attribute. If this attribute contains test_suites, the tests inside
          those will not be filtered by this test_suite (they are considered to be
          filtered already).

          If the tests attribute is unspecified or empty, the rule will default to
          including all test rules in the current BUILD file that are not tagged as
          manual. These rules are still subject to tag filtering.

         */
        .add(
            attr("tests", LABEL_LIST)
                .orderIndependent()
                .allowedFileTypes()
                .nonconfigurable("policy decision: should be consistent across configurations"))
        // This magic attribute contains all *test rules in the package, iff
        // tests=[].
        .add(
            attr("$implicit_tests", LABEL_LIST)
                .orderIndependent()
                .nonconfigurable("Accessed in TestTargetUtils without config context"))
        .build();
  }

  @Override
  public Metadata getMetadata() {
    return RuleDefinition.Metadata.builder()
        .name("test_suite")
        .ancestors(BaseRuleClasses.BaseRule.class)
        .factoryClass(TestSuite.class)
        .build();
  }
}

/*

A test_suite defines a set of tests that are considered "useful" to humans. This
allows projects to define sets of tests, such as "tests you must run before checkin", "our
project's stress tests" or "all small tests."

Examples

A test suite to run all of the small tests in the current package.

test_suite(
    name = "small_tests",
    tags = ["small"],
)

A test suite that runs a specified set of tests:

test_suite(
    name = "smoke_tests",
    tests = [
        "system_unittest",
        "public_api_unittest",
    ],
)

A test suite to run all tests in the current package which are not flaky.

test_suite(
    name = "non_flaky_test",
    tags = ["-flaky"],
)

*/


text:
body {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  overflow: hidden;
  background: linear-gradient(141deg, #0fb8ad 0%, #1fc8db 51%, #2cb5e8 75%);
  font-family: sans-serif;
}

button {
  background: #1fc8db;
  border: 1px solid #ccc;
  padding: 6px;
  margin-top: 6px;
  color: white;
  transition: background 0.25s;
}

button:focus {
  outline: none;
}

button[data-clicked] {
  background:purple;
}

#div1 {
  background-color: white;
  border: 1px solid #ccc;
  padding: 16px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}


text:
<?php namespace Anomaly\Streams\Platform\Model\Users;

use Anomaly\Streams\Platform\Entry\EntryModel;

class UsersRolesEntryModel extends EntryModel
{

    use \Illuminate\Database\Eloquent\SoftDeletes;

    protected $searchable = false;

    protected $table = 'users_roles';

    protected $titleName = 'name';

    protected $rules = [
'name' => 'required',
'slug' => 'required|unique:users_roles,slug',
'description' => '',
'permissions' => '',
];

    protected $fields = [
'name',
'slug',
'description',
'permissions',
];

    protected $dates = ['created_at', 'updated_at', 'deleted_at'];

    protected $relationships = [];

    protected $translatedAttributes = ['name', 'description'];

    protected $translationForeignKey = 'entry_id';

    protected $translationModel = 'Anomaly\Streams\Platform\Model\Users\UsersRolesEntryTranslationsModel';

    protected $stream = [
'id' => '18',
'namespace' => 'users',
'slug' => 'roles',
'prefix' => 'users_',
'title_column' => 'name',
'order_by' => 'id',
'locked' => '0',
'hidden' => '0',
'sortable' => '0',
'searchable' => '0',
'trashable' => '1',
'translatable' => '1',
'config' => 'a:0:{}',
'assignments' => [
[
'id' => 115,
'sort_order' => 115,
'stream_id' => 18,
'field_id' => 100,
'config' => 'a:0:{}',
'unique' => 0,
'required' => 1,
'translatable' => 1,
'field' => [
'id' => '100',
'namespace' => 'users',
'slug' => 'name',
'type' => 'anomaly.field_type.text',
'config' => 'a:0:{}',
'locked' => '1',
'translations' => [
[
'id' => 100,
'field_id' => 100,
'locale' => 'en',
'name' => 'anomaly.module.users::field.name.name',
'placeholder' => 'anomaly.module.users::field.name.placeholder',
'warning' => 'anomaly.module.users::field.name.warning',
'instructions' => 'anomaly.module.users::field.name.instructions',
],
],
],
'translations' => [
[
'id' => 115,
'assignment_id' => 115,
'locale' => 'en',
'label' => 'anomaly.module.users::field.name.label.roles',
'warning' => 'anomaly.module.users::field.name.warning.roles',
'placeholder' => 'anomaly.module.users::field.name.placeholder.roles',
'instructions' => 'anomaly.module.users::field.name.instructions.roles',
],
],
],
[
'id' => 116,
'sort_order' => 116,
'stream_id' => 18,
'field_id' => 108,
'config' => 'a:0:{}',
'unique' => 1,
'required' => 1,
'translatable' => 0,
'field' => [
'id' => '108',
'namespace' => 'users',
'slug' => 'slug',
'type' => 'anomaly.field_type.slug',
'config' => 'a:1:{s:7:"slugify";s:4:"name";}',
'locked' => '1',
'translations' => [
[
'id' => 108,
'field_id' => 108,
'locale' => 'en',
'name' => 'anomaly.module.users::field.slug.name',
'placeholder' => 'anomaly.module.users::field.slug.placeholder',
'warning' => 'anomaly.module.users::field.slug.warning',
'instructions' => 'anomaly.module.users::field.slug.instructions',
],
],
],
'translations' => [
[
'id' => 116,
'assignment_id' => 116,
'locale' => 'en',
'label' => 'anomaly.module.users::field.slug.label.roles',
'warning' => 'anomaly.module.users::field.slug.warning.roles',
'placeholder' => 'anomaly.module.users::field.slug.placeholder.roles',
'instructions' => 'anomaly.module.users::field.slug.instructions.roles',
],
],
],
[
'id' => 117,
'sort_order' => 117,
'stream_id' => 18,
'field_id' => 101,
'config' => 'a:0:{}',
'unique' => 0,
'required' => 0,
'translatable' => 1,
'field' => [
'id' => '101',
'namespace' => 'users',
'slug' => 'description',
'type' => 'anomaly.field_type.textarea',
'config' => 'a:0:{}',
'locked' => '1',
'translations' => [
[
'id' => 101,
'field_id' => 101,
'locale' => 'en',
'name' => 'anomaly.module.users::field.description.name',
'placeholder' => 'anomaly.module.users::field.description.placeholder',
'warning' => 'anomaly.module.users::field.description.warning',
'instructions' => 'anomaly.module.users::field.description.instructions',
],
],
],
'translations' => [
[
'id' => 117,
'assignment_id' => 117,
'locale' => 'en',
'label' => 'anomaly.module.users::field.description.label.roles',
'warning' => 'anomaly.module.users::field.description.warning.roles',
'placeholder' => 'anomaly.module.users::field.description.placeholder.roles',
'instructions' => 'anomaly.module.users::field.description.instructions.roles',
],
],
],
[
'id' => 118,
'sort_order' => 118,
'stream_id' => 18,
'field_id' => 96,
'config' => 'a:0:{}',
'unique' => 0,
'required' => 0,
'translatable' => 0,
'field' => [
'id' => '96',
'namespace' => 'users',
'slug' => 'permissions',
'type' => 'anomaly.field_type.checkboxes',
'config' => 'a:0:{}',
'locked' => '1',
'translations' => [
[
'id' => 96,
'field_id' => 96,
'locale' => 'en',
'name' => 'anomaly.module.users::field.permissions.name',
'placeholder' => 'anomaly.module.users::field.permissions.placeholder',
'warning' => 'anomaly.module.users::field.permissions.warning',
'instructions' => 'anomaly.module.users::field.permissions.instructions',
],
],
],
'translations' => [
[
'id' => 118,
'assignment_id' => 118,
'locale' => 'en',
'label' => 'anomaly.module.users::field.permissions.label.roles',
'warning' => 'anomaly.module.users::field.permissions.warning.roles',
'placeholder' => 'anomaly.module.users::field.permissions.placeholder.roles',
'instructions' => 'anomaly.module.users::field.permissions.instructions.roles',
],
],
],
],
'translations' => [
[
'id' => 18,
'stream_id' => 18,
'locale' => 'en',
'name' => 'anomaly.module.users::stream.roles.name',
'description' => 'anomaly.module.users::stream.roles.description',
],
],
];

}


text:
<?xml version='1.0'?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->

<synapseSample>
    <sampleID>1</sampleID>
    <sampleName>Simple content based routing (CBR) of messages</sampleName>
    <synapseConfig>
        <axis2Repo>modules/integration/target/test_repos/synapse</axis2Repo>
        <axis2Xml>modules/integration/target/test_repos/synapse/conf/axis2_def.xml</axis2Xml>
        <synapseXml>repository/conf/sample/synapse_sample_1.xml</synapseXml>
    </synapseConfig>
    <backEndServerConfig>
        <axis2Server id='0'>
            <axis2Repo>modules/integration/target/test_repos/axis2Server</axis2Repo>
            <axis2Xml>modules/integration/target/test_repos/axis2Server/conf/axis2_def.xml</axis2Xml>
        </axis2Server>
    </backEndServerConfig>
    <clientConfig>
	<clientRepo>modules/integration/target/test_repos/axis2Client</clientRepo>
    </clientConfig>
</synapseSample>


text:
window.scroll(0,document.querySelector(this.href).offsetTop - 20);
/* prevent default action*/
return false;


text:
layout: post
date:	2013-03-18 12:01:00
title:  Delightful finger rhyme...
tags: [archived-posts]
categories: archives
permalink: /:categories/:year/:month/:day/:title/
---
<lj-embed id="965"/>

She learnt this at

<a href="http://urbansprouts.wordpress.com/"> Urban Sprouts </a>

and I was delighted when she suddenly shared it with me!


text:
from __future__ import annotations

import time
from io import BytesIO
from threading import Thread

from django.conf import settings

try:
    from minio import Minio, S3Error
    from minio.deleteobjects import DeleteObject
    from urllib3 import PoolManager
    from urllib3.exceptions import ReadTimeoutError
except ImportError:
    # Enforce
    settings.S3_BUCKET = None

_client = None

def client():
    if not settings.S3_BUCKET:
        raise Exception("Object storage is not configured")

    global _client
    if _client is None:
        _client = Minio(
            settings.S3_ENDPOINT,
            settings.S3_ACCESS_KEY,
            settings.S3_SECRET_KEY,
            region=settings.S3_REGION,
            http_client=PoolManager(timeout=settings.S3_TIMEOUT),
        )

    return _client

ASCII_J = ord("j")
ASCII_Z = ord("z")

def enc(n):
    """Generate an object key in the "<sorting prefix>-<n>" form.

    >>> [enc(i) for i in range(0, 5)]
    ['zj-0', 'zi-1', 'zh-2', 'zg-3', 'zf-4']

    The purpose of the sorting prefix is to sort keys with smaller n values
    last:

    >>> sorted([enc(i) for i in range(0, 5)])
    ['zf-4', 'zg-3', 'zh-2', 'zi-1', 'zj-0']

    This allows efficient lookup of objects with n
    values below a specific threshold. For example, the following
    retrieves all keys at bucket's root directory with n < 123:

    >>> client.list_objects(bucket_name, start_after=enc(123))
    """
    s = str(n)
    len_inverted = chr(ASCII_Z - len(s) + 1)
    inverted = "".join(chr(ASCII_J - int(c)) for c in s)
    return len_inverted + inverted + "-" + s

def get_object(code, n):
    if not settings.S3_BUCKET:
        return None

    key = "%s/%s" % (code, enc(n))
    response = None
    try:
        response = client().get_object(settings.S3_BUCKET, key)
        return response.read()
    except S3Error:
        return None
    finally:
        if response:
            response.close()
            response.release_conn()

def put_object(code, n, data):
    key = "%s/%s" % (code, enc(n))
    retries = 10
    while True:
        try:
            client().put_object(settings.S3_BUCKET, key, BytesIO(data), len(data))
            break
        except S3Error as e:
            if e.code == "InternalError" and retries > 0:
                retries -= 1
                print("InternalError, retrying (retries=%d)..." % retries)
                continue

            raise e

def _remove_objects(code, upto_n):
    if upto_n <= 0:
        return

    prefix = "%s/" % code
    start_after = prefix + enc(upto_n + 1)
    q = client().list_objects(settings.S3_BUCKET, prefix, start_after=start_after)
    delete_objs = [DeleteObject(obj.object_name) for obj in q]
    if delete_objs:
        num_objs = len(delete_objs)
        try:
            start = time.time()
            errors = client().remove_objects(settings.S3_BUCKET, delete_objs)
            for e in errors:
                print("remove_objects error: ", e)
            total = time.time() - start
            print("remove_objects for %d objects took %.1fs" % (num_objs, total))
        except ReadTimeoutError:
            print("remove_objects timed out for %d objects" % num_objs)

def remove_objects(check_code, upto_n):
    """Remove keys with n values below or equal to `upto_n`.

    The S3 API calls can take seconds to complete,
    therefore run the removal code on thread.
    """
    Thread(target=_remove_objects, args=(check_code, upto_n)).start()


text:
/* global PaymentRequest:false */

/**
 * Launches the PaymentRequest UI that requests contact details.
 */
function buy() {  // eslint-disable-line no-unused-vars
  try {
    new PaymentRequest(
        [{supportedMethods: ['visa']}],
        {total: {label: 'Total', amount: {currency: 'USD', value: '5.00'}}},
        {requestPayerName: true, requestPayerEmail: true,
         requestPayerPhone: true})
        .show()
        .then(function(resp) {
          resp.complete('success')
              .then(function() {
                print(
                    resp.payerName + '
' + resp.payerEmail + '
' +
                    resp.payerPhone + '
' + resp.methodName + '
' +
                    JSON.stringify(resp.details, undefined, 2));
              })
              .catch(function(error) {
                print(error);
              });
        })
        .catch(function(error) {
          print(error);
        });
  } catch (error) {
    print(error.message);
  }
}


text:
<?php

namespace Google\AdsApi\AdManager\v202211;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class ProposalCompanyAssociation
{

    /**
     * @var int $companyId
     */
    protected $companyId = null;

    /**
     * @var string $type
     */
    protected $type = null;

    /**
     * @var int[] $contactIds
     */
    protected $contactIds = null;

    /**
     * @param int $companyId
     * @param string $type
     * @param int[] $contactIds
     */
    public function __construct($companyId = null, $type = null, array $contactIds = null)
    {
      $this->companyId = $companyId;
      $this->type = $type;
      $this->contactIds = $contactIds;
    }

    /**
     * @return int
     */
    public function getCompanyId()
    {
      return $this->companyId;
    }

    /**
     * @param int $companyId
     * @return \Google\AdsApi\AdManager\v202211\ProposalCompanyAssociation
     */
    public function setCompanyId($companyId)
    {
      $this->companyId = (!is_null($companyId) && PHP_INT_SIZE === 4)
          ? floatval($companyId) : $companyId;
      return $this;
    }

    /**
     * @return string
     */
    public function getType()
    {
      return $this->type;
    }

    /**
     * @param string $type
     * @return \Google\AdsApi\AdManager\v202211\ProposalCompanyAssociation
     */
    public function setType($type)
    {
      $this->type = $type;
      return $this;
    }

    /**
     * @return int[]
     */
    public function getContactIds()
    {
      return $this->contactIds;
    }

    /**
     * @param int[]|null $contactIds
     * @return \Google\AdsApi\AdManager\v202211\ProposalCompanyAssociation
     */
    public function setContactIds(array $contactIds = null)
    {
      $this->contactIds = $contactIds;
      return $this;
    }

}


text:
<?php

require_once _CENTREON_PATH_ . "/www/class/centreonDB.class.php";
require_once _CENTREON_PATH_ . "/www/class/centreonHost.class.php";
require_once _CENTREON_PATH_ . "/www/class/centreonHook.class.php";
require_once __DIR__ . "/centreon_configuration_objects.class.php";

class CentreonConfigurationHost extends CentreonConfigurationObjects
{
    /**
     * @var CentreonDB
     */
    protected $pearDBMonitoring;

    /**
     * CentreonConfigurationHost constructor.
     */
    public function __construct()
    {
        global $pearDBO;
        parent::__construct();
        $this->pearDBMonitoring = new CentreonDB('centstorage');
        $pearDBO = $this->pearDBMonitoring;
    }

    /**
     * @return array
     * @throws RestBadRequestException
     */
    public function getList()
    {
        global $centreon;

        $userId = $centreon->user->user_id;
        $isAdmin = $centreon->user->admin;
        $aclHosts = '';
        $additionalTables = '';
        $additionalCondition = '';
        $explodedValues = '';
        $queryValues = array();
        $query = '';

        // Check for select2 'q' argument
        if (false === isset($this->arguments['q'])) {
            $queryValues["hostName"] = '%%';
        } else {
            $queryValues["hostName"] = '%' . (string)$this->arguments['q'] . '%';
        }
        $query .= 'SELECT SQL_CALC_FOUND_ROWS DISTINCT host_name, host_id, host_activate ' .
            'FROM ( ' .
            '( SELECT DISTINCT h.host_name, h.host_id, h.host_activate ' .
            'FROM host h ';

        if (isset($this->arguments['hostgroup'])) {
            $additionalTables .= ',hostgroup_relation hg ';
            $additionalCondition .= 'AND hg.host_host_id = h.host_id AND hg.hostgroup_hg_id IN (';
            foreach (explode(',', $this->arguments['hostgroup']) as $hgId => $hgValue) {
                if (!is_numeric($hgValue)) {
                    throw new \RestBadRequestException('Error, host group id must be numerical');
                }
                $explodedValues .= ':hostgroup' . $hgId . ',';
                $queryValues['hostgroup'][$hgId] = (int)$hgValue;
            }
            $explodedValues = rtrim($explodedValues, ',');
            $additionalCondition .= $explodedValues . ') ';
        }
        $query .= $additionalTables . 'WHERE h.host_register = "1" ';

        /* Get ACL if user is not admin */
        if (!$isAdmin) {
            $acl = new CentreonACL($userId, $isAdmin);
            $aclHosts .= 'AND h.host_id IN (' . $acl->getHostsString('ID', $this->pearDBMonitoring) . ') ';
        }
        $query .= $aclHosts;
        $query .= $additionalCondition . ') ';

        // Check for virtual hosts
        $virtualHostCondition = '';
        if (!isset($this->arguments['hostgroup']) && isset($this->arguments['h']) && $this->arguments['h'] == 'all') {
            $allVirtualHosts = CentreonHook::execute('Host', 'getVirtualHosts');
            foreach ($allVirtualHosts as $virtualHosts) {
                foreach ($virtualHosts as $vHostId => $vHostName) {
                    $virtualHostCondition .= 'UNION ALL ' .
                        "(SELECT :hostNameTable$vHostId as host_name, "
                        . ":virtualHostId$vHostId as host_id, "
                        . "'1' AS host_activate ) ";
                    $queryValues['virtualHost'][$vHostId] = (string)$vHostName;
                }
            }
        }
        $query .= $virtualHostCondition .
            ') t_union ' .
            'WHERE host_name LIKE :hostName ' .
            'ORDER BY host_name ';

        if (isset($this->arguments['page_limit']) && isset($this->arguments['page'])) {
            if (
                !is_numeric($this->arguments['page'])
                || !is_numeric($this->arguments['page_limit'])
                || $this->arguments['page_limit'] < 1
            ) {
                throw new \RestBadRequestException('Error, limit must be an integer greater than zero');
            }
            $offset = ($this->arguments['page'] - 1) * $this->arguments['page_limit'];
            $query .= 'LIMIT :offset, :limit';
            $queryValues['offset'] = (int)$offset;
            $queryValues['limit'] = (int)$this->arguments['page_limit'];
        }

        $stmt = $this->pearDB->prepare($query);
        $stmt->bindParam(':hostName', $queryValues['hostName'], PDO::PARAM_STR);

        if (isset($queryValues['hostgroup'])) {
            foreach ($queryValues['hostgroup'] as $hgId => $hgValue) {
                $stmt->bindValue(':hostgroup' . $hgId, $hgValue, PDO::PARAM_INT);
            }
        }
        if (isset($queryValues['virtualHost'])) {
            foreach ($queryValues['virtualHost'] as $vhId => $vhValue) {
                $stmt->bindValue(':hostNameTable' . $vhId, $vhValue, PDO::PARAM_STR);
                $stmt->bindValue(':virtualHostId' . $vhId, $vhId, PDO::PARAM_INT);
            }
        }
        if (isset($queryValues['offset'])) {
            $stmt->bindParam(':offset', $queryValues["offset"], PDO::PARAM_INT);
            $stmt->bindParam(':limit', $queryValues["limit"], PDO::PARAM_INT);
        }
        $stmt->execute();
        $hostList = array();
        while ($data = $stmt->fetch()) {
            $hostList[] = array(
                'id' => htmlentities($data['host_id']),
                'text' => $data['host_name'],
                'status' => (bool) $data['host_activate'],
            );
        }

        return array(
            'items' => $hostList,
            'total' => (int) $this->pearDB->numberRows()
        );
    }

    /**
     *
     * @return type
     * @throws RestBadRequestException
     */
    public function getServices()
    {
        // Check for id
        if (false === isset($this->arguments['id'])) {
            throw new RestBadRequestException("Missing host id");
        }
        $id = $this->arguments['id'];

        $allServices = false;
        if (isset($this->arguments['all'])) {
            $allServices = true;
        }

        $hostObj = new CentreonHost($this->pearDB);
        $serviceList = array();
        $serviceListRaw = $hostObj->getServices($id, false, $allServices);

        foreach ($serviceListRaw as $service_id => $service_description) {
            if ($allServices || service_has_graph($id, $service_id)) {
                $serviceList[$service_id] = $service_description;
            }
        }

        return $serviceList;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minHeight="?android:attr/listPreferredItemHeight"
    android:orientation="vertical"
    android:padding="5dp">

    <TextView
        android:id="@+id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:textColor="@android:color/black" />

    <TextView
        android:id="@+id/text2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:textColor="@android:color/darker_gray" />
</LinearLayout>


text:
package com.amazonaws.services.elastictranscoder.model.transform;

import static com.amazonaws.util.StringUtils.UTF8;
import static com.amazonaws.util.StringUtils.COMMA_SEPARATOR;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.elastictranscoder.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;

/**
 * CreatePipelineRequest Marshaller
 */
public class CreatePipelineRequestMarshaller implements
        Marshaller<Request<CreatePipelineRequest>, CreatePipelineRequest> {

    private static final String DEFAULT_CONTENT_TYPE = "";

    public Request<CreatePipelineRequest> marshall(
            CreatePipelineRequest createPipelineRequest) {

        if (createPipelineRequest == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        Request<CreatePipelineRequest> request = new DefaultRequest<CreatePipelineRequest>(
                createPipelineRequest, "AmazonElasticTranscoder");

        request.setHttpMethod(HttpMethodName.POST);

        String uriResourcePath = "/2012-09-25/pipelines";

        request.setResourcePath(uriResourcePath);

        try {
            StringWriter stringWriter = new StringWriter();
            JSONWriter jsonWriter = new JSONWriter(stringWriter);

            jsonWriter.object();

            if (createPipelineRequest.getName() != null) {
                jsonWriter.key("Name").value(createPipelineRequest.getName());
            }

            if (createPipelineRequest.getInputBucket() != null) {
                jsonWriter.key("InputBucket").value(
                        createPipelineRequest.getInputBucket());
            }

            if (createPipelineRequest.getOutputBucket() != null) {
                jsonWriter.key("OutputBucket").value(
                        createPipelineRequest.getOutputBucket());
            }

            if (createPipelineRequest.getRole() != null) {
                jsonWriter.key("Role").value(createPipelineRequest.getRole());
            }

            if (createPipelineRequest.getAwsKmsKeyArn() != null) {
                jsonWriter.key("AwsKmsKeyArn").value(
                        createPipelineRequest.getAwsKmsKeyArn());
            }

            if (createPipelineRequest.getNotifications() != null) {
                jsonWriter.key("Notifications");
                NotificationsJsonMarshaller.getInstance().marshall(
                        createPipelineRequest.getNotifications(), jsonWriter);
            }

            if (createPipelineRequest.getContentConfig() != null) {
                jsonWriter.key("ContentConfig");
                PipelineOutputConfigJsonMarshaller.getInstance().marshall(
                        createPipelineRequest.getContentConfig(), jsonWriter);
            }

            if (createPipelineRequest.getThumbnailConfig() != null) {
                jsonWriter.key("ThumbnailConfig");
                PipelineOutputConfigJsonMarshaller.getInstance().marshall(
                        createPipelineRequest.getThumbnailConfig(), jsonWriter);
            }

            jsonWriter.endObject();

            String snippet = stringWriter.toString();
            byte[] content = snippet.getBytes(UTF8);
            request.setContent(new StringInputStream(snippet));
            request.addHeader("Content-Length",
                    Integer.toString(content.length));
            if (!request.getHeaders().containsKey("Content-Type")) {
                request.addHeader("Content-Type", DEFAULT_CONTENT_TYPE);
            }
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }

        return request;
    }

}


text:
export { MatMenu, MatMenuDefaultOptions, MAT_MENU_DEFAULT_OPTIONS } from './menu-directive';
export { MatMenuItem } from './menu-item';
export { MatMenuTrigger } from './menu-trigger';
export { MatMenuPanel } from './menu-panel';
export { MenuPositionX, MenuPositionY } from './menu-positions';


text:
package jenkins.model.lazy;

import jenkins.model.lazy.AbstractLazyLoadRunMap.Direction;

import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;

/**
 * Set that backs {@link AbstractLazyLoadRunMap#entrySet()}.
 *
 * @author Kohsuke Kawaguchi
 */
class LazyLoadRunMapEntrySet<R> extends AbstractSet<Entry<Integer,R>> {
    private final AbstractLazyLoadRunMap<R> owner;

    /**
     * Lazily loaded all entries.
     */
    private Set<Entry<Integer,R>> all;

    LazyLoadRunMapEntrySet(AbstractLazyLoadRunMap<R> owner) {
        this.owner = owner;
    }

    private synchronized Set<Entry<Integer,R>> all() {
        if (all==null)
            all = new BuildReferenceMapAdapter<>(owner, owner.all()).entrySet();
        return all;
    }

    synchronized void clearCache() {
        all = null;
    }

    @Override
    public int size() {
        return all().size();
    }

    @Override
    public boolean isEmpty() {
        return owner.newestBuild()==null;
    }

    @Override
    public boolean contains(Object o) {
        if (o instanceof Entry) {
            Entry e = (Entry) o;
            Object k = e.getKey();
            if (k instanceof Integer) {
                return owner.getByNumber((Integer)k).equals(e.getValue());
            }
        }
        return false;
    }

    @Override
    public Iterator<Entry<Integer,R>> iterator() {
        return new Iterator<Entry<Integer,R>>() {
            R last = null;
            R next = owner.newestBuild();

            public boolean hasNext() {
                return next!=null;
            }

            public Entry<Integer,R> next() {
                last = next;
                if (last!=null) {
                    next = owner.search(owner.getNumberOf(last)-1, Direction.DESC);
                } else
                    throw new NoSuchElementException();
                return entryOf(last);
            }

            private Entry<Integer, R> entryOf(R r) {
                return new SimpleImmutableEntry<>(owner.getNumberOf(r), r);
            }

            public void remove() {
                if (last==null)
                    throw new UnsupportedOperationException();
                owner.removeValue(last);
            }
        };
    }

    @Override
    public Object[] toArray() {
        return all().toArray();
    }

    @Override
    public <T> T[] toArray(T[] a) {
        return all().toArray(a);
    }

    @Override
    public boolean add(Entry<Integer, R> integerREntry) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean remove(Object o) {
        if (o instanceof Entry) {
            Entry e = (Entry) o;
            return owner.removeValue((R)e.getValue());
        }
        return false;
    }
}


text:
<?php namespace Gzero\Cms\Jobs;

use Gzero\Cms\Models\ContentTranslation;
use Gzero\Core\DBTransactionTrait;
use Gzero\DomainException;

class DeleteContentTranslation {

    use DBTransactionTrait;

    /** @var ContentTranslation */
    protected $translation;

    /**
     * Create a new job instance.
     *
     * @param ContentTranslation $translation Content translation model
     */
    public function __construct(ContentTranslation $translation)
    {
        $this->translation = $translation;
    }

    /**
     * Execute the job.
     *
     * @throws DomainException
     *
     * @return bool
     */
    public function handle()
    {
        if ($this->translation->is_active) {
            throw new DomainException('Cannot delete active translation');
        }

        return $this->dbTransaction(function () {
            $lastAction = $this->translation->delete();

            event('content.translation.deleted', [$this->translation]);

            return $lastAction;
        });
    }
}


text:
export Canvas, Units, Rotation, canvas, deferredcanvas,
       draw, drawpart, set_unit_box, set_box

# A box giving the coordinate system used by a canvas.
type Units
    x0::Float64
    y0::Float64
    width::Float64
    height::Float64

    function Units()
        new(0.0, 0.0, 1.0, 1.0)
    end

    function Units(width::Number,
                   height::Number)
        new(0.0, 0.0, width, height)
    end

    function Units(x0::Number,
                   y0::Number,
                   width::Number,
                   height::Number)
        new(x0, y0, width, height)
    end
end

# Note: Units has almost the same representation as BoundingBox, except no unit
# is associated with the numbers.
function convert(::Type{BoundingBox}, u::Units)
    BoundingBox(u.x0, u.y0, u.width, u.height)
end

function convert(::Type{Units}, u::BoundingBox)
    Units(u.x0.value, u.y0.value, u.width.value, u.height.value)
end

# Canvases are containers for forms and other canvases with an associated
# coordinate transform.
abstract Canvas

# An identity element for the canvas monoid.
type EmptyCanvas <: Canvas end
const empty_canvas = EmptyCanvas()

# A deferred canvas is a function that produces a canvas and is evaluated when
# the graphic is drawn. This is useful when the layout of the contents of a
# canvas depends on its size in absolute coordinates, which is only known, in
# general at draw time.
#
# The function `f` must have the signature:
#   f(box::BoundingBox, unit_box::BoundingBox)
#
# Where box is the bounding box in absolute coordinates of the parent canvas,
# and unit_box is its unit box.
#
# Another way to think of this: a canvas in to an expression what a
# deferredcanvas is to a macro.
#
type DeferredCanvas <: Canvas
    f::Function
    order::Integer
end

deferredcanvas(f::Function) = DeferredCanvas(f, 0)
deferredcanvas(f::Function, order::Integer) = DeferredCanvas(f, order)

# non-empty tree of canvases.
type CanvasTree <: Canvas
    box::BoundingBox
    form::Form
    property::Property
    unit_box::Units
    rot::Rotation
    children::List{Canvas}

    # Z-order of this canvas relative to its siblings.
    order::Integer

    # True if this canvas should use its parent's coordinate system.
    units_inherited::Bool

    # True if children of the canvas should be clipped by its bounding box.
    clip::Bool

    function CanvasTree(box::BoundingBox,
                        form::Form,
                        property::Property,
                        unit_box::Units,
                        rot::Rotation,
                        children::List{Canvas},
                        order::Integer,
                        units_inherited::Bool,
                        clip::Bool)

        new(box, form, property, unit_box, rot,
            children, order, units_inherited, clip)
    end

    function CanvasTree(x0::MeasureOrNumber=0.0w,
                        y0::MeasureOrNumber=0.0h,
                        width::MeasureOrNumber=1.0w,
                        height::MeasureOrNumber=1.0h;
                        unit_box=Units(),
                        rotation=Rotation(),
                        units_inherited=false,
                        order=0,
                        clip=false)
        new(BoundingBox(x0, y0, width, height),
                empty_form,
                empty_property,
                unit_box,
                rotation,
                ListNil{Canvas}(),
                order,
                units_inherited,
                clip)
    end

    # shallow copy constructor
    function CanvasTree(c::CanvasTree)
        new(c.box, c.form, c.property, c.unit_box,
            c.rot, c.children, c.order, c.units_inherited, c.clip)
    end
end

# Alias constructor functions
const canvas = CanvasTree

copy(c::CanvasTree) = CanvasTree(c)

# Return a new Canvas with unit_box substituted.
function set_unit_box(c::CanvasTree, unit_box::Units)
    c = copy(c)
    c.unit_box = unit_box
    c
end

# Return a new Canvas with the box substituted
function set_box(c::CanvasTree, box::BoundingBox)
    c = copy(c)
    c.box = box
    c
end

function show(io::IO, c::CanvasTree)
    print(io, "Canvas(")
    show(io, c.children)
    print(io, ")")
end

# Similar to dump(), but briefer
function contents(io, c::CanvasTree, n::Int, indent)
    lc = length(c.children)
    lf = length(c.form)
    println(indent, "Canvas with ", lc, lc == 1 ? " child" : " children",
            " and ", lf, lf == 1 ? " form" : " forms")
    if n > 0
        # Children
        i = 1
        for cc in c.children
            contents(io, cc, n - 1, string(indent, "  "))
            if i > 10
                println(io, indent, "  ...")
                break
            end
            i += 1
        end
        # Form
        contents(io, c.form, n, indent)
    end
end
contents(io, c::CanvasTree, n::Int) = contents(io, c, n, "")
contents(io, c::CanvasTree) = contents(io, c, 10, "")
contents(c::CanvasTree, args...) = contents(OUTPUT_STREAM, c, args...)

compose(canvas::Canvas) = canvas

# Compositions of canvases is tree joining by making b a subtree of a.
#     a      b             a___
#    / \    / \    --->   / \  \
#   X   Y  U   V         X   Y  b
#                              / \
#                             U   V
function compose(canvases::Canvas...)
    root = empty_canvas
    for canvas in canvases
        if canvas === empty_canvas
            continue
        elseif root === empty_canvas
            root = copy(canvas)
        else
            root.children = cons(canvas, root.children)
        end
    end
    root
end

# Composition of forms into canvases
function compose(a::CanvasTree, b::Form)
    CanvasTree(a.box, combine(a.form, b), a.property,
               a.unit_box, a.rot, a.children, a.order, a.units_inherited, a.clip)
end

function compose(a::EmptyCanvas, b::Form)
    a
end

function compose(a::CanvasTree, b::Property)
    CanvasTree(a.box, a.form, combine(a.property, b),
               a.unit_box, a.rot, a.children, a.order, a.units_inherited, a.clip)
end

function compose(a::EmptyCanvas, b::Property)
    a
end

function compose(a::DeferredCanvas, b::Union(Canvas, Form, Property))
    error("Error: Deferred canvases cannot be composed with.")
end

# Draw a realization of the graphic on a given backend.
#
# Args:
#   backend: Backend on which to draw the graphic.
#   root_canvas: Root node of the graphic.
#
# Returns:
#   nothing
#
# Effects:
#   The root_canvas will be finished after the call to draw. If you wish to draw
#   multiple canvases, use `drawpart`.
#
function draw(backend::Backend, root_canvas::Canvas)
    drawpart(backend, root_canvas)
    finish(backend)
end

# Draw without finishing the backend.
function drawpart(backend::Backend, root_canvas::Canvas)
    S = {(root_canvas, NativeTransform(), BoundingBox(), root_box(backend))}
    while !isempty(S)
        s = pop!(S)

        if s == :POP_PROPERTY
            pop_property(backend)
            continue
        end

        (canvas, parent_t, unit_box, parent_box) = s

        if canvas === empty_canvas
            continue
        end

        if typeof(canvas) == DeferredCanvas
            abs_parent_box =
                BoundingBox(convert(SimpleMeasure{MillimeterUnit}, parent_box.x0),
                            convert(SimpleMeasure{MillimeterUnit}, parent_box.y0),
                            convert(SimpleMeasure{MillimeterUnit}, parent_box.width),
                            convert(SimpleMeasure{MillimeterUnit}, parent_box.height))

            canvas = canvas.f(abs_parent_box, unit_box)
            if !(typeof(canvas) <: Canvas)
                error("Error: A deferred canvas function did not evaluate to a canvas.")
            end
        end

        box = native_measure(canvas.box, parent_t, unit_box, parent_box, backend)
        rot = native_measure(canvas.rot, parent_t, unit_box, box, backend)
        t = combine(rot, parent_t)

        if !canvas.units_inherited
            unit_box = convert(BoundingBox, canvas.unit_box)
        end

        property = canvas.property
        if canvas.clip
            property |= clip(Point(box.x0, box.y0),
                             Point(box.x0 + box.width, box.y0),
                             Point(box.x0 + box.width, box.y0 + box.height),
                             Point(box.x0, box.y0 + box.height))
        end

        if !is(property, empty_property)
            push!(S, :POP_PROPERTY)
            push_property(backend, native_measure(property, t, unit_box,
                                                  box, backend))
        end

        draw(backend, t, unit_box, box, canvas.form)

        ordered_children = Array((Integer, Integer, Canvas), length(canvas.children))
        for (i, child) in enumerate(canvas.children)
            # The tuple here includes i so canvases are never compared to break
            # ties.
            ordered_children[i] = (child.order, i, child)
        end
        sort!(ordered_children)
        reverse!(ordered_children)

        for (_, _, child) in ordered_children
            push!(S, (child, t, unit_box, box))
        end
    end
end