text:
package net.desertconsulting.mochatemplate.parser.node;

import net.desertconsulting.mochatemplate.parser.Parser;
import java.io.UnsupportedEncodingException;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

/**
 * This attribute parser supports data-ignore attribute, any other template related
 * stuff in the parent node will be ignored when this attribute is encountered.
 *
 * @author Patrizio Bruno {@literal <desertconsulting@gmail.com>}
 */
public class IgnoreAttributeParser extends TemplateAttributeParser {

    private static final String SUPPORTED_FIELD = "ignore";

    public IgnoreAttributeParser(ScriptEngine engine) {
        super(engine);
    }

    @Override
    public boolean eval(TemplateNode dataNode, AttributeParserArguments args, Parser parser) throws ScriptException, UnsupportedEncodingException {
        dataNode.getNode().removeAttr(args.getAttributeName());
        return false;
    }

    @Override
    public String supportedAttr() {
        return SUPPORTED_FIELD;
    }
}


text:
Форма Для передачи (SendActForm2, SendInformationForm3, SendActForm5)

                                Ваш браузер не поддерживает встроенные фреймы!

redpajama_set_name: RedPajamaGithub


text:
from __future__ import absolute_import, division, print_function

# Import standard modules
import numpy as np

# Import the relevant PTS classes and modules
from ....core.tools.logging import log

# -----------------------------------------------------------------

class IonizingStellarMapMaker(object):

    """
    This class...
    """

    def __init__(self):

        """
        The constructor ...
        :return:
        """

        # Call the constructor of the base class
        super(IonizingStellarMapMaker, self).__init__()

        # -- Attributes --

        self.map = None

    # -----------------------------------------------------------------

    def run(self):

        """
        This function ...
        :return:
        """

        # 1. Call the setup function
        self.setup()

        # ...

        #
        self.make_map()

        # Return the map
        return self.map

    # -----------------------------------------------------------------

    def setup(self):

        """
        This function ...
        :return:
        """

        pass

    # -----------------------------------------------------------------

    def make_map(self):

        """
        This function ...
        :return:
        """

        # H-ALPHA HAS BEEN CONVERTED TO LSUN (ABOVE)

        # Young ionizing stars = Ha + 0.031 x MIPS24

        # CALCULATE THE IONIZING STARS MAP BASED ON THE CONVERTED H ALPHA AND THE DISK-SUBTRACTED 24 MICRON IMAGE

        # Calculate the young stellar contribution to the 24 micron image
        mips_young_stars = self.get_mips_young_stars_map()

        # Save the mips_young_stars map
        mips_young_path = fs.join(self.maps_intermediate_path, "24mu_young.fits")
        mips_young_stars.save(mips_young_path)

        # Calculate ionizing stars map and ratio
        ionizing = self.images["Halpha"].frames.primary + 0.031 * mips_young_stars

        # ionizing_ratio = self.ha / (0.031*mips_young_stars)

        # MASK NEGATIVE AND LOW SIGNAL-TO-NOISE PIXELS

        # Set pixels to zero with low signal-to-noise in the H Alpha image
        # ionizing[self.ha < self.config.ionizing_stars.ha_snr_level*self.ha_errors] = 0.0
        # ionizing_ratio[self.ha < self.config.ionizing_stars.ha_snr_level*self.ha_errors] = 0.0

        # Set pixels to zero with low signal-to-noise in the 24 micron image
        # ionizing[self.mips < self.config.ionizing_stars.mips_snr_level*self.mips_errors] = 0.0
        # ionizing_ratio[self.mips < self.config.ionizing_stars.mips_snr_level*self.mips_errors] = 0.0

        # Make sure all pixel values are larger than or equal to zero
        # ionizing[ionizing < 0.0] = 0.0
        # ionizing_ratio[ionizing < 0.0] = 0.0

        # New
        ionizing[self.cutoff_masks["Halpha"]] = 0.0

        # Set the ionizing stars map
        self.map = ionizing

    # -----------------------------------------------------------------

    def get_mips_young_stars_map(self):

        """
        This function ...
        :return:
        """

        # Inform the user
        log.info("Subtracting the old stellar contribution from the 24 micron emission ...")

        ## Subtract old stellar contribution from FUV and MIPS 24 emission

        #     From the FUV and 24 micron maps we must subtract the diffuse radiation (old stellar contribution),
        #     for this we typically use an exponential disk
        #     (scale length detemermined by GALFIT)

        ## MIPS HAS BEEN CONVERTED TO LSUN (ABOVE)

        flux_mips = np.sum(self.images["24mu"].frames.primary)

        # typisch 20% en 35% respectievelijk
        # 48% voor MIPS 24 komt van Lu et al. 2014

        factor = 0.48 * flux_mips / np.sum(self.disk)

        # Subtract the disk contribution to the 24 micron image
        new_mips = self.images["24mu"].frames.primary - factor * self.disk

        # Make sure all pixels of the disk-subtracted maps are larger than or equal to zero
        new_mips[new_mips < 0.0] = 0.0

        # Set zero where low signal-to-noise ratio
        # new_mips[self.mips < self.config.ionizing_stars.mips_young_stars.mips_snr_level*self.mips_errors] = 0.0

        # Return the new 24 micron frame
        return new_mips

# -----------------------------------------------------------------


text:
package jenkins.advancedqueue.jobinclusion;

import hudson.DescriptorExtensionList;
import hudson.ExtensionPoint;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.model.Job;
import jenkins.advancedqueue.DecisionLogger;
import jenkins.model.Jenkins;

/**
 * @author Magnus Sandberg
 * @since 3.0
 */
public abstract class JobInclusionStrategy implements ExtensionPoint, Describable<JobInclusionStrategy> {

	static public class AbstractJobInclusionStrategyDescriptor<T extends JobInclusionStrategy> extends Descriptor<JobInclusionStrategy> {

		private final String displayName;

		protected AbstractJobInclusionStrategyDescriptor(String displayName) {
			this.displayName = displayName;
		}

		@Override
		public String getDisplayName() {
			return displayName;
		}

	};

	@SuppressWarnings("unchecked")
	public Descriptor<JobInclusionStrategy> getDescriptor() {
		return Jenkins.get().getDescriptor(this.getClass());
	}

	abstract public boolean contains(DecisionLogger decisionLogger, Job<?, ?> job);

	public static DescriptorExtensionList<JobInclusionStrategy, Descriptor<JobInclusionStrategy>> all() {
		return Jenkins.get().getDescriptorList(JobInclusionStrategy.class);
	}

}


text:
static NSString * const AGDSegueIdentifierChat = @"Chat";

@interface AGDLoginViewController ()

@property (weak, nonatomic) IBOutlet UITextField *keyTextField;
@property (weak, nonatomic) IBOutlet UITextField *roomNumberTextField;

@end

@implementation AGDLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *vendorKey = [userDefaults objectForKey:AGDKeyVendorKey];
    if (vendorKey) {
        self.keyTextField.text = vendorKey;
    } else {
        NSURL *innerKeyUrl = [NSURL URLWithString:@"http://192.168.99.253:8970/agora.inner.test.key.txt"];
        NSString *innerVendorKey = [NSString stringWithContentsOfURL:innerKeyUrl
                                                     encoding:NSASCIIStringEncoding
                                                        error:nil];

        self.keyTextField.text = [innerVendorKey
                                  stringByReplacingOccurrencesOfString:@"\n" withString:@""];; // Please use your own key. The inner test key is just invalid in public.
    }

}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}

#pragma mark -

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if (![segue.identifier isEqualToString:AGDSegueIdentifierChat]) {return;}

    AGDChatViewController *chatViewController = segue.destinationViewController;
    chatViewController.dictionary = @{AGDKeyChannel: self.roomNumberTextField.text,
                                      AGDKeyVendorKey: self.keyTextField.text};

    UIButton *button = (UIButton *)sender;
    if (button.tag == 1) {
        chatViewController.chatType = AGDChatTypeVideo;
    } else {
        chatViewController.chatType = AGDChatTypeAudio;
    }
}

#pragma mark -

- (IBAction)didClickPushChatViewController:(id)sender
{

    if ([self isValidInput]) {
        [self performSegueWithIdentifier:AGDSegueIdentifierChat sender:sender];
    }
}

- (BOOL)isValidInput
{
    [self.view endEditing:YES];
    if (_keyTextField.text.length && _roomNumberTextField.text.length) {
        return YES;
    } else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil
                                                            message:NSLocalizedString(@"enter_key_room", nil)
                                                           delegate:nil
                                                  cancelButtonTitle:NSLocalizedString(@"done", nil)
                                                  otherButtonTitles:nil];
        [alertView show];
        return NO;
    }
}

- (IBAction)didTapHideKeyboard:(id)sender
{
    [self.view endEditing:YES];
}

@end


text: /* CSS for ebook */


text:
<?php

class Edge_UniqueQuoteItem_Helper_Data extends Mage_Core_Helper_Abstract
{
    public function getSimilarItems($item)
    {
        $similarItems = array();
        $keyString = $this->getItemKeyString($item);

        $quote = Mage::getSingleton('checkout/session')->getQuote();
        foreach ($quote->getAllVisibleItems() as $quoteItem) {
            if ($this->getItemKeyString($quoteItem) === $keyString) {
                $similarItems[] = $quoteItem;
            }
        }
        return $similarItems;
    }

    public function getItemKeyString($item)
    {
        $buyRequest = $item->getBuyRequest();

        $key = array(
            $item->getProductType(),
            $item->getProductId(),
            $item->getStoreId(),
            $item->getSku(),
            $item->getPriceInclTax()
        );

        switch ($item->getProductType()) {
            case 'downloadable':
                if ($buyRequest->getLinks()) {
                    $key[] = http_build_query($buyRequest->getLinks());
                }
                break;
            case 'configurable':
                if ($buyRequest->getSuperAttribute()) {
                    $key[] = http_build_query($buyRequest->getSuperAttribute());
                }
                break;
            case 'bundle':
                if ($buyRequest->getBundleOption()) {
                    $key[] = http_build_query($buyRequest->getBundleOption());
                }
                if ($buyRequest->getBundleOptionQty()) {
                    $key[] = http_build_query($buyRequest->getBundleOptionQty());
                }
                break;
        }

        if ($buyRequest->getOptions()) {
            $key[] = http_build_query($buyRequest->getOptions());
        }

        $keyString = implode(':', $key);
        return $keyString;
    }

    public function joinLineItems(&$items)
    {
        $joinedItems = array();
        foreach ($items as $item) {
            $keyString = $this->getItemKeyString($item);
            if (!isset($joinedItems[$keyString])) {
                $joinedItems[$keyString] = $item;
            } else {
                $joinedItems[$keyString]->setQty($joinedItems[$keyString]->getQty() + 1);
            }
        }
        $items = $joinedItems;
    }
}


text:
package naftoreiclag.village.gamestates;

import org.lwjgl.opengl.Display;

public abstract class GameState
{
	// Delta information, used to syncronize steps
	public static class DeltaStopwatch
	{
		// Get the time in milliseconds
		public static long getTime()
		{
			// Get the time, then convert it to milliseconds, then return it
			return System.nanoTime() / 1000000;
		}

		// Keep track of whenever the timer was last reset
		private long timeWhenTimerWasLastReset;

		// Reset the timer to zero
		public void reset()
		{
			timeWhenTimerWasLastReset = getTime();
		}

		// Time elapsed since getDelta() was last called (No reset, useful for waiting until delta will exceed a minimum value.)
		public long getDuration()
		{
			long timeWhenThisMethodWasCalled = getTime();
			long howLongAgoWasTheLastReset = timeWhenThisMethodWasCalled - timeWhenTimerWasLastReset;
			return howLongAgoWasTheLastReset;
		}

		// Time elapsed since getDelta() was last called (It resets the timer)
		public long getDurationAndReset()
		{
			long timeWhenThisMethodWasCalled = getTime();
			long howLongAgoWasTheLastReset = timeWhenThisMethodWasCalled - timeWhenTimerWasLastReset;
			timeWhenTimerWasLastReset = timeWhenThisMethodWasCalled;
			return howLongAgoWasTheLastReset;
		}
	}

	// Minimum number of milliseconds that must occur between steps
	public final long minimumTimeBetweenSteps;

	// It's the constructor, dummy!
	protected GameState(long minimumTimeBetweenSteps)
	{
		this.minimumTimeBetweenSteps = minimumTimeBetweenSteps;
	}

	/* Like run() in Runnable, but returns a new GameState for the Main class to run (to prevent a stack overflow error)
	 * Most subclasses should not override this; they should override tick instead.
	 */
	public GameState run()
	{
		// Setup
		this.simpleSetup();

		// Init delta tracking
		DeltaStopwatch d = new DeltaStopwatch();

		// Begin ticking and handle return value
		GameState returnVal;
		while(true)
		{
			// Do not execute a step too quickly
			if(d.getDuration() < minimumTimeBetweenSteps)
			{
				continue;
			}

			// Perform tick and get return value
			returnVal = this.simpleStep(d.getDurationAndReset());

			// However, we must check for some special escape cases.

			// If user is trying to close the program via the "x" on the window or other system means,
			if(Display.isCloseRequested())
			{
				// Return a shutdown.
				returnVal = this.getNewShutdownGameState();
			}

			// If something was non-null was returned, return it.
			// Note: in order to return null to close program, return instance of GameStateShutdown from simpleTick()
			if(returnVal != null)
			{
				// Cleanup
				this.simpleCleanup();

				// Goto the next state
				return returnVal;
			}
		}
	}

	// Subclasses can override what to return when close is requested
	protected GameState getNewShutdownGameState()
	{
		return new GameStateShutdown();
	}

	/* NOTE: Methods overridden with the prefix "simple" imply that there is some underlying handling of these,
	 *       and therefore you aren't overriding any actual handing or "under the hood" stuff.
	 */

	// Override these methods
	protected abstract GameState simpleStep(long delta);
	protected abstract void simpleSetup();
	protected abstract void simpleCleanup();
}


text:
using System;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;
using Synker.Resource;

namespace Synker
{
    /// <summary>
    /// 一定の間隔でイベントを発生させるための機能を提供します。
    /// </summary>
    public class Interval : IDisposable
    {
        #region -- Private Fields --

        private volatile bool requestedStop;
        private Task tickerTask;
        private int intervalMilliseconds = 10;
        private BlockingMode mode = BlockingMode.Nonblocking;

        #endregion

        #region -- Public Properties --

        /// <summary>
        /// イベントを発生する間隔値をミリ秒で設定または取得します。
        /// 設定値は 1 ミリ秒以上の値でなくてはなりません。
        /// </summary>
        /// <exception cref="ObjectDisposedException">オブジェクトが破棄された後に呼び出されると発生します。</exception>
        public int IntervalMilliseconds
        {
            get { return intervalMilliseconds; }
            set
            {
                if (IsDisposed)
                    throw new ObjectDisposedException(GetType().FullName, Language.Interval_ObjectDisposed);

                if (value < 1)
                    throw new ArgumentOutOfRangeException(nameof(value), value, Language.Interval_ArgumentOutOfRange_1);

                intervalMilliseconds = value;
            }
        }

        /// <summary>
        /// タイマが動作しているかを表す真偽値を取得します。
        /// </summary>
        public bool Running { get; private set; }

        /// <summary>
        /// イベントが発生した回数を取得します。
        /// </summary>
        public long TickCount { get; private set; }

        /// <summary>
        /// ブロッキングモードを表す <see cref="BlockingMode"/> 列挙体の値を取得または設定します。
        /// </summary>
        /// <exception cref="ArgumentOutOfRangeException">与えられた引数が有効な <see cref="BlockingMode"/> 列挙体の値でないときに発生します。</exception>
        public BlockingMode Mode
        {
            get { return mode; }
            set
            {
                if (!Enum.IsDefined(typeof(BlockingMode), value))
                    throw new ArgumentOutOfRangeException(nameof(value), value, Language.Timeout_ArgumentOutOfRange_2);

                mode = value;
            }
        }

        /// <summary>
        /// オブジェクトが破棄されたかを表す真偽値を取得します。
        /// </summary>
        public bool IsDisposed { get; private set; }

        #endregion

        #region -- Public Events --

        /// <summary>
        /// 指定された間隔が経過し、イベントを発生させようとしたときに発生します。
        /// </summary>
        public event EventHandler<TimerElapsedEventArgs> Elapsed;

        #endregion

        #region -- Constructors --

        /// <summary>
        /// パラメータを指定せずに新しい <see cref="Interval"/> クラスのインスタンスを指定します。
        /// </summary>
        public Interval()
        {
            Reset();
        }

        #endregion

        #region -- Public Methods --

        /// <summary>
        /// タイマを動作させ、イベントを発生できる状態にします。
        /// </summary>
        /// <exception cref="ObjectDisposedException">オブジェクトが破棄された後に呼び出されると発生します。</exception>
        public void Start()
        {
            if (IsDisposed)
                throw new ObjectDisposedException(GetType().FullName, Language.Interval_ObjectDisposed);

            if (Running)
                return;

            requestedStop = false;
            Running = true;

            if (mode == BlockingMode.Blocking)
                Tick();
            else
                tickerTask = Task.Factory.StartNew(Tick);
        }

        /// <summary>
        /// タイマを停止し、イベントの発生を止めます。
        /// </summary>
        public void Stop()
        {
            Stop(TimeSpan.FromMilliseconds(-1));
        }

        /// <summary>
        /// タイマを停止し、イベントの発生を止め、指定された時間だけ停止を待ちます。
        /// </summary>
        /// <param name="timeout">停止待機時間を表す <see cref="TimeSpan"/> 型のインスタンス。</param>
        /// <exception cref="ObjectDisposedException">オブジェクトが破棄された後に呼び出されると発生します。</exception>
        public void Stop(TimeSpan timeout)
        {
            if (IsDisposed)
                throw new ObjectDisposedException(GetType().FullName, Language.Interval_ObjectDisposed);

            if (!Running)
                return;

            requestedStop = true;
            tickerTask?.Wait(timeout);
            tickerTask?.Dispose();
            tickerTask = null;
            Running = false;
        }

        /// <summary>
        /// イベント発生カウントを初期化し、再び発生ができる状態にリセットします。
        /// </summary>
        /// <exception cref="ObjectDisposedException">オブジェクトが破棄された後に呼び出されると発生します。</exception>
        public void Reset()
        {
            if (IsDisposed)
                throw new ObjectDisposedException(GetType().FullName, Language.Interval_ObjectDisposed);

            TickCount = 0L;
            requestedStop = false;
        }

        /// <summary>
        /// タイマを停止し、再び開始します。
        /// </summary>
        public void Restart()
        {
            Restart(TimeSpan.FromMilliseconds(-1));
        }

        /// <summary>
        /// 指定された時間だけ停止を待ち、タイマを再び開始します。
        /// </summary>
        /// <param name="timeout">停止待機時間を表す <see cref="TimeSpan"/> 型のインスタンス。</param>
        /// <exception cref="ObjectDisposedException">オブジェクトが破棄された後に呼び出されると発生します。</exception>
        public void Restart(TimeSpan timeout)
        {
            if (IsDisposed)
                throw new ObjectDisposedException(GetType().FullName, Language.Interval_ObjectDisposed);

            Stop(timeout);
            Start();
        }

        /// <summary>
        /// このオブジェクトで使用されているリソースを破棄します。
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
        }

        #endregion

        #region -- Public Static Methods --

        /// <summary>
        /// 間隔と呼び出されるメソッドを指定して新しい <see cref="Interval"/> クラスのインスタンスを初期化し、
        /// タイマを開始させます。
        /// </summary>
        /// <param name="milliseconds">イベントを発生するミリ秒単位の間隔値。</param>
        /// <param name="callback">呼び出されるメソッド。</param>
        /// <returns>新しい <see cref="Interval"/> クラスのインスタンス。</returns>
        public static Interval StartNew(int milliseconds, Action<object, TimerElapsedEventArgs> callback)
        {
            if (callback == null)
                throw new ArgumentNullException(nameof(callback));

            var interval = new Interval { IntervalMilliseconds = milliseconds };
            interval.Elapsed += new EventHandler<TimerElapsedEventArgs>(callback);
            interval.Start();

            return interval;
        }

        #endregion

        #region -- Protected Methods --

        protected virtual void Dispose(bool disposing)
        {
            if (IsDisposed) return;

            Stop();

            IsDisposed = true;

            if (disposing)
                GC.SuppressFinalize(this);
        }

        ~Interval()
        {
            Dispose(false);
        }

        #endregion

        #region -- Private Methods --

        private void Tick()
        {
            var processTime = 0L;
            var oldTick = Stopwatch.GetTimestamp();
            var frequency = Stopwatch.Frequency;
            var milliFrequency = (long)(frequency * 0.001);
            var gap = 0.0;
            var nowTick = oldTick;

            while (!requestedStop)
            {
                TickCount++;

                var deltaTickDouble = intervalMilliseconds * 0.001 * frequency;
                var deltaTick = (long)deltaTickDouble;
                gap += deltaTickDouble - deltaTick;
                var gapDelta = (long)gap;
                gap -= gapDelta;

                var targetTick = oldTick + deltaTick + gapDelta;

                {
                    var beforeProcessTick = Stopwatch.GetTimestamp();

                    Elapsed?.Invoke(
                        this,
                        new TimerElapsedEventArgs(frequency, TickCount, oldTick - nowTick, processTime));

                    nowTick = Stopwatch.GetTimestamp();
                    processTime = nowTick - beforeProcessTick;
                }

                if (requestedStop)
                    break;

                while (!requestedStop && Stopwatch.GetTimestamp() + milliFrequency < targetTick)
                    Thread.Sleep(1);

                oldTick = targetTick;
            }
        }

        #endregion
    }
}


text:
using System.Threading;

namespace Spira.Core
{
    public static class EventWaitHandleExm
    {
        public static void NullSafeSet(this EventWaitHandle handle)
        {
            if (handle != null)
                handle.Set();
        }
    }
}


text:
<?php

namespace Seed\CoreBundle\Form\Validator;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Seed\CoreBundle\Repository\OrganizationUserRepository;
use Seed\CoreBundle\Entity\OrganizationUser;

class IsUniqueEmailValidator extends ConstraintValidator
{
    private $our;

    public function __construct(OrganizationUserRepository $our) {
        $this->our = $our;
    }

    public function validate($email, Constraint $constraint)
    {
        if ($constraint->getClass() == OrganizationUser::class) {
            $user = $this->our->findOneByEmail($email);
        }

        if ($user) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('%email%', $email)
                ->addViolation();
        }
    }
}


text:
#ifndef _WX_MSW_LIBRARIES_H_
#  define _WX_MSW_LIBRARIES_H_
/*
 * Notes:
 *
 * In general the preferred place to add libs is in the bakefiles. This file
 * can be used where libs must be added conditionally, for those compilers that
 * support a way to do that.
 */
#  if  defined __VISUALC__ && wxUSE_ACCESSIBILITY
#    pragma  comment(lib, "oleacc")
#  endif
#  if  defined __VISUALC__ && wxUSE_UXTHEME
#    pragma  comment(lib, "uxtheme")
#  endif
#endif


text:
UILabel subclass simple circular progress for iOS - Objective C.

![MALabelProgress](https://github.com/miguelappsonline/MALabelProgress/blob/master/Examples/example_one.gif)
![MALabelProgress](https://github.com/miguelappsonline/MALabelProgress/blob/master/Examples/example_two.gif)
![MALabelProgress](https://github.com/miguelappsonline/MALabelProgress/blob/master/Examples/example_three.gif)

## Usage

### Style

```objective-c
// You can customize the lines width, lines color, fill color and label's font.
-(void) setStyleWithLineWidth:(CGFloat) lineWidth
                progressWidth:(CGFloat) progressWidth
                    lineColor:(UIColor*) lineColor
                progressColor:(UIColor*) progressColor
                    fillColor:(UIColor*) fillColor
                    labelFont:(UIFont*) font;
```

### Update progress value

```objective-c

// Set a percentage of the progress. Values between 0-100.
// The label's text shows the number of percent 0-100.
// unFillMode to show the progress inverted
-(void) setProgressPercent:(CGFloat) percent
             andUnfillMode:(BOOL) unFillMode
                  animated:(BOOL) animated

// Set a progress between two dates related to the current date.
// The label's text shows the number of days left to the end date.
// unFillMode to show the progress inverted
-(void) setProgressWithStartDate:(NSDate*) start
                      andEndDate:(NSDate*) endDate
                   andUnfillMode:(BOOL) unFillMode
                        animated:(BOOL) animated;

```


text:
"""Tests for the aggregates admin api."""

import mock
from webob import exc

from nova.api.openstack.compute.contrib import aggregates as aggregates_v2
from nova.api.openstack.compute.plugins.v3 import aggregates as aggregates_v21
from nova import context
from nova import exception
from nova import test
from nova.tests.unit.api.openstack import fakes
from nova.tests.unit import matchers

AGGREGATE_LIST = [
        {"name": "aggregate1", "id": "1", "availability_zone": "nova1"},
        {"name": "aggregate2", "id": "2", "availability_zone": "nova1"},
        {"name": "aggregate3", "id": "3", "availability_zone": "nova2"},
        {"name": "aggregate1", "id": "4", "availability_zone": "nova1"}]
AGGREGATE = {"name": "aggregate1",
                  "id": "1",
                  "availability_zone": "nova1",
                  "metadata": {"foo": "bar"},
                  "hosts": ["host1, host2"]}

FORMATTED_AGGREGATE = {"name": "aggregate1",
                  "id": "1",
                  "availability_zone": "nova1"}

class FakeRequest(object):
    environ = {"nova.context": context.get_admin_context()}

class AggregateTestCaseV21(test.NoDBTestCase):
    """Test Case for aggregates admin api."""

    add_host = 'self.controller._add_host'
    remove_host = 'self.controller._remove_host'
    set_metadata = 'self.controller._set_metadata'
    bad_request = exception.ValidationError

    def _set_up(self):
        self.controller = aggregates_v21.AggregateController()
        self.req = fakes.HTTPRequest.blank('/v3/os-aggregates',
                                           use_admin_context=True)
        self.user_req = fakes.HTTPRequest.blank('/v3/os-aggregates')
        self.context = self.req.environ['nova.context']

    def setUp(self):
        super(AggregateTestCaseV21, self).setUp()
        self._set_up()

    def test_index(self):
        def stub_list_aggregates(context):
            if context is None:
                raise Exception()
            return AGGREGATE_LIST
        self.stubs.Set(self.controller.api, 'get_aggregate_list',
                       stub_list_aggregates)

        result = self.controller.index(self.req)

        self.assertEqual(AGGREGATE_LIST, result["aggregates"])

    def test_index_no_admin(self):
        self.assertRaises(exception.PolicyNotAuthorized,
                          self.controller.index,
                          self.user_req)

    def test_create(self):
        def stub_create_aggregate(context, name, availability_zone):
            self.assertEqual(context, self.context, "context")
            self.assertEqual("test", name, "name")
            self.assertEqual("nova1", availability_zone, "availability_zone")
            return AGGREGATE
        self.stubs.Set(self.controller.api, "create_aggregate",
                       stub_create_aggregate)

        result = self.controller.create(self.req, body={"aggregate":
                                          {"name": "test",
                                           "availability_zone": "nova1"}})
        self.assertEqual(FORMATTED_AGGREGATE, result["aggregate"])

    def test_create_no_admin(self):
        self.assertRaises(exception.PolicyNotAuthorized,
                          self.controller.create, self.user_req,
                          body={"aggregate":
                              {"name": "test",
                               "availability_zone": "nova1"}})

    def test_create_with_duplicate_aggregate_name(self):
        def stub_create_aggregate(context, name, availability_zone):
            raise exception.AggregateNameExists(aggregate_name=name)
        self.stubs.Set(self.controller.api, "create_aggregate",
                       stub_create_aggregate)

        self.assertRaises(exc.HTTPConflict, self.controller.create,
                          self.req, body={"aggregate":
                                     {"name": "test",
                                      "availability_zone": "nova1"}})

    def test_create_with_incorrect_availability_zone(self):
        def stub_create_aggregate(context, name, availability_zone):
            raise exception.InvalidAggregateAction(action='create_aggregate',
                                                   aggregate_id="'N/A'",
                                                   reason='invalid zone')

        self.stubs.Set(self.controller.api, "create_aggregate",
                       stub_create_aggregate)

        self.assertRaises(exc.HTTPBadRequest,
                          self.controller.create,
                          self.req, body={"aggregate":
                                     {"name": "test",
                                      "availability_zone": "nova_bad"}})

    def test_create_with_no_aggregate(self):
        self.assertRaises(self.bad_request, self.controller.create,
                          self.req, body={"foo":
                                     {"name": "test",
                                      "availability_zone": "nova1"}})

    def test_create_with_no_name(self):
        self.assertRaises(self.bad_request, self.controller.create,
                          self.req, body={"aggregate":
                                     {"foo": "test",
                                      "availability_zone": "nova1"}})

    def test_create_with_no_availability_zone(self):
        def stub_create_aggregate(context, name, availability_zone):
            self.assertEqual(context, self.context, "context")
            self.assertEqual("test", name, "name")
            self.assertIsNone(availability_zone, "availability_zone")
            return AGGREGATE
        self.stubs.Set(self.controller.api, "create_aggregate",
                       stub_create_aggregate)

        result = self.controller.create(self.req,
                                        body={"aggregate": {"name": "test"}})
        self.assertEqual(FORMATTED_AGGREGATE, result["aggregate"])

    def test_create_with_null_name(self):
        self.assertRaises(self.bad_request, self.controller.create,
                          self.req, body={"aggregate":
                                     {"name": "",
                                      "availability_zone": "nova1"}})

    def test_create_with_name_too_long(self):
        self.assertRaises(self.bad_request, self.controller.create,
                          self.req, body={"aggregate":
                                     {"name": "x" * 256,
                                      "availability_zone": "nova1"}})

    def test_create_with_availability_zone_too_long(self):
        self.assertRaises(self.bad_request, self.controller.create,
                          self.req, body={"aggregate":
                                     {"name": "test",
                                      "availability_zone": "x" * 256}})

    def test_create_with_null_availability_zone(self):
        aggregate = {"name": "aggregate1",
                     "id": "1",
                     "availability_zone": None,
                     "metadata": {},
                     "hosts": []}

        formatted_aggregate = {"name": "aggregate1",
                     "id": "1",
                     "availability_zone": None}

        def stub_create_aggregate(context, name, az_name):
            self.assertEqual(context, self.context, "context")
            self.assertEqual("aggregate1", name, "name")
            self.assertIsNone(az_name, "availability_zone")
            return aggregate
        self.stubs.Set(self.controller.api, 'create_aggregate',
                       stub_create_aggregate)

        result = self.controller.create(self.req,
                                        body={"aggregate":
                                         {"name": "aggregate1",
                                          "availability_zone": None}})
        self.assertEqual(formatted_aggregate, result["aggregate"])

    def test_create_with_empty_availability_zone(self):
        self.assertRaises(self.bad_request, self.controller.create,
                          self.req, body={"aggregate":
                                     {"name": "test",
                                      "availability_zone": ""}})

    def test_create_with_extra_invalid_arg(self):
        self.assertRaises(self.bad_request, self.controller.create,
                          self.req, body={"name": "test",
                                          "availability_zone": "nova1",
                                          "foo": 'bar'})

    def test_show(self):
        def stub_get_aggregate(context, id):
            self.assertEqual(context, self.context, "context")
            self.assertEqual("1", id, "id")
            return AGGREGATE
        self.stubs.Set(self.controller.api, 'get_aggregate',
                       stub_get_aggregate)

        aggregate = self.controller.show(self.req, "1")

        self.assertEqual(AGGREGATE, aggregate["aggregate"])

    def test_show_no_admin(self):
        self.assertRaises(exception.PolicyNotAuthorized,
                          self.controller.show,
                          self.user_req, "1")

    def test_show_with_invalid_id(self):
        def stub_get_aggregate(context, id):
            raise exception.AggregateNotFound(aggregate_id=2)

        self.stubs.Set(self.controller.api, 'get_aggregate',
                       stub_get_aggregate)

        self.assertRaises(exc.HTTPNotFound,
                          self.controller.show, self.req, "2")

    def test_update(self):
        body = {"aggregate": {"name": "new_name",
                              "availability_zone": "nova1"}}

        def stub_update_aggregate(context, aggregate, values):
            self.assertEqual(context, self.context, "context")
            self.assertEqual("1", aggregate, "aggregate")
            self.assertEqual(body["aggregate"], values, "values")
            return AGGREGATE
        self.stubs.Set(self.controller.api, "update_aggregate",
                       stub_update_aggregate)

        result = self.controller.update(self.req, "1", body=body)

        self.assertEqual(AGGREGATE, result["aggregate"])

    def test_update_no_admin(self):
        body = {"aggregate": {"availability_zone": "nova"}}
        self.assertRaises(exception.PolicyNotAuthorized,
                          self.controller.update,
                          self.user_req, "1", body=body)

    def test_update_with_only_name(self):
        body = {"aggregate": {"name": "new_name"}}

        def stub_update_aggregate(context, aggregate, values):
            return AGGREGATE
        self.stubs.Set(self.controller.api, "update_aggregate",
                       stub_update_aggregate)

        result = self.controller.update(self.req, "1", body=body)

        self.assertEqual(AGGREGATE, result["aggregate"])

    def test_update_with_only_availability_zone(self):
        body = {"aggregate": {"availability_zone": "nova1"}}

        def stub_update_aggregate(context, aggregate, values):
            return AGGREGATE
        self.stubs.Set(self.controller.api, "update_aggregate",
                       stub_update_aggregate)
        result = self.controller.update(self.req, "1", body=body)
        self.assertEqual(AGGREGATE, result["aggregate"])

    def test_update_with_no_updates(self):
        test_metadata = {"aggregate": {}}
        self.assertRaises(self.bad_request, self.controller.update,
                          self.req, "2", body=test_metadata)

    def test_update_with_no_update_key(self):
        test_metadata = {"asdf": {}}
        self.assertRaises(self.bad_request, self.controller.update,
                          self.req, "2", body=test_metadata)

    def test_update_with_wrong_updates(self):
        test_metadata = {"aggregate": {"status": "disable",
                                     "foo": "bar"}}
        self.assertRaises(self.bad_request, self.controller.update,
                          self.req, "2", body=test_metadata)

    def test_update_with_null_name(self):
        test_metadata = {"aggregate": {"name": ""}}
        self.assertRaises(self.bad_request, self.controller.update,
                          self.req, "2", body=test_metadata)

    def test_update_with_name_too_long(self):
        test_metadata = {"aggregate": {"name": "x" * 256}}
        self.assertRaises(self.bad_request, self.controller.update,
                          self.req, "2", body=test_metadata)

    def test_update_with_availability_zone_too_long(self):
        test_metadata = {"aggregate": {"availability_zone": "x" * 256}}
        self.assertRaises(self.bad_request, self.controller.update,
                          self.req, "2", body=test_metadata)

    def test_update_with_empty_availability_zone(self):
        test_metadata = {"aggregate": {"availability_zone": ""}}
        self.assertRaises(self.bad_request, self.controller.update,
                          self.req, "2", body=test_metadata)

    def test_update_with_null_availability_zone(self):
        body = {"aggregate": {"availability_zone": None}}
        aggre = {"name": "aggregate1",
                     "id": "1",
                     "availability_zone": None}

        def stub_update_aggregate(context, aggregate, values):
            self.assertEqual(context, self.context, "context")
            self.assertEqual("1", aggregate, "aggregate")
            self.assertIsNone(values["availability_zone"], "availability_zone")
            return aggre
        self.stubs.Set(self.controller.api, "update_aggregate",
                       stub_update_aggregate)

        result = self.controller.update(self.req, "1", body=body)

        self.assertEqual(aggre, result["aggregate"])

    def test_update_with_bad_aggregate(self):
        test_metadata = {"aggregate": {"name": "test_name"}}

        def stub_update_aggregate(context, aggregate, metadata):
            raise exception.AggregateNotFound(aggregate_id=2)
        self.stubs.Set(self.controller.api, "update_aggregate",
                       stub_update_aggregate)

        self.assertRaises(exc.HTTPNotFound, self.controller.update,
                self.req, "2", body=test_metadata)

    def test_update_with_duplicated_name(self):
        test_metadata = {"aggregate": {"name": "test_name"}}

        def stub_update_aggregate(context, aggregate, metadata):
            raise exception.AggregateNameExists(aggregate_name="test_name")

        self.stubs.Set(self.controller.api, "update_aggregate",
                       stub_update_aggregate)
        self.assertRaises(exc.HTTPConflict, self.controller.update,
                self.req, "2", body=test_metadata)

    def test_invalid_action(self):
        body = {"append_host": {"host": "host1"}}
        self.assertRaises(self.bad_request,
                          eval(self.add_host), self.req, "1", body=body)

    def test_update_with_invalid_action(self):
        with mock.patch.object(self.controller.api, "update_aggregate",
            side_effect=exception.InvalidAggregateAction(
                action='invalid', aggregate_id='agg1', reason= "not empty")):
            body = {"aggregate": {"availability_zone": "nova"}}
            self.assertRaises(exc.HTTPBadRequest, self.controller.update,
                              self.req, "1", body=body)

    def test_add_host(self):
        def stub_add_host_to_aggregate(context, aggregate, host):
            self.assertEqual(context, self.context, "context")
            self.assertEqual("1", aggregate, "aggregate")
            self.assertEqual("host1", host, "host")
            return AGGREGATE
        self.stubs.Set(self.controller.api, "add_host_to_aggregate",
                       stub_add_host_to_aggregate)

        aggregate = eval(self.add_host)(self.req, "1",
                                        body={"add_host": {"host":
                                                           "host1"}})

        self.assertEqual(aggregate["aggregate"], AGGREGATE)

    def test_add_host_no_admin(self):
        self.assertRaises(exception.PolicyNotAuthorized,
                          eval(self.add_host),
                          self.user_req, "1",
                          body={"add_host": {"host": "host1"}})

    def test_add_host_with_already_added_host(self):
        def stub_add_host_to_aggregate(context, aggregate, host):
            raise exception.AggregateHostExists(aggregate_id=aggregate,
                                                host=host)
        self.stubs.Set(self.controller.api, "add_host_to_aggregate",
                       stub_add_host_to_aggregate)

        self.assertRaises(exc.HTTPConflict, eval(self.add_host),
                          self.req, "1",
                          body={"add_host": {"host": "host1"}})

    def test_add_host_with_bad_aggregate(self):
        def stub_add_host_to_aggregate(context, aggregate, host):
            raise exception.AggregateNotFound(aggregate_id=aggregate)
        self.stubs.Set(self.controller.api, "add_host_to_aggregate",
                       stub_add_host_to_aggregate)

        self.assertRaises(exc.HTTPNotFound, eval(self.add_host),
                          self.req, "bogus_aggregate",
                          body={"add_host": {"host": "host1"}})

    def test_add_host_with_bad_host(self):
        def stub_add_host_to_aggregate(context, aggregate, host):
            raise exception.ComputeHostNotFound(host=host)
        self.stubs.Set(self.controller.api, "add_host_to_aggregate",
                       stub_add_host_to_aggregate)

        self.assertRaises(exc.HTTPNotFound, eval(self.add_host),
                          self.req, "1",
                          body={"add_host": {"host": "bogus_host"}})

    def test_add_host_with_missing_host(self):
        self.assertRaises(self.bad_request, eval(self.add_host),
                self.req, "1", body={"add_host": {"asdf": "asdf"}})

    def test_add_host_with_invalid_format_host(self):
        self.assertRaises(self.bad_request, eval(self.add_host),
                self.req, "1", body={"add_host": {"host": "a" * 300}})

    def test_add_host_with_multiple_hosts(self):
        self.assertRaises(self.bad_request, eval(self.add_host),
                self.req, "1", body={"add_host": {"host": ["host1", "host2"]}})

    def test_add_host_raises_key_error(self):
        def stub_add_host_to_aggregate(context, aggregate, host):
            raise KeyError
        self.stubs.Set(self.controller.api, "add_host_to_aggregate",
                       stub_add_host_to_aggregate)
        self.assertRaises(exc.HTTPInternalServerError,
                          eval(self.add_host), self.req, "1",
                          body={"add_host": {"host": "host1"}})

    def test_add_host_with_invalid_request(self):
        self.assertRaises(self.bad_request, eval(self.add_host),
                self.req, "1", body={"add_host": "1"})

    def test_add_host_with_non_string(self):
        self.assertRaises(self.bad_request, eval(self.add_host),
                self.req, "1", body={"add_host": {"host": 1}})

    def test_remove_host(self):
        def stub_remove_host_from_aggregate(context, aggregate, host):
            self.assertEqual(context, self.context, "context")
            self.assertEqual("1", aggregate, "aggregate")
            self.assertEqual("host1", host, "host")
            stub_remove_host_from_aggregate.called = True
            return {}
        self.stubs.Set(self.controller.api,
                       "remove_host_from_aggregate",
                       stub_remove_host_from_aggregate)
        eval(self.remove_host)(self.req, "1",
                                  body={"remove_host": {"host": "host1"}})

        self.assertTrue(stub_remove_host_from_aggregate.called)

    def test_remove_host_no_admin(self):
        self.assertRaises(exception.PolicyNotAuthorized,
                          eval(self.remove_host),
                          self.user_req, "1",
                          body={"remove_host": {"host": "host1"}})

    def test_remove_host_with_bad_aggregate(self):
        def stub_remove_host_from_aggregate(context, aggregate, host):
            raise exception.AggregateNotFound(aggregate_id=aggregate)
        self.stubs.Set(self.controller.api,
                       "remove_host_from_aggregate",
                       stub_remove_host_from_aggregate)

        self.assertRaises(exc.HTTPNotFound, eval(self.remove_host),
                          self.req, "bogus_aggregate",
                          body={"remove_host": {"host": "host1"}})

    def test_remove_host_with_host_not_in_aggregate(self):
        def stub_remove_host_from_aggregate(context, aggregate, host):
            raise exception.AggregateHostNotFound(aggregate_id=aggregate,
                                                  host=host)
        self.stubs.Set(self.controller.api,
                       "remove_host_from_aggregate",
                       stub_remove_host_from_aggregate)

        self.assertRaises(exc.HTTPNotFound, eval(self.remove_host),
                          self.req, "1",
                          body={"remove_host": {"host": "host1"}})

    def test_remove_host_with_bad_host(self):
        def stub_remove_host_from_aggregate(context, aggregate, host):
            raise exception.ComputeHostNotFound(host=host)
        self.stubs.Set(self.controller.api,
                       "remove_host_from_aggregate",
                       stub_remove_host_from_aggregate)

        self.assertRaises(exc.HTTPNotFound, eval(self.remove_host),
                self.req, "1", body={"remove_host": {"host": "bogushost"}})

    def test_remove_host_with_missing_host(self):
        self.assertRaises(self.bad_request, eval(self.remove_host),
                self.req, "1", body={"asdf": "asdf"})

    def test_remove_host_with_multiple_hosts(self):
        self.assertRaises(self.bad_request, eval(self.remove_host),
                self.req, "1", body={"remove_host": {"host":
                                                     ["host1", "host2"]}})

    def test_remove_host_with_extra_param(self):
        self.assertRaises(self.bad_request, eval(self.remove_host),
                self.req, "1", body={"remove_host": {"asdf": "asdf",
                                                     "host": "asdf"}})

    def test_remove_host_with_invalid_request(self):
        self.assertRaises(self.bad_request,
                          eval(self.remove_host),
                self.req, "1", body={"remove_host": "1"})

    def test_remove_host_with_missing_host_empty(self):
        self.assertRaises(self.bad_request,
                          eval(self.remove_host),
                self.req, "1", body={"remove_host": {}})

    def test_set_metadata(self):
        body = {"set_metadata": {"metadata": {"foo": "bar"}}}

        def stub_update_aggregate(context, aggregate, values):
            self.assertEqual(context, self.context, "context")
            self.assertEqual("1", aggregate, "aggregate")
            self.assertThat(body["set_metadata"]['metadata'],
                            matchers.DictMatches(values))
            return AGGREGATE
        self.stubs.Set(self.controller.api,
                       "update_aggregate_metadata",
                       stub_update_aggregate)

        result = eval(self.set_metadata)(self.req, "1", body=body)

        self.assertEqual(AGGREGATE, result["aggregate"])

    def test_set_metadata_delete(self):
        body = {"set_metadata": {"metadata": {"foo": None}}}

        with mock.patch.object(self.controller.api,
                               'update_aggregate_metadata') as mocked:
            mocked.return_value = AGGREGATE
            result = eval(self.set_metadata)(self.req, "1", body=body)

        self.assertEqual(AGGREGATE, result["aggregate"])
        mocked.assert_called_once_with(self.context, "1",
                                       body["set_metadata"]["metadata"])

    def test_set_metadata_no_admin(self):
        self.assertRaises(exception.PolicyNotAuthorized,
                          eval(self.set_metadata),
                          self.user_req, "1",
                          body={"set_metadata": {"metadata":
                                                    {"foo": "bar"}}})

    def test_set_metadata_with_bad_aggregate(self):
        body = {"set_metadata": {"metadata": {"foo": "bar"}}}

        def stub_update_aggregate(context, aggregate, metadata):
            raise exception.AggregateNotFound(aggregate_id=aggregate)
        self.stubs.Set(self.controller.api,
                       "update_aggregate_metadata",
                       stub_update_aggregate)
        self.assertRaises(exc.HTTPNotFound, eval(self.set_metadata),
                self.req, "bad_aggregate", body=body)

    def test_set_metadata_with_missing_metadata(self):
        body = {"asdf": {"foo": "bar"}}
        self.assertRaises(self.bad_request, eval(self.set_metadata),
                          self.req, "1", body=body)

    def test_set_metadata_with_extra_params(self):
        body = {"metadata": {"foo": "bar"}, "asdf": {"foo": "bar"}}
        self.assertRaises(self.bad_request, eval(self.set_metadata),
                          self.req, "1", body=body)

    def test_set_metadata_without_dict(self):
        body = {"set_metadata": {'metadata': 1}}
        self.assertRaises(self.bad_request, eval(self.set_metadata),
                          self.req, "1", body=body)

    def test_set_metadata_with_empty_key(self):
        body = {"set_metadata": {"metadata": {"": "value"}}}
        self.assertRaises(self.bad_request, eval(self.set_metadata),
                          self.req, "1", body=body)

    def test_set_metadata_with_key_too_long(self):
        body = {"set_metadata": {"metadata": {"x" * 256: "value"}}}
        self.assertRaises(self.bad_request, eval(self.set_metadata),
                          self.req, "1", body=body)

    def test_set_metadata_with_value_too_long(self):
        body = {"set_metadata": {"metadata": {"key": "x" * 256}}}
        self.assertRaises(self.bad_request, eval(self.set_metadata),
                          self.req, "1", body=body)

    def test_set_metadata_with_string(self):
        body = {"set_metadata": {"metadata": "test"}}
        self.assertRaises(self.bad_request, eval(self.set_metadata),
                          self.req, "1", body=body)

    def test_delete_aggregate(self):
        def stub_delete_aggregate(context, aggregate):
            self.assertEqual(context, self.context, "context")
            self.assertEqual("1", aggregate, "aggregate")
            stub_delete_aggregate.called = True
        self.stubs.Set(self.controller.api, "delete_aggregate",
                       stub_delete_aggregate)

        self.controller.delete(self.req, "1")
        self.assertTrue(stub_delete_aggregate.called)

    def test_delete_aggregate_no_admin(self):
        self.assertRaises(exception.PolicyNotAuthorized,
                          self.controller.delete,
                          self.user_req, "1")

    def test_delete_aggregate_with_bad_aggregate(self):
        def stub_delete_aggregate(context, aggregate):
            raise exception.AggregateNotFound(aggregate_id=aggregate)
        self.stubs.Set(self.controller.api, "delete_aggregate",
                       stub_delete_aggregate)

        self.assertRaises(exc.HTTPNotFound, self.controller.delete,
                self.req, "bogus_aggregate")

    def test_delete_aggregate_with_host(self):
        with mock.patch.object(self.controller.api, "delete_aggregate",
                               side_effect=exception.InvalidAggregateAction(
                               action="delete", aggregate_id="agg1",
                               reason="not empty")):
            self.assertRaises(exc.HTTPBadRequest,
                              self.controller.delete,
                              self.req, "agg1")

class AggregateTestCaseV2(AggregateTestCaseV21):
    add_host = 'self.controller.action'
    remove_host = 'self.controller.action'
    set_metadata = 'self.controller.action'
    bad_request = exc.HTTPBadRequest

    def _set_up(self):
        self.controller = aggregates_v2.AggregateController()
        self.req = FakeRequest()
        self.user_req = fakes.HTTPRequest.blank('/v2/os-aggregates')
        self.context = self.req.environ['nova.context']

    def test_add_host_raises_key_error(self):
        def stub_add_host_to_aggregate(context, aggregate, host):
            raise KeyError
        self.stubs.Set(self.controller.api, "add_host_to_aggregate",
                       stub_add_host_to_aggregate)
        # NOTE(mtreinish) The check for a KeyError here is to ensure that
        # if add_host_to_aggregate() raises a KeyError it propagates. At
        # one point the api code would mask the error as a HTTPBadRequest.
        # This test is to ensure that this doesn't occur again.
        self.assertRaises(KeyError, eval(self.add_host), self.req, "1",
                          body={"add_host": {"host": "host1"}})

    def test_add_host_to_aggregate_with_non_admin(self):
        rule_name = "compute_extension:aggregates"
        self.policy.set_rules({rule_name: ""})
        self.assertRaises(exception.AdminRequired, self.controller._add_host,
                          self.user_req, '1', {'host': 'fake_host'})

    def test_remove_host_from_aggregate_with_non_admin(self):
        rule_name = "compute_extension:aggregates"
        self.policy.set_rules({rule_name: ""})
        self.assertRaises(exception.AdminRequired,
                          self.controller._remove_host, self.user_req,
                          '1', {'host': 'fake_host'})


text:
'use strict';

const assert = require('assert');
const parse = require('@emmetio/abbreviation');
const Profile = require('@emmetio/output-profile');
const replaceVariables = require('@emmetio/variable-resolver');
const format = require('../').default;

describe('Main formatter', () => {
	const expand = (abbr, syntax) =>
        format(parse(abbr), new Profile(), syntax);

	it('expand', () => {
		assert.equal(expand('a>b'), '');
		assert.equal(expand('a>b', 'html'), '');
		assert.equal(expand('a>b', 'slim'), 'a\n\tb');
		assert.equal(expand('a>b', 'haml'), '%a\n\t%b');
		assert.equal(expand('a[foo={bar}]>b[foo=foo]', 'html'), '');
	});
});


text:
package main

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"strings"
)

type jResult struct {
	Poster string
}

const baseURL = "http://www.omdbapi.com"

func main() {
	query := strings.Join(os.Args[1:], "+")
	url := fmt.Sprintf("%s/?t=%s", baseURL, query)
	fmt.Println(url)
	download(getImgURL(url))
}

func getImgURL(url string) string {
	response, err := http.Get(url)
	if err != nil {
		log.Fatal(err)
	}
	defer response.Body.Close()
	if response.StatusCode != http.StatusOK {
		log.Printf("Faile to access %v", response.StatusCode)
	}
	var result jResult
	if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
		log.Fatal(err)
	}
	return result.Poster
}

func download(url string) {
	response, err := http.Get(url)
	if err != nil {
		log.Fatal(err)
	}
	defer response.Body.Close()
	if response.StatusCode != http.StatusOK {
		log.Printf("Faile to access %v", response.StatusCode)
	}
	file, err := os.Create("poster.jpg")
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()
	io.Copy(file, response.Body)
}


text:
layout: docs
title: Popovers
description: Documentation and examples for adding Bootstrap popovers, like those found in iOS, to any element on your site.
group: components
toc: true
---

## Overview

Things to know when using the popover plugin:

- Popovers rely on the third party library [Popper](https://popper.js.org/) for positioning. You must include [popper.min.js]({{< param "cdn.popper" >}}) before `bootstrap.js`, or use one `bootstrap.bundle.min.js` which contains Popper.
- Popovers require the [popover plugin]({{< docsref "/components/popovers" >}}) as a dependency.
- Popovers are opt-in for performance reasons, so **you must initialize them yourself**.
- Zero-length `title` and `content` values will never show a popover.
- Specify `container: 'body'` to avoid rendering problems in more complex components (like our input groups, button groups, etc).
- Triggering popovers on hidden elements will not work.
- Popovers for `.disabled` or `disabled` elements must be triggered on a wrapper element.
- When triggered from anchors that wrap across multiple lines, popovers will be centered between the anchors' overall width. Use `.text-nowrap` on your `<a>`s to avoid this behavior.
- Popovers must be hidden before their corresponding elements have been removed from the DOM.
- Popovers can be triggered thanks to an element inside a shadow DOM.

{{< callout info >}}
{{< partial "callout-info-sanitizer.md" >}}
{{< /callout >}}

{{< callout info >}}
{{< partial "callout-info-prefersreducedmotion.md" >}}
{{< /callout >}}

Keep reading to see how popovers work with some examples.

## Examples

### Enable popovers

As mentioned above, you must initialize popovers before they can be used. One way to initialize all popovers on a page would be to select them by their `data-bs-toggle` attribute, like so:

```js
const popoverTriggerList = document.querySelectorAll('[data-bs-toggle="popover"]')
const popoverList = [...popoverTriggerList].map(popoverTriggerEl => new bootstrap.Popover(popoverTriggerEl))
```

### Live demo

We use JavaScript similar to the snippet above to render the following live popover. Titles are set via `data-bs-title` and body content is set via `data-bs-content`.

{{< callout warning >}}
{{< partial "callout-warning-data-bs-title-vs-title.md" >}}
{{< /callout >}}

{{< example stackblitz_add_js="true" >}}
<button type="button" class="btn btn-lg btn-danger" data-bs-toggle="popover" data-bs-title="Popover title" data-bs-content="And here's some amazing content. It's very engaging. Right?">Click to toggle popover</button>
{{< /example >}}

### Four directions

Four options are available: top, right, bottom, and left. Directions are mirrored when using Bootstrap in RTL. Set `data-bs-placement` to change the direction.

{{< example stackblitz_add_js="true" >}}
<button type="button" class="btn btn-secondary" data-bs-container="body" data-bs-toggle="popover" data-bs-placement="top" data-bs-content="Top popover">
  Popover on top
</button>
<button type="button" class="btn btn-secondary" data-bs-container="body" data-bs-toggle="popover" data-bs-placement="right" data-bs-content="Right popover">
  Popover on right
</button>
<button type="button" class="btn btn-secondary" data-bs-container="body" data-bs-toggle="popover" data-bs-placement="bottom" data-bs-content="Bottom popover">
  Popover on bottom
</button>
<button type="button" class="btn btn-secondary" data-bs-container="body" data-bs-toggle="popover" data-bs-placement="left" data-bs-content="Left popover">
  Popover on left
</button>
{{< /example >}}

### Custom `container`

When you have some styles on a parent element that interfere with a popover, you'll want to specify a custom `container` so that the popover's HTML appears within that element instead. This is common in responsive tables, input groups, and the like.

```js
const popover = new bootstrap.Popover('.example-popover', {
  container: 'body'
})
```

### Custom popovers

{{< added-in "5.2.0" >}}

You can customize the appearance of popovers using [CSS variables](#variables). We set a custom class with `data-bs-custom-class="custom-popover"` to scope our custom appearance and use it to override some of the local CSS variables.

{{< scss-docs name="custom-popovers" file="site/assets/scss/_component-examples.scss" >}}

{{< example class="custom-popover-demo" stackblitz_add_js="true" >}}
<button type="button" class="btn btn-secondary"
        data-bs-toggle="popover" data-bs-placement="right"
        data-bs-custom-class="custom-popover"
        data-bs-title="Custom popover"
        data-bs-content="This popover is themed via CSS variables.">
  Custom popover
</button>
{{< /example >}}

### Dismiss on next click

Use the `focus` trigger to dismiss popovers on the user's next click of a different element than the toggle element.

{{< callout danger >}}
#### Specific markup required for dismiss-on-next-click

For proper cross-browser and cross-platform behavior, you must use the `<a>` tag, _not_ the `<button>` tag, and you also must include a [`tabindex`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex) attribute.
{{< /callout >}}

{{< example stackblitz_add_js="true" >}}
Dismissible popover
{{< /example >}}

```js
const popover = new bootstrap.Popover('.popover-dismiss', {
  trigger: 'focus'
})
```

### Disabled elements

Elements with the `disabled` attribute aren't interactive, meaning users cannot hover or click them to trigger a popover (or tooltip). As a workaround, you'll want to trigger the popover from a wrapper `<div>` or `<span>`, ideally made keyboard-focusable using `tabindex="0"`.

For disabled popover triggers, you may also prefer `data-bs-trigger="hover focus"` so that the popover appears as immediate visual feedback to your users as they may not expect to _click_ on a disabled element.

{{< example stackblitz_add_js="true" >}}

  <button class="btn btn-primary" type="button" disabled>Disabled button</button>

{{< /example >}}

## CSS

### Variables

{{< added-in "5.2.0" >}}

As part of Bootstrap's evolving CSS variables approach, popovers now use local CSS variables on `.popover` for enhanced real-time customization. Values for the CSS variables are set via Sass, so Sass customization is still supported, too.

{{< scss-docs name="popover-css-vars" file="scss/_popover.scss" >}}

### Sass variables

{{< scss-docs name="popover-variables" file="scss/_variables.scss" >}}

## Usage

Enable popovers via JavaScript:

```js
const exampleEl = document.getElementById('example')
const popover = new bootstrap.Popover(exampleEl, options)
```

{{< callout warning >}}
### Making popovers work for keyboard and assistive technology users

To allow keyboard users to activate your popovers, you should only add them to HTML elements that are traditionally keyboard-focusable and interactive (such as links or form controls). Although arbitrary HTML elements (such as `<span>`s) can be made focusable by adding the `tabindex="0"` attribute, this will add potentially annoying and confusing tab stops on non-interactive elements for keyboard users, and most assistive technologies currently do not announce the popover's content in this situation. Additionally, do not rely solely on `hover` as the trigger for your popovers, as this will make them impossible to trigger for keyboard users.

While you can insert rich, structured HTML in popovers with the `html` option, we strongly recommend that you avoid adding an excessive amount of content. The way popovers currently work is that, once displayed, their content is tied to the trigger element with the `aria-describedby` attribute. As a result, the entirety of the popover's content will be announced to assistive technology users as one long, uninterrupted stream.

Additionally, while it is possible to also include interactive controls (such as form elements or links) in your popover (by adding these elements to the `allowList` of allowed attributes and tags), be aware that currently the popover does not manage keyboard focus order. When a keyboard user opens a popover, focus remains on the triggering element, and as the popover usually does not immediately follow the trigger in the document's structure, there is no guarantee that moving forward/pressing TAB will move a keyboard user into the popover itself. In short, simply adding interactive controls to a popover is likely to make these controls unreachable/unusable for keyboard users and users of assistive technologies, or at the very least make for an illogical overall focus order. In these cases, consider using a modal dialog instead.
{{< /callout >}}

### Options

{{< markdown >}}
{{< partial "js-data-attributes.md" >}}
{{< /markdown >}}

{{< callout warning >}}
Note that for security reasons the `sanitize`, `sanitizeFn`, and `allowList` options cannot be supplied using data attributes.
{{< /callout >}}

{{< bs-table "table" >}}
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `allowList` | object | [Default value]({{< docsref "/getting-started/javascript#sanitizer" >}}) | Object which contains allowed attributes and tags. |
| `animation` | boolean | `true` | Apply a CSS fade transition to the popover |
| `boundary` | string, element | `'clippingParents'` | Overflow constraint boundary of the popover (applies only to Popper's preventOverflow modifier). By default, it's `'clippingParents'` and can accept an HTMLElement reference (via JavaScript only). For more information refer to Popper's [detectOverflow docs](https://popper.js.org/docs/v2/utils/detect-overflow/#boundary). |
| `container` | string, element, false | `false` | Appends the popover to a specific element. Example: `container: 'body'`. This option is particularly useful in that it allows you to position the popover in the flow of the document near the triggering element - which will prevent the popover from floating away from the triggering element during a window resize. |
| `content` | string, element, function | `''` | Default content value if `data-bs-content` attribute isn't present. If a function is given, it will be called with its `this` reference set to the element that the popover is attached to.
| `customClass` | string, function | `''` | Add classes to the popover when it is shown. Note that these classes will be added in addition to any classes specified in the template. To add multiple classes, separate them with spaces: `'class-1 class-2'`. You can also pass a function that should return a single string containing additional class names. |
| `delay` | number, object | `0` | Delay showing and hiding the popover (ms)—doesn't apply to manual trigger type. If a number is supplied, delay is applied to both hide/show. Object structure is: `delay: { "show": 500, "hide": 100 }`. |
| `fallbackPlacements` | string, array | `['top', 'right', 'bottom', 'left']` | Define fallback placements by providing a list of placements in array (in order of preference). For more information refer to Popper's [behavior docs](https://popper.js.org/docs/v2/modifiers/flip/#fallbackplacements). |
| `html` | boolean | `false` | Allow HTML in the popover. If true, HTML tags in the popover's `title` will be rendered in the popover. If false, `innerText` property will be used to insert content into the DOM. Use text if you're worried about XSS attacks. |
| `offset` | number, string, function | `[0, 0]` | Offset of the popover relative to its target. You can pass a string in data attributes with comma separated values like: `data-bs-offset="10,20"`. When a function is used to determine the offset, it is called with an object containing the popper placement, the reference, and popper rects as its first argument. The triggering element DOM node is passed as the second argument. The function must return an array with two numbers: [skidding](https://popper.js.org/docs/v2/modifiers/offset/#skidding-1), [distance](https://popper.js.org/docs/v2/modifiers/offset/#distance-1). For more information refer to Popper's [offset docs](https://popper.js.org/docs/v2/modifiers/offset/#options). |
| `placement` | string, function | `'top'` | How to position the popover: auto, top, bottom, left, right. When `auto` is specified, it will dynamically reorient the popover. When a function is used to determine the placement, it is called with the popover DOM node as its first argument and the triggering element DOM node as its second. The `this` context is set to the popover instance. |
| `popperConfig` | null, object, function | `null` | To change Bootstrap's default Popper config, see [Popper's configuration](https://popper.js.org/docs/v2/constructors/#options). When a function is used to create the Popper configuration, it's called with an object that contains the Bootstrap's default Popper configuration. It helps you use and merge the default with your own configuration. The function must return a configuration object for Popper.|
| `sanitize` | boolean | `true` | Enable or disable the sanitization. If activated `'template'`, `'content'` and `'title'` options will be sanitized. |
| `sanitizeFn` | null, function | `null` | Here you can supply your own sanitize function. This can be useful if you prefer to use a dedicated library to perform sanitization. |
| `selector` | string, false | `false` | If a selector is provided, popover objects will be delegated to the specified targets. In practice, this is used to also apply popovers to dynamically added DOM elements (`jQuery.on` support). See [this issue]({{< param repo >}}/issues/4215) and [an informative example](https://codepen.io/Johann-S/pen/djJYPb). |
| `template` | string | `'<div class="popover" role="popover"><div class="popover-arrow"></div><div class="popover-inner"></div></div>'` | Base HTML to use when creating the popover. The popover's `title` will be injected into the `.popover-inner`. `.popover-arrow` will become the popover's arrow. The outermost wrapper element should have the `.popover` class and `role="popover"`. |
| `title` | string, element, function | `''` | Default title value if `title` attribute isn't present. If a function is given, it will be called with its `this` reference set to the element that the popover is attached to. |
| `trigger` | string | `'hover focus'` | How popover is triggered: click, hover, focus, manual. You may pass multiple triggers; separate them with a space. `'manual'` indicates that the popover will be triggered programmatically via the `.popover('show')`, `.popover('hide')` and `.popover('toggle')` methods; this value cannot be combined with any other trigger. `'hover'` on its own will result in popovers that cannot be triggered via the keyboard, and should only be used if alternative methods for conveying the same information for keyboard users is present. |
{{< /bs-table >}}

{{< callout info >}}
#### Data attributes for individual popovers

Options for individual popovers can alternatively be specified through the use of data attributes, as explained above.
{{< /callout >}}

#### Using function with `popperConfig`

```js
const popover = new bootstrap.Popover(element, {
  popperConfig(defaultBsPopperConfig) {
    // const newPopperConfig = {...}
    // use defaultBsPopperConfig if needed...
    // return newPopperConfig
  }
})
```

### Methods

{{< callout danger >}}
{{< partial "callout-danger-async-methods.md" >}}
{{< /callout >}}

{{< bs-table "table" >}}
| Method | Description |
| --- | --- |
| `disable` | Removes the ability for an element's popover to be shown. The popover will only be able to be shown if it is re-enabled. |
| `dispose` | Hides and destroys an element's popover (Removes stored data on the DOM element). Popovers that use delegation (which are created using [the `selector` option](#options)) cannot be individually destroyed on descendant trigger elements. |
| `enable` | Gives an element's popover the ability to be shown. **Popovers are enabled by default.** |
| `getInstance` | _Static_ method which allows you to get the popover instance associated with a DOM element. |
| `getOrCreateInstance` | *Static* method which allows you to get the popover instance associated with a DOM element, or create a new one in case it wasn't initialized |
| `hide` | Hides an element's popover. **Returns to the caller before the popover has actually been hidden** (i.e. before the `hidden.bs.popover` event occurs). This is considered a "manual" triggering of the popover. |
| `setContent` | Gives a way to change the popover's content after its initialization. |
| `show` | Reveals an element's popover. **Returns to the caller before the popover has actually been shown** (i.e. before the `shown.bs.popover` event occurs). This is considered a "manual" triggering of the popover. Popovers whose title and content are both zero-length are never displayed. |
| `toggle` | Toggles an element's popover. **Returns to the caller before the popover has actually been shown or hidden** (i.e. before the `shown.bs.popover` or `hidden.bs.popover` event occurs). This is considered a "manual" triggering of the popover. |
| `toggleEnabled` | Toggles the ability for an element's popover to be shown or hidden. |
| `update` | Updates the position of an element's popover. |
{{< /bs-table >}}

```js
// getOrCreateInstance example
const popover = bootstrap.Popover.getOrCreateInstance('#example') // Returns a Bootstrap popover instance

// setContent example
myPopover.setContent({
  '.popover-header': 'another title',
  '.popover-body': 'another content'
})

```

{{< callout info >}}
The `setContent` method accepts an `object` argument, where each property-key is a valid `string` selector within the popover template, and each related property-value can be `string` | `element` | `function` | `null`
{{< /callout >}}

### Events

{{< bs-table >}}
| Event | Description |
| --- | --- |
| `hide.bs.popover` | This event is fired immediately when the `hide` instance method has been called. |
| `hidden.bs.popover` | This event is fired when the popover has finished being hidden from the user (will wait for CSS transitions to complete). |
| `inserted.bs.popover` | This event is fired after the `show.bs.popover` event when the popover template has been added to the DOM. |
| `show.bs.popover` | This event fires immediately when the `show` instance method is called. |
| `shown.bs.popover` | This event is fired when the popover has been made visible to the user (will wait for CSS transitions to complete). |
{{< /bs-table >}}

```js
const myPopoverTrigger = document.getElementById('myPopover')
myPopoverTrigger.addEventListener('hidden.bs.popover', () => {
  // do something...
})
```


text:
plsql.execute <<-SQL
CREATE OR REPLACE
 PROCEDURE award_bonus (
  emp_id NUMBER, sales_amt NUMBER) AS
  commission    REAL;
  comm_missing  EXCEPTION;
BEGIN
  SELECT commission_pct INTO commission
    FROM employees2
      WHERE employee_id = emp_id;

  IF commission IS NULL THEN
    RAISE comm_missing;
  ELSE
    UPDATE employees2
      SET salary = NVL(salary,0) + sales_amt*commission
        WHERE employee_id = emp_id;
  END IF;
END;
SQL


text:
/**
 * ape framework module for installing modules.
 * @module ape-installing
 */

"use strict";

module.exports = {
    get done() { return require('./done'); },
    get unlessGlobal() { return require('./unless_global'); }
};


text:
Get Started

We have a few options for you to start designing and building with SAP Hybris Techné fast.

Install with Bower

Compiled and minified CSS, Source LESS, JavaScript, and fonts, but no documentation.

                        INSTALL TECHNE WITH BOWER

                    The recommended way to integrate Techné into your project is by installing all resources with bower. Bower is a package manager for the web, which makes it easy for you to keep track of your project dependencies. If you have bower already installed simply run bower install hyTechne

                    This will provide you source files ansd precompiled resources at the same time, fitting for each skill level. If not, bower requires you first to install nodejs which includes the node package modules (NPM) package manager. After successful installation run:

                    npm install -g bower and run bower install hyTechne afterwards, to get Techné.

We're on GitHub

Bundle including Default files and all the source files (LESS/JS) not yet compiled.

                        VIEW SOURCE ON GITHUB

Download Pre-Bundled Zip

Precompiled and minified version of Techné ready to grab and use.

                        DOWNLOAD THE .ZIP

NPM Install

Techne is also avialable as a NPM package. You can install with the following command in terminal or command prompt:

npm install techne

Starter Pages

                    In order to make your UI design and development work even faster and have better consistency across Builder UI Modules we've introduced some generic page layout starters you can use and customize as needed. Preview examples of the Starter Pages.

                        STARTER PAGES ON GITHUB

Design Resources

Axure Libraries and Masters

Download our Axure RP library and hit the ground running... The library offers page layouts and specifications

                                AXURE RP LIBRARY

Color Swatches

                    Download the full set of application color swatches - primary colors as well as secondary colors

                        DOWNLOAD COLOR SWATCHES

Fonts

                    Download Dosis and Open Sans font families from the link below or find it included in our GitHub project.

                                DOWNLOAD DOSIS FONT

                                DOWNLOAD OPEN SANS FONT

Contribute back to Techné

                    So you wrote a new component or fixed a bug in Techné? You want to contribute? That's actually super easy. Just pull our repository from github, make your changes in a feature-branch, push it to origin and create a pull-request to our develop brach.

                        FIND US ON GITHUB

How to build Techné Documentation locally

                    Techné is using Gulp as build system.

Installing Gulp

                    Gulp requires you first to install nodejs which includes the node package modules (NPM) package manager. Then you can simply run npm install --global gulp

                    (Note the —global, otherwise you would not be able to run gulp systemwide)

IMPORTANT: The variable @bower-path is not defined per default. It is required that you define this variable in your own stylesheet and point to your bower_components folder. (No trailing slash).

Example:@bower-path: '../../bower_components';

Available Commands

gulp

Default task that builds all resources (js/less/..) and starts a local server with running watch-task

gulp dist

Create a prebuilt bundle including zip file for distribution

gulp build

Build all resources including documentation

gulp watch

Listen for file changes in src folder for compilation

gulp styleguide

Build docs

gulp connect

start server

gulp setpath

Generate _resource-paths.less file based on settings in config.json to handle file paths correctly.

Troubleshooting

Should you encounter problems with installing dependencies or running Grunt commands, first delete the /node_modules/ directory generated by npm. Then, rerun npm install.

Still having problems or have questions about Techné? Ask Hybris Experts


text:
/* Using a ternary operator to declare variable 'app' as an empty object regardless of which script is run first. Pseudocode: If app already exists (first condition), then do nothing. If it doesn't, then create it as an object with a nested store object.
*/
var app = app? app : {
  store: {
    // The submittedTasks object is appended with a new property every time the user submits a task (by hitting 'Enter'), with key: value pairs of the form: row-x: "Task content string". Deleting or completing a task removes the corresponding property from this object.
    submittedTasks: {},
    // The completedTasks object  is appended with a new property every time the user completes a task (by clicking the checkbox), with key: value pairs of the form: row-x: "Task content string". These tasks can be viewed underneath the to do list and restored to the list.
    completedTasks: {},
  }
};

// Listen for when a task from the list-item module has been completed
document.body.addEventListener("complete", function(event) {
   // receive the row number (rowNum) and task string (taskString) from list-item module for the most recently completed task
  var taskInfo = event.detail;
  }
);


text:
package petablox.analyses.inst;

import soot.Local;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.jimple.internal.JAssignStmt;

import petablox.analyses.alloc.DomH;
import petablox.analyses.method.DomM;
import petablox.analyses.var.DomV;
import petablox.project.Petablox;
import petablox.project.Messages;
import petablox.project.analyses.ProgramRel;
import petablox.util.soot.SootUtilities;

/**
 * Relation containing each tuple (m,v,h) such that method m contains
 * object allocation statement h which assigns to local variable v.
 *
 * @author Mayur Naik (mhn@cs.stanford.edu)
 */
@Petablox(
    name = "MobjValAsgnInst",
    sign = "M0,V0,H0:M0_V0_H0"
)
public class RelMobjValAsgnInst extends ProgramRel {
    public void fill() {
        DomM domM = (DomM) doms[0];
        DomV domV = (DomV) doms[1];
        DomH domH = (DomH) doms[2];
        int numA = domH.getLastA() + 1;
        for (int hIdx = 1; hIdx < numA; hIdx++) {
            Unit q = (Unit) domH.get(hIdx);
            SootMethod m = SootUtilities.getMethod(q);
            int mIdx = domM.indexOf(m);
            assert (mIdx >= 0);
            Local vo=null;
            if(q instanceof JAssignStmt){
            	JAssignStmt j = (JAssignStmt)q;
            	Value left = j.leftBox.getValue();
            	if(SootUtilities.isNewStmt(j))
            		vo = (Local)left;
            	else if(SootUtilities.isNewArrayStmt(j))
            		vo = (Local)left;
            	else if(SootUtilities.isNewMultiArrayStmt(j))
            		vo = (Local)left;
            	else if(j.containsInvokeExpr())
            		vo = (Local)left;
            	else{
            		Messages.fatal("Unknown quad in domain H: " + q);
                    vo = null;
            	}
            }
            int vIdx = domV.indexOf(vo);
            if (vIdx >= 0)
                add(mIdx, vIdx, hIdx);
        }
    }
}


text: Bitte schenken Sie der Auswahl und Aufbereitung Ihrer CSV-Dateien besondere Beachtung.


text:
package v1

import (
	"github.com/rancher/norman/lifecycle"
	"github.com/rancher/norman/resource"
	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/runtime"
)

type ResourceQuotaLifecycle interface {
	Create(obj *v1.ResourceQuota) (runtime.Object, error)
	Remove(obj *v1.ResourceQuota) (runtime.Object, error)
	Updated(obj *v1.ResourceQuota) (runtime.Object, error)
}

type resourceQuotaLifecycleAdapter struct {
	lifecycle ResourceQuotaLifecycle
}

func (w *resourceQuotaLifecycleAdapter) HasCreate() bool {
	o, ok := w.lifecycle.(lifecycle.ObjectLifecycleCondition)
	return !ok || o.HasCreate()
}

func (w *resourceQuotaLifecycleAdapter) HasFinalize() bool {
	o, ok := w.lifecycle.(lifecycle.ObjectLifecycleCondition)
	return !ok || o.HasFinalize()
}

func (w *resourceQuotaLifecycleAdapter) Create(obj runtime.Object) (runtime.Object, error) {
	o, err := w.lifecycle.Create(obj.(*v1.ResourceQuota))
	if o == nil {
		return nil, err
	}
	return o, err
}

func (w *resourceQuotaLifecycleAdapter) Finalize(obj runtime.Object) (runtime.Object, error) {
	o, err := w.lifecycle.Remove(obj.(*v1.ResourceQuota))
	if o == nil {
		return nil, err
	}
	return o, err
}

func (w *resourceQuotaLifecycleAdapter) Updated(obj runtime.Object) (runtime.Object, error) {
	o, err := w.lifecycle.Updated(obj.(*v1.ResourceQuota))
	if o == nil {
		return nil, err
	}
	return o, err
}

func NewResourceQuotaLifecycleAdapter(name string, clusterScoped bool, client ResourceQuotaInterface, l ResourceQuotaLifecycle) ResourceQuotaHandlerFunc {
	if clusterScoped {
		resource.PutClusterScoped(ResourceQuotaGroupVersionResource)
	}
	adapter := &resourceQuotaLifecycleAdapter{lifecycle: l}
	syncFn := lifecycle.NewObjectLifecycleAdapter(name, clusterScoped, adapter, client.ObjectClient())
	return func(key string, obj *v1.ResourceQuota) (runtime.Object, error) {
		newObj, err := syncFn(key, obj)
		if o, ok := newObj.(runtime.Object); ok {
			return o, err
		}
		return nil, err
	}
}


text:
<?php

namespace Lab1353\Monkyz\Controllers;

use File;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Lab1353\Monkyz\Models\DynamicModel;
use Lab1353\Monkyz\Helpers\SettingsHelper as HSettings;

class PanelController extends MonkyzController
{

	public function __construct()
	{
		$this->init();
	}

	public function getDashboard()
	{
		// settings
		$hsettings = new HSettings();
		$settings = $hsettings->getAll();

		// counters
		$cache_key = 'monkyz-widgets-counters';
		$counters = [];
		if (!empty($settings['dashboard_counters'])) {
			if (Cache::has($cache_key)) {
				$counters = Cache::get($cache_key);
			} else {
				$tables = $this->htables->getTables();
				$config_tables = array_keys(config('monkyz-tables.tables'));
				foreach ($tables as $table => $params) {
					if (in_array($table, $config_tables)) {
						if (!empty($settings['counters_'.$table])) {
							$m = new DynamicModel($table);
							$c = $m->count();

							$counters[$table] = [
								'count' => $c,
								'icon'  => $params['icon'],
							];
						}
					}
				}
				Cache::put($cache_key, $counters, (int)config('monkyz.cache_minutes', 60));
			}
		}

		// serverinfo
		$serverinfo = [];
		if (!empty($settings['dashboard_serverinfo'])) {
			$serverinfo = [
				'url'	=> config('app.url'),
				'php version'   => request()->server('PHP_VERSION'),
				'server ip'   => request()->server('SERVER_ADDR'),
				'web server'   => request()->server('SERVER_SOFTWARE'),
			];
		}

		// analytics
		$analytics = [];
		if (!empty($settings['dashboard_analytics'])) {
			$cache_key = 'monkyz-widgets-analytics';
			if (Cache::has($cache_key)) {
				$analytics = Cache::get($cache_key);
			} else {
				$viewId = $settings['analytics_viewid'];
				if (!empty($viewId)) {
					$config = config('laravel-analytics');
					$client = \Spatie\Analytics\AnalyticsClientFactory::createForConfig($config);
					$classAnalytics = new \Spatie\Analytics\Analytics($client, $viewId);
					$analytics['TotalVisitorsAndPageViews'] = $classAnalytics->fetchTotalVisitorsAndPageViews(\Spatie\Analytics\Period::days(14));
					Cache::put($cache_key, $analytics, (int)config('monkyz.cache_minutes', 60));
				} else {
					$analytics = 'Set parameter viewId in Settings page';
				}
			}
		}

		return view('monkyz::panel.dashboard')->with(compact('counters','serverinfo','settings','analytics'));
	}

	public function getInfo()
	{
		$path = dirname(dirname(__DIR__));

		// CHANGELOG
		$content = File::get(str_finish($path, '/').'CHANGELOG.md');
		$content = substr($content, strpos($content, '#development)')+13);
		$content = substr($content, strpos($content, '[')+1);
		$version = substr($content, 0, strpos($content, ' '));

		// PAGE TITLE
		$page_title = 'Monkyz '.$version.'';

		// README
		$content = File::get(str_finish($path, '/').'README.md');
		$content = substr($content, strpos($content, '### Links'));
		$content = substr($content, 0, strpos($content, "\n## "));
		$content = str_replace("\n", '', $content);

		$md_links = substr($content, strpos($content, '### Links')+9);
		$md_links = substr($md_links, 0, strpos($md_links, '### Vendors'));
		$md_vendors = substr($content, strpos($content, '### Vendors')+11);
		$md_vendors = substr($md_vendors, strpos($md_vendors, ':')+1);
		$md_vendors = substr($md_vendors, 0, strpos($md_vendors, '### Tools'));
		$md_tools = substr($content, strpos($content, '### Tools')+9);

		$urls = [
			'links' => $this->convertMDListToArray($md_links),
			'vendors' => $this->convertMDListToArray($md_vendors),
			'tools' => $this->convertMDListToArray($md_tools),
		];

		return view('monkyz::panel.info')->with(compact('page_title', 'urls'));
	}

	private function convertMDListToArray($md)
	{
		$arr = [];
		$t = explode('- ', $md);
		foreach ($t as $v) {
			if (!empty($v)) {
				$name = substr($v, 1, strpos($v, ']')-1);
				$link = substr($v, strpos($v, '(')+1, strpos($v, ')')-strpos($v, '(')-1);
				$arr[$name]	= $link;
			}
		}

		return $arr;
	}
}


text:
import numpy as np
from PIL import Image
import svgwrite
from PIL import Image, ImageDraw, ImageStat

dwg = svgwrite.Drawing('output.svg',profile='full',size=('30cm','30cm'),id='f-multiply-opacity',preserveAspectRatio='xMinYMin meet')

def gcr(im, percentage):
    '''basic "Gray Component Replacement" function. Returns a CMYK image with
       percentage gray component removed from the CMY channels and put in the
       K channel, ie. for percentage=100, (41, 100, 255, 0) >> (0, 59, 214, 41)'''
    cmyk_im = im.convert('CMYK')
    if not percentage:
        return cmyk_im
    cmyk_im = cmyk_im.split()
    cmyk = []
    for i in xrange(4):
        cmyk.append(cmyk_im[i].load())
    for x in xrange(im.size[0]):
        for y in xrange(im.size[1]):
            gray = min(cmyk[0][x,y], cmyk[1][x,y], cmyk[2][x,y]) * percentage / 100
            for i in xrange(3):
                cmyk[i][x,y] = cmyk[i][x,y] - gray
            cmyk[3][x,y] = gray
    return Image.merge('CMYK', cmyk_im)

def halftone(im, cmyk, sample, scale):
    '''Returns list of half-tone images for cmyk image. sample (pixels),
       determines the sample box size from the original image. The maximum
       output dot diameter is given by sample * scale (which is also the number
       of possible dot sizes). So sample=1 will presevere the original image
       resolution, but scale must be >1 to allow variation in dot size.'''
    #cmyk = cmyk.split()
    dots = []
    angle = 0
    count = 0
    cmyk = cmyk.split()
    for channel in cmyk:
        count=count+1

        #channel = channel.rotate(angle, expand=1)
        size = channel.size[0]*scale, channel.size[1]*scale
        #half_tone = Image.new('L', size)
        #draw = ImageDraw.Draw(half_tone)
        for x in xrange(0, channel.size[0], sample):
            for y in xrange(0, channel.size[1], sample):
                box = channel.crop((x, y, x + sample, y + sample))
                stat = ImageStat.Stat(box)
                diameter = (stat.mean[0] / 255)**0.5
                edge = 0.5*(1-diameter)
                x_pos, y_pos = (x+edge)*scale, (y+edge)*scale
                box_edge = sample*diameter*scale
                if(count==1):
                  dwg.add(dwg.ellipse(((2*x_pos+box_edge)/2,(2*y_pos+box_edge)/2),(box_edge-5,box_edge-5),fill='cyan',style="mix-blend-mode: multiply;"))
                elif(count==2):
                  dwg.add(dwg.ellipse(((2*x_pos+box_edge)/2,(2*y_pos+box_edge)/2),(box_edge-5,box_edge-5),fill='magenta',style="mix-blend-mode: multiply;",transform = ("rotate(1.5)")))
                elif(count==3):
                  dwg.add(dwg.ellipse(((2*x_pos+box_edge)/2,(2*y_pos+box_edge)/2),(box_edge-5,box_edge-5),fill='yellow',style="mix-blend-mode: multiply;",transform = ("rotate(3)")))

                #draw.ellipse((x_pos, y_pos, x_pos + box_edge, y_pos + box_edge), fill=255)
        #half_tone = half_tone.rotate(-angle, expand=1)
        #width_half, height_half = half_tone.size
        #xx=(width_half-im.size[0]*scale) / 2
        #yy=(height_half-im.size[1]*scale) / 2
        #half_tone = half_tone.crop((xx, yy, xx + im.size[0]*scale, yy + im.size[1]*scale))
        #dots.append(half_tone)
        #angle += 15

def main():
  fname = 'tree.jpg'
  image = Image.open(fname)
  cmyk = gcr(image, 0)
  #output_cyan = draw_svg(cmyk[0])
  #output_magenta = draw_svg(cmyk[1])
  #output_yellow = dr(cmyk[2])
  #draw_svg(output_cyan,'cyan')
  #draw_svg(output_magenta,'magenta')
  #draw_svg(output_yellow,'yellow')
  halftone(image,cmyk,10,1)
  dwg.save()

if __name__=="__main__":
  main()


text:
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('heritages', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='UserProfile',
            fields=[
                ('id', models.AutoField(auto_created=True,
                                        primary_key=True,
                                        serialize=False,
                                        verbose_name='ID')),
                ('date_of_birth', models.DateField(null=True,
                                                   verbose_name='Date of Birth')),
                ('note', models.TextField(blank=True,
                                          null=True,
                                          verbose_name='Notes')),
                ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE,
                                              related_name='profile',
                                              to=settings.AUTH_USER_MODEL)),
            ],
        ),
    ]


text:
package api

import (
	"fmt"
	"strconv"
	"time"

	"github.com/go-pesa/go-pesa/internal/http"
	"github.com/go-pesa/go-pesa/internal/types"
	"github.com/go-pesa/go-pesa/internal/utils"
)

//CheckIdentity checks the user's identity
func (client *Client) CheckIdentity(customerPhone int) types.StkResponse {
	var stkresponse types.StkResponse

	// if check("stkpush", client) {
	// 	return stkresponse
	// }

	timestamp := time.Now().Format("20060102150405")
	endpoint := identityCheck
	businessShortCode := strconv.Itoa(client.BusinessShortCode)
	password := utils.EncodePassword(businessShortCode, client.PassKey, timestamp)

	pushObject := &types.IdentityRequest{

		Initiator:         client.Initiator,
		BusinessShortCode: businessShortCode,
		Password:          password,
		Timestamp:         timestamp,
		TransactionType:   "CheckIdentity",
		PhoneNumber:       customerPhone,
		CallBackURL:       client.TransactionCallback,
		TransactionDesc:   "",
	}
	var headers = []types.Header{
		types.Header{
			Key:   "authorization",
			Value: fmt.Sprintf("Bearer %s", getToken(client.Key, client.Secret, client.ProductionURL, client.cache)),
		},
	}

	res := http.Post(endpoint, client.ProductionURL, headers, pushObject)

	utils.Unmarshal(res, &stkresponse)

	return stkresponse
}


text:
@interface ControlChart : PlotItem<CPTPlotDataSource>
{
    @private
    NSArray *plotData;
    double meanValue;
    double standardError;
}

@end


text:
package me.scana.okgradle.internal.dsl.api;

import me.scana.okgradle.internal.dsl.api.android.externalNativeBuild.CMakeModel;
import me.scana.okgradle.internal.dsl.api.android.externalNativeBuild.NdkBuildModel;
import org.jetbrains.annotations.NotNull;

public interface ExternalNativeBuildModel {
  @NotNull
  CMakeModel cmake();

  @NotNull
  ExternalNativeBuildModel removeCMake();

  @NotNull
  NdkBuildModel ndkBuild();

  @NotNull
  ExternalNativeBuildModel removeNdkBuild();
}