text:
package com.hodinv.uilib.sample;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.hodinv.uilib.ContentFragment;
import com.hodinv.uilib.utils.EnumsHelper;

/**
 * Demo of main fragment
 * Created by vhodin on 17.12.2015.
 */
public class FirstFragment extends ContentFragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        return LayoutInflater.from(getContext()).inflate(R.layout.dummy, container, false);
    }

    @Override
    public String getTitle() {
        return EnumsHelper.getInstance().getTitle(Titles.FIRST);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.main, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menu_sub) {
            startFragmentWithStacking(new SubFragment().arguments().putString(SubFragment.KEY, "info").build());
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public int getMenuId() {
        return R.id.menu_first;
    }
}


text:
import {HarnessPredicate} from '@angular/cdk/testing';
import {MatLegacyChipHarness} from './chip-harness';
import {LegacyChipOptionHarnessFilters} from './chip-harness-filters';

/**
 * @deprecated Use `MatChipOptionHarness` from `@angular/material/chips/testing` instead. See https://material.angular.io/guide/mdc-migration for information about migrating.
 * @breaking-change 17.0.0
 */
export class MatLegacyChipOptionHarness extends MatLegacyChipHarness {
  /** The selector for the host element of a selectable chip instance. */
  static override hostSelector = '.mat-chip';

  /**
   * Gets a `HarnessPredicate` that can be used to search for a `MatChipOptionHarness`
   * that meets certain criteria.
   * @param options Options for filtering which chip instances are considered a match.
   * @return a `HarnessPredicate` configured with the given options.
   */
  static override with(
    options: LegacyChipOptionHarnessFilters = {},
  ): HarnessPredicate<MatLegacyChipOptionHarness> {
    return new HarnessPredicate(MatLegacyChipOptionHarness, options)
      .addOption('text', options.text, (harness, label) =>
        HarnessPredicate.stringMatches(harness.getText(), label),
      )
      .addOption(
        'selected',
        options.selected,
        async (harness, selected) => (await harness.isSelected()) === selected,
      );
  }

  /** Whether the chip is selected. */
  override async isSelected(): Promise<boolean> {
    return (await this.host()).hasClass('mat-chip-selected');
  }

  /** Selects the given chip. Only applies if it's selectable. */
  override async select(): Promise<void> {
    if (!(await this.isSelected())) {
      await this.toggle();
    }
  }

  /** Deselects the given chip. Only applies if it's selectable. */
  override async deselect(): Promise<void> {
    if (await this.isSelected()) {
      await this.toggle();
    }
  }

  /** Toggles the selected state of the given chip. */
  override async toggle(): Promise<void> {
    return (await this.host()).sendKeys(' ');
  }
}

redpajama_set_name: RedPajamaGithub


text:
@implementation NSObject (PLeakTrack)

- (void)watchAllRetainedProperties:(int)level
{
    if (level >= 5) { //don't go too deep
        return;
    }

    NSMutableArray* watchedProperties = @[].mutableCopy;

    //track class level1
    NSString* className = NSStringFromClass([self class]);
    if ([className hasPrefix:@"UI"] || [className hasPrefix:@"NS"] || [className hasPrefix:@"_"]) {
        return;
    }
    NSArray* l1Properties = [self getAllPropertyNames:[self class]];
    [watchedProperties addObjectsFromArray:l1Properties];

    //track class level2
    NSString* superClassName = NSStringFromClass([self superclass]);
    if ([superClassName hasPrefix:@"UI"] == false &&
        [superClassName hasPrefix:@"NS"] == false &&
        [superClassName hasPrefix:@"_"] == false)
    {
        NSArray* l2Properties = [self getAllPropertyNames:[self superclass]];
        [watchedProperties addObjectsFromArray:l2Properties];
    }

    //track class level3
    if ([[self superclass] superclass]) {
        NSString* superSuperClassName = NSStringFromClass([[self superclass] superclass]);
        if ([superSuperClassName hasPrefix:@"UI"] == false &&
            [superSuperClassName hasPrefix:@"NS"] == false &&
            [superSuperClassName hasPrefix:@"_"] == false)
        {
            NSArray* l3Properties = [self getAllPropertyNames:[[self superclass] superclass]];
            [watchedProperties addObjectsFromArray:l3Properties];
        }
    }

    for (NSString* name in watchedProperties) {

        id cur = [self valueForKey:name];
        if (cur) {
            BOOL ret = [cur markAlive];
            if (ret) {
                [cur pProxy].weakHost = self;
                [cur watchAllRetainedProperties:level+1];
            }
        }

//        SEL setter = [self setterForPropertyName:name];
//        if (setter) {
//            __weak __typeof(self) wself = self;
//
//            //check current value
//            id cur = [self valueForKey:name];
//
//            if (cur) {
//
//                BOOL ret = [cur markAlive];
//                if (ret) {
//                    [cur pProxy].weakHost = wself;
//                    [cur watchAllRetainedProperties:level+1];
//                }
//            }
//
//            //check future value
//            [self aspect_hookSelector:setter withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo, id newValue){
//
//                if (newValue != nil) {
//                    BOOL ret = [newValue markAlive];
//                    if (ret) {
//                        [newValue pProxy].weakHost = wself;
//                        [newValue watchAllRetainedProperties:0];
//                    }
//                }
//
//            } error:nil];
//
//        }
    }

}

- (void)didObserveNewValue:(id)value
{
    if (value) {

        BOOL ret = [value markAlive];
        if (ret) {
            [value pProxy].weakHost = self;
            [value watchAllRetainedProperties:0];
        }
    }
}

- (BOOL)isAlive
{
    BOOL alive = true;

    if (self.pProxy.weakHost == nil) {
        alive = false;
    }

    return alive;
}

#pragma mark- mess with runtime

- (NSArray*)getAllPropertyNames:(Class)cls
{
    unsigned int i, count = 0;

    objc_property_t* properties = class_copyPropertyList(cls, &count );

    if(count == 0)
    {
        free(properties);
        return nil;
    }

    NSMutableArray* names = @[].mutableCopy;

    for (i = 0; i < count; i++)
    {
        objc_property_t property = properties[i];

        NSString* typeName = @"";
        const char* str = property_getTypeString(property);
        if (str != NULL) {
            typeName = [NSString stringWithUTF8String:str];
        }

        NSString* name = [NSString stringWithUTF8String:property_getName(property)];

        //we are only interested in a very limited group of types
        if ([typeName isEqualToString:@"T@\"PObjectProxy\""] ||
            [typeName hasPrefix:@"T@\"UI"] ||
            [typeName hasPrefix:@"T@\"NS"] ||
            [typeName rangeOfString:@"KVO"].location != NSNotFound) {
            continue;
        }

        bool isStrong = isStrongProperty(property);
        if (isStrong == false)
        {
            continue;
        }

        [names addObject:name];
    }

    return names;
}

- (SEL)setterForPropertyName:(NSString*)name
{
    objc_property_t property = class_getProperty([self class], [name UTF8String]);
    if (property == nil)
        return nil;

    SEL result = property_getSetter(property);
    if (result != nil)
        return result;

    NSMutableString* setterName = @"set".mutableCopy;
    NSString* upcaseName = [name stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[name substringToIndex:1] capitalizedString]];
    [setterName appendString:upcaseName];
    [setterName appendString:@":"];

    if ([[self class] instancesRespondToSelector:NSSelectorFromString(setterName)] == false)
    {
        return nil; //no proper setter found
    }

    return NSSelectorFromString(setterName);
}

SEL property_getSetter(objc_property_t property)
{
    const char* attrs = property_getAttributes(property);
    if (attrs == nil)
        return nil;

    const char* p = strstr(attrs, ",S");
    if (p == nil)
        return nil;

    p += 2;
    const char* e = strchr(p, ',');
    if (e == nil)
    {
        return sel_getUid(p);
    }
    if (e == p)
    {
        return nil;
    }

    int len = (int)(e - p);
    char* selPtr = malloc(len + 1);
    memcpy(selPtr, p, len);
    selPtr[len] = '\0';
    SEL result = sel_getUid(selPtr);
    free(selPtr);

    return result;
}

bool isStrongProperty(objc_property_t property)
{
    const char* attrs = property_getAttributes( property );
    if (attrs == NULL)
        return false;

    const char* p = attrs;
    p = strchr(p, '&');
    if (p == NULL) {
        return false;
    }
    else
    {
        return true;
    }
}

const char* property_getTypeString( objc_property_t property )
{
    const char * attrs = property_getAttributes( property );
    if (attrs == NULL)
        return NULL;

    static char buffer[256];
    const char * e = strchr( attrs, ',' );
    if (e == NULL)
        return NULL;

    int len = (int)(e - attrs);
    memcpy(buffer, attrs, len);
    buffer[len] = '\0';

    return buffer;
}

@end


text:
module ServiceProfessionalFeedbacksHelper
end


text:
package net.imagej.legacy.search;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import javax.xml.parsers.ParserConfigurationException;

import net.imagej.legacy.IJ1Helper;
import net.imagej.legacy.LegacyService;

import org.scijava.command.CommandInfo;
import org.scijava.log.LogService;
import org.scijava.module.ModuleInfo;
import org.scijava.platform.PlatformService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.script.ScriptInfo;
import org.scijava.search.DefaultSearchAction;
import org.scijava.search.SearchAction;
import org.scijava.search.SearchActionFactory;
import org.scijava.search.SearchResult;
import org.scijava.search.module.ModuleSearchResult;
import org.scijava.ui.UIService;
import org.scijava.util.AppUtils;
import org.scijava.util.FileUtils;
import org.scijava.util.Manifest;
import org.scijava.util.POM;
import org.scijava.util.Types;
import org.xml.sax.SAXException;

/**
 * Search action for viewing the source code of a SciJava module.
 *
 * @author Curtis Rueden
 */
@Plugin(type = SearchActionFactory.class)
public class SourceSearchActionFactory implements SearchActionFactory {

	@Parameter
	private LogService log;

	@Parameter
	private UIService uiService;

	@Parameter
	private PlatformService platformService;

	@Override
	public boolean supports(final SearchResult result) {
		return result instanceof ModuleSearchResult;
	}

	@Override
	public SearchAction create(final SearchResult result) {
		return new DefaultSearchAction("Source", //
			() -> source(((ModuleSearchResult) result).info()));
	}

	private void source(final ModuleInfo info) {
		// HACK: For now, we special case each kind of module.
		// In the future, we should make it more extensible.
		// HelpService? ModuleService#help? Some other type of plugin?

		if (info instanceof ScriptInfo) {
			// SciJava script.
			sourceForScript((ScriptInfo) info);
			return;
		}

		final String id = info.getIdentifier();
		if (id != null && id.startsWith("legacy:")) {
			// ImageJ 1.x command.
			sourceForLegacyCommand(info);
			return;
		}

		try {
			// Some other kind of module; use the delegate class.
			sourceForClass(info, info.loadDelegateClass());
		}
		catch (final ClassNotFoundException exc) {
			log.debug(exc);
			errorMessage(info);
		}
	}

	private void sourceForScript(final ScriptInfo info) {
		legacyService().openScriptInTextEditor(info);
	}

	private void sourceForLegacyCommand(final ModuleInfo info) {
		if (!(info instanceof CommandInfo)) {
			log.debug("Not a CommandInfo: " + info.getTitle());
			errorMessage(info);
			return;
		}
		final CommandInfo cInfo = (CommandInfo) info;
		final Object className = cInfo.getPresets().get("className");
		if (className == null || !(className instanceof String)) {
			log.debug("Weird class name: " + className);
			errorMessage(info);
			return;
		}
		final IJ1Helper ij1Helper = legacyService().getIJ1Helper();
		if (ij1Helper == null) {
			log.debug("Null IJ1Helper");
			errorMessage(info);
			return;
		}
		final ClassLoader classLoader = ij1Helper.getClassLoader();
		if (classLoader == null) {
			log.debug("Null IJ1 class loader");
			errorMessage(info);
			return;
		}
		try {
			final Class<?> c = classLoader.loadClass((String) className);
			sourceForClass(info, c);
		}
		catch (final ClassNotFoundException exc) {
			log.debug(exc);
			errorMessage(info);
		}
	}

	private void sourceForClass(final ModuleInfo info, final Class<?> c) {
		final POM pom = getPOM(c, null, null);
		if (pom == null) {
			log.debug("No Maven POM found for class: " + c.getName());
			errorMessage(info);
			return;
		}

		final String scmURL = pom.getSCMURL();
		if (scmURL == null) {
			if (log.isDebug()) log.debug("No <scm><url> for " + coord(pom));
			errorMessage(info);
			return;
		}
		if (!scmURL.matches("^(git|http|https)://github.com/[^/]+/[^/]+/?$")) {
			log.debug("Not a standard GitHub project URL: " + scmURL);
			openURL(scmURL);
			return;
		}

		// Try to extract a tag or commit hash.
		final String tag;
		final String scmTag = pom.getSCMTag();
		if (scmTag == null || scmTag.equals("HEAD")) {
			if (log.isDebug()) {
				log.debug(scmTag == null ? //
					"No SCM tag available; using commit hash." : //
					"Weird SCM tag '" + scmTag + "'; using commit hash.");
			}
			final Manifest m = Manifest.getManifest(c);
			tag = m == null ? null : m.getImplementationBuild();
			if (tag == null) log.debug("No commit hash found.");
		}
		else tag = scmTag;
		if (tag == null) {
			// No tag or commit hash could be extracted.
			openURL(scmURL);
			return;
		}

		// Build a precise GitHub URL.
		final StringBuilder url = new StringBuilder();
		url.append(scmURL);
		if (!scmURL.endsWith("/")) url.append("/");
		final boolean originalImageJ = url.toString().endsWith("imagej/ImageJ/");
		url.append("blob/");
		url.append(tag);
		url.append(originalImageJ ? "/" : "/src/main/java/");
		url.append(c.getName().replaceAll("\\.", "/"));
		url.append(".java");
		openURL(url.toString());
	}

	private void openURL(final String urlPath) {
		try {
			platformService.open(new URL(urlPath));
		}
		catch (final IOException exc) {
			log.error(exc);
			uiService.showDialog("Platform error opening source URL: " + urlPath);
		}
	}

	private LegacyService legacyService() {
		return log.context().service(LegacyService.class);
	}

	private String coord(final POM pom) {
		final String g = pom.getGroupId();
		final String a = pom.getArtifactId();
		final String v = pom.getVersion();
		return g + ":" + a + ":" + v;
	}

	private void errorMessage(final ModuleInfo info) {
		uiService.showDialog("Source location unknown for " + info.getTitle());
	}

	// TODO: Migrate this improved routine to org.scijava.util.POM.

	/**
	 * Gets the Maven POM associated with the given class.
	 *
	 * @param c The class to use as a base when searching for a pom.xml.
	 * @param groupId The Maven groupId of the desired POM.
	 * @param artifactId The Maven artifactId of the desired POM.
	 */
	private static POM getPOM(final Class<?> c, final String groupId,
		final String artifactId)
	{
		try {
			final URL location = Types.location(c);
			if (!location.getProtocol().equals("file") ||
				location.toString().endsWith(".jar"))
			{
				// look for pom.xml in JAR's META-INF/maven subdirectory
				if (groupId == null || artifactId == null) {
					// groupId and/or artifactId is unknown; scan for the POM
					final URL pomBase = new URL("jar:" + //
						location.toString() + "!/META-INF/maven");
					for (final URL url : FileUtils.listContents(pomBase, true, true)) {
						if (url.toExternalForm().endsWith("/pom.xml")) {
							return new POM(url);
						}
					}
				}
				else {
					// known groupId and artifactId; grab it directly
					final String pomPath =
						"META-INF/maven/" + groupId + "/" + artifactId + "/pom.xml";
					final URL pomURL =
						new URL("jar:" + location.toString() + "!/" + pomPath);
					return new POM(pomURL);
				}
			}
			// look for the POM in the class's base directory
			final File file = FileUtils.urlToFile(location);
			final File baseDir = AppUtils.getBaseDirectory(file, null);
			final File pomFile = new File(baseDir, "pom.xml");
			return new POM(pomFile);
		}
		catch (final IOException | ParserConfigurationException | SAXException e) {
			return null;
		}
	}
}


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">

        <!-- android:textColorPrimary is the  color of the title text
       in the Toolbar, in the Theme.AppCompat theme:  -->
        <item name="android:actionBarStyle">@style/MyActionBar</item>
        <item name="actionBarStyle">@style/MyActionBar</item>

    </style>

    <style name="MyActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
        <item name="background">@color/kit_lighter_green</item>

    </style>

    <style name="ToolbarTheme" parent="AppTheme">
        <item name="android:textColorPrimary">#FFF</item>
    </style>
</resources>


text:
package org.odlabs.wiquery.core.util;

import org.apache.wicket.Component;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.Component.IVisitor;

/**
 * $Id$
 * <p>
 * Class to retrieve the Wicket component with the specified markup identifiant
 * </p>
 *
 * @author Julien Roche
 * @since 1.0
 */
public class MarkupIdVisitor implements IVisitor<Component> {
	// Properties
	private String id;
	private Component foundComponent;

	/**Constructor
	 * @param id Markup identifiant
	 */
	public MarkupIdVisitor(String id) {
		this.id = id;
	}

	/* (non-Javadoc)
	 * @see org.apache.wicket.Component.IVisitor#component(org.apache.wicket.Component)
	 */
	public Object component(Component component) {
		if (component.getMarkupId().equals(this.id)) {
			this.foundComponent = component;
			return IVisitor.STOP_TRAVERSAL;
		}
		if (component instanceof MarkupContainer) {
			return ((MarkupContainer) component).visitChildren(this);
		}
		return IVisitor.CONTINUE_TRAVERSAL;
	}

	/**
	 * @return the markup identifiant
	 */
	public String getId() {
		return id;
	}

	/**
	 * @return the Wicket component that have been found
	 */
	public Component getFoundComponent() {
		return foundComponent;
	}
}


text:
create function get_cards_in_support(input character varying) returns SETOF joined_cards
    language plpgsql
as
$$
begin

    return query
        select *
        from joined_cards
        where supportname ilike input
        order by name;

end;
$$;


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

class Program
{
    static void Main(string[] args)
    {
        int commandsNumber = int.Parse(Console.ReadLine());
        ShoppingCenter center = new ShoppingCenter();
        //StringBuilder builder = new StringBuilder();

        for (int i = 0; i < commandsNumber; i++)
        {
            string line = Console.ReadLine();

            int firstSpace = line.IndexOf(" ");

            string command = line.Substring(0, firstSpace);

            string[] arguments = line.Substring(firstSpace + 1).Split(';');

            switch (command)
            {
                case "AddProduct":

                    string name = arguments[0];
                    double price = double.Parse(arguments[1]);
                    string producer = arguments[2];

                    Product p = new Product(name, price, producer);
                    center.Add(p);
                    //builder.AppendLine("Product added");
                    Console.WriteLine("Product added");
                    break;

                case "DeleteProducts":

                    if(arguments.Length == 1)
                    {

                        int count = center.DeleteProductsByProducer(arguments[0]);
                        if(count == 0)
                        {
                            //builder.AppendLine("No products found");
                            Console.WriteLine("No products found");
                        }
                        else
                        {
                            //builder.AppendLine(count.ToString() + " products deleted");
                            Console.WriteLine(count.ToString() + " products deleted");
                        }

                    }
                    else
                    {
                        int count = center.DeleteProductsByProducerAndName(arguments[0], arguments[1]);
                        if(count == 0)
                        {
                            //builder.AppendLine("No products found");
                            Console.WriteLine("No products found");
                        }
                        else
                        {
                            //builder.AppendLine(count.ToString() + " products deleted");
                            Console.WriteLine(count.ToString() + " products deleted");
                        }
                    }
                    break;

                case "FindProductsByName":
                    List<Product> resultByName = center.FindProductsByName(arguments[0]).ToList();
                    if(resultByName.Count != 0)
                    {
                        //resultByName.ForEach(x => builder.AppendLine(x.ToString()));
                        resultByName.ForEach(Console.WriteLine);
                    }
                    else
                    {
                        //builder.AppendLine("No products found");
                        Console.WriteLine("No products found");
                    }
                    break;
                case "FindProductsByProducer":
                    List<Product> resultByPRoducer = center.FindProductsByProducer(arguments[0]).ToList();
                    if (resultByPRoducer.Count != 0)
                    {
                        //resultByPRoducer.ForEach(x => builder.AppendLine(x.ToString()));
                        resultByPRoducer.ForEach(Console.WriteLine);
                    }
                    else
                    {
                        //builder.AppendLine("No products found");
                        Console.WriteLine("No products found");
                    }
                    break;
                case "FindProductsByPriceRange":
                    List<Product> resultByPrice = center.FindProductsByPriceRAnge(
                        double.Parse(arguments[0]),
                        double.Parse(arguments[1]))
                        .OrderBy(x => x).ToList();
                    if (resultByPrice.Count != 0)
                    {
                        //resultByPrice.ForEach(x => builder.AppendLine(x.ToString()));
                        resultByPrice.ForEach(Console.WriteLine);
                    }
                    else
                    {
                        //builder.AppendLine("No products found");
                        Console.WriteLine("No products found");
                    }
                    break;

            }

        }
        //Console.WriteLine(builder.ToString().Trim());

    }
}


text:
/*globals queryUtil:true*/
define(['lodash'], function (_) {
    /*eslint strict:0 */

    if (typeof window !== 'object') {
        return {
            load: function(name, parentRequire, onLoad) {
                onLoad(false);
            }
        };
    }

    var model = window.rendererModel || window.editorModel || {};
    var params = {
        experiments: true,
        experimentsoff: false
    };

    var experiments = _.mapValues(model.runningExperiments, function(value) {
        return value === 'new';
    });

    //TODO: Is this needed? It should be possible to add experiments to the vm from the QS with ?experiment=x:new&experiment=y:off
    experiments = _.reduce(params, function (soFar, paramValue, paramName) {
        var queryValue = queryUtil.getParameterByName(paramName);
        var paramExperiments = queryValue.split(',').filter(Boolean);
        var additions = _(paramExperiments).map(function (exp) {return [exp, paramValue]; }).zipObject().value();
        return _.assign(soFar, additions);
    }, experiments || {});

    return {
        load: function (name, parentRequire, onload) {
            onload(Boolean(experiments[name]));
        }
    };
});


text:
using content::BrowserThread;

namespace app_list {

UrlIconSource::UrlIconSource(const IconLoadedCallback& icon_loaded_callback,
                             content::BrowserContext* browser_context,
                             const GURL& icon_url,
                             int icon_size,
                             int default_icon_resource_id)
    : icon_loaded_callback_(icon_loaded_callback),
      browser_context_(browser_context),
      icon_url_(icon_url),
      icon_size_(icon_size),
      default_icon_resource_id_(default_icon_resource_id),
      icon_fetch_attempted_(false) {
  DCHECK(!icon_loaded_callback_.is_null());
}

UrlIconSource::~UrlIconSource() {
}

void UrlIconSource::StartIconFetch() {
  icon_fetch_attempted_ = true;

  auto resource_request = std::make_unique<network::ResourceRequest>();
  resource_request->url = icon_url_;
  resource_request->credentials_mode = network::mojom::CredentialsMode::kOmit;
  net::NetworkTrafficAnnotationTag traffic_annotation =
      net::DefineNetworkTrafficAnnotation("url_icon_source_fetch", R"(
          semantics {
            sender: "URL Icon Source"
            description:
              "Chrome OS downloads an icon for a web store result."
            trigger:
              "When a user initiates a web store search and views results. "
            data:
              "URL of the icon. "
              "No user information is sent."
            destination: WEBSITE
          }
          policy {
            cookies_allowed: NO
            setting: "Unconditionally enabled on Chrome OS."
            policy_exception_justification:
              "Not implemented, considered not useful."
          })");
  simple_loader_ = network::SimpleURLLoader::Create(std::move(resource_request),
                                                    traffic_annotation);
  network::mojom::URLLoaderFactory* loader_factory =
      content::BrowserContext::GetDefaultStoragePartition(browser_context_)
          ->GetURLLoaderFactoryForBrowserProcess()
          .get();
  simple_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
      loader_factory, base::BindOnce(&UrlIconSource::OnSimpleLoaderComplete,
                                     base::Unretained(this)));
}

gfx::ImageSkiaRep UrlIconSource::GetImageForScale(float scale) {
  if (!icon_fetch_attempted_)
    StartIconFetch();

  if (!icon_.isNull())
    return icon_.GetRepresentation(scale);

  return ui::ResourceBundle::GetSharedInstance()
      .GetImageSkiaNamed(default_icon_resource_id_)->GetRepresentation(scale);
}

void UrlIconSource::OnSimpleLoaderComplete(
    std::unique_ptr<std::string> response_body) {
  if (!response_body) {
    return;
  }

  // Call start to begin decoding.  The ImageDecoder will call OnImageDecoded
  // with the data when it is done.
  ImageDecoder::Start(this, *response_body);
}

void UrlIconSource::OnImageDecoded(const SkBitmap& decoded_image) {
  icon_ = gfx::ImageSkiaOperations::CreateResizedImage(
      gfx::ImageSkia::CreateFrom1xBitmap(decoded_image),
      skia::ImageOperations::RESIZE_BEST,
      gfx::Size(icon_size_, icon_size_));

  icon_loaded_callback_.Run();
}

void UrlIconSource::OnDecodeImageFailed() {
  // Failed to decode image. Do nothing and just use the default icon.
}

}  // namespace app_list


text:
package org.apache.logging.log4j.jul;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Log4j Core implementation of the JUL {@link Logger} class. Note that this implementation does
 * not use the {@link java.util.logging.Handler} class. Instead, logging is delegated to the
 * underlying Log4j {@link org.apache.logging.log4j.core.Logger} which uses
 * {@link org.apache.logging.log4j.core.Appender Appenders} instead.
 *
 * @since 2.1
 */
public class CoreLogger extends ApiLogger {

    private final org.apache.logging.log4j.core.Logger logger;

    /**
     * Constructs a Logger using a Log4j {@link org.apache.logging.log4j.core.Logger}.
     *
     * @param logger the underlying Logger to base this Logger on
     */
    CoreLogger(final org.apache.logging.log4j.core.Logger logger) {
        super(logger);
        this.logger = logger;
    }

    @Override
    public void setLevel(final Level level) throws SecurityException {
        super.doSetLevel(level); // checks permissions
        logger.setLevel(LevelTranslator.toLevel(level));
    }

    /**
     * Marks the underlying {@link org.apache.logging.log4j.core.Logger} as additive.
     *
     * @param additive {@code true} if this Logger should be additive
     * @see org.apache.logging.log4j.core.Logger#setAdditive(boolean)
     */
    @Override
    public synchronized void setUseParentHandlers(final boolean additive) {
        logger.setAdditive(additive);
    }

    /**
     * Indicates if the underlying {@link org.apache.logging.log4j.core.Logger} is additive. Note that the
     * Log4j version of JDK Loggers do not use Handlers.
     *
     * @return {@code true} if this Logger is additive, or {@code false} otherwise
     * @see org.apache.logging.log4j.core.Logger#isAdditive()
     */
    @Override
    public synchronized boolean getUseParentHandlers() {
        return logger.isAdditive();
    }

    @Override
    public Logger getParent() {
        final org.apache.logging.log4j.core.Logger parent = logger.getParent();
        return parent == null ? null : Logger.getLogger(parent.getName());
    }
}


text:
using System.Windows;
using System.Windows.Forms;
using OsEngine.OsTrader.Panels;
using TextBox = System.Windows.Forms.TextBox;

namespace OsEngine.Charts.CandleChart.Indicators
{
    /// <summary>
    /// Логика взаимодействия для PivotPointsRobotUi.xaml
    /// </summary>
    public partial class PivotPointsUi : Window
    {
        private PivotPoints _pivotPoints;

        /// <summary>
        /// изменялись ли настройки индикатора
        /// </summary>
        public bool IsChange;

        public PivotPointsUi(PivotPoints pivotPoints)
        {
            InitializeComponent();
            _pivotPoints = pivotPoints;

            CheckBoxPaintOnOff.IsChecked = _pivotPoints.PaintOn;

            HostR1.Child = new TextBox();
            HostR1.Child.BackColor = _pivotPoints.ColorR1;

            HostR2.Child = new TextBox();
            HostR2.Child.BackColor = _pivotPoints.ColorR2;

            HostR3.Child = new TextBox();
            HostR3.Child.BackColor = _pivotPoints.ColorR3;

            HostS1.Child = new TextBox();
            HostS1.Child.BackColor = _pivotPoints.ColorS1;

            HostS2.Child = new TextBox();
            HostS2.Child.BackColor = _pivotPoints.ColorS2;

            HostS3.Child = new TextBox();
            HostS3.Child.BackColor = _pivotPoints.ColorS3;

        }

        private void ButtonAccept_Click(object sender, RoutedEventArgs e)
        {
            _pivotPoints.ColorR1 = HostR1.Child.BackColor;
            _pivotPoints.ColorR2 = HostR2.Child.BackColor;
            _pivotPoints.ColorR3 = HostR3.Child.BackColor;

            _pivotPoints.ColorS1 = HostS1.Child.BackColor;
            _pivotPoints.ColorS2 = HostS2.Child.BackColor;
            _pivotPoints.ColorS3 = HostS3.Child.BackColor;

            _pivotPoints.PaintOn = CheckBoxPaintOnOff.IsChecked.Value;
            _pivotPoints.Save();

            IsChange = true;
            Close();
        }

        private void ButtonR1_Click(object sender, RoutedEventArgs e)
        {
            ColorDialog dialog = new ColorDialog();
            dialog.Color = HostR1.Child.BackColor;
            dialog.ShowDialog();
            HostR1.Child.BackColor = dialog.Color;
        }

        private void ButtonR2_Click(object sender, RoutedEventArgs e)
        {
            ColorDialog dialog = new ColorDialog();
            dialog.Color = HostR2.Child.BackColor;
            dialog.ShowDialog();
            HostR2.Child.BackColor = dialog.Color;
        }

        private void ButtonR3_Click(object sender, RoutedEventArgs e)
        {
            ColorDialog dialog = new ColorDialog();
            dialog.Color = HostR3.Child.BackColor;
            dialog.ShowDialog();
            HostR3.Child.BackColor = dialog.Color;
        }

        private void ButtonS1_Click(object sender, RoutedEventArgs e)
        {
            ColorDialog dialog = new ColorDialog();
            dialog.Color = HostS1.Child.BackColor;
            dialog.ShowDialog();
            HostS1.Child.BackColor = dialog.Color;
        }

        private void ButtonS2_Click(object sender, RoutedEventArgs e)
        {
            ColorDialog dialog = new ColorDialog();
            dialog.Color = HostS2.Child.BackColor;
            dialog.ShowDialog();
            HostS2.Child.BackColor = dialog.Color;
        }

        private void ButtonS3_Click(object sender, RoutedEventArgs e)
        {
            ColorDialog dialog = new ColorDialog();
            dialog.Color = HostS3.Child.BackColor;
            dialog.ShowDialog();
            HostS3.Child.BackColor = dialog.Color;
        }

    }
}


text:
#include <modules/base/scale/staticscale.h>

#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>

namespace {
    constexpr openspace::properties::Property::PropertyInfo ScaleInfo = {
        "Scale",
        "Scale",
        "This value is used as a scaling factor for the scene graph node that this "
        "transformation is attached to relative to its parent"
    };

    struct [[codegen::Dictionary(StaticScale)]] Parameters {
        // [[codegen::verbatim(ScaleInfo.description)]]
        float scale;
    };
#include "staticscale_codegen.cpp"
} // namespace

namespace openspace {

documentation::Documentation StaticScale::Documentation() {
    return codegen::doc<Parameters>("base_scale_static");
}

glm::dvec3 StaticScale::scaleValue(const UpdateData&) const {
    return glm::dvec3(_scaleValue);
}

StaticScale::StaticScale() : _scaleValue(ScaleInfo, 1.f, 0.1f, 100.f) {
    addProperty(_scaleValue);

    _scaleValue.onChange([this]() {
        requireUpdate();
    });
}

StaticScale::StaticScale(const ghoul::Dictionary& dictionary) : StaticScale() {
    const Parameters p = codegen::bake<Parameters>(dictionary);
    _scaleValue = p.scale;
}

} // namespace openspace


text:
package org.ovirt.engine.core.vdsbroker.irsbroker;

import org.ovirt.engine.core.common.vdscommands.MarkPoolInReconstructModeVDSCommandParameters;
import org.ovirt.engine.core.compat.LogCompat;
import org.ovirt.engine.core.compat.LogFactoryCompat;

public class MarkPoolInReconstructModeVDSCommand<P extends MarkPoolInReconstructModeVDSCommandParameters>
        extends IrsBrokerCommand<P> {

    public MarkPoolInReconstructModeVDSCommand(P parameters) {
        super(parameters);
    }

    @Override
    protected void ExecuteVDSCommand() {
        try {
            IrsProxyData proxyData = getCurrentIrsProxyData();
            switch (getParameters().getReconstructMarkAction()) {
            case ClearJobs:
                proxyData.clearPoolTimers();
                break;
            case ClearCache:
                proxyData.clearCache();
                break;
            default:
                break;
            }
        } catch (Exception e) {
            log.error("Could not change timers for pool " + getParameters().getStoragePoolId(), e);
        }
        getVDSReturnValue().setSucceeded(true);
    }

    private static LogCompat log = LogFactoryCompat.getLog(MarkPoolInReconstructModeVDSCommand.class);
}


text:
<?php

namespace SP\SeleniumDriver\Test;

use PHPUnit_Framework_TestCase;
use SP\SeleniumDriver\Server;
use GuzzleHttp\Psr7\Response;

/**
 * @coversDefaultClass SP\SeleniumDriver\Server
 */
class ServerTest extends PHPUnit_Framework_TestCase
{
    /**
     * @covers ::__construct
     */
    public function testConstruct()
    {
        $server = new Server(['base_uri' => 'http://127.0.0.1:44412/wd/hub/']);

        $this->assertEquals('http://127.0.0.1:44412/wd/hub/', (string) $server->getClient()->getConfig('base_uri'));
    }

    /**
     * @covers ::newSessionBaseUri
     */
    public function testNewSessionBaseUri()
    {
        $client = $this->getMock('GuzzleHttp\Client');

        $client
            ->expects($this->at(0))
            ->method('request')
            ->with('post', 'session', ['body' => json_encode(['desiredCapabilities' => ['browserName' => 'firefox']])])
            ->willReturn(new Response(200, [], '{"sessionId":"123123"}'));

        $client
            ->expects($this->at(2))
            ->method('request')
            ->with('post', 'session', ['body' => json_encode(['desiredCapabilities' => ['browserName' => 'firefox']])])
            ->willReturn(new Response(200, [], '{}'));

        $client
            ->expects($this->exactly(2))
            ->method('getConfig')
            ->with('base_uri')
            ->willReturn('http://127.0.0.1:44412/wd/hub/');

        $server = $this->getMockBuilder('SP\SeleniumDriver\Server')
            ->disableOriginalConstructor()
            ->setMethods(['getClient'])
            ->getMock();

        $server
            ->expects($this->exactly(2))
            ->method('getClient')
            ->willReturn($client);

        $base_uri = $server->newSessionBaseUri();

        $this->assertEquals('http://127.0.0.1:44412/wd/hub/session/123123/', (string) $base_uri);

        $this->setExpectedException(
            'RuntimeException',
            'No "sessionId" response. Maybe http://127.0.0.1:44412/wd/hub/ is not a valid selenium server'
        );

        $server->newSessionBaseUri();
    }

    /**
     * @covers ::newSessionClient
     */
    public function testNewSessionClient()
    {
        $server = $this->getMockBuilder('SP\SeleniumDriver\Server')
            ->disableOriginalConstructor()
            ->setMethods(['newSessionBaseUri'])
            ->getMock();

        $server
            ->expects($this->once())
            ->method('newSessionBaseUri')
            ->willReturn('http://127.0.0.1:44412/wd/hub/session/123123/');

        $client = $server->newSessionClient();

        $this->assertInstanceOf('GuzzleHttp\Client', $client);
        $this->assertEquals('http://127.0.0.1:44412/wd/hub/session/123123/', (string) $client->getConfig('base_uri'));
    }
}


text:
namespace Azure.ResourceManager.MachineLearning.Models
{
    /// <summary> The UsernamePasswordAuthTypeWorkspaceConnectionProperties. </summary>
    public partial class UsernamePasswordAuthTypeWorkspaceConnectionProperties : WorkspaceConnectionPropertiesV2
    {
        /// <summary> Initializes a new instance of UsernamePasswordAuthTypeWorkspaceConnectionProperties. </summary>
        public UsernamePasswordAuthTypeWorkspaceConnectionProperties()
        {
            AuthType = ConnectionAuthType.UsernamePassword;
        }

        /// <summary> Initializes a new instance of UsernamePasswordAuthTypeWorkspaceConnectionProperties. </summary>
        /// <param name="authType"> Authentication type of the connection target. </param>
        /// <param name="category"> Category of the connection. </param>
        /// <param name="target"></param>
        /// <param name="value"> Value details of the workspace connection. </param>
        /// <param name="valueFormat"> format for the workspace connection value. </param>
        /// <param name="credentials"></param>
        internal UsernamePasswordAuthTypeWorkspaceConnectionProperties(ConnectionAuthType authType, ConnectionCategory? category, string target, string value, ValueFormat? valueFormat, WorkspaceConnectionUsernamePassword credentials) : base(authType, category, target, value, valueFormat)
        {
            Credentials = credentials;
            AuthType = authType;
        }

        /// <summary> Gets or sets the credentials. </summary>
        public WorkspaceConnectionUsernamePassword Credentials { get; set; }
    }
}


text:
package com.thales.training.myspingproj.impl;

public class WarTest {

}


text:
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from prepare import PrepareData

class PrepareDataLin(PrepareData):
    def get_test_data(self):
        test = pd.read_csv('dataset/prepared/test.csv')
        test = test.drop(['VARIETY', 'YEAR', 'FAMILY', 'LOCATION', 'CHECK', 'REPNO', 'CLASS_OF'], 1)
        test = test.drop(test.columns[[0]], axis=1)
        test = test.rename(columns={'YIELD': 'Y'})

        return {'x': PrepareData.get_feature(test), 'y': PrepareData.get_label(test)}

    def get_training_data(self):
        training = pd.read_csv('dataset/prepared/train.csv')
        training = training.drop(['VARIETY', 'YEAR', 'FAMILY', 'LOCATION', 'CHECK', 'REPNO', 'CLASS_OF'], 1)
        training = training.drop(training.columns[[0]], axis=1)
        training = training.rename(columns={'YIELD': 'Y'})

        # encode VARIETY
        # le = LabelEncoder()
        # le.fit(training['VARIETY'])
        # training['VARIETY'] = le.transform(training['VARIETY'])

        return {'x': PrepareData.get_feature(training), 'y': PrepareData.get_label(training)}

    def get_data(self):
        return self.get_training_data()


text:
package de.iritgo.aktera.address;

import de.iritgo.aktera.*;

@PublicAPI
@SuppressWarnings("serial")
public class NoSuchAddressStoreTypeException extends Exception
{
	public NoSuchAddressStoreTypeException()
	{
	}

	public NoSuchAddressStoreTypeException(String message)
	{
		super(message);
	}

	public NoSuchAddressStoreTypeException(Throwable cause)
	{
		super(cause);
	}

	public NoSuchAddressStoreTypeException(String message, Throwable cause)
	{
		super(message, cause);
	}
}


text:
using System;
using System.Collections.Generic;
using Renci.SshNet.Common;
using System.IO;

namespace Renci.SshNet.Sftp
{
    /// <summary>
    /// Encapsulates the results of an asynchronous directory synchronization operation.
    /// </summary>
    public class SftpSynchronizeDirectoriesAsyncResult : AsyncResult<IEnumerable<FileInfo>>
    {
        /// <summary>
        /// Gets the number of files read so far.
        /// </summary>
        public int FilesRead { get; private set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="SftpListDirectoryAsyncResult" /> class.
        /// </summary>
        /// <param name="asyncCallback">The async callback.</param>
        /// <param name="state">The state.</param>
        public SftpSynchronizeDirectoriesAsyncResult(AsyncCallback asyncCallback, Object state)
            : base(asyncCallback, state)
        {
        }

        /// <summary>
        /// Updates asynchronous operation status information.
        /// </summary>
        /// <param name="filesRead">The files read.</param>
        internal void Update(int filesRead)
        {
            this.FilesRead = filesRead;
        }
    }
}


text:
#region license

/*
DirectShowLib - Provide access to DirectShow interfaces via .NET
Copyright (C) 2006
http://sourceforge.net/projects/directshownet/

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#endregion

using System;
using System.Drawing;
using System.Runtime.InteropServices;

namespace DirectShowLib.MultimediaStreaming
{
    #region Utility classes

    sealed public class MsResults
    {
        private MsResults()
        {
            // Prevent people from trying to instantiate this class
        }

        public const int S_Pending                  = unchecked((int)0x00040001);
        public const int S_NoUpdate                 = unchecked((int)0x00040002);
        public const int S_EndOfStream              = unchecked((int)0x00040003);
        public const int E_SampleAlloc              = unchecked((int)0x80040401);
        public const int E_PurposeId                = unchecked((int)0x80040402);
        public const int E_NoStream                 = unchecked((int)0x80040403);
        public const int E_NoSeeking                = unchecked((int)0x80040404);
        public const int E_Incompatible             = unchecked((int)0x80040405);
        public const int E_Busy                     = unchecked((int)0x80040406);
        public const int E_NotInit                  = unchecked((int)0x80040407);
        public const int E_SourceAlreadyDefined     = unchecked((int)0x80040408);
        public const int E_InvalidStreamType        = unchecked((int)0x80040409);
        public const int E_NotRunning               = unchecked((int)0x8004040a);
    }

    sealed public class MsError
    {
        private MsError()
        {
            // Prevent people from trying to instantiate this class
        }

        public static string GetErrorText(int hr)
        {
            string sRet = null;

            switch(hr)
            {
                case MsResults.S_Pending:
                    sRet = "Sample update is not yet complete.";
                    break;
                case MsResults.S_NoUpdate:
                    sRet = "Sample was not updated after forced completion.";
                    break;
                case MsResults.S_EndOfStream:
                    sRet = "End of stream. Sample not updated.";
                    break;
                case MsResults.E_SampleAlloc:
                    sRet = "An IMediaStream object could not be removed from an IMultiMediaStream object because it still contains at least one allocated sample.";
                    break;
                case MsResults.E_PurposeId:
                    sRet = "The specified purpose ID can't be used for the call.";
                    break;
                case MsResults.E_NoStream:
                    sRet = "No stream can be found with the specified attributes.";
                    break;
                case MsResults.E_NoSeeking:
                    sRet = "Seeking not supported for this IMultiMediaStream object.";
                    break;
                case MsResults.E_Incompatible:
                    sRet = "The stream formats are not compatible.";
                    break;
                case MsResults.E_Busy:
                    sRet = "The sample is busy.";
                    break;
                case MsResults.E_NotInit:
                    sRet = "The object can't accept the call because its initialize function or equivalent has not been called.";
                    break;
                case MsResults.E_SourceAlreadyDefined:
                    sRet = "Source already defined.";
                    break;
                case MsResults.E_InvalidStreamType:
                    sRet = "The stream type is not valid for this operation.";
                    break;
                case MsResults.E_NotRunning:
                    sRet = "The IMultiMediaStream object is not in running state.";
                    break;
                default:
                    sRet = DsError.GetErrorText(hr);
                    break;
            }

            return sRet;
        }

        /// <summary>
        /// If hr has a "failed" status code (E_*), throw an exception.  Note that status
        /// messages (S_*) are not considered failure codes.  If DES or DShow error text
        /// is available, it is used to build the exception, otherwise a generic com error
        /// is thrown.
        /// </summary>
        /// <param name="hr">The HRESULT to check</param>
        public static void ThrowExceptionForHR(int hr)
        {
            // If an error has occurred
            if (hr < 0)
            {
                // If a string is returned, build a com error from it
                string buf = GetErrorText(hr);

                if (buf != null)
                {
                    throw new COMException(buf, hr);
                }
                else
                {
                    // No string, just use standard com error
                    Marshal.ThrowExceptionForHR(hr);
                }
            }
        }
    }

    #endregion

    #region Classes

    /// <summary>
    /// From CLSID_AMMultiMediaStream
    /// </summary>
    [ComImport, Guid("49c47ce5-9ba4-11d0-8212-00c04fc32c45")]
    public class AMMultiMediaStream
    {
    }

    /// <summary>
    /// From CLSID_AMMediaTypeStream
    /// </summary>
    [ComImport, Guid("CF0F2F7C-F7BF-11d0-900D-00C04FD9189D")]
    public class AMMediaTypeStream
    {
    }

    /// <summary>
    /// From CLSID_AMDirectDrawStream
    /// </summary>
    [ComImport, Guid("49c47ce4-9ba4-11d0-8212-00c04fc32c45")]
    public class AMDirectDrawStream
    {
    }

    /// <summary>
    /// From CLSID_AMAudioStream
    /// </summary>
    [ComImport, Guid("8496e040-af4c-11d0-8212-00c04fc32c45")]
    public class AMAudioStream
    {
    }

    /// <summary>
    /// From CLSID_AMAudioData
    /// </summary>
    [ComImport, Guid("f2468580-af8a-11d0-8212-00c04fc32c45")]
    public class AMAudioData
    {
    }

    #endregion

    #region Declarations

    /// <summary>
    /// From COMPLETION_STATUS_FLAGS
    /// </summary>
    [Flags]
    public enum CompletionStatusFlags
    {
        None = 0x0,
        NoUpdateOk = 0x1,
        Wait = 0x2,
        Abort = 0x4
    }

    /// <summary>
    /// From unnamed enum
    /// </summary>
    [Flags]
    public enum SSUpdate
    {
        None = 0x0,
        ASync = 0x1,
        Continuous = 0x2
    }

    /// <summary>
    /// From STREAM_STATE
    /// </summary>
    public enum StreamState
    {
        // Fields
        Run = 1,
        Stop = 0
    }

    /// <summary>
    /// From STREAM_TYPE
    /// </summary>
    public enum StreamType
    {
        // Fields
        Read = 0,
        Transform = 2,
        Write = 1
    }

    /// <summary>
    /// From unnamed enum
    /// </summary>
    public enum MMSSF
    {
        HasClock = 0x1,
        SupportSeek = 0x2,
        Asynchronous = 0x4
    }

    #endregion

    #region GUIDS

    sealed public class MSPID
    {
        private MSPID()
        {
            // Prevent people from trying to instantiate this class
        }

        /// <summary> MSPID_PrimaryVideo </summary>
        public static readonly Guid PrimaryVideo = new Guid(0xa35ff56a, 0x9fda, 0x11d0, 0x8f, 0xdf, 0x0, 0xc0, 0x4f, 0xd9, 0x18, 0x9d);

        /// <summary> MSPID_PrimaryAudio </summary>
        public static readonly Guid PrimaryAudio = new Guid(0xa35ff56b, 0x9fda, 0x11d0, 0x8f, 0xdf, 0x0, 0xc0, 0x4f, 0xd9, 0x18, 0x9d);
    }

    #endregion

    #region Interfaces

    [ComImport,
    InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
    Guid("B502D1BD-9A57-11D0-8FDE-00C04FD9189D")]
    public interface IMediaStream
    {
        [PreserveSig]
        int GetMultiMediaStream(
            [MarshalAs(UnmanagedType.Interface)] out IMultiMediaStream ppMultiMediaStream
            );

        [PreserveSig]
        int GetInformation(
            out Guid pPurposeId,
            out StreamType pType
            );

        [PreserveSig]
        int SetSameFormat(
            [In, MarshalAs(UnmanagedType.Interface)] IMediaStream pStreamThatHasDesiredFormat,
            [In] int dwFlags
            );

        [PreserveSig]
        int AllocateSample(
            [In] int dwFlags,
            [MarshalAs(UnmanagedType.Interface)] out IStreamSample ppSample
            );

        [PreserveSig]
        int CreateSharedSample(
            [In, MarshalAs(UnmanagedType.Interface)] IStreamSample pExistingSample,
            [In] int dwFlags,
            [MarshalAs(UnmanagedType.Interface)] out IStreamSample ppNewSample
            );

        [PreserveSig]
        int SendEndOfStream(
            int dwFlags
            );
    }

    [ComImport,
    Guid("B502D1BC-9A57-11D0-8FDE-00C04FD9189D"),
    InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    public interface IMultiMediaStream
    {
        [PreserveSig]
        int GetInformation(
            out MMSSF pdwFlags,
            out StreamType pStreamType
            );

        [PreserveSig]
        int GetMediaStream(
            [In, MarshalAs(UnmanagedType.LPStruct)] Guid idPurpose,
            [MarshalAs(UnmanagedType.Interface)] out IMediaStream ppMediaStream
            );

        [PreserveSig]
        int EnumMediaStreams(
            [In] int Index,
            [MarshalAs(UnmanagedType.Interface)] out IMediaStream ppMediaStream
            );

        [PreserveSig]
        int GetState(
            out StreamState pCurrentState
            );

        [PreserveSig]
        int SetState(
            [In] StreamState NewState
            );

        [PreserveSig]
        int GetTime(
            out long pCurrentTime
            );

        [PreserveSig]
        int GetDuration(
            out long pDuration
            );

        [PreserveSig]
        int Seek(
            [In] long SeekTime
            );

        [PreserveSig]
        int GetEndOfStreamEventHandle(
            out IntPtr phEOS
            );
    }

    [ComImport,
    Guid("B502D1BE-9A57-11D0-8FDE-00C04FD9189D"),
    InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    public interface IStreamSample
    {
        [PreserveSig]
        int GetMediaStream(
            [MarshalAs(UnmanagedType.Interface)] out IMediaStream ppMediaStream
            );

        [PreserveSig]
        int GetSampleTimes(
            out long pStartTime,
            out long pEndTime,
            out long pCurrentTime
            );

        [PreserveSig]
        int SetSampleTimes(
            [In] DsLong pStartTime,
            [In] DsLong pEndTime
            );

        [PreserveSig]
        int Update(
            [In] SSUpdate dwFlags,
            [In] IntPtr hEvent,
            [In] IntPtr pfnAPC,
            [In] IntPtr dwAPCData
            );

        [PreserveSig]
        int CompletionStatus(
            [In] CompletionStatusFlags dwFlags,
            [In] int dwMilliseconds
            );
    }

    #endregion
}


text:
package com.bladecoder.engineeditor.ui.components;

import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.Container;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.Tree;
import com.badlogic.gdx.scenes.scene2d.ui.Tree.Node;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.Selection;
import com.badlogic.gdx.utils.Array;

public abstract class EditTree extends Table {

	protected EditToolbar toolbar;
    protected Tree tree;
    protected Skin skin;
    protected Container<ScrollPane> container;

	private ImageButton upBtn;
	private ImageButton downBtn;
	private ImageButton leftBtn;
	private ImageButton rightBtn;

	public EditTree(Skin skin) {
		super(skin);

		this.skin = skin;
		upBtn = new ImageButton(skin);
		downBtn = new ImageButton(skin);
		leftBtn = new ImageButton(skin);
		rightBtn = new ImageButton(skin);

		tree = new Tree(skin);

		ScrollPane scrollPane = new ScrollPane(tree, skin);
		container = new Container<ScrollPane>(scrollPane);
		container.fill();
		container.prefHeight(1000);

		toolbar = new EditToolbar(skin);
//		debug();
		add(toolbar).expandX().fillX();
		row().fill();
		add(container).expandY().fill();

		toolbar.addToolBarButton(upBtn, "ic_up", "Move up", "Move up");
		toolbar.addToolBarButton(downBtn, "ic_down", "Move down", "Move down");
		toolbar.addToolBarButton(leftBtn, "ic_left", "Child",
				"Move to child option");
		toolbar.addToolBarButton(rightBtn, "ic_right", "Parent",
				"Move to parent option");
		toolbar.addCreateListener(new ChangeListener() {

			@Override
			public void changed(ChangeEvent event, Actor actor) {
				create();
			}
		});

		toolbar.addEditListener(new ChangeListener() {

			@Override
			public void changed(ChangeEvent event, Actor actor) {
				edit();
			}
		});

		toolbar.addDeleteListener(new ChangeListener() {

			@Override
			public void changed(ChangeEvent event, Actor actor) {
				delete();
			}
		});

		toolbar.addCopyListener(new ChangeListener() {

			@Override
			public void changed(ChangeEvent event, Actor actor) {
				copy();
			}
		});

		toolbar.addPasteListener(new ChangeListener() {

			@Override
			public void changed(ChangeEvent event, Actor actor) {
				paste();
			}
		});

		upBtn.addListener(new ChangeListener() {

			@Override
			public void changed(ChangeEvent event, Actor actor) {
				upNode();
			}
		});

		downBtn.addListener(new ChangeListener() {

			@Override
			public void changed(ChangeEvent event, Actor actor) {
				downNode();
			}
		});

		leftBtn.addListener(new ChangeListener() {

			@Override
			public void changed(ChangeEvent event, Actor actor) {
				leftNode();
			}
		});

		rightBtn.addListener(new ChangeListener() {

			@Override
			public void changed(ChangeEvent event, Actor actor) {
				rightNode();
			}
		});

		tree.addListener(new ChangeListener() {
			@Override
			public void changed(ChangeEvent event, Actor actor) {
				Selection<Node> selection = tree.getSelection();

				if (selection.isEmpty()) {
					upBtn.setDisabled(true);
					downBtn.setDisabled(true);

					leftBtn.setDisabled(true);
					rightBtn.setDisabled(true);
				} else {

					Node nodeSel = selection.first();

					int level = nodeSel.getLevel();
					Array<Node> siblings = getSiblings();

					upBtn.setDisabled(siblings.get(0) == nodeSel);
					downBtn.setDisabled(siblings.get(siblings.size - 1) == nodeSel);

					leftBtn.setDisabled(level==1);
					rightBtn.setDisabled(siblings.get(0) == nodeSel);
				}

				toolbar.disableEdit(selection == null);
			}

		});
    }

	public Array<Node> getSiblings() {
		Selection<Node> selection = tree.getSelection();
		Node nodeSel = selection.first();

		int level = nodeSel.getLevel();
		Array<Node> siblings = (level == 1) ? tree.getRootNodes(): nodeSel.getParent().getChildren();

		return siblings;
	}

	abstract protected void create();
	abstract protected void edit();
	abstract protected void delete();
	abstract protected void copy();
	abstract protected void paste();
	abstract protected void upNode();
	abstract protected void downNode();
	abstract protected void leftNode();
	abstract protected void rightNode();
}


text:
Contains classes for accessing and publishing data on a device.  It includes three main
categories of APIs:

Content sharing ({@link android.content})

For sharing content between application components. The most important classes are:

{@link android.content.ContentProvider} and {@link android.content.ContentResolver}
  for managing and publishing persistent data associated with an application.

{@link android.content.Intent} and {@link android.content.IntentFilter}, for delivering
  structured messages between different application components—allowing components to initiate
  other components and return results.

Package management ({@link android.content.pm})

For accessing information about an Android package (an {@code .apk}), including information
about its activities, permissions, services, signatures, and providers. The most important class for
accessing this information is {@link android.content.pm.PackageManager}.

Resource management ({@link android.content.res})

For retrieving resource data associated with an application, such as strings, drawables,
media, and device configuration details. The most important class for accessing this data is {@link
android.content.res.Resources}.


text:
namespace tzw {
	class GuidObj
	{
	public:
		GuidObj();
		virtual char * getGUID();
		virtual char * genGUID();
		virtual void setGUID(const char * newUUID);
		virtual ~GuidObj();
	protected:
		char m_uuid[TZW_UUID_LEN];
	};
} // namespace tzw


text:
title: Анимирование переходов между состояниями
type: guide
order: 14
---

Система анимирования переходов Vue предоставляет много простых методов для анимации появления и исчезновения элементов и также списков, но как насчёт анимации самих данных? Например:

- чисел и арифметических выражений
- отображаемых цветов
- позиции SVG-элементов
- размеров и прочих свойств элементов

Все эти параметры либо хранятся как числа, либо могут быть сконвертированы в числа. Это значит, что мы можем использовать сторонние библиотеки для анимации, в сочетании с компонентными и реактивными системами Vue.

## Анимация состояния при помощи наблюдателей

Наблюдатели позволяют нам анимировать изменения любых числовых свойств. В такой абстрактной форме это может звучать сложновато, так что давайте просто разберём пример с использованием  [Tween.js](https://github.com/tweenjs/tween.js):

``` html
<script src="https://unpkg.com/tween.js@16.3.4"></script>

<div id="animated-number-demo">
  <input v-model.number="number" type="number" step="20">
  <p>{{ animatedNumber }}</p>
</div>
```

``` js
new Vue({
  el: '#animated-number-demo',
  data: {
    number: 0,
    animatedNumber: 0
  },
  watch: {
    number: function(newValue, oldValue) {
      var vm = this
      function animate () {
        if (TWEEN.update()) {
          requestAnimationFrame(animate)
        }
      }

      new TWEEN.Tween({ tweeningNumber: oldValue })
        .easing(TWEEN.Easing.Quadratic.Out)
        .to({ tweeningNumber: newValue }, 500)
        .onUpdate(function () {
          vm.animatedNumber = this.tweeningNumber.toFixed(0)
        })
        .start()

      animate()
    }
  }
})
```

{% raw %}

  <input v-model.number="number" type="number" step="20">

{{ animatedNumber }}

{% endraw %}

Когда вы изменяете число, это изменение в элементе под полем ввода анимируется. Для демонстрации — неплохо, но как насчёт параметров, которые напрямую как числа не хранятся, например таких как CSS-цвета? Используя [Color.js](https://github.com/brehaut/color-js), мы можем решить эту задачу:

``` html
<script src="https://unpkg.com/tween.js@16.3.4"></script>
<script src="https://unpkg.com/color-js@1.0.3/color.js"></script>

<div id="example-7">
  <input
    v-model="colorQuery"
    v-on:keyup.enter="updateColor"
    placeholder="Enter a color"
  >
  <button v-on:click="updateColor">Обновить</button>
  <p>Предпросмотр:</p>
  <span
    v-bind:style="{ backgroundColor: tweenedCSSColor }"
    class="example-7-color-preview"
  ></span>
  <p>{{ tweenedCSSColor }}</p>
</div>
```

``` js
var Color = net.brehaut.Color

new Vue({
  el: '#example-7',
  data: {
    colorQuery: '',
    color: {
      red: 0,
      green: 0,
      blue: 0,
      alpha: 1
    },
    tweenedColor: {}
  },
  created: function () {
    this.tweenedColor = Object.assign({}, this.color)
  },
  watch: {
    color: function () {
      function animate () {
        if (TWEEN.update()) {
          requestAnimationFrame(animate)
        }
      }

      new TWEEN.Tween(this.tweenedColor)
        .to(this.color, 750)
        .start()

     animate()
    }
  },
  computed: {
    tweenedCSSColor: function () {
      return new Color({
        red: this.tweenedColor.red,
        green: this.tweenedColor.green,
        blue: this.tweenedColor.blue,
        alpha: this.tweenedColor.alpha
      }).toCSS()
    }
  },
  methods: {
    updateColor: function () {
      this.color = new Color(this.colorQuery).toRGB()
      this.colorQuery = ''
    }
  }
})
```

``` css
.example-7-color-preview {
  display: inline-block;
  width: 50px;
  height: 50px;
}
```

{% raw %}

  <input
    v-model="colorQuery"
    v-on:keyup.enter="updateColor"
    placeholder="Enter a color"
  >
  <button v-on:click="updateColor">Обновить</button>

Предпросмотр:

{{ tweenedCSSColor }}

{% endraw %}

## Динамические переходы между состояниями

Как и для анимированных компонентов, данные, на которых основываются переходы, могут обновляться в режиме реального времени, что особенно полезно для прототипирования! Даже используя простой SVG-полигон можно достичь многих интересных эффектов, труднодостижимых без небольшой игры с переменными.

{% raw %}

  <svg width="200" height="200" class="demo-svg">
    <polygon :points="points" class="demo-polygon"></polygon>
    <circle cx="100" cy="100" r="90" class="demo-circle"></circle>
  </svg>
  Количество сторон: {{ sides }}
  <input
    class="demo-range-input"
    type="range"
    min="3"
    max="500"
    v-model.number="sides"
  >
  Минимальный радиус: {{ minRadius }}%
  <input
    class="demo-range-input"
    type="range"
    min="0"
    max="90"
    v-model.number="minRadius"
  >
  Интервал обновления: {{ updateInterval }} milliseconds
  <input
    class="demo-range-input"
    type="range"
    min="10"
    max="2000"
    v-model.number="updateInterval"
  >

{% endraw %}

См. [этот fiddle](https://jsfiddle.net/chrisvfritz/65gLu2b6/) для исходного кода.

## Представление переходов как компонентов

Управление множеством переходов может быстро переусложнить экземпляр или компонент. К счастью, многие анимации могут быть выделены в специализированные дочерние компоненты. Давайте проделаем эту операцию с анимированным числом из одного из предыдущих примеров:

``` html
<script src="https://unpkg.com/tween.js@16.3.4"></script>

<div id="example-8">
  <input v-model.number="firstNumber" type="number" step="20"> +
  <input v-model.number="secondNumber" type="number" step="20"> =
  {{ result }}
  <p>
    <animated-integer v-bind:value="firstNumber"></animated-integer> +
    <animated-integer v-bind:value="secondNumber"></animated-integer> =
    <animated-integer v-bind:value="result"></animated-integer>
  </p>
</div>
```

``` js
// Эта логика перехода может быть отныне повторно использована
// с любыми целыми числами, которые мы бы хотели анимировать в приложении.
// Кроме того, компоненты предоставляют удобный интерфейс для конфигурирования
// более сложных и динамичных переходов.

Vue.component('animated-integer', {
  template: '<span>{{ tweeningValue }}</span>',
  props: {
    value: {
      type: Number,
      required: true
    }
  },
  data: function () {
    return {
      tweeningValue: 0
    }
  },
  watch: {
    value: function (newValue, oldValue) {
      this.tween(oldValue, newValue)
    }
  },
  mounted: function () {
    this.tween(0, this.value)
  },
  methods: {
    tween: function (startValue, endValue) {
      var vm = this
      function animate () {
        if (TWEEN.update()) {
          requestAnimationFrame(animate)
        }
      }

      new TWEEN.Tween({ tweeningValue: startValue })
        .to({ tweeningValue: endValue }, 500)
        .onUpdate(function () {
          vm.tweeningValue = this.tweeningValue.toFixed(0)
        })
        .start()

      animate()
    }
  }
})

// В самом экземпляре Vue больше не осталось никакой логики анимаций
new Vue({
  el: '#example-8',
  data: {
    firstNumber: 20,
    secondNumber: 40
  },
  computed: {
    result: function () {
      return this.firstNumber + this.secondNumber
    }
  }
})
```

{% raw %}

  <input v-model.number="firstNumber" type="number" step="20"> +
  <input v-model.number="secondNumber" type="number" step="20"> =
  {{ result }}

    <animated-integer v-bind:value="firstNumber"></animated-integer> +
    <animated-integer v-bind:value="secondNumber"></animated-integer> =
    <animated-integer v-bind:value="result"></animated-integer>

{% endraw %}

В дочерних компонентах можно использовать любую комбинацию стратегий переходов, упомянутую на этой странице, наряду со [встроенной системой переходов Vue](transitions.html). Вместе, они предоставляют практически безграничные возможности.

## Оживление проектов

Анимация, в одном из определений, означает оживление. К сожалению, когда дизайнеры создают новые иконки, логотипы и талисманы, результаты обычно окажутся изображениями или статичными SVG. Таким образом осьминожек в GitHub, птичка в Twitter, и многие другие логотипы напоминают живых существ, но в действительности не кажутся живыми.

Vue может помочь. Поскольку SVG это всего лишь данные, нам нужны только примеры того, как выглядят эти существа когда они радуются, думают или встревожены. Затем Vue берёт на себя всю работу по реализации переходов между этими состояниями, помогая создавать более эмоциональные приветственные страницы, индикаторы загрузки и уведомления.

Sarah Drasner демонстрирует это в демо ниже, используя комбинацию временных и интерактивных изменений состояния:

Посмотрите на Vue-контролируемый Wall-E от Sarah Drasner (@sdras) на CodePen.


text:
package com.github.btrekkie.reductions.planar.test;

import java.util.Arrays;
import java.util.List;

import com.github.btrekkie.reductions.planar.IPlanarGadget;
import com.github.btrekkie.reductions.planar.Point;

/** A horizontal or vertical wire gadget for testing.  See IPlanarWireFactory. */
class TestWireGadget implements IPlanarGadget {
    private final int width;

    private final int height;

    /** Whether this is a horizontal wire rather than a vertical wire. */
    private final boolean isHorizontal;

    public TestWireGadget(int width, int height, boolean isHorizontal) {
        this.width = width;
        this.height = height;
        this.isHorizontal = isHorizontal;
    }

    @Override
    public int width() {
        return width;
    }

    @Override
    public int height() {
        return height;
    }

    @Override
    public List<Point> ports() {
        if (isHorizontal) {
            return Arrays.asList(new Point(0, height / 3), new Point(width, height / 3));
        } else {
            return Arrays.asList(new Point(width / 2, 0), new Point(width / 2, height));
        }
    }
}


text:
function getCounterstream() {
  $.get("/counterstream", renderCountstream);
}

function renderCountstream(data) {
  renderSection('#counterstream', data);
}

function getQ2() {
  $.get("/q2", renderQ2);
}

function renderQ2(data) {
  renderSection('#q2', data);
}

function getYLE() {
  $.get("/yle", renderYLE);
}

function renderYLE(data) {
  renderSection('#yle', data);
}

function getSecondInversion() {
  $.get("/second-inversion", renderSecondInversion);
}

function renderSecondInversion(data) {
  renderSection('#second-inversion', data);
}

function renderSection(id, data) {
  $(id.concat(' .title')).text(data.title);
  $(id.concat(' .composer')).text(data.composer);
}

function renderPieces() {
  getCounterstream();
  getQ2();
  getSecondInversion();
  getYLE();
}

function start() {
  renderPieces();
  setInterval(renderPieces, 60 * 1000);
}

$(start());


text:
"""Classes and functions for running tasks using IPython1"""

from __future__ import with_statement

import sys
import os, os.path
import tempfile
import cPickle

from pebl import config, result
from pebl.taskcontroller.base import _BaseSubmittingController, DeferredResult
from pebl.learner import custom

try:
    import ipython1.kernel.api as ipy1kernel
except:
    ipy1kernel = False

class IPython1DeferredResult(DeferredResult):
    def __init__(self, ipy1_taskcontroller, taskid):
        self.tc = ipy1_taskcontroller
        self.taskid = taskid

    @property
    def result(self):
        if not hasattr(self, 'ipy1result'):
            self.ipy1result = self.tc.getTaskResult(self.taskid, block=True)

        return self.ipy1result['result']

    @property
    def finished(self):
        rst = self.tc.getTaskResult(self.taskid, block=False)
        if rst:
            self.ipy1result = rst
            return True
        return False

class IPython1Controller(_BaseSubmittingController):
    _params = (
        config.StringParameter(
            'ipython1.controller',
            'IPython1 TaskController (default is 127.0.0.1:10113)',
            default='127.0.0.1:10113'
        )
    )

    def __init__(self, tcserver=None):
        """Create a IPython1Controller instance.

        tcserver is the server and port of the Ipython1 TaskController.
        It should be of the form <ip>:<port>. (default is "127.0.0.1:10113").

        """

        if not ipy1kernel:
            print "IPython1 not found."
            return None

        self.tcserver = tcserver or config.get('ipython1.controller')
        self.tc = ipy1kernel.TaskController(tuple(self.tcserver.split(':')))

    def submit(self, tasks):
        drs = []
        for task in tasks:
            # create an ipython1 task from pebl task
            ipy1task = ipy1kernel.Task(
                "from pebl.pebl_script import runtask_picklestr; result = runtask_picklestr(task)",
                resultNames = ['result'],
                setupNS = {'task': cPickle.dumps(task)}
            )

            task.ipy1_taskid = self.tc.run(ipy1task)
            drs.append(IPython1DeferredResult(self.tc, task.ipy1_taskid))
        return drs

    def retrieve(self, deferred_results):
        # block/wait for all tasks
        taskids = [dr.taskid for dr in deferred_results]
        self.tc.barrier(taskids)
        return [dr.result for dr in deferred_results]


text:
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.Text;
using Moq;
using PowerShellTools.Intellisense;

namespace PowerShellTools.Test.IntelliSense
{
    [TestClass]
    public class TabCompleteUnitTests
    {
        private const string TestScript = "Begin tab complete test - {0} - end test";
        private const int TestStartPoint = 26;
        private static readonly List<Completion> TestCompletions = new List<Completion>()
        {
            new Completion("abc"),
            new Completion("testtesttest"),
            new Completion("1")
        };

        private string _mockedScript;
        private int _mockedCaret;

        [TestMethod]
        public void TestCyclingReplaceNext()
        {
            var selectedCompletion = TestCompletions[1];

            _mockedScript = String.Format(TestScript, selectedCompletion.DisplayText);
            _mockedCaret = TestStartPoint + selectedCompletion.DisplayText.Length;

            var textBuffer = TextBufferMock();

            var tabCompleteSession = new TabCompleteSession(TestCompletions, new CompletionSelectionStatus(selectedCompletion, true, true), TestStartPoint);

            tabCompleteSession.ReplaceWithNextCompletion(textBuffer, _mockedCaret);
            Assert.AreEqual(GetExpectedScript(2), _mockedScript);

            tabCompleteSession.ReplaceWithNextCompletion(textBuffer, _mockedCaret);
            Assert.AreEqual(GetExpectedScript(0), _mockedScript);

            tabCompleteSession.ReplaceWithNextCompletion(textBuffer, _mockedCaret);
            Assert.AreEqual(GetExpectedScript(1), _mockedScript);

            tabCompleteSession.ReplaceWithNextCompletion(textBuffer, _mockedCaret);
            Assert.AreEqual(GetExpectedScript(2), _mockedScript);
        }

        [TestMethod]
        public void TestCyclingReplacePrevious()
        {
            var selectedCompletion = TestCompletions[1];

            _mockedScript = String.Format(TestScript, selectedCompletion.DisplayText);
            _mockedCaret = TestStartPoint + selectedCompletion.DisplayText.Length;

            var textBuffer = TextBufferMock();

            var tabCompleteSession = new TabCompleteSession(TestCompletions, new CompletionSelectionStatus(selectedCompletion, true, true), TestStartPoint);

            tabCompleteSession.ReplaceWithPreviousCompletion(textBuffer, _mockedCaret);
            Assert.AreEqual(GetExpectedScript(0), _mockedScript);

            tabCompleteSession.ReplaceWithPreviousCompletion(textBuffer, _mockedCaret);
            Assert.AreEqual(GetExpectedScript(2), _mockedScript);

            tabCompleteSession.ReplaceWithPreviousCompletion(textBuffer, _mockedCaret);
            Assert.AreEqual(GetExpectedScript(1), _mockedScript);

            tabCompleteSession.ReplaceWithPreviousCompletion(textBuffer, _mockedCaret);
            Assert.AreEqual(GetExpectedScript(0), _mockedScript);
        }

        [TestMethod]
        public void TestReplaceNextWithNoSelectedCompletion()
        {
            var textBuffer = TextBufferMock();

            var tabCompleteSession = CreateTabSessionWithNoSelectedCompletion(new CompletionSelectionStatus(null, false, false));
            tabCompleteSession.ReplaceWithNextCompletion(textBuffer, _mockedCaret);
            Assert.AreEqual(GetExpectedScript(0), _mockedScript);

            tabCompleteSession = CreateTabSessionWithNoSelectedCompletion(new CompletionSelectionStatus(TestCompletions[0], false, false));
            tabCompleteSession.ReplaceWithNextCompletion(textBuffer, _mockedCaret);
            Assert.AreEqual(GetExpectedScript(0), _mockedScript);

            tabCompleteSession = CreateTabSessionWithNoSelectedCompletion(new CompletionSelectionStatus(new Completion("bogusCompletion"), true, false));
            tabCompleteSession.ReplaceWithNextCompletion(textBuffer, _mockedCaret);
            Assert.AreEqual(GetExpectedScript(0), _mockedScript);
        }

        [TestMethod]
        public void TestReplacePreviousWithNoSelectedCompletion()
        {
            var textBuffer = TextBufferMock();

            var tabCompleteSession = CreateTabSessionWithNoSelectedCompletion(new CompletionSelectionStatus(null, false, false));
            tabCompleteSession.ReplaceWithPreviousCompletion(textBuffer, _mockedCaret);
            Assert.AreEqual(GetExpectedScript(2), _mockedScript);

            tabCompleteSession = CreateTabSessionWithNoSelectedCompletion(new CompletionSelectionStatus(TestCompletions[0], false, false));
            tabCompleteSession.ReplaceWithPreviousCompletion(textBuffer, _mockedCaret);
            Assert.AreEqual(GetExpectedScript(2), _mockedScript);

            tabCompleteSession = CreateTabSessionWithNoSelectedCompletion(new CompletionSelectionStatus(new Completion("bogusCompletion"), true, false));
            tabCompleteSession.ReplaceWithPreviousCompletion(textBuffer, _mockedCaret);
            Assert.AreEqual(GetExpectedScript(2), _mockedScript);
        }

        private TabCompleteSession CreateTabSessionWithNoSelectedCompletion(CompletionSelectionStatus selectionStatus)
        {
            _mockedScript = String.Format(TestScript, String.Empty);
            _mockedCaret = TestStartPoint;

            return new TabCompleteSession(TestCompletions, selectionStatus, TestStartPoint);
        }

        private string GetExpectedScript(int index)
        {
            return String.Format(TestScript, TestCompletions[index].DisplayText);
        }

        private ITextBuffer TextBufferMock()
        {
            var textBufferMock = new Mock<ITextBuffer>();
            textBufferMock.Setup(t => t.Replace(It.IsAny<Span>(), It.IsAny<string>()))
                .Callback<Span, string>((replaceSpan, replaceWith) =>
                {
                    _mockedScript = _mockedScript.Remove(replaceSpan.Start, replaceSpan.Length);
                    _mockedScript = _mockedScript.Insert(replaceSpan.Start, replaceWith);
                    _mockedCaret = replaceSpan.Start + replaceWith.Length;
                });
            return textBufferMock.Object;
        }
    }
}


text:
namespace Gu.Wpf.ValidationScope.Tests
{
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;

    public class TestValidationError : ValidationError
    {
        private static readonly BindingExpressionBase DummyBindingExpression = BindingOperations.SetBinding(new DependencyObject(), FrameworkElement.DataContextProperty, new Binding());

        private TestValidationError(BindingExpressionBase bindingInError)
            : base(TestValidationRule.Default, bindingInError)
        {
        }

        public static TestValidationError GetFor(BindingExpressionBase expression)
        {
            return new TestValidationError(expression);
        }

        public static TestValidationError Create()
        {
            return new TestValidationError(DummyBindingExpression);
        }

        public static TestValidationError GetFor(UIElement element, DependencyProperty property)
        {
            return TestValidationError.GetFor(BindingOperations.SetBinding(element, property, new Binding("Foo")));
        }
    }
}


text:
package com.staticvillage.traktandroid.model.shows;

import com.google.gson.annotations.SerializedName;
import com.staticvillage.traktandroid.model.common.Show;

/**
 * Created by joelparrish on 10/30/16.
 */

public class WatchedShow {
    @SerializedName("watcher_count")
    private long watcherCount;
    @SerializedName("play_count")
    private long playCount;
    @SerializedName("collected_count")
    private long collectedCount;
    @SerializedName("collector_count")
    private long collectorCount;
    private Show show;

    public long getWatcherCount() {
        return watcherCount;
    }

    public void setWatcherCount(long watcherCount) {
        this.watcherCount = watcherCount;
    }

    public long getPlayCount() {
        return playCount;
    }

    public void setPlayCount(long playCount) {
        this.playCount = playCount;
    }

    public long getCollectedCount() {
        return collectedCount;
    }

    public void setCollectedCount(long collectedCount) {
        this.collectedCount = collectedCount;
    }

    public Show getShow() {
        return show;
    }

    public void setShow(Show show) {
        this.show = show;
    }

    public long getCollectorCount() {
        return collectorCount;
    }

    public void setCollectorCount(long collectorCount) {
        this.collectorCount = collectorCount;
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Poseidon.Recovery.ClientDx
{
    using Poseidon.Base.Framework;
    using Poseidon.Common;
    using Poseidon.Winform.Base;
    using Poseidon.Winform.Core.Utility;
    using Poseidon.Recovery.Core.BL;
    using Poseidon.Recovery.Core.DL;
    using Poseidon.Recovery.Core.Utility;

    /// <summary>
    /// 表具表格控件
    /// </summary>
    public partial class MeterGrid : WinEntityGrid<Meter>
    {
        #region Constructor
        public MeterGrid()
        {
            InitializeComponent();
        }
        #endregion //Constructor

        #region Method
        /// <summary>
        /// 初始化
        /// </summary>
        public void Init()
        {
            ControlUtil.BindEnumToComboBox(this.cmbEnergyType, typeof(MeterEnergyType));
            ControlUtil.BindEnumToComboBox(this.cmbChargeType, typeof(MeterChargeType));
        }
        #endregion //Method
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator">
    <rotate android:fromDegrees="0"
        android:toDegrees="90"
        android:pivotX="0"
        android:pivotY="100%"
        android:duration="500"/>
    <scale android:fromXScale="1"
        android:toXScale="0"
        android:fromYScale="1"
        android:toYScale="0"
        android:pivotX="50%"
        android:pivotY="100%"
        android:duration="500"/>
</set>


text:
define(['get-type'],
function (getType) {
   'use strict';
    function Search (collection) {
        this.contains = false;
        this.thisFor = function (thing, blob) {
            blob = blob || collection;
            var type = getType(blob),
                keys = type === "object" ? Object.keys(blob) : null,
                len = type === "object" ? Object.keys(blob).length : blob.length,
                n,
                key;
            for (n = 0; n < len; n++) {
                key = keys ? keys[n] : n;
                if (blob[key] === thing) {
                    this.contains = true;
                    break;
                }
                if (getType(blob[key]) === 'object' || getType(blob[key]) === 'array') {
                    this.thisFor(thing, blob[key]);
                }
            }
            return this.contains;
        };
        return this;
    }
    function search (collection, thing) {
        return new Search(collection).thisFor(thing);
    }
    return search;
});