text:
"""
.. module:: eulerlib.numtheory
    :synopsis: Number theory related functions.

.. moduleauthor:: Sameer Marathe

"""

__all__ = ["is_square", "gcd", "lcm", "lcm_n", "nCr", "nPr", "digital_sum",
           "digital_root","Divisors"]

from .prime_numbers import primes

def is_square(num):
    """Determines if a positive integer *num* is the perfect square.

    :param num: Integer to be checked
    :returns: A tuple (is_square,root)

    .. note::

       * *is_square* is *True* if *num* is a perfect square.
       * The integer *root* <= (square root of *num*).

    Uses `Digit-by-digit algorithm
    <http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Digit-by-
    digit_calculation>`_ in base 10.
    """
    if(num == 0):
        pn = 0
        rn = 1
    else:
        z = num
        test = []
        while(z !=0):
            test.append(z%100)
            z = z//100
        test.reverse()
        pn = 0
        rn = 0
        for i in range(len(test)):
            #get an estimate of xn
            c = 100*rn + test[i]
            xn = 1
            while ((20*pn+xn)*xn <= c):
                xn += 1
            xn -= 1
            rn = c - (20*pn+xn)*xn
            pn = pn*10 + xn
    if(rn == 0):
        return (True,pn)
    else:
        return (False,pn)

def gcd(a,b):
    """Calculates Greatest Common Divisor of two integers.

    :param a: First integer
    :param b: Second integer
    :returns: Greatest Common Divisor (GCD) of *a* and *b*

    Uses `Euclid's algorithm
    <http://en.wikipedia.org/wiki/Greatest_common_divisor#
    Using_Euclid.27s_algorithm>`_.
    """
    if(a==b): return a
    if(a== 0): return b
    if(b== 0): return a
    if(a==1 or b==1): return 1
    if(a>b):
        big, small = a, b
    else:
        big, small = b, a
    r = big%small
    while(r != 0):
        big = small
        small = r
        r = big%small
    return small

def lcm(a,b):
    """Calculates the `Least Common Multiple
    <http://en.wikipedia.org/wiki/Least_common_multiple>`_ (LCM) of two
    integers.

    :param a: First integer
    :param b: Second integer
    :returns: Least Common Multiple (LCM) of *a* and *b*
    """
    lcm_ab = 0
    if a!=0 or b!=0:
        lcm_ab = abs(a*b)/gcd(a,b)
    return lcm_ab

def lcm_n(num_list):
    """Calculate the `Least Common Multiple`_ of a list of
    integers.

    :param num_list: A list of integers *[i1,i2,i3,...,in]*
    :returns: LCM of the integers in *num_list*

    Uses the associative property LCM(a,b,c) = LCM(*LCM(a,b)*,c)
    """
    result = 0
    lennum = len(num_list)
    if not (lennum <=1 or sum(num_list) == 0):
        cindex = 1
        while cindex < lennum:
            if cindex == 1:
                curr_lcm = lcm(num_list[cindex-1],num_list[cindex])
            else:
                curr_lcm = lcm(curr_lcm,num_list[cindex])
            cindex += 1
        result = curr_lcm
    return result

def nCr(n,r):
    """Calculate ways of selecting *r* members out of a collection of *n*
    members.

    :param n: Size of the collection
    :param r: Number of members to be selected from the collection
    :returns: n!/[r!(n-r)!]

    .. note::

        :sup:`n` C :sub:`r` is typically read as *n combination r*. Order of
        members *is not* important in the combination. E.g. There are :sup:`4`
        C :sub:`2` = 6 ways of selecting two members out of a collection
        (A, B, C, D) => AB, AC, AD, BC, BD, CD.
    """
    result = 0
    if n >= 0 and r >= 0 and r <= n:
        num = 1
        denom = 1
        for i in range(r):
            num *= (n-i)
            denom *= (i+1)
        result = num/denom
    return result

def nPr(n,r):
    """Calculate number of permutations of length *r* out of a collection of
    *n* members (No repeated members).

    :param n: Size of the collection
    :param r: Number of members to be permutated.
    :returns: n!/[(n-r)!]

    .. note::

        :sup:`n` P :sub:`r` is typically read as *n permutation r*. Order of
        members *is* important in the permutation. E.g. There are :sup:`4` P
        :sub:`2` = 12 permutations of length 2 out of a collection
        (A, B, C, D) => AB, AC, AD, BA, BC, BD, CA, CB, CD, DA, DB, DC.
    """
    result = 0
    if n >= 0 and r >= 0 and r <= n:
        num = 1
        denom = 1
        for i in range(r):
            num *= (n-i)
        result = num/denom
    return result

def digital_sum(num):
    """Calculate the `digital sum <http://en.wikipedia.org/wiki/Digit_sum>`_
    of a number *num* in base 10

    :param num: Number for which digital sum is to be calculated. *num* should
                be in base 10.
    :returns: Digital sum of *num* in base 10.
    """
    from .etc import num_to_list
    testnum = num
    if num < 0:
        testnum = abs(num)
    return sum(num_to_list(testnum))

def digital_root(num):
    """Calculate the `digital root
    <http://en.wikipedia.org/wiki/Digital_root>`_ of a number *num* in base 10.

    :param num: Number for which digital root is to be calculated. *num*
                should be in base 10.
    :returns: Digital root of *num* in base 10.
    """
    testnum = num
    if num < 0:
        testnum = abs(num)
    while testnum > 9:
        testnum = digital_sum(testnum)
    return testnum

class Divisors:
    """Implements methods related to prime factors and divisors.

    :param maxnum: Upper limit for the list of primes. (default = 1000)
    """

    def __init__(self,maxnum=1000):
        """Constructor for *Divisors* class
        """
        self.limit = maxnum
        self.primes_table = primes(maxnum)
        self.sigma_table = {}
        self.primefact_table = {}
        self.pfactonly_table = {}
        self.divisors_table = {}

    def sigma_function(self,num):
        """Calculates the `divisor functions
        <http://en.wikipedia.org/wiki/Divisor_function>`_ (sigma functions).

        :param num: Integer for which sigma functions are needed.
        :returns: A tuple (sigma0,sigma1,s(n))

        .. note::

            * sigma0 = number of divisors of *num*.
            * sigma1 = sum of *all* divisors of *num*
            * s(n) = sum of *proper* divisors of *num*
              (includes 1, excludes *num*)

        """
        if num in self.sigma_table:
            return self.sigma_table[num]
        elif ((num < 1) or (num > self.limit)):
            return ()
        elif num == 1:
            return (1,1,0)
        elif (num in self.primes_table):
            return (2,num+1,1)
        else:
            sigma0 = 1
            sigma1 = 1
            #Implement divisor fucntion
            pfs = self.prime_factors(num)
            for (pi,ai) in pfs:
                sigma0 = sigma0*(ai+1)
                temp = 0
                for i in range(ai+1):
                    temp = temp + pi**i
                sigma1 = sigma1*temp
            result = (sigma0,sigma1,sigma1-num)
            self.sigma_table[num] = result
            return result

    def prime_factors(self,num):
        """Returns the `prime factors`_ *pf* :sub:`i` of *num* and the maximum
        power *a* :sub:`i` for each prime factor *pf* :sub:`i`.

        :param num: An integer for which prime factors are needed
        :returns: A list of tuples [(pf1,a1),...(pfi,ai)]

        .. note::

            num = (pf1**a1)*(pf2**a2)..*(pfi**ai)
        """
        if num in self.primefact_table:
            return self.primefact_table[num]
        elif ((num < 2) or (num > self.limit)):
            return []
        elif num in self.primes_table:
            self.primefact_table[num] = [(num,1)]
            return [(num,1)]
        else:
            result = []
            tnum = num
            for prime in self.primes_table:
                if(tnum%prime==0):
                    ai = 2
                    pdiv = prime*prime
                    while(tnum%pdiv==0):
                        ai += 1
                        pdiv *= prime
                    ai -= 1
                    pdiv //= prime
                    result.append((prime,ai))
                    tnum //= pdiv
                    if(tnum in self.primes_table):
                        result.append((tnum,1))
                        break
                    elif(tnum==1):
                        break
            self.primefact_table[num] = result
            return result

    def prime_factors_only(self,num):
        """Returns the `prime factors
        <http://en.wikipedia.org/wiki/Prime_factor>`_ *pf* :sub:`i` of *num*.

        :param num: An integer for which prime factors are needed
        :returns: A list [pf1,pf2,...pfi] of prime factors of *num*
        """
        if num in self.pfactonly_table:
            return self.pfactonly_table[num]
        elif ((num < 2) or (num > self.limit)):
            return []
        elif num in self.primes_table:
            self.pfactonly_table[num] = [num]
            return [num]
        else:
            result = []
            tnum = num
            for prime in self.primes_table:
                if(tnum%prime==0):
                    result.append(prime)
                    pdiv = prime*prime
                    while(tnum%pdiv == 0):
                        pdiv *= prime
                    pdiv //= prime
                    tnum //= pdiv
                    if(tnum in self.primes_table):
                        result.append(tnum)
                        break
                    elif(tnum == 1):
                        break
            self.pfactonly_table[num] = result
            return result

    def divisors(self,num):
        """Returns a list of ALL divisors of *num* (including 1 and num).

        :param num: An integer for which divisors are needed.
        :returns: A list [d1,d2,...dn] of divisors of *num*
        """
        result = []
        if (num < 1) or (num > self.limit):
            return result
        result.append(1)
        if (num == 1):
            return result
        elif (num in self.primes_table):
            result.append(num)
            self.divisors_table[num] = result
            return result
        else:
            pfs = self.prime_factors(num)
            for (pi,ai) in pfs:
                newdivs = []
                for i in range(ai):
                    fact = pi**(i+1)
                    for div in result:
                        newdivs.append(div*fact)
                result += newdivs
                newdivs = []
            result.sort()
            self.divisors_table[num] = result
            return result

    def phi(self,num):
        """Returns the number of `totatives
        <http://en.wikipedia.org/wiki/Totative>`_ of *num*

        :param num: Integer for which number of totatives are needed.
        :returns: Number of totatives of *num*

        .. note::

            A totative of an integer *num* is any integer *i* such that,
            0 < i < n and *GCD(i,num) == 1*.

        Uses `Euler's totient function
        <http://en.wikipedia.org/wiki/Euler%27s_totient_function>`_.
        """
        if(num < 1):
            return 0
        if(num == 1):
            return 1
        if(num in self.primes_table):
            return num-1
        pfs = self.prime_factors_only(num)
        prod = num
        for pfi in pfs:
            prod = prod*(pfi-1)/pfi
        return prod


text:
package org.jbpm.console.ng.gc.client.util;

import java.util.Date;

import com.github.gwtbootstrap.client.ui.Button;
import com.github.gwtbootstrap.client.ui.ButtonGroup;
import com.github.gwtbootstrap.client.ui.NavLink;
import com.github.gwtbootstrap.client.ui.base.IconAnchor;
import com.github.gwtbootstrap.client.ui.base.UnorderedList;
import com.github.gwtbootstrap.client.ui.constants.IconSize;
import com.github.gwtbootstrap.client.ui.constants.IconType;
import com.github.gwtbootstrap.client.ui.resources.ButtonSize;
import com.github.gwtbootstrap.datepicker.client.ui.DateBox;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.HasValueChangeHandlers;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.datepicker.client.CalendarUtil;
import org.jbpm.console.ng.ga.model.CalendarListContainer;
import org.jbpm.console.ng.gc.client.i18n.Constants;
import org.jbpm.console.ng.gc.client.util.TaskUtils.TaskView;

/**
 * Encapsulates set of components which are able to select day/week/month.
 * Contains also buttons for going to previous or next day/week/month.
 */
public class LiCalendarPicker extends Composite implements HasValueChangeHandlers<Date> {

    private Constants constants = GWT.create(Constants.class);

    public enum ViewType {

        DAY, WEEK, MONTH, GRID;
    }

    private Date currentDate;
    private ViewType viewType;

    private NavLink calendarLink;

    private IconAnchor calendarIcon;

    public NavLink dayViewTasksNavLink;

    public NavLink weekViewTasksNavLink;

    public NavLink monthViewTasksNavLink;

    public NavLink buttonGroupLi;

    public ButtonGroup buttonGroup;

    private UnorderedList ul;

    private Button previousButton;

    private Button nextButton;

    private Button todayButton;

    private CalendarListContainer listContainer;

    public LiCalendarPicker() {
        ul = new UnorderedList();
        currentDate = new Date();
        viewType = ViewType.DAY;
        initWidget(ul);
    }

    public void init() {
        calendarLink = new NavLink();
        dayViewTasksNavLink = new NavLink();
        weekViewTasksNavLink = new NavLink();
        monthViewTasksNavLink = new NavLink();

        previousButton = new Button();
        previousButton.setSize(ButtonSize.SMALL);
        nextButton = new Button();
        nextButton.setSize(ButtonSize.SMALL);
        todayButton = new Button();
        todayButton.setSize(ButtonSize.SMALL);
        buttonGroup = new ButtonGroup();
        buttonGroupLi = new NavLink();

        ul.add(calendarLink);

        initPrevNextTodayButtons();

        ul.add(buttonGroupLi);

        NavLink dividerNavLink1 = new NavLink();
        dividerNavLink1.setStyleName("divider-vertical");
        dividerNavLink1.remove(dividerNavLink1.getAnchor());
        ul.add(dividerNavLink1);

        ul.add(dayViewTasksNavLink);

        ul.add(weekViewTasksNavLink);

        ul.add(monthViewTasksNavLink);
        NavLink dividerNavLink2 = new NavLink();
        dividerNavLink2.setStyleName("divider-vertical");
        dividerNavLink2.remove(dividerNavLink1.getAnchor());
        ul.add(dividerNavLink2);

        dayViewTasksNavLink.setStyleName("");
        weekViewTasksNavLink.setStyleName("");
        monthViewTasksNavLink.setStyleName("");
        dayViewTasksNavLink.setText(constants.Day());
        dayViewTasksNavLink.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                listContainer.setDayView();
            }

        });

        weekViewTasksNavLink.setText(constants.Week());
        weekViewTasksNavLink.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                listContainer.setWeekView();

            }
        });

        monthViewTasksNavLink.setText(constants.Month());
        monthViewTasksNavLink.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                listContainer.setMonthView();

            }
        });

        calendarIcon = new IconAnchor();
        calendarLink.add(calendarIcon);

        initCalendarIcon();
        updateCalendarLabelText();
    }

    public void clear() {
        ul.clear();
    }

    public CalendarListContainer getListContainer() {
        return listContainer;
    }

    public void setListContainer(CalendarListContainer listContainer) {
        this.listContainer = listContainer;
    }

    private void initPrevNextTodayButtons() {
        previousButton.setIcon(IconType.CARET_LEFT);
        previousButton.setTitle( Constants.INSTANCE.Previous() );
        previousButton.setIconSize( IconSize.SMALL );
        previousButton.addClickHandler( new ClickHandler() {
            @Override
            public void onClick( ClickEvent event ) {
                adjustDate( true );
                updateTodayButtonEnabled();
            }
        } );
        nextButton.setIcon( IconType.CARET_RIGHT );
        nextButton.setTitle( Constants.INSTANCE.Next() );
        nextButton.setIconSize(IconSize.SMALL);
        nextButton.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                adjustDate(false);
                updateTodayButtonEnabled();
            }
        });
        todayButton.setText(constants.Today());
        todayButton.setEnabled(false);
        todayButton.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                setCurrentDate(new Date());
                propagateDateChanges();
                updateTodayButtonEnabled();
            }
        });

        buttonGroup.add(previousButton);
        buttonGroup.add(todayButton);
        buttonGroup.add(nextButton);
        buttonGroupLi.remove(buttonGroupLi.getAnchor());
        buttonGroupLi.addWidget(buttonGroup);

    }

    public void setCalendarView(TaskView taskView) {
        dayViewTasksNavLink.setStyleName("");
        weekViewTasksNavLink.setStyleName("");
        monthViewTasksNavLink.setStyleName("");
        setViewType(taskView.name().toLowerCase());
        switch (taskView) {
        case DAY:
            dayViewTasksNavLink.setStyleName("active");
            break;
        case WEEK:
            weekViewTasksNavLink.setStyleName("active");
            break;
        case MONTH:
            monthViewTasksNavLink.setStyleName("active");
            updateTodayButtonEnabled();
            break;
        default:
            throw new IllegalStateException("Unrecognized view type '" + taskView + "'!");
        }
    }

    public String getViewType() {
        return viewType.toString();
    }

    public void setViewType(String viewType) {
        this.viewType = ViewType.valueOf(viewType.toUpperCase());
        updateTodayButtonEnabled();
        updateCalendarLabelText();
    }

    public Date getCurrentDate() {
        return currentDate;
    }

    public void setCurrentDate(Date currentDate) {
        this.currentDate = currentDate;
    }

    /**
     * Adjust the date (back or to future) based on current view type
     * (day/week/month).
     *
     * @param back
     *            flag that indicates if the date should be adjusted to future
     *            (+) or back (-)
     */
    public void adjustDate(boolean back) {
        switch (viewType) {
        case DAY:
            if (back) {
                CalendarUtil.addDaysToDate(currentDate, -1);
            } else {
                CalendarUtil.addDaysToDate(currentDate, 1);
            }
            break;

        case WEEK:
            if (back) {
                CalendarUtil.addDaysToDate(currentDate, -7);
            } else {
                CalendarUtil.addDaysToDate(currentDate, 7);
            }

            break;

        case MONTH:
            if (back) {
                currentDate = DateUtils.getSameOrClosestDateInPreviousMonth(currentDate);
            } else {
                currentDate = DateUtils.getSameOrClosestDateInNextMonth(currentDate);
            }

            break;
        case GRID:
            // no date change needed
            break;

        }
        propagateDateChanges();
    }

    public void propagateDateChanges() {
        updateCalendarLabelText();
        ValueChangeEvent.fire(this, currentDate);
    }

    /**
     * Updates the label text based on current view type and current date.
     *

     * Examples for day, week and month:
     *

     *
day view: 2013-05-02
     *
week view: May 06 - May 12 2013
     *
month view: May 2013
     *

     */
    private void updateCalendarLabelText() {
        switch (viewType) {
        case DAY: {
            calendarLink.setVisible(true);
            DateTimeFormat fmt = DateTimeFormat.getFormat("EEE, dd MMMM");
            calendarLink.setText(fmt.format(currentDate));
            break;
        }
        case WEEK: {
            calendarLink.setVisible(true);
            DateTimeFormat fmt = DateTimeFormat.getFormat("dd MMM");
            DateRange weekRange = DateUtils.getWeekDateRange(currentDate);
            String text = fmt.format(weekRange.getStartDate());
            text = text + " - " + fmt.format(weekRange.getEndDate());
            calendarLink.setText(text);
            break;
        }
        case MONTH: {
            calendarLink.setVisible(true);
            DateTimeFormat fmt = DateTimeFormat.getFormat("MMMM yy");
            calendarLink.setText(fmt.format(currentDate));
            break;
        }
        case GRID:
            calendarLink.setVisible(false);
            break;

        default:
            throw new IllegalStateException("Unrecognized view type " + viewType);
        }
    }

    /**
     * Registers handler that is called when the current date value changes.
     */
    @Override
    public HandlerRegistration addValueChangeHandler(final ValueChangeHandler<Date> handler) {
        return addHandler(handler, ValueChangeEvent.getType());
    }

    private void initCalendarIcon() {
        calendarIcon.setIcon(IconType.CALENDAR);
        calendarIcon.setTitle( Constants.INSTANCE.Select_Date() );
        calendarIcon.setIconSize(IconSize.SMALL);
        calendarIcon.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                DateBox dateBox = new DateBox();
                dateBox.setAutoClose(true);
                dateBox.setValue(currentDate, false);
                dateBox.addValueChangeHandler(new ValueChangeHandler<Date>() {
                    @Override
                    public void onValueChange(ValueChangeEvent<Date> event) {
                        currentDate = event.getValue();
                        propagateDateChanges();
                        updateTodayButtonEnabled();
                    }
                });
                calendarLink.add(dateBox);
                dateBox.show();
                dateBox.removeFromParent();
            }
        });
    }

    /**
     * Determines if 'today' is within the currently displayed date range (e.g.
     * week or month). If it is, the 'Today' button is disabled, otherwise its
     * enabled.
     *

     * Clicking on "Today" button when current day (today) is already displayed
     * is useless, so its better to disable the button.
     */
    private void updateTodayButtonEnabled() {
        boolean todayBtnEnabled = true;
        Date today = new Date();

        switch (viewType) {
        case DAY:
            if (DateUtils.areDatesEqual(today, currentDate)) {
                todayBtnEnabled = false;
            }
            break;

        case WEEK:
            DateRange weekRange = DateUtils.getWeekDateRange(currentDate);
            if (DateUtils.isDateInRange(today, weekRange)) {
                todayBtnEnabled = false;
            }
            break;

        case MONTH:
            DateRange monthRange = DateUtils.getMonthDateRange(currentDate);
            if (DateUtils.isDateInRange(today, monthRange)) {
                todayBtnEnabled = false;
            }
            break;
        case GRID:
            todayBtnEnabled = false;
            break;
        default:
            throw new IllegalStateException("Unrecognized calendar view type: " + viewType);
        }
        todayButton.setEnabled(todayBtnEnabled);
    }

}

redpajama_set_name: RedPajamaGithub


text: Ejemplo de como usar mvp


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using ThinkingHome.Core.Plugins;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;

namespace ThinkingHome.Core.Infrastructure
{
    public class ServiceContext : IServiceContext
    {
        private readonly Dictionary<Type, PluginBase> plugins;

        public ServiceContext(
            IEnumerable<PluginBase> loadedPlugins,
            IConfigurationSection configuration,
            ILoggerFactory loggerFactory,
            IStringLocalizerFactory localizerFactory)
        {
            plugins = loadedPlugins.ToDictionary(p => p.GetType());

            foreach (var plugin in plugins.Values)
            {
                var type = plugin.GetType();

                plugin.Context = this;
                plugin.Logger = loggerFactory.CreateLogger(type);
                plugin.Configuration = configuration.GetSection(type.FullName);
                plugin.StringLocalizer = localizerFactory.Create(type);
            }
        }

        public IReadOnlyCollection<PluginBase> GetAllPlugins(PluginsOrder order = PluginsOrder.Direct)
        {
            var sortedValues = order == PluginsOrder.Direct
                ? plugins.Values.OrderBy(p => p.DependencyIndex)
                : plugins.Values.OrderByDescending(p => p.DependencyIndex);

            return new ReadOnlyCollection<PluginBase>(sortedValues.ToList());
        }
    }
}


text:
(function () {
  'use strict';

  angular
    .module('starter',
            ['ionic',
             'campusmap',
             'dashboard',
             'busroutes',
             'dining',
             'notes',
             'quickLinks',
			 'sports',
             'about',
             'campusEvents',
             'gpa',
             'wirelessReport',
             '720kb.tooltips'
           ]);

  //instantiate submodules here
  angular
    .module('dashboard', []);

  angular
    .module('campusmap', ['leaflet-directive','swipe']);

  angular
    .module('busroutes', ['leaflet-directive', 'swipe']);

  angular
    .module('dining', ['leaflet-directive', 'swipe']);

  angular
    .module('notes', ['leaflet-directive', 'swipe']);

  angular
    .module('quickLinks', ['leaflet-directive', 'swipe']);

  angular
    .module('sports', ['leaflet-directive', 'swipe']);

  angular
    .module('about', ['leaflet-directive', 'swipe']);

  angular
    .module('campusEvents', ['leaflet-directive', 'swipe']);

  angular
    .module('gpa', ['leaflet-directive', 'swipe']);

  angular
    .module('wirelessReport', ['leaflet-directive', 'swipe']);

})();


text:
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;

namespace SignalR.Infrastructure
{
    internal class SafeSet<T>
    {
        private readonly ConcurrentDictionary<T, object> _items;

        public SafeSet()
        {
            _items = new ConcurrentDictionary<T, object>();
        }

        public SafeSet(IEqualityComparer<T> comparer)
        {
            _items = new ConcurrentDictionary<T, object>(comparer);
        }

        public SafeSet(IEnumerable<T> items)
        {
            _items = new ConcurrentDictionary<T, object>(items.Select(x => new KeyValuePair<T, object>(x, null)));
        }

        public ICollection<T> GetSnapshot()
        {
            // The Keys property locks, so Select instead
            return _items.Keys;
        }

        public void Add(T item)
        {
            _items.TryAdd(item, null);
        }

        public bool Remove(T item)
        {
            object _;
            return _items.TryRemove(item, out _);
        }

        public bool Any()
        {
            return _items.Any();
        }

        public long Count
        {
            get { return _items.Count; }
        }
    }
}


text:
@class Protocol;

@protocol Prot
@end

struct FooS {
  int x;
};

void foo() {
  Protocol *p = @protocol(Prot);
  @encode(struct FooS);
}

@interface I
+(void)clsMeth;
@end

void foo2() {
  [I clsMeth];
}

// RUN: c-index-test -index-file %s | FileCheck %s
// CHECK: [indexEntityReference]: kind: objc-protocol | name: Prot | {{.*}} | loc: 12:27
// CHECK: [indexEntityReference]: kind: struct | name: FooS | {{.*}} | loc: 13:18
// CHECK: [indexEntityReference]: kind: objc-class | name: I | {{.*}} | loc: 21:4


text:
/* This file was generated by upbc (the upb compiler) from the input
 * file:
 *
 *     envoy/config/cluster/v3/outlier_detection.proto
 *
 * Do not edit -- your changes will be discarded when the file is
 * regenerated. */

#ifndef ENVOY_CONFIG_CLUSTER_V3_OUTLIER_DETECTION_PROTO_UPBDEFS_H_
#define ENVOY_CONFIG_CLUSTER_V3_OUTLIER_DETECTION_PROTO_UPBDEFS_H_

#include "upb/def.h"
#include "upb/port_def.inc"
#ifdef __cplusplus
extern "C" {
#endif

#include "upb/def.h"

#include "upb/port_def.inc"

extern _upb_DefPool_Init envoy_config_cluster_v3_outlier_detection_proto_upbdefinit;

UPB_INLINE const upb_MessageDef *envoy_config_cluster_v3_OutlierDetection_getmsgdef(upb_DefPool *s) {
  _upb_DefPool_LoadDefInit(s, &envoy_config_cluster_v3_outlier_detection_proto_upbdefinit);
  return upb_DefPool_FindMessageByName(s, "envoy.config.cluster.v3.OutlierDetection");
}

#ifdef __cplusplus
}  /* extern "C" */
#endif

#include "upb/port_undef.inc"

#endif  /* ENVOY_CONFIG_CLUSTER_V3_OUTLIER_DETECTION_PROTO_UPBDEFS_H_ */


text:
package main

import (
	"fmt"
	"os"
	"os/user"

	"github.com/PagerDuty/chef-search-stresser/stresser"
	"github.com/jessevdk/go-flags"
)

type binArgs struct {
	Queries     []string `short:"q" long:"query" description:"set some queries to run for testing. Defaults to ['roles:*' 'name:*']. One flag for each query"`
	Concurrency uint     `short:"c" long:"concurrency" default:"1" description:"set the number of concurrent searches to run"`
	Partial     bool     `short:"p" long:"partial" default:"false" description:"run partial search"`
	Full        bool     `short:"f" long:"full" default:"false" description:"run full search"`
	PemFile     string   `short:"k" long:"client-key" description:"path to the client.pem file" default:"/etc/chef/client.pem"`
	ChefServer  string   `short:"S" long:"server" description:"specify which Chef server to use"`
	ClientName  string   `short:"N" long:"name" description:"name of the client being used"`
	PrintErr    bool     `short:"E" long:"print-errors" default:"false" description:"print out errors that occured"`
	DisableSeed bool     `long:"disable-seed" default:"false" description:"by default, we seed the random number generator to help with better randomization of the queries ran"`
}

func (a *binArgs) parse(args []string) (string, error) {
	if args == nil {
		args = os.Args
	}

	p := flags.NewParser(a, flags.HelpFlag|flags.PassDoubleDash)

	_, err := p.ParseArgs(args[1:])

	// determine if there was a parsing error
	// unfortunately, help message is returned as an error
	if err != nil {
		// determine whether this was a help message by doing a type
		// assertion of err to *flags.Error and check the error type
		// if it was a help message, do not return an error
		if errType, ok := err.(*flags.Error); ok {
			if errType.Type == flags.ErrHelp {
				return err.Error(), nil
			}
		}

		return "", err
	}

	if a.Partial && a.Full {
		return "", fmt.Errorf("unable to run both full and partial search tests at the same time")
	}

	if !a.Partial && !a.Full {
		return "", fmt.Errorf("need to choose one mode of operation: --partial or --full; see --help for more details")
	}

	if a.ClientName == "" {
		curUser, err := user.Current()

		if err != nil {
			return "", fmt.Errorf("error getting user: %s", err.Error())
		}

		a.ClientName = curUser.Username
	}

	if len(a.Queries) == 0 {
		a.Queries = stresser.DefaultQueries
	}

	return "", err
}


text:
namespace cv {
namespace gapi {
namespace wip {
namespace onevpl {

class GAPI_EXPORTS SharedLock {
public:
    SharedLock();
    ~SharedLock() = default;

    size_t shared_lock();
    size_t unlock_shared();

    void lock();
    bool try_lock();
    void unlock();

    bool owns() const;
private:
    SharedLock(const SharedLock&) = delete;
    SharedLock& operator= (const SharedLock&) = delete;
    SharedLock(SharedLock&&) = delete;
    SharedLock& operator== (SharedLock&&) = delete;

    std::atomic<bool> exclusive_lock;
    std::atomic<size_t> shared_counter;
};
} // namespace onevpl
} // namespace wip
} // namespace gapi
} // namespace cv

#endif // GAPI_STREAMING_ONEVPL_ACCELERATORS_SURFACE_SHARED_LOCK_HPP


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace System.Windows.Data
{
  public partial class CollectionContainer : System.Windows.DependencyObject, System.Collections.Specialized.INotifyCollectionChanged, System.Windows.IWeakEventListener
  {
    #region Methods and constructors
    public CollectionContainer()
    {
    }

    protected virtual new void OnContainedCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs args)
    {
      Contract.Requires(args != null);
    }

    protected virtual new bool ReceiveWeakEvent(Type managerType, Object sender, EventArgs e)
    {
      Contract.Requires(e != null);
      return default(bool);
    }

    public bool ShouldSerializeCollection()
    {
      return default(bool);
    }

    bool System.Windows.IWeakEventListener.ReceiveWeakEvent(Type managerType, Object sender, EventArgs e)
    {
      return default(bool);
    }
    #endregion

    #region Properties and indexers
    public System.Collections.IEnumerable Collection
    {
      get
      {
        return default(System.Collections.IEnumerable);
      }
      set
      {
      }
    }
    #endregion

    #region Events
    protected virtual new event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged
    {
      add
      {
      }
      remove
      {
      }
    }

    event System.Collections.Specialized.NotifyCollectionChangedEventHandler System.Collections.Specialized.INotifyCollectionChanged.CollectionChanged
    {
      add
      {
      }
      remove
      {
      }
    }
    #endregion

    #region Fields
    public readonly static System.Windows.DependencyProperty CollectionProperty;
    #endregion
  }
}


text:
<?php

namespace AppBundle\Admin\GestionService;

use AppBundle\Entity\Projet;
use UserBundle\Entity\Travailleur;
use UserBundle\Entity\Utilisateur;
use Doctrine\ORM\EntityRepository;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\CoreBundle\Form\Type\BooleanType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;

class SolliciterAdmin extends AbstractAdmin
{
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->tab('Solliciter un travailleur', array('class' => 'row'))
                ->with('Général', array('class' => 'col-md-6'))
                    ->add('utilisateur', EntityType::class, array(
                        'class' => Utilisateur::class,
                        'multiple' => false,
                        'query_builder' => function (EntityRepository $er) {
                            return $er->createQueryBuilder('u')
                                ->orderBy('u.username', 'ASC');
                        },
                        'choice_label' => 'username',
                    ))
                    ->add('travailleur', 'sonata_type_model', array(
                        'class' => Travailleur::class,
                        'multiple' => false,
                        'property' => 'username',
                    ))
                ->end()
                ->with(null, array('class' => 'col-md-6'))
                    ->add('valide', BooleanType::class, array(
                        'required' => true,
                    ))
                ->end()
            ->end()
        ;
    }

    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add('date')
            ->add('valide')
            ->add('utilisateur')
            ->add('travailleur');
    }

    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier('utilisateur', null, array(
                'associated_property' => 'username'
            ))
            ->addIdentifier('travailleur', null, array(
                'associated_property' => 'username'
            ))
            ->addIdentifier('date')
            ->addIdentifier('valide', null, array(
                'editable' => true
            ))
            ->add('_action', null, array(
                'actions' => array(
                    'show' => array(),
                    'edit' => array(),
                    'delete' => array(),
                )
            ));
    }

    protected function configureShownFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier('date')
            ->addIdentifier('valide')
            ->addIdentifier('utilisateur')
            ->addIdentifier('travailleur');
    }

    public function toString($object)
    {
        return $object instanceof \AppBundle\Entity\Solliciter
            ? $object->getUtilisateur()->getUsername() .' | '. $object->getTravailleur()->getUsername() .' | '. $object->getDate()->format('Y-M-d')
            : 'Project';
    }
}


text:
import * as React from 'react'
import {TileLink} from './tile-link'
import Paper from '@material-ui/core/Paper'
import Typography from '@material-ui/core/Typography'
import classes from './tile.pcss'

export interface ITileProps {
  /** Title of the tile */
  title: string
  /** Icon for the title, in React element format */
  icon: React.ReactNode
  /** Path of the link for this tile links to */
  to?: string
  /** `true` for external (not in the scope of this app) link */
  external?: boolean
  /** Same functionality as HTML anchor element's `target` props */
  target?: string
}

/**
 * A tile represents a block on menu
 */
export class Tile extends React.Component<ITileProps> {
  public render() {
    const {title, icon, external, target} = this.props
    const to = this.props.to || '/'

    return (
      <TileLink to={to} external={external} target={target}>
        <Paper className={classes.tile} elevation={4}>

{icon}

          <Typography className={classes.titleContainer} variant="title">{title}</Typography>
        </Paper>
      </TileLink>
    )
  }
}


text:
(function(){
	//this service will be used to use ANY RESt API.
	"use strict";
	angular.module('dcbiApp.data').service('queryService', queryService);

	queryService.$inject = ['$http', 'dataService', 'MUTATION', 'CCN', 'BOTH'];
	function queryService($http, dataService, MUTATION, CCN, BOTH)
	{
		var that = this;//storing this because refernce to 'this' is lost during a promise
		that.dataService = dataService;

		//creates the config required for making a web service request
		that.createRequest = function(gene,type)
		{
			if(gene.indexOf(' ') > 0){
				var re = / /g;
				gene = gene.replace(re,'+');
			}
			var ccnUrl = 'http://www.cbioportal.org/webservice.do?cmd=getProfileData&genetic_profile_id=gbm_tcga_gistic&id_type=gene_symbol&gene_list='+gene+'&case_set_id=gbm_tcga_cnaseq';
			var mutationUrl = 'http://www.cbioportal.org/webservice.do?cmd=getProfileData&genetic_profile_id=gbm_tcga_mutations&id_type=gene_symbol&gene_list='+gene+'&case_set_id=gbm_tcga_cnaseq';
			switch(type)
			{
				case MUTATION:
					that.makeRequest([mutationUrl], type);
					break;
				case CCN:
					that.makeRequest([ccnUrl], type);
					break;
				case BOTH:
					that.makeRequest([mutationUrl, ccnUrl], type);
					break;
			}

		};

		//the actual request(s)
		that.makeRequest = function (urls, type)
		{
			//make the appropriate number of web service calls
			var urlCounter = urls.length;
			for(var i=0; i< urlCounter; i++)
			{
				$http({
					method: 'GET',
					url:urls[i]
				}).then(function successCallback(response) {// this callback will be called asynchronously when the response is available

					that.dataService.parseDataToObject(response.data,type);

				}, function errorCallback(response) {// called asynchronously if an error occurs or server returns response with an error status.
					console.log("error", response);
				});
			}
		}

	}

})();


text:
// This is a non-public, unstable API, but it's very convenient
import { loadProtosWithOptionsSync } from '@grpc/proto-loader/build/src/util';
import { experimental, logVerbosity } from '@grpc/grpc-js';
import { Any__Output } from './generated/google/protobuf/Any';
import Filter = experimental.Filter;
import FilterFactory = experimental.FilterFactory;
import { TypedStruct__Output as TypedStruct__Output } from './generated/xds/type/v3/TypedStruct';
import { FilterConfig__Output } from './generated/envoy/config/route/v3/FilterConfig';
import { HttpFilter__Output } from './generated/envoy/extensions/filters/network/http_connection_manager/v3/HttpFilter';

const TRACER_NAME = 'http_filter';

function trace(text: string): void {
  experimental.trace(logVerbosity.DEBUG, TRACER_NAME, text);
}

const TYPED_STRUCT_UDPA_URL = 'type.googleapis.com/udpa.type.v1.TypedStruct';
const TYPED_STRUCT_UDPA_NAME = 'udpa.type.v1.TypedStruct';
const TYPED_STRUCT_XDS_URL = 'type.googleapis.com/xds.type.v3.TypedStruct';
const TYPED_STRUCT_XDS_NAME = 'xds.type.v3.TypedStruct';

const FILTER_CONFIG_URL = 'type.googleapis.com/envoy.config.route.v3.FilterConfig';
const FILTER_CONFIG_NAME = 'envoy.config.route.v3.FilterConfig';

const resourceRoot = loadProtosWithOptionsSync([
  'udpa/type/v1/typed_struct.proto',
  'xds/type/v3/typed_struct.proto',
  'envoy/config/route/v3/route_components.proto'], {
    keepCase: true,
    includeDirs: [
      // Paths are relative to src/build
      __dirname + '/../../deps/xds/',
      __dirname + '/../../deps/envoy-api/',
      __dirname + '/../../deps/protoc-gen-validate/'
    ],
  }
);

export interface HttpFilterConfig {
  typeUrl: string;
  config: any;
}

export interface HttpFilterFactoryConstructor<FilterType extends Filter> {
  new(config: HttpFilterConfig, overrideConfig?: HttpFilterConfig): FilterFactory<FilterType>;
}

export interface HttpFilterRegistryEntry {
  parseTopLevelFilterConfig(encodedConfig: Any__Output): HttpFilterConfig | null;
  parseOverrideFilterConfig(encodedConfig: Any__Output): HttpFilterConfig | null;
  httpFilterConstructor: HttpFilterFactoryConstructor<Filter>;
}

const FILTER_REGISTRY = new Map<string, HttpFilterRegistryEntry>();

export function registerHttpFilter(typeName: string, entry: HttpFilterRegistryEntry) {
  trace('Registered filter with type URL ' + typeName);
  FILTER_REGISTRY.set(typeName, entry);
}

const toObjectOptions = {
  longs: String,
  enums: String,
  defaults: true,
  oneofs: true
}

function parseAnyMessage<MessageType>(message: Any__Output): MessageType | null {
  const typeName = message.type_url.substring(message.type_url.lastIndexOf('/') + 1);
  const messageType = resourceRoot.lookup(typeName);
  if (messageType) {
    const decodedMessage = (messageType as any).decode(message.value);
    return decodedMessage.$type.toObject(decodedMessage, toObjectOptions) as MessageType;
  } else {
    return null;
  }
}

export function getTopLevelFilterUrl(encodedConfig: Any__Output): string {
  let typeUrl: string;
  if (encodedConfig.type_url === TYPED_STRUCT_UDPA_URL || encodedConfig.type_url === TYPED_STRUCT_XDS_URL) {
    const typedStruct = parseAnyMessage<TypedStruct__Output>(encodedConfig)
    if (typedStruct) {
      return typedStruct.type_url;
    } else {
      throw new Error('Failed to parse TypedStruct');
    }
  } else {
    return encodedConfig.type_url;
  }
}

export function validateTopLevelFilter(httpFilter: HttpFilter__Output): boolean {
  if (!httpFilter.typed_config) {
    trace(httpFilter.name + ' validation failed: typed_config unset');
    return false;
  }
  const encodedConfig = httpFilter.typed_config;
  let typeUrl: string;
  try {
    typeUrl = getTopLevelFilterUrl(encodedConfig);
  } catch (e) {
    trace(httpFilter.name + ' validation failed with error ' + e.message);
    return false;
  }
  const registryEntry = FILTER_REGISTRY.get(typeUrl);
  if (registryEntry) {
    const parsedConfig = registryEntry.parseTopLevelFilterConfig(encodedConfig);
    if (parsedConfig === null) {
      trace(httpFilter.name + ' validation failed: config parsing failed');
    }
    return parsedConfig !== null;
  } else {
    if (httpFilter.is_optional) {
      return true;
    } else {
      trace(httpFilter.name + ' validation failed: filter is not optional and registry does not contain type URL ' + typeUrl);
      return false;
    }
  }
}

export function validateOverrideFilter(encodedConfig: Any__Output): boolean {
  let typeUrl: string;
  let realConfig: Any__Output;
  let isOptional = false;
  if (encodedConfig.type_url === FILTER_CONFIG_URL) {
    const filterConfig = parseAnyMessage<FilterConfig__Output>(encodedConfig);
    if (filterConfig) {
      isOptional = filterConfig.is_optional;
      if (filterConfig.config) {
        realConfig = filterConfig.config;
      } else {
        trace('Override filter validation failed: FilterConfig config field is empty');
        return false;
      }
    } else {
      trace('Override filter validation failed: failed to parse FilterConfig message');
      return false;
    }
  } else {
    realConfig = encodedConfig;
  }
  if (realConfig.type_url === TYPED_STRUCT_UDPA_URL || realConfig.type_url === TYPED_STRUCT_XDS_URL) {
    const typedStruct = parseAnyMessage<TypedStruct__Output>(encodedConfig);
    if (typedStruct) {
      typeUrl = typedStruct.type_url;
    } else {
      trace('Override filter validation failed: failed to parse TypedStruct message');
      return false;
    }
  } else {
    typeUrl = realConfig.type_url;
  }
  const registryEntry = FILTER_REGISTRY.get(typeUrl);
  if (registryEntry) {
    const parsedConfig = registryEntry.parseOverrideFilterConfig(encodedConfig);
    if (parsedConfig === null) {
      trace('Override filter validation failed: config parsing failed. Type URL: ' + typeUrl);
    }
    return parsedConfig !== null;
  } else {
    if (isOptional) {
      return true;
    } else {
      trace('Override filter validation failed: filter is not optional and registry does not contain type URL ' + typeUrl);
      return false;
    }
  }
}

export function parseTopLevelFilterConfig(encodedConfig: Any__Output) {
  let typeUrl: string;
  try {
    typeUrl = getTopLevelFilterUrl(encodedConfig);
  } catch (e) {
    return null;
  }
  const registryEntry = FILTER_REGISTRY.get(typeUrl);
  if (registryEntry) {
    return registryEntry.parseTopLevelFilterConfig(encodedConfig);
  } else {
    // Filter type URL not found in registry
    return null;
  }
}

export function parseOverrideFilterConfig(encodedConfig: Any__Output) {
  let typeUrl: string;
  let realConfig: Any__Output;
  if (encodedConfig.type_url === FILTER_CONFIG_URL) {
    const filterConfig = parseAnyMessage<FilterConfig__Output>(encodedConfig);
    if (filterConfig) {
      if (filterConfig.config) {
        realConfig = filterConfig.config;
      } else {
        return null;
      }
    } else {
      return null;
    }
  } else {
    realConfig = encodedConfig;
  }
  if (realConfig.type_url === TYPED_STRUCT_UDPA_URL || realConfig.type_url === TYPED_STRUCT_XDS_URL) {
    const typedStruct = parseAnyMessage<TypedStruct__Output>(encodedConfig);
    if (typedStruct) {
      typeUrl = typedStruct.type_url;
    } else {
      return null;
    }
  } else {
    typeUrl = realConfig.type_url;
  }
  const registryEntry = FILTER_REGISTRY.get(typeUrl);
  if (registryEntry) {
    return registryEntry.parseOverrideFilterConfig(encodedConfig);
  } else {
    return null;
  }
}

export function createHttpFilter(config: HttpFilterConfig, overrideConfig?: HttpFilterConfig): FilterFactory<Filter> | null {
  const registryEntry = FILTER_REGISTRY.get(config.typeUrl);
  if (registryEntry) {
    return new registryEntry.httpFilterConstructor(config, overrideConfig);
  } else {
    return null;
  }
}


text:
class ShellViewsDelegateAura : public views::DesktopTestViewsDelegate {
 public:
  ShellViewsDelegateAura() : use_transparent_windows_(false) {
  }

  virtual ~ShellViewsDelegateAura() {
    ViewsDelegate::views_delegate = NULL;
  }

  void SetUseTransparentWindows(bool transparent) {
    use_transparent_windows_ = transparent;
  }

  // Overridden from views::TestViewsDelegate:
  virtual bool UseTransparentWindows() const OVERRIDE {
    return use_transparent_windows_;
  }

 private:
  bool use_transparent_windows_;

  DISALLOW_COPY_AND_ASSIGN(ShellViewsDelegateAura);
};

// TODO(beng): This stuff should NOT be in the views namespace!
namespace views {

// Maintain the UI controls and web view for content shell
class ShellWindowDelegateView : public WidgetDelegateView,
                                public TextfieldController,
                                public ButtonListener {
 public:
  enum UIControl {
    BACK_BUTTON,
    FORWARD_BUTTON,
    STOP_BUTTON
  };

  ShellWindowDelegateView(content::Shell* shell)
    : shell_(shell),
      toolbar_view_(new View),
      contents_view_(new View) {
  }
  virtual ~ShellWindowDelegateView() {}

  // Update the state of UI controls
  void SetAddressBarURL(const GURL& url) {
    url_entry_->SetText(ASCIIToUTF16(url.spec()));
  }
  void SetWebContents(content::WebContents* web_contents) {
    contents_view_->SetLayoutManager(new FillLayout());
    web_view_ = new WebView(web_contents->GetBrowserContext());
    web_view_->SetWebContents(web_contents);
    web_contents->Focus();
    contents_view_->AddChildView(web_view_);
    Layout();
  }
  void SetWindowTitle(const string16& title) { title_ = title; }
  void EnableUIControl(UIControl control, bool is_enabled) {
    if (control == BACK_BUTTON) {
      back_button_->SetState(is_enabled ? CustomButton::STATE_NORMAL
          : CustomButton::STATE_DISABLED);
    } else if (control == FORWARD_BUTTON) {
      forward_button_->SetState(is_enabled ? CustomButton::STATE_NORMAL
          : CustomButton::STATE_DISABLED);
    } else if (control == STOP_BUTTON) {
      stop_button_->SetState(is_enabled ? CustomButton::STATE_NORMAL
          : CustomButton::STATE_DISABLED);
    }
  }

 private:
  // Initialize the UI control contained in shell window
  void InitShellWindow() {
    set_background(Background::CreateStandardPanelBackground());

    GridLayout* layout = new GridLayout(this);
    SetLayoutManager(layout);

    ColumnSet* column_set = layout->AddColumnSet(0);
    column_set->AddPaddingColumn(0, 2);
    column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
                          GridLayout::USE_PREF, 0, 0);
    column_set->AddPaddingColumn(0, 2);

    layout->AddPaddingRow(0, 2);

    // Add toolbar buttons and URL text field
    {
      layout->StartRow(0, 0);
      GridLayout* toolbar_layout = new GridLayout(toolbar_view_);
      toolbar_view_->SetLayoutManager(toolbar_layout);

      ColumnSet* toolbar_column_set =
          toolbar_layout->AddColumnSet(0);
      // Back button
      back_button_ = new NativeTextButton(this, ASCIIToUTF16("Back"));
      gfx::Size back_button_size = back_button_->GetPreferredSize();
      toolbar_column_set->AddColumn(GridLayout::CENTER,
                                    GridLayout::CENTER, 0,
                                    GridLayout::FIXED,
                                    back_button_size.width(),
                                    back_button_size.width() / 2);
      // Forward button
      forward_button_ = new NativeTextButton(this, ASCIIToUTF16("Forward"));
      gfx::Size forward_button_size = forward_button_->GetPreferredSize();
      toolbar_column_set->AddColumn(GridLayout::CENTER,
                                    GridLayout::CENTER, 0,
                                    GridLayout::FIXED,
                                    forward_button_size.width(),
                                    forward_button_size.width() / 2);
      // Refresh button
      refresh_button_ = new NativeTextButton(this, ASCIIToUTF16("Refresh"));
      gfx::Size refresh_button_size = refresh_button_->GetPreferredSize();
      toolbar_column_set->AddColumn(GridLayout::CENTER,
                                    GridLayout::CENTER, 0,
                                    GridLayout::FIXED,
                                    refresh_button_size.width(),
                                    refresh_button_size.width() / 2);
      // Stop button
      stop_button_ = new NativeTextButton(this, ASCIIToUTF16("Stop"));
      gfx::Size stop_button_size = stop_button_->GetPreferredSize();
      toolbar_column_set->AddColumn(GridLayout::CENTER,
                                    GridLayout::CENTER, 0,
                                    GridLayout::FIXED,
                                    stop_button_size.width(),
                                    stop_button_size.width() / 2);
      toolbar_column_set->AddPaddingColumn(0, 2);
      // URL entry
      url_entry_ = new Textfield();
      url_entry_->SetController(this);
      toolbar_column_set->AddColumn(GridLayout::FILL,
                                    GridLayout::FILL, 1,
                                    GridLayout::USE_PREF, 0, 0);

      // Fill up the first row
      toolbar_layout->StartRow(0, 0);
      toolbar_layout->AddView(back_button_);
      toolbar_layout->AddView(forward_button_);
      toolbar_layout->AddView(refresh_button_);
      toolbar_layout->AddView(stop_button_);
      toolbar_layout->AddView(url_entry_);

      layout->AddView(toolbar_view_);
    }

    layout->AddPaddingRow(0, 5);

    // Add web contents view as the second row
    {
      layout->StartRow(1, 0);
      layout->AddView(contents_view_);
    }

    layout->AddPaddingRow(0, 5);
  }
  // Overridden from TextfieldController
  virtual void ContentsChanged(Textfield* sender,
                               const string16& new_contents) OVERRIDE {
  }
  virtual bool HandleKeyEvent(Textfield* sender,
                              const ui::KeyEvent& key_event) OVERRIDE {
   if (sender == url_entry_ && key_event.key_code() == ui::VKEY_RETURN) {
     std::string text = UTF16ToUTF8(url_entry_->text());
     GURL url(text);
     if (!url.has_scheme()) {
       url = GURL(std::string("http://") + std::string(text));
       url_entry_->SetText(ASCIIToUTF16(url.spec()));
     }
     shell_->LoadURL(url);
     return true;
   }
   return false;
  }

  // Overridden from ButtonListener
  virtual void ButtonPressed(Button* sender, const ui::Event& event) OVERRIDE {
    if (sender == back_button_)
      shell_->GoBackOrForward(-1);
    else if (sender == forward_button_)
      shell_->GoBackOrForward(1);
    else if (sender == refresh_button_)
      shell_->Reload();
    else if (sender == stop_button_)
      shell_->Stop();
  }

  // Overridden from WidgetDelegateView
  virtual bool CanResize() const OVERRIDE { return true; }
  virtual bool CanMaximize() const OVERRIDE { return true; }
  virtual string16 GetWindowTitle() const OVERRIDE {
    return title_;
  }
  virtual void WindowClosing() OVERRIDE {
    if (shell_) {
      delete shell_;
      shell_ = NULL;
    }
  }
  virtual View* GetContentsView() OVERRIDE { return this; }

  // Overridden from View
  virtual void ViewHierarchyChanged(bool is_add,
                                    View* parent,
                                    View* child) OVERRIDE {
    if (is_add && child == this) {
      InitShellWindow();
    }
  }

 private:
  // Hold a reference of Shell for deleting it when the window is closing
  content::Shell* shell_;

  // Window title
  string16 title_;

  // Toolbar view contains forward/backward/reload button and URL entry
  View* toolbar_view_;
  NativeTextButton* back_button_;
  NativeTextButton* forward_button_;
  NativeTextButton* refresh_button_;
  NativeTextButton* stop_button_;
  Textfield* url_entry_;

  // Contents view contains the web contents view
  View* contents_view_;
  WebView* web_view_;

  DISALLOW_COPY_AND_ASSIGN(ShellWindowDelegateView);
};

}  // namespace views

using views::ShellWindowDelegateView;

namespace content {

aura::client::StackingClient* Shell::stacking_client_ = NULL;
views::ViewsDelegate* Shell::views_delegate_ = NULL;

// static
void Shell::PlatformInitialize() {
#if defined(OS_CHROMEOS)
  chromeos::DBusThreadManager::Initialize();
#endif
#if defined(OS_CHROMEOS)
  stacking_client_ = new content::ShellStackingClientAsh();
  gfx::Screen::SetScreenInstance(
      gfx::SCREEN_TYPE_NATIVE, new aura::TestScreen);
#else
  stacking_client_ = new views::DesktopStackingClient();
  gfx::Screen::SetScreenInstance(
      gfx::SCREEN_TYPE_NATIVE, views::CreateDesktopScreen());
#endif
  aura::client::SetStackingClient(stacking_client_);
  views_delegate_ = new ShellViewsDelegateAura();
}

void Shell::PlatformExit() {
  if (stacking_client_)
    delete stacking_client_;
  if (views_delegate_)
    delete views_delegate_;
#if defined(OS_CHROMEOS)
  chromeos::DBusThreadManager::Shutdown();
#endif
  aura::Env::DeleteInstance();
}

void Shell::PlatformCleanUp() {
}

void Shell::PlatformEnableUIControl(UIControl control, bool is_enabled) {
  ShellWindowDelegateView* delegate_view =
    static_cast<ShellWindowDelegateView*>(window_widget_->widget_delegate());
  if (control == BACK_BUTTON) {
    delegate_view->EnableUIControl(ShellWindowDelegateView::BACK_BUTTON,
        is_enabled);
  } else if (control == FORWARD_BUTTON) {
    delegate_view->EnableUIControl(ShellWindowDelegateView::FORWARD_BUTTON,
        is_enabled);
  } else if (control == STOP_BUTTON) {
    delegate_view->EnableUIControl(ShellWindowDelegateView::STOP_BUTTON,
        is_enabled);
  }
}

void Shell::PlatformSetAddressBarURL(const GURL& url) {
  ShellWindowDelegateView* delegate_view =
    static_cast<ShellWindowDelegateView*>(window_widget_->widget_delegate());
  delegate_view->SetAddressBarURL(url);
}

void Shell::PlatformSetIsLoading(bool loading) {
}

void Shell::PlatformCreateWindow(int width, int height) {
  window_widget_ =
      views::Widget::CreateWindowWithBounds(new ShellWindowDelegateView(this),
               gfx::Rect(0, 0, width, height));
  window_ = window_widget_->GetNativeWindow();
  window_widget_->Show();
}

void Shell::PlatformSetContents() {
  ShellWindowDelegateView* delegate_view =
    static_cast<ShellWindowDelegateView*>(window_widget_->widget_delegate());
  delegate_view->SetWebContents(web_contents_.get());
}

void Shell::PlatformResizeSubViews() {
}

void Shell::Close() {
  window_widget_->Close();
}

void Shell::PlatformSetTitle(const string16& title) {
  ShellWindowDelegateView* delegate_view =
    static_cast<ShellWindowDelegateView*>(window_widget_->widget_delegate());
  delegate_view->SetWindowTitle(title);
  window_widget_->UpdateWindowTitle();
}

}  // namespace content


text:
#ifndef V_VAdaptiveAllocator_Interface
#define V_VAdaptiveAllocator_Interface

/*********************
 *****  Library  *****
 *********************/

#include "V.h"

/************************
 *****  Components  *****
 ************************/

#include "VTransient.h"

/**************************
 *****  Declarations  *****
 **************************/

/*************************
 *****  Definitions  *****
 *************************/

namespace V {
    class V_API VAdaptiveAllocator : public VTransient {
	DECLARE_FAMILY_MEMBERS (VAdaptiveAllocator, VTransient);

    //  Globals
    public:
        static size_t g_sIncrementDelay;
        static size_t g_sIncrementMin;
        static size_t g_sIncrementMax;
        static size_t g_sIncrementMultiplier;

    //  Parameters
    public:
	class V_API Parameters : public VTransient {
	    DECLARE_FAMILY_MEMBERS (Parameters, VTransient);

	//  Construction
	public:
	    Parameters () :
		m_sIncrementDelay	(g_sIncrementDelay),
		m_sIncrementMin		(g_sIncrementMin),
		m_sIncrementMax		(g_sIncrementMax),
		m_sIncrementMultiplier	(g_sIncrementMultiplier)
	    {
	    }

	//  Destruction
	public:
	    ~Parameters () {
	    }

	//  Access
	public:
	    size_t incrementDelay () const {
		return m_sIncrementDelay;
	    }
	    size_t incrementMin () const {
		return m_sIncrementMin;
	    }
	    size_t incrementMax () const {
		return m_sIncrementMax;
	    }
	    size_t incrementMultiplier () const {
		return m_sIncrementMultiplier;
	    }

	//  Update
	public:
	    void setIncrementDelay (size_t iValue) {
		m_sIncrementDelay = iValue;
	    }
	    void setIncrementMin (size_t iValue) {
		m_sIncrementMin = iValue;
	    }
	    void setIncrementMax (size_t iValue) {
		m_sIncrementMax = iValue;
	    }
	    void setIncrementMultiplier (size_t iValue) {
		m_sIncrementMultiplier = iValue;
	    }

	//  State
	private:
	    size_t m_sIncrementDelay;
	    size_t m_sIncrementMin;
	    size_t m_sIncrementMax;
	    size_t m_sIncrementMultiplier;
	};

    //  Construction
    public:
	VAdaptiveAllocator (Parameters *pParameters) {
	    reset (pParameters);
	}
	VAdaptiveAllocator () : m_pParameters (0) {
	    reset ();
	}

    //  Destruction
    public:
	~VAdaptiveAllocator () {
	}

    //  Parameter Access
    public:
        size_t incrementDelay () const {
            return m_pParameters ? m_pParameters->incrementDelay() : g_sIncrementDelay;
        }
        size_t incrementMin () const {
            return m_pParameters ? m_pParameters->incrementMin() : g_sIncrementMin;
        }
        size_t incrementMax () const {
            return m_pParameters ? m_pParameters->incrementMax() : g_sIncrementMax;
        }
        size_t incrementMultiplier () const {
            return m_pParameters ? m_pParameters->incrementMultiplier() : g_sIncrementMultiplier;
        }

    //  Use
    public:
	void reset (Parameters *pParameters) {
	    m_pParameters = pParameters;
	    reset ();
	}
	void reset ();

    //  Use
    public:
	size_t nextSize (size_t sRequired);

    //  State
    private:
	Parameters*	m_pParameters;
	size_t		m_sCurrentIncrement;
	unsigned int	m_sTimeToNextAdaptiveCall;
    };
}

#endif


text:
var TodoController;

TodoController = Ember.ObjectController.extend({
  actions: {
    editTodo: function() {
      return this.set('isEditing', true);
    },
    removeTodo: function() {
      var todo;
      todo = this.get('model');
      todo.deleteRecord();
      return todo.save();
    },
    acceptChanges: function() {
      this.set('isEditing', false);
      if (Ember.isEmpty(this.get('model.title'))) {
        return this.send('removeTodo');
      } else {
        return this.get('model').save();
      }
    }
  },
  isEditing: false,
  isCompleted: (function(key, value) {
    var model;
    model = this.get('model');
    if (value === void 0) {
      return model.get('isCompleted');
    } else {
      model.set('isCompleted', value);
      model.save();
      return value;
    }
  }).property('model.isCompleted')
});

export default TodoController;


text:
extern CGFloat const maxPercentComplete;

@interface GVGameCenterManager : NSObject <GKLeaderboardViewControllerDelegate, GKAchievementViewControllerDelegate>

@property (nonatomic, retain, readonly) NSDictionary *achievementCache;

+ (instancetype)manager;

+ (BOOL)isGameCenterAvailable;

@property (nonatomic, assign, readonly) BOOL authenticated;
- (void)authenticateLocalUserWithCompletionHandler:(void(^)(NSError *error))completionHandler;

#pragma mark - Leader Board

- (void)reportScore:(int64_t)score
        forCategory:(NSString *)category
  completionHandler:(void(^)(GKScore *scope, NSError *error))completionHandler;
- (void)reloadHighScoresForCategory:(NSString *)category
                  completionHandler:(void(^)(GKLeaderboard *leaderBoard, NSError *error))completionHandler;

- (void)showLeaderboardWithCatagory:(NSString *)category
                          timeScope:(GKLeaderboardTimeScope)timeScope
                   InViewController:(UIViewController *)viewController
                  completionHandler:(void(^)())completionHandler;

#pragma mark - achievement

- (void)submitAchievement:(NSString *)identifier
          percentComplete:(double)percentComplete
        completionHandler:(void(^)(GKAchievement *achievement, NSError *error))completionHandler;
- (void)resetAchievementsWithCompletionHandler:(void(^)(NSError *error))completionHandler;

- (void)showAchievementsInViewController:(UIViewController *)viewController
                       completionHandler:(void(^)())completionHandler;

#pragma mark - other

- (void)mapPlayerIDtoPlayer:(NSString *)playerID
          completionHandler:(void(^)(GKPlayer *player, NSError *error))completionHandler;

@end


text:
<?php

namespace Solve\Database\Adapters;
use Solve\Database\QC;
use Solve\Database\Exceptions\MysqlDBAdapterException;

require_once 'BaseDBAdapter.php';
require_once dirname(__FILE__) . '/../Exceptions/MysqlDBAdapterException.php';

/**
 * Class MysqlDBAdapter
 * @package Solve\Database\Adapters
 *
 * @changed
 * Class MysqlDBAdapter is used to ...
 *
 * @version 1.0
 * @author Alexandr Viniychuk <alexandr.viniychuk@icloud.com>
 */
class MysqlDBAdapter extends BaseDBAdapter {

    private $_pregParametricParams      = null;
    private $_pregParametricCounter     = 1;

    /**
     * @var \PDO connection
     */
    private $_dbh                       = null;

    public function connect($options) {
        if (!extension_loaded('pdo')) throw new \Exception('PDO extension is not loaded.');
        try {
            $this->_dbh = new \PDO(($dsn = self::compileDSN($options)), $options['user'], $options['pass']);
            $this->_dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        } catch(\PDOException $e) {
            throw new MysqlDBAdapterException('Database connection error, check access to '.(empty($options['name']) ? "(empty profile)" : $options['name']) . "\n".$e->getMessage());
        }

        try {
            if (!empty($options['name'])) {
                $this->_dbh->query('USE '.$options['name']);
            }
            $this->_dbh->setAttribute(\PDO::ATTR_AUTOCOMMIT , true);
            if (empty($options['charset'])) $options['charset'] = 'utf8';
            $this->_dbh->query('SET NAMES '.$options['charset']);
        } catch (\PDOException $e) {
            throw new MysqlDBAdapterException('Database connection error, check access to '.$options['name']."\n".$e->getMessage());
        }

        return true;
    }

    /**
     * Execute query
     *
     * @param QC $query
     * @throws MysqlDBAdapterException
     */
    public function executeQuery(QC $query) {
        $type   = $query->getType();
        $methodName = 'execute' . ucfirst($type);
        if (method_exists($this, $methodName)) {
            $result = $this->$methodName($query);
        } else {
            throw new MysqlDBAdapterException('Invalid method specified: '.$type);
        }

        return $result;
    }

    /**
     * Process query to SQL
     * @param QC $qc
     * @param mixed $type
     * @return mixed
     * @throws MysqlDBAdapterException
     */
    public function buildQuery(QC $qc, $type = null) {
        if (!$type) $type = $qc->getType();

        $methodName = 'build' . ucfirst($type);
        if (method_exists($this, $methodName)) {
            $result = $this->$methodName($qc);
        } else {
            throw new MysqlDBAdapterException('Invalid method specified: '.$type);
        }
        return $result;
    }

    private function buildSelect(QC $q) {
        if ($q->getModifier('rawSelect')) {
            $sqlArray = $q->getModifier('rawSelect');
            return $sqlArray[0];
        }

        $sql = 'SELECT ';

        $fields = $q->getQueryParams('fields');
        if (empty($fields)) {
            $fields = '*';
        } else {
            $fields = $this->escapeSqlName($fields);
        }
        $sql .= $fields . ' FROM ';
        $sql .= $this->escapeSqlName($this->requireTable($q));

        $joins = $q->getJoins();
        if (!empty($joins)) {
            $sql .= ' ';
            foreach($joins as $type => $list) {
                foreach($list as $join) {
                    $sql .= strtoupper($type) . ' JOIN '. $join[0]
                        .(strpos($join[1], ' ') === false ? ' USING ('.$this->escapeSqlName($join[1]) : ' ON ('.$join[1]).')';
                }
            }
        }

        $c = $q->getCriteria();
        if (!empty($c)) {
            $sql .= ' WHERE ' . $this->processCriteria($c);
        }
        $sql .= $this->processModifiers($q);
        return $sql;
    }

    /**
     * @param \PDOStatement $res
     * @return array
     */
    public function fetchSelectResult($res) {
        return $res->rowCount() ? $res->fetchAll(\PDO::FETCH_ASSOC) : array();
    }

    private function executeSelect(QC $q) {
        $sql = $this->buildSelect($q);

        $res = $this->_dbh->query($sql);
        return $this->fetchSelectResult($res);
    }

    private function buildInsert(QC $q) {
        $sql = 'INSERT INTO' . ' ' . $this->escapeSqlName($q->getTables()) . ' ';

        $keys = array();
        $data = $q->getQueryParams('data');
        if (count($data)) {
            if (!array_key_exists(0, $data)) {
                $data = array($data);
            }
            foreach($data as $i=>$item) {
                if (!is_array($item)) continue;

                if (array_key_exists(0, $item)) {
                    unset($data[$i]);
                    foreach($item as $sub_item) {
                        $keys = array_merge($keys, array_keys($sub_item));
                        $data[] = $sub_item;
                    }
                } else {
                    $keys = array_merge($keys, array_keys($item));
                }
            }
            $keys = array_unique($keys);
            if (count($keys)) {
                $sql .= '(`'.implode('`, `',$keys).'`) VALUES ';
                foreach($data as $item) {
                    $sql .= '(';
                    foreach($keys as $key) {
                        $sql .= (isset($item[$key]) ? $this->escapeOne($item[$key]) : '""').", ";
                    }
                    $sql = substr($sql, 0, -2).'), ';
                }
            } else {
                $sql.= 'SET ';
                foreach($q->getQueryParams('data') as $item) $sql.= $item.',';
            }
            $sql = substr($sql, 0, -2);
        } else {
            $sql .= '() VALUES ()';
        }
        $sql .= $this->processModifiers($q);

        return $sql;
    }

    private function executeInsert(QC $q) {
        $sql = $this->buildInsert($q);
        $res = $this->_dbh->query($sql);
        return $res ? $this->_dbh->lastInsertId() : false;
    }

    private function buildReplace(QC $q) {
        $sql = $this->buildInsert($q);
        $sql = str_replace('INSERT', 'REPLACE', $sql);

        return $sql;
    }

    private function executeReplace(QC $q) {
        $sql = $this->buildReplace($q);
        $res = $this->_dbh->query($sql);
        return $res ? $this->_dbh->lastInsertId() : false;
    }

    private function buildUpdate(QC $q) {
//        var_dump($q->getQueryParams('data'));die();
        $sql = 'UPDATE ' . $this->escapeSqlName($q->getTables())
            .' SET '.$this->processData($q->getQueryParams('data'), ', ');
        $c = $q->getCriteria();
        if (!empty($c)) {
            $sql .= ' WHERE ' . $this->processCriteria($c);
        }
        $sql .= $this->processModifiers($q);
        return $sql;
    }

    private function executeUpdate(QC $q) {
        $sql = $this->buildUpdate($q);
        $res = $this->_dbh->query($sql);
        return $res ? $res->rowCount() : false;
    }

    private function buildDelete(QC $q) {
        $sql = 'DELETE FROM' . ' ' . $this->escapeSqlName($q->getTables());

        $c = $q->getCriteria();
        if (!empty($c)) {
            $sql .= ' WHERE ' . $this->processCriteria($c);
        }
        $sql .= $this->processModifiers($q);

        return $sql;
    }

    private function executeDelete(QC $q) {
        $sql = $this->buildDelete($q);
        $res = $this->_dbh->query($sql);
        return $res ? $res->rowCount() : false;
    }

    private function requireTable(QC $q) {
        if (!($tables = $q->getTables())) {
            throw new MysqlDBAdapterException('This query requires a table to be specified');
        }
        return $tables;
    }

    private function processModifiers(QC $q) {
        $sql = '';
        if (($groupBy = $q->getModifier('groupBy'))) $sql .= ' GROUP BY ' . $this->escapeSqlName($groupBy[0]);
        if (($orderBy = $q->getModifier('orderBy'))) $sql .= ' ORDER BY ' . $this->escapeSqlName($orderBy[0]);
        if ($q->getModifier('one')) {
            $sql .= ' LIMIT 1';
        } elseif(($limit = $q->getModifier('limit'))) {
            if (count($limit) > 1) $limit[0] = implode(', ', $limit);
            $sql .= ' LIMIT '.$limit[0];
        }
        return $sql;
    }

    private function processCriteria($params) {
        $sql = '';
        foreach($params as $p) {
            if (!empty($p['isComplex'])) {
                $sql .= ' '.strtoupper($p['method']) . ' ' . $this->processCriteria($p['params']);
            } else {
                $sql .= ' '.strtoupper($p['method']) . ' (' . $this->processParametricCondition($p['params']) . ')';
            }
        }
        $sql = '(' . substr($sql, strlen($params[0]['method']) + 2) . ')';

        return $sql;
    }

    private function processData($data, $glue = ',') {
        $sql = '';
        if (array_key_exists(0, $data)) {
            $sql .= $this->processParametricCondition($data);
        } else {
            foreach($data as $field => $value) {
                if (is_array($value)) throw new MysqlDBAdapterException('You tried to set array as a value in data part');
                $sql .=  $glue . ' ' . $this->processParametricCondition(array($field => $value));
            }
            $sql = substr($sql, strlen($glue) + 1);
        }

        return $sql;
    }

    public function executeSQL($sql) {
        return $this->_dbh->query($sql);
    }

    private function processParametricCondition($condition) {
        $sql = '';
        if (count($condition) > 1) {
            if ($this->isValidSQLIdentifier($condition[0])) {
                $sql = $this->escapeSqlName($condition[0]);
                if (is_array($condition[1])) {
                    $sql .= ' IN (' . $this->escape($condition[1]);
                } else {
                    $sql .= ' = ' . $this->escapeOne($condition[1]);
                }
            } else {
                $savedParams = $this->_pregParametricParams;
                $this->_pregParametricParams = $condition;
                $sql = preg_replace_callback('#:[dfsbna\?]#', array($this, 'onPregParameterCallback'), $condition[0]);
                $this->_pregParametricParams = $savedParams;
                $this->_pregParametricCounter = 1;
            }
        } else {
            if (array_key_exists(0, $condition) && is_string($condition[0])) {
                $sql .= $condition[0];
            } else {
                if (array_key_exists(0, $condition)) {
                    $condition = $condition[0];
                }
                foreach($condition as $key=>$value) {
                    if (is_scalar($value) || is_null($value)) {
                        $sql .=  $this->escapeSqlName($key) . ' = ' . $this->escapeOne($value);
                    } else {
                        $sql .=  $this->escapeSqlName($key) . ' IN (' . $this->escape($value) . ')';
                    }
                    $sql .= ' AND ';
                }
                $sql = substr($sql, 0, -5);
            }
        }
        return $sql;
    }

    private function onPregParameterCallback($params) {
        if (array_key_exists($this->_pregParametricCounter, $this->_pregParametricParams)) {
            if ($params[0] == ':d') {
                return intval($this->_pregParametricParams[$this->_pregParametricCounter++]);
            } elseif ($params[0] == ':f') {
                return floatval($this->_pregParametricParams[$this->_pregParametricCounter++]);
            } elseif ($params[0] == ':s') {
                return $this->escapeOne($this->_pregParametricParams[$this->_pregParametricCounter++], 'string');
            } elseif ($params[0] == ':?') {
                return substr($this->escapeOne($this->_pregParametricParams[$this->_pregParametricCounter++], 'string'), 1, -1);
            }
        } else {
            throw new MysqlDBAdapterException('Invalid parameters count for parametric query');
        }
    }

    /**
     * Escape on value using database driver specific
     *
     * @param mixed $value to be escaped
     * @param mixed $type force type definition
     * @return mixed escaped
     */
    protected function escapeOne($value, $type = false) {
        if ($type === false) {
            $type = gettype($value);
        }
        if (strpos($value, '#sql#') !== false) {
            return substr($value, 5);
        }
        if (in_array($type, array('integer'))) {
            return $value;
        } elseif ($type == 'boolean') {
            return intval($value);
        } elseif ($type == 'NULL') {
            return 'null';
        } else {
            return $this->_dbh->quote($value);
        }
    }

    public function __destruct() {
    }

}


text:
var postcss = require('postcss');
var chai = require('chai');
var expect = chai.expect;

var path = require('path');
var testHelpers = require('./test_helpers');

var helpers = require('../lib/helpers');

describe('helpers', function () {

    it('Defaults should extend objects', function (done) {
        var a = {};
        var b = { param: true };

        var c = helpers.defaults(a, b);

        expect(c).to.eql(a);
        expect(c.param).to.eql(b.param);

        done();
    });

    it('Defaults should not rewrite already defined parameters in source', function (done) {
        var a = { param: true };
        var b = { param: false };

        var c = helpers.defaults(a, b);

        expect(c.param).to.eql(true);

        done();
    });

    it('Extend should extend objects for first argument', function (done) {
        var a = {};
        var b = {};
        var c = { something: false };

        var d = helpers.extend(a, b, c);

        expect(d).to.eql(a);
        expect(d).to.not.eql(b);

        done();
    });

    it('Extend should not deeply extend objects', function (done) {
        var a = {};
        var b = {
            something: {
                test: true
            }
        };

        helpers.extend(a, b);

        expect(a.something).to.be.eql(b.something);

        helpers.extend(a, {
            something: {
                another: false
            }
        });

        expect(a.something.test).to.eql(undefined);
        expect(a.something.another).to.eql(false);

        done();
    });

    it('getFileName should return proper filename', function (done) {
        var destination = path.parse(testHelpers.testPath);
        var fileName;

        fileName = helpers.getFileName('test', destination, 0);
        expect(fileName).to.be.eql(testHelpers.testPath);

        fileName = helpers.getFileName('test-%i%', destination, 11);
        expect(fileName).to.be.eql(testHelpers.testDir + '/test-11.css');

        fileName = helpers.getFileName('%original%test%i%', destination, 1);
        expect(fileName).to.be.eql(testHelpers.testDir + '/testtest1.css');

        done();
    });

    it('find should find object in array', function (done) {
        var obj00 = { iam: '00' };
        var obj01 = { iam: '01' };
        var obj10 = { iam: '10' };
        var obj11 = { iam: '11' };
        var obj20 = { iam: '20' };
        var obj21 = { iam: '21' };
        var arr = [
            [obj00, obj01],
            [obj10, obj11],
            [obj20, obj21]
        ];
        var obj;

        obj = helpers.find(obj20, arr);
        expect(obj).to.be.eql(obj21);

        obj = helpers.find(obj10, arr);
        expect(obj).to.be.eql(obj11);

        obj = helpers.find(obj21, arr);
        expect(obj).to.be.not.ok;

        done();
    });

    it('parents should return all parents', function (done) {
        var root = postcss.root();
        var node = postcss.parse(
            '@media (max-heigth: 10px){ a{} @media (max-width: 10px) { b{} } }'
        );
        root.append(node);
        var parents;

        parents = helpers.parents(root);
        expect(parents).to.have.length(0);

        parents = helpers.parents(root.nodes[0]);
        expect(parents).to.have.length(0);

        parents = helpers.parents(root.nodes[0].nodes[1].nodes[0]);
        expect(parents).to.have.length(2);
        expect(parents[1]).to.be.eql(root.nodes[0]);

        done();
    });

});


text:
Rust bindings for FreeType library

## Requirements

  * *Rust*: We currently compile against the *master* branch. The releases on
    http://www.rust-lang.org tend to not work.
  * *Cargo*: We use Cargo to compile the project.
  * *FreeType2 development libraries*: install through your favourite package
    management tool, or via http://www.freetype.org/download.html

## Build

Clone this repo then run
```
cd freetype-rs
cargo build
```

## Examples

To build examples, use `cargo test`. They are all built in `./target/debug/examples/*`.

To run examples, use `cargo run --example name`, for example:
```
cargo run --example single_glyph examples/assets/FiraSans-Regular.ttf A
```

[How to contribute](https://github.com/PistonDevelopers/piston/blob/master/CONTRIBUTING.md)


text:
function animateStatusChangeRows(rows){
	rows.animate({backgroundColor: '#FFF'}, 1000,
		function(){
					$(this).removeClass('bg-success').attr('style','');
				});
}

function statusChanged(selector,jobId){
	var status = $(selector).val();
	$.ajax({
		url: 'status',
		dataType: "json",
		data: {
			status: status,
			id: jobId,
		},
		type: 'POST',
		success: function(data){
			$('[name=salesNumber]').text(data.sales);
			$('[name=salesPercentage]').text(data.cogsPercentage);

			var targetTab = $(selector).parents('.tab-content').children('#job-content-'+status);
			var row = $(selector).closest("tr");
			row.removeClass('selected');
			row.addClass('bg-success');
			if(targetTab[0] != null){
				targetTab.find('tbody').prepend(row.remove());
			}else{
				animateStatusChangeRows(row);
			}
		}
	});
}

var addPaginationListener = function(){
	$(".td-clickable").click(function() {
		window.document.location = $(this).parent().data("href");
	});
}

jQuery(document).ready(function($) {
   $( ".nav-tabs a" ).on( "click", function() {
           //only fade out succuess highlight if has been seen
           var status = $(this).parent().data('status');
           var successRows = $('.tab-content').children('#job-content-'+status)
                   .find('.bg-success');
           animateStatusChangeRows(successRows);
   });
    $(".td-clickable").click(function() {
        window.document.location = $(this).parent().data("href");
	});
});


text:
namespace iMgmt
{
    partial class frmProductsRecord1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

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

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.dataGridView1 = new System.Windows.Forms.DataGridView();
            this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.Column2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.Column3 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.txtProductname = new System.Windows.Forms.TextBox();
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.txtCategory = new System.Windows.Forms.TextBox();
            this.groupBox3 = new System.Windows.Forms.GroupBox();
            this.txtCompany = new System.Windows.Forms.TextBox();
            this.groupBox4 = new System.Windows.Forms.GroupBox();
            this.Button3 = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
            this.groupBox1.SuspendLayout();
            this.groupBox2.SuspendLayout();
            this.groupBox3.SuspendLayout();
            this.groupBox4.SuspendLayout();
            this.SuspendLayout();
            //
            // dataGridView1
            //
            this.dataGridView1.BackgroundColor = System.Drawing.SystemColors.ButtonHighlight;
            this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.Column1,
            this.Column2,
            this.Column3});
            this.dataGridView1.Location = new System.Drawing.Point(2, 94);
            this.dataGridView1.MultiSelect = false;
            this.dataGridView1.Name = "dataGridView1";
            this.dataGridView1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.dataGridView1.Size = new System.Drawing.Size(745, 489);
            this.dataGridView1.TabIndex = 2;
            this.dataGridView1.RowHeaderMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dataGridView1_RowHeaderMouseClick);
            this.dataGridView1.RowPostPaint += new System.Windows.Forms.DataGridViewRowPostPaintEventHandler(this.dataGridView1_RowPostPaint);
            //
            // Column1
            //
            this.Column1.HeaderText = "Product Name";
            this.Column1.Name = "Column1";
            this.Column1.Width = 250;
            //
            // Column2
            //
            this.Column2.HeaderText = "Category";
            this.Column2.Name = "Column2";
            this.Column2.Width = 200;
            //
            // Column3
            //
            this.Column3.HeaderText = "Company";
            this.Column3.Name = "Column3";
            this.Column3.Width = 250;
            //
            // groupBox1
            //
            this.groupBox1.Controls.Add(this.txtProductname);
            this.groupBox1.Location = new System.Drawing.Point(5, 3);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(213, 82);
            this.groupBox1.TabIndex = 3;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "Search by Product Name";
            //
            // txtProductname
            //
            this.txtProductname.Location = new System.Drawing.Point(16, 40);
            this.txtProductname.Name = "txtProductname";
            this.txtProductname.Size = new System.Drawing.Size(178, 24);
            this.txtProductname.TabIndex = 0;
            this.txtProductname.TextChanged += new System.EventHandler(this.txtProductname_TextChanged);
            //
            // groupBox2
            //
            this.groupBox2.Controls.Add(this.txtCategory);
            this.groupBox2.Location = new System.Drawing.Point(224, 3);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(205, 82);
            this.groupBox2.TabIndex = 4;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "Search by Category";
            //
            // txtCategory
            //
            this.txtCategory.Location = new System.Drawing.Point(16, 40);
            this.txtCategory.Name = "txtCategory";
            this.txtCategory.Size = new System.Drawing.Size(175, 24);
            this.txtCategory.TabIndex = 0;
            this.txtCategory.TextChanged += new System.EventHandler(this.txtCategory_TextChanged);
            //
            // groupBox3
            //
            this.groupBox3.Controls.Add(this.txtCompany);
            this.groupBox3.Location = new System.Drawing.Point(435, 3);
            this.groupBox3.Name = "groupBox3";
            this.groupBox3.Size = new System.Drawing.Size(200, 82);
            this.groupBox3.TabIndex = 5;
            this.groupBox3.TabStop = false;
            this.groupBox3.Text = "Search by Company";
            //
            // txtCompany
            //
            this.txtCompany.Location = new System.Drawing.Point(16, 40);
            this.txtCompany.Name = "txtCompany";
            this.txtCompany.Size = new System.Drawing.Size(168, 24);
            this.txtCompany.TabIndex = 0;
            this.txtCompany.TextChanged += new System.EventHandler(this.txtCompany_TextChanged);
            //
            // groupBox4
            //
            this.groupBox4.Controls.Add(this.Button3);
            this.groupBox4.Location = new System.Drawing.Point(644, 3);
            this.groupBox4.Name = "groupBox4";
            this.groupBox4.Size = new System.Drawing.Size(89, 82);
            this.groupBox4.TabIndex = 19;
            this.groupBox4.TabStop = false;
            //
            // Button3
            //
            this.Button3.Font = new System.Drawing.Font("Palatino Linotype", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.Button3.Location = new System.Drawing.Point(13, 23);
            this.Button3.Name = "Button3";
            this.Button3.Size = new System.Drawing.Size(63, 43);
            this.Button3.TabIndex = 2;
            this.Button3.Text = "&Export Excel";
            this.Button3.UseVisualStyleBackColor = true;
            this.Button3.Click += new System.EventHandler(this.Button3_Click);
            //
            // frmProductsRecord
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 17F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.SystemColors.ButtonHighlight;
            this.ClientSize = new System.Drawing.Size(749, 585);
            this.Controls.Add(this.groupBox4);
            this.Controls.Add(this.groupBox3);
            this.Controls.Add(this.groupBox2);
            this.Controls.Add(this.groupBox1);
            this.Controls.Add(this.dataGridView1);
            this.Font = new System.Drawing.Font("Palatino Linotype", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
            this.MaximizeBox = false;
            this.Name = "frmProductsRecord";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "Products Record";
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmProductsRecord_FormClosing);
            this.Load += new System.EventHandler(this.frmProductsRecord_Load);
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.groupBox2.ResumeLayout(false);
            this.groupBox2.PerformLayout();
            this.groupBox3.ResumeLayout(false);
            this.groupBox3.PerformLayout();
            this.groupBox4.ResumeLayout(false);
            this.ResumeLayout(false);

        }

        #endregion

        public System.Windows.Forms.DataGridView dataGridView1;
        private System.Windows.Forms.DataGridViewTextBoxColumn Column1;
        private System.Windows.Forms.DataGridViewTextBoxColumn Column2;
        private System.Windows.Forms.DataGridViewTextBoxColumn Column3;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.TextBox txtProductname;
        private System.Windows.Forms.GroupBox groupBox2;
        private System.Windows.Forms.TextBox txtCategory;
        private System.Windows.Forms.GroupBox groupBox3;
        private System.Windows.Forms.TextBox txtCompany;
        internal System.Windows.Forms.GroupBox groupBox4;
        internal System.Windows.Forms.Button Button3;
    }
}


text:
int main()
{
	AllyInvest::TestAssetList();
	AllyInvest::TestGetAllyAsset();
	AllyInvest::TestMakeStockOrder();
	AllyInvest::TestMakeOptionOrder();
	AllyInvest::TestMakeMultiLegOptionOrder();
	AllyInvest::TestDate();
	AllyInvest::TestIsCaseInsensitveMatch();
	return 0;
}


text:
'use strict';

var expect = require('chai').expect;

var chlg = require('../../lib/chlg');

var commands = [
  'init',
  'release',
  'show',
  'insert',
  'add',
  'change',
  'deprecate',
  'remove',
  'fix',
  'security'
];

describe('chlg', function () {

  commands.forEach(function (command) {
    it('should export chlg-' + command, function () {
      expect(chlg[command]).to.be.a('function');
    });
  });

});


text:
var League = DS.Model.extend({
  title: DS.attr('string'),
  fantasyTeam: DS.attr('hasMany')
});

export default League;


text:
using namespace std;

class EmptyStackException { };

class IntStack
{
    public:
        // Initializes an empty stack.
        IntStack();

        // Determines whether the stack is empty.
        bool empty();

        // Adds 'item' to the top of the stack.
        void push(int item);

        // Removes the top of the stack (i.e. removes the element that was added
        // most recently), and returns it.
        int pop();

        // Retrieves the top of the stack.
        int top();

    private:
        vector<int> vec;
};

IntStack::IntStack() {
    //empty;
}

bool IntStack::empty() {
    return vec.empty();
}

void IntStack::push(int item) {
    vec.push_back(item);
}

int IntStack::pop() {
    if (empty()) {
        throw EmptyStackException();
    }

    int top = vec.back();
    vec.pop_back();
    return top;
}

int IntStack::top() {
    return vec[vec.size() - 1];
}


text:
#ifndef SIGAR_OS_H
#define SIGAR_OS_H

#include <fcntl.h>
#include <errno.h>
#include <dlfcn.h>
#include <procinfo.h>
#include <sys/resource.h>

enum {
    KOFFSET_LOADAVG,
    KOFFSET_VAR,
    KOFFSET_SYSINFO,
    KOFFSET_IFNET,
    KOFFSET_VMINFO,
    KOFFSET_CPUINFO,
    KOFFSET_TCB,
    KOFFSET_MAX
};

typedef struct {
    time_t mtime;
    int num;
    char **devs;
} swaps_t;

typedef int (*proc_fd_func_t) (sigar_t *, sigar_pid_t, sigar_proc_fd_t *);

struct sigar_t {
    SIGAR_T_BASE;
    int kmem;
    /* offsets for seeking on kmem */
    long koffsets[KOFFSET_MAX];
    proc_fd_func_t getprocfd;
    int pagesize;
    swaps_t swaps;
    time_t last_getprocs;
    sigar_pid_t last_pid;
    struct procsinfo64 *pinfo;
    struct cpuinfo *cpuinfo;
    int cpuinfo_size;
    int cpu_mhz;
    char model[128];
    int aix_version;
    int thrusage;
    sigar_cache_t *diskmap;
};

#define HAVE_STRERROR_R

#define SIGAR_EPERM_KMEM (SIGAR_OS_START_ERROR+EACCES)

#endif /* SIGAR_OS_H */


text:
require 'rest-client'

# Module supposed to extend the RestClient response to add helper methods.
module Wow::ApiClient::Response
  # Parse the response body of a rest client
  # Should extend the response object of a RestClient request
  # e.g.
  # ```
  # result = RestClient.get('http://example.com/some.json')
  # result.extend Wow::ApiClient::Response
  # result.data
  # > Hash {...}
  # ```
  def data
    @data ||= JSON.parse(body, symbolize_names: true)
  end
end