text:
package org.apache.geode.rest.internal.web.controllers;

import static org.assertj.core.api.AssertionsForClassTypes.assertThat;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.internal.AvailablePortHelper;
import org.apache.geode.management.configuration.DiskStore;
import org.apache.geode.management.operation.RebalanceOperation;
import org.apache.geode.management.operation.RestoreRedundancyRequest;
import org.apache.geode.test.dunit.rules.ClusterStartupRule;
import org.apache.geode.test.dunit.rules.MemberVM;
import org.apache.geode.test.junit.categories.BackwardCompatibilityTest;
import org.apache.geode.test.junit.rules.GfshCommandRule;
import org.apache.geode.test.junit.rules.MemberStarterRule;
import org.apache.geode.test.version.TestVersion;
import org.apache.geode.test.version.VersionManager;
import org.apache.geode.util.internal.GeodeJsonMapper;

@Category({BackwardCompatibilityTest.class})
@RunWith(Parameterized.class)
public class RestAPICompatibilityTest {
  private final String oldVersion;
  private static final ObjectMapper mapper = GeodeJsonMapper.getMapper();

  @Parameterized.Parameters(name = "{0}")
  public static Collection<String> data() {
    List<String> result = VersionManager.getInstance().getVersionsWithoutCurrent();
    result.removeIf(s -> TestVersion.compare(s, "1.11.0") < 0);
    return result;
  }

  @Rule
  public ClusterStartupRule cluster = new ClusterStartupRule();

  @Rule
  public GfshCommandRule gfsh = new GfshCommandRule();

  public RestAPICompatibilityTest(String oldVersion) throws JsonProcessingException {
    this.oldVersion = oldVersion;
    DiskStore diskStore = new DiskStore();
    diskStore.setName("diskStore");
    postRESTAPICalls = new HashMap<>();
    // {REST endpoint,{Body, Successful Status Message, Introduced in version}}
    postRESTAPICalls.put("/management/v1/operations/rebalances",
        new String[] {mapper.writeValueAsString(new RebalanceOperation()), "Operation started",
            "1.11.0"});
    postRESTAPICalls.put("/management/v1/operations/restoreRedundancy",
        new String[] {mapper.writeValueAsString(new RestoreRedundancyRequest()),
            "Operation started", "1.13.1"});
  }

  private static Map<String, String[]> postRESTAPICalls;

  private static final String[][] getRESTAPICalls = {
      // REST endpoint , status
      {"/geode-mgmt/v1/management/commands?cmd=rebalance", "OK"}
  };

  @Test
  public void restCommandExecutedOnLatestLocatorShouldBeBackwardsCompatible() throws Exception {
    int[] locatorPorts = AvailablePortHelper.getRandomAvailableTCPPorts(2);
    int locatorPort1 = locatorPorts[0];
    int locatorPort2 = locatorPorts[1];

    // Initialize all cluster members with old versions
    cluster.startLocatorVM(0, locatorPort1, oldVersion, MemberStarterRule::withHttpService);
    cluster.startLocatorVM(1, locatorPort2, oldVersion,
        x -> x.withConnectionToLocator(locatorPort1).withHttpService());
    cluster
        .startServerVM(2, oldVersion, s -> s.withRegion(RegionShortcut.PARTITION, "region")
            .withConnectionToLocator(locatorPort1, locatorPort2));
    cluster
        .startServerVM(3, oldVersion, s -> s.withRegion(RegionShortcut.PARTITION, "region")
            .withConnectionToLocator(locatorPort1, locatorPort2));

    // Roll locators to the current version
    cluster.stop(0);
    // gradle sets a property telling us where the build is located
    final String buildDir = System.getProperty("geode.build.dir", System.getProperty("user.dir"));
    MemberVM locator1 = cluster.startLocatorVM(0, l -> l.withHttpService().withPort(locatorPort1)
        .withConnectionToLocator(locatorPort2)
        .withSystemProperty("geode.build.dir", buildDir));
    cluster.stop(1);

    cluster.startLocatorVM(1,
        x -> x.withConnectionToLocator(locatorPort1).withHttpService().withPort(locatorPort2)
            .withConnectionToLocator(locatorPort1)
            .withSystemProperty("geode.build.dir", buildDir));

    gfsh.connectAndVerify(locator1);
    gfsh.execute("list members");
    // Execute REST api calls to from the new locators to the old servers to ensure that backwards
    // compatibility is maintained

    executeAndValidatePOSTRESTCalls(locator1.getHttpPort());
    executeAndValidateGETRESTCalls(locator1.getHttpPort());

  }

  void executeAndValidatePOSTRESTCalls(int locator) throws Exception {

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
      for (Map.Entry<String, String[]> entry : postRESTAPICalls.entrySet()) {
        // Skip the test is the version is before the REST api was introduced.
        if (TestVersion.compare(oldVersion, entry.getValue()[2]) < 0) {
          continue;
        }
        HttpPost post =
            new HttpPost("http://localhost:" + locator + entry.getKey());
        post.addHeader("Content-Type", "application/json");
        post.addHeader("Accept", "application/json");
        StringEntity jsonStringEntity =
            new StringEntity(entry.getValue()[0], ContentType.DEFAULT_TEXT);
        post.setEntity(jsonStringEntity);
        CloseableHttpResponse response = httpClient.execute(post);

        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(content))) {
          String line;
          StringBuilder sb = new StringBuilder();
          while ((line = reader.readLine()) != null) {
            sb.append(line);
          }
          JsonNode jsonObject = mapper.readTree(sb.toString());
          String statusCode = jsonObject.findValue("statusCode").textValue();
          assertThat(statusCode).satisfiesAnyOf(
              value -> assertThat(value).isEqualTo("ACCEPTED"),
              value -> assertThat(value).contains("OK"));
          String statusMessage = jsonObject.findValue("statusMessage").textValue();
          assertThat(statusMessage).contains(entry.getValue()[1]);
        }
      }
    }
  }

  public static void executeAndValidateGETRESTCalls(int locator) throws Exception {

    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
      for (String[] commandExpectedResponsePair : getRESTAPICalls) {
        HttpGet get =
            new HttpGet("http://localhost:" + locator +
                commandExpectedResponsePair[0]);
        CloseableHttpResponse response = httpclient.execute(get);
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(content))) {
          String line;
          StringBuilder sb = new StringBuilder();
          while ((line = reader.readLine()) != null) {
            sb.append(line);
          }
          JsonNode jsonObject = mapper.readTree(sb.toString());
          String statusCode = jsonObject.findValue("status").textValue();
          assertThat(statusCode).contains(commandExpectedResponsePair[1]);
        }
      }
    }
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.zwy.kutils.widget.loadingdialog.bean (kutils 2.4 API)</title>
<meta name="date" content="2017-08-01">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

com.zwy.kutils.widget.loadingdialog.bean

类

BottomSheetBean

BuildBean

PopuBean

TieBean

redpajama_set_name: RedPajamaGithub


text:
<?php

class XML_Model extends Memory_Model
{
//---------------------------------------------------------------------------
//  Housekeeping methods
//---------------------------------------------------------------------------

    protected $xml = null;

    /**
    * Constructor.
    * @param string $origin Filename of the XML file
    * @param string $keyfield  Name of the primary key field
    * @param string $entity	Entity name meaningful to the persistence
    */
    function __construct($origin = null, $keyfield = 'id', $entity = null)
    {
        parent::__construct();

        // guess at persistent name if not specified
        if ($origin == null)
                $this->_origin = get_class($this);
        else
                $this->_origin = $origin;

        // remember the other constructor fields
        $this->_keyfield = $keyfield;
        $this->_entity = $entity;

        // start with an empty collection
        $this->_data = array(); // an array of objects
        $this->_fields = array(); // an array of strings
        // and populate the collection
        $this->load();
    }

    /**
    * Load the collection state appropriately, depending on persistence choice.
    * OVER-RIDE THIS METHOD in persistence choice implementations
    */
    protected function load()
    {
        //---------------------
        $this->xml = simplexml_load_file($this->_origin);

        // Have all the field names even if file is empty
        $this->_fields[] = 'id';
        $this->_fields[] = 'task';
        $this->_fields[] = 'priority';
        $this->_fields[] = 'size';
        $this->_fields[] = 'group';
        $this->_fields[] = 'deadline';
        $this->_fields[] = 'status';
        $this->_fields[] = 'flag';

        foreach ($this->xml->tasks->item as $item)
        {
            $record = new stdClass();
            $record->id = (int) $item->id;
            $record->task = (string) $item->task;
            $record->priority = (int) $item->priority;
            $record->size = (int) $item->size;
            $record->group = (int) $item->group;
            $record->deadline = (string) $item->deadline;
            $record->status = (int) $item->status;
            $record->flag = (int) $item->flag;
            $this->_data[$record->id] = $record;
        }

        // --------------------
        // rebuild the keys table
        $this->reindex();
    }

    /**
    * Store the collection state appropriately, depending on persistence choice.
    * OVER-RIDE THIS METHOD in persistence choice implementations
    */
    protected function store()
    {
        $this->parseXML();
        // rebuild the keys table
        $this->reindex();
        //---------------------
        if (($handle = fopen($this->_origin, "w")) !== FALSE)
        {
            //save it with appropriate indentations
            $dom = new DOMDocument('1.0', 'utf-8');
            $dom->preserveWhiteSpace = false;
            $dom->formatOutput = true;
            $dom->loadXML($this->xml->asXML());

            fputs($handle, $dom->saveXML());
            fclose($handle);
        }
        // --------------------
    }

    protected function parseXML(){
        //save it with appropriate indentations
        $dom = new DOMDocument('1.0', 'utf-8');
        $dom->preserveWhiteSpace = false;
        $dom->formatOutput = true;
        $xml = new SimpleXMLElement('<xml></xml>');
        $tasks = $xml->addChild('tasks');

        foreach ($this->_data as $key => $record) {
            $item = $tasks->addChild('item');
            //parse value
            foreach ($this->fields() as $field) {
                $item->addChild($field, $record->$field);
            }
        }
        $this->xml = $xml;
    }
}


text:
package rpmpack

// FileType is the type of a file inside a RPM package.
type FileType int32

// https://refspecs.linuxbase.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/pkgformat.html#AEN27560
// The RPMFile.Type tag value shall identify various characteristics of the file in the payload that it describes.
// It shall be an INT32 value consisting of either the value GenericFile (0) or
// the bitwise inclusive or of one or more of the following values. Some of these combinations may make no sense
const (
	// GenericFile is just a basic file in an RPM
	GenericFile FileType = 1 << iota >> 1
	// ConfigFile is a configuration file, and an existing file should be saved during a
	// package upgrade operation and not removed during a package removal operation.
	ConfigFile
	// DocFile is a file that contains documentation.
	DocFile
	// DoNotUseFile is reserved for future use; conforming packages may not use this flag.
	DoNotUseFile
	// MissingOkFile need not exist on the installed system.
	MissingOkFile
	// NoReplaceFile similar to the ConfigFile, this flag indicates that during an upgrade operation
	// the original file on the system should not be altered.
	NoReplaceFile
	// SpecFile is the package specification file.
	SpecFile
	// GhostFile is not actually included in the payload, but should still be considered as a part of the package.
	// For example, a log file generated by the application at run time.
	GhostFile
	// LicenceFile contains the license conditions.
	LicenceFile
	// ReadmeFile contains high level notes about the package.
	ReadmeFile
	// ExcludeFile is not a part of the package, and should not be installed.
	ExcludeFile
)

// RPMFile contains a particular file's entry and data.
type RPMFile struct {
	Name  string
	Body  []byte
	Mode  uint
	Owner string
	Group string
	MTime uint32
	Type  FileType
}


text: %~dp0/Scripts/Python.exe bibleSpam.py


text:
from __future__ import with_statement

# stdlib
from optparse import OptionParser, make_option
import subprocess
import logging
import sys
import tempfile
import os
import pkg_resources
import shutil
import shlex
import errno
import re

# internal
from . import  zipdir

DEVNULL = open(os.devnull, "w")

_dirty_files = []
def destroy_dirty_files():
    global _dirty_files

    log = logging.getLogger("superzippy")

    for i in _dirty_files:
        log.debug("Deleting %s.", i)
        shutil.rmtree(i)

    _dirty_files = []

def parse_arguments(args = sys.argv[1:]):
    option_list = [
        make_option(
            "-v", "--verbose", action = "count", default=0,
            help =
                "May be specified thrice. If specified once, INFO messages "
                "and above are output. If specified twice, DEBUG messages and "
                "above are output. If specified thrice, DEBUG messages and "
                "above are output, along with the output from any invoked "
                "programs. By default, only WARN messages and above are "
                "output."
        ),
        make_option(
            "-q", "--quiet", action = "store_true",
            help = "Only CRITICAL log messages will be output."
        ),
        make_option(
            "-o", "--output", action = "store", default = None,
            help =
                "The name of the output file. Defaults to the name of the "
                "last package specified on the command line."
        ),
        make_option(
            "-r", "--requirements", action = "append", default = [],
            help =
                "A path to a requirements.txt file to parse and install from. "
                "This option may be specified multiple times."
        ),
        make_option(
            "-c", "--raw-copy", action = "append", default = [],
            dest = "raw_copy",
            help =
                "A path to a file or directory to copy into the created "
                "executable directly. Useful when you don't have a setup.py "
                "for your project."
        ),
        make_option(
            "--raw-copy-rename", action = "append", default = [],
            dest = "raw_copy_rename",
            help =
                "Takes 2 arguments, first a path to a file or directory to "
                "copy into the zuper zip directly, and second the name that "
                "file should have (this name will be importable from within "
                "the executable."
        )
    ]

    parser = OptionParser(
        usage = "usage: %prog [options] [PACKAGE1 PACKAGE2 ...] [ENTRY POINT]",
        description =
            "Zips up a package and adds superzippy's super bootstrap logic to "
            "it. ENTRY POINT should be in the format module:function. Just "
            "like the entry_point option for distutils. Each PACKAGE string "
            "will be passed directly to pip so you may use options and expect "
            "normal results (ex: 'PyYAML --without-libyaml').",
        option_list = option_list
    )

    options, args = parser.parse_args(args)

    if len(args) < 1:
        parser.error("1 or more arguments must be supplied.")

    return (options, args)

def setup_logging(options, args):
    if options.verbose >= 2:
        log_level = logging.DEBUG
    elif options.verbose == 1:
        log_level = logging.INFO
    elif options.quiet:
        log_level = logging.CRITICAL
    else:
        log_level = logging.WARN

    format = "[%(levelname)s] %(message)s"

    logging.basicConfig(level = log_level, format = format)

    logging.getLogger("superzippy").debug("Logging initialized.")

def main(options, args):
    log = logging.getLogger("superzippy")

    packages = args[0:-1]
    entry_point = args[-1]

    # Append any requirements.txt files to the packages list.
    packages += ["-r %s" % i for i in options.requirements]

    # Create the virtualenv directory
    virtualenv_dir = tempfile.mkdtemp()
    _dirty_files.append(virtualenv_dir)

    #### Create virtual environment

    log.debug("Creating virtual environment at %s.", virtualenv_dir)
    output_target = None if options.verbose >= 3 else DEVNULL

    return_value = subprocess.call(
        ["virtualenv", virtualenv_dir],
        stdout = output_target,
        stderr = subprocess.STDOUT
    )

    if return_value != 0:
        log.critical(
            "virtualenv returned non-zero exit status (%d).", return_value
        )
        return 1

    ##### Install package and dependencies

    pip_path = os.path.join(virtualenv_dir, "bin", "pip")

    for i in packages:
        log.debug("Installing package with `pip install %s`.", i)

        command = [pip_path, "install"] + shlex.split(i)
        return_value = subprocess.call(
            command,
            stdout = output_target,
            stderr = subprocess.STDOUT
        )

        if return_value != 0:
            log.critical("pip returned non-zero exit status (%d).", return_value)
            return 1

    if not packages:
        log.warn("No packages specified.")

    #### Uninstall extraneous packages (pip and setuptools)
    return_value = subprocess.call(
        [pip_path, "uninstall", "--yes", "pip", "setuptools"],
        stdout = output_target,
        stderr = subprocess.STDOUT
    )

    if return_value != 0:
        log.critical("pip returned non-zero exit status (%d).",
            return_value)
        return 1

    #### Move site packages over to build directory

    # TODO: We should look at pip's source code and figure out how it decides
    # where site-packages is and use the same algorithm.

    build_dir = tempfile.mkdtemp()
    _dirty_files.append(build_dir)

    site_package_dir = None
    for root, dirs, files in os.walk(virtualenv_dir):
        if "site-packages" in dirs:
            found = os.path.join(root, "site-packages")

            # We'll only use the first one, but we want to detect them all.
            if site_package_dir is not None:
                log.warn(
                    "Multiple site-packages directories found. `%s` will be "
                    "used. `%s` was found afterwards.",
                    site_package_dir,
                    found
                )
            else:
                site_package_dir = found

    # A couple .pth files are consistently left over from the previous step,
    # delete them.
    extraneous_pth_files = ["easy-install.pth", "setuptools.pth"]
    for i in extraneous_pth_files:
        path = os.path.join(site_package_dir, i)
        if os.path.exists(path):
            os.remove(path)

    shutil.move(site_package_dir, build_dir)

    #### Perform any necessary raw copies.
    raw_copies = options.raw_copy_rename

    for i in options.raw_copy:
        if i[-1] == "/":
            i = i[0:-1]

        raw_copies.append((i, os.path.basename(i)))

    for file_path, dest_name in raw_copies:
        log.debug(
            "Performing raw copy of `%s`, destination name: `%s`.",
            file_path,
            dest_name
        )

        dest = os.path.join(build_dir, "site-packages", dest_name)

        try:
            shutil.copytree(file_path, dest)
        except OSError as e:
            if e.errno == errno.ENOTDIR:
                shutil.copy(file_path, dest)
            else:
                raise

    ##### Install bootstrapper

    log.debug("Adding bootstrapper to the archive.")

    bootstrap_files = {
        "__init__.py": "__init__.py",
        "bootstrapper.py": "__main__.py",
        "zipsite.py": "zipsite.py",
        "module_locator.py": "module_locator.py"
    }

    for k, v in bootstrap_files.items():
        source = pkg_resources.resource_stream("superzippy.bootstrapper", k)
        dest = open(os.path.join(build_dir, v), "wb")

        shutil.copyfileobj(source, dest)

        source.close()
        dest.close()

    ##### Install configuration

    log.debug("Adding configuration file to archive.")

    with open(os.path.join(build_dir, "superconfig.py"), "w") as f:
        f.write("entry_point = '%s'" % entry_point)

    ##### Zip everything up into final file

    log.debug("Zipping up %s.", build_dir)

    if options.output:
        output_file = options.output
    elif packages:
        last_package = shlex.split(packages[-1])[0]

        if os.path.isdir(last_package):
            # Figure out the name of the package the user pointed at on their
            # system.
            setup_program = subprocess.Popen(["/usr/bin/env", "python",
                os.path.join(last_package, "setup.py"), "--name"],
                stdout = subprocess.PIPE, stderr = DEVNULL)
            if setup_program.wait() != 0:
                log.critical("Could not determine name of package at %s.",
                    last_package)
                return 1

            # Grab the output of the setup program
            package_name_raw = setup_program.stdout.read()

            # Decode the output into text. Whatever our encoding is is
            # probably the same as what the setup.py program spat out.
            package_name_txt = package_name_raw.decode(
                sys.stdout.encoding or "UTF-8")

            # Strip any leading and trailing whitespace
            package_name = package_name_txt.strip()

            # Verify that what we got was a valid package name (this handles
            # most cases where an error occurs in the setup.py program).
            if re.match("[A-Za-z0-9_-]+", package_name) is None:
                log.critical("Could nto determine name of package. setup.py "
                    "is reporting an illegal name of %s", package_name)
                return 1

            output_file = package_name + ".sz"
        else:
            # Just use the name of a package we're going to pull down from
            # the cheese shop, but cut off any versioning information (ex:
            # bla==2.3 will become bla).
            for k, c in enumerate(last_package):
                if c in ("=", ">", "<"):
                    output_file = last_package[0:k] + ".sz"
                    break
            else:
                output_file = last_package + ".sz"

    else:
        log.critical("No output file or packages specified.")
        return 1

    try:
        zipdir.zip_directory(build_dir, output_file)
    except IOError:
        log.critical(
            "Could not write to output file at '%s'.",
            output_file,
            exc_info = sys.exc_info()
        )
        return 1

    #### Make that file executable

    with open(output_file, "rb") as f:
        data = f.read()

    with open(output_file, "wb") as f:
        f.write(b"#!/usr/bin/env python\n" + data)

    os.chmod(output_file, 0o755)

    return 0

def run():
    options, args = parse_arguments()
    setup_logging(options, args)
    try:
        main(options, args)
    finally:
        destroy_dirty_files()

if __name__ == "__main__":
    run()


text:
using namespace std;

class Labyrinthe
{
    public:
        Labyrinthe(int l, int h);
        Labyrinthe(string& path);

        int largeur;
        int hauteur;

        ifstream textFile;
        bool read(string& path);
        void display();
		void afficher();

        Noeud* dijkstra();
        Noeud* a_Star();
        void tracer_Backtrack(Noeud* n);

        virtual ~Labyrinthe();
    protected:
    private:
        char** data;
        int largeur_Reel;
};

#endif // LABYRINTHE_H


text:
package react

// PProps are the props for a <div> component
type PProps struct {
	ClassName               string
	DangerouslySetInnerHTML *DangerousInnerHTML
	ID                      string
	Key                     string

	OnChange
	OnClick

	Role  string
	Style *CSS
}

func (p *PProps) assign(v *_PProps) {

	v.ClassName = p.ClassName

	v.DangerouslySetInnerHTML = p.DangerouslySetInnerHTML

	if p.ID != "" {
		v.ID = p.ID
	}

	if p.Key != "" {
		v.Key = p.Key
	}

	if p.OnChange != nil {
		v.o.Set("onChange", p.OnChange.OnChange)
	}

	if p.OnClick != nil {
		v.o.Set("onClick", p.OnClick.OnClick)
	}

	v.Role = p.Role

	// TODO: until we have a resolution on
	// https://github.com/gopherjs/gopherjs/issues/236
	v.Style = p.Style.hack()

}


text:
@implementation MCMAdAdapter

- (id) init{
    if ((self=[super init])){
        adViewDict_ = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (void) dealloc {
    [adViewDict_ release];
    [super dealloc];
}

- (void) viewDidLoad:(UIViewController *)vc{
    if ([[[MCMCoreManager sharedInstance] valueForKey:kMCMCoreKeyAdWhirlId] length]<=0){

        [MCMLog log:@"Malcom Ad - The module has been included in the binary but no AdWhirlId configured in MCMCore-Info.plist" inLine:__LINE__ fromMethod:[NSString stringWithCString:__PRETTY_FUNCTION__ encoding:NSUTF8StringEncoding]];
        return;

    }

    //Check the ad is not disabled
    if ([vc respondsToSelector:@selector(shouldLoadAd)]){
        if ([vc performSelector:@selector(shouldLoadAd)]==NO){
            [adViewDict_ removeObjectForKey:[NSString stringWithFormat:@"%x", vc]];
            return;
        }
    }

    //AdWhirl methods
	AdWhirlView *adWhirlView = [AdWhirlView requestAdWhirlViewWithDelegate:self];

    CGSize adSize = [adWhirlView actualAdSize];

    [adWhirlView setFrame:CGRectMake((adWhirlView.superview.frame.size.width-adSize.width)/2, adWhirlView.superview.frame.size.height-adSize.height, adSize.width, adSize.height)];

    [adWhirlView setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin];
    [adWhirlView setHidden:YES];
	[vc.view addSubview:adWhirlView];

    [adViewDict_ setObject:adWhirlView forKey:[NSString stringWithFormat:@"%x", vc]];
}

- (void) viewRotate:(UIViewController *)vc toOrientation:(UIInterfaceOrientation)orientation{

    AdWhirlView *adWhirlView = [adViewDict_ objectForKey:[NSString stringWithFormat:@"%x", vc]];
    if (adWhirlView){
        [adWhirlView rotateToOrientation:orientation];
    }
}

#pragma mark AdWhirl delegate

- (NSString *)adWhirlApplicationKey {
	return [[MCMCoreManager sharedInstance] valueForKey:kMCMCoreKeyAdWhirlId];
}

- (UIViewController *)viewControllerForPresentingModalView {

	NSObject<UIApplicationDelegate> *appDelegate = [[UIApplication sharedApplication] delegate];

    if ([appDelegate respondsToSelector:@selector(navigationController)]) {

        return [((id) appDelegate) navigationController];

    }

    if ([appDelegate respondsToSelector:@selector(tabBarController)])
        return [((id) appDelegate) tabBarController];

    if ([[[UIApplication sharedApplication] keyWindow] respondsToSelector:@selector(rootViewController)])
        return [[[UIApplication sharedApplication] keyWindow] rootViewController];

    return nil;
}

- (NSURL *)adWhirlConfigURL{
    NSString *url = [[[MCMCoreManager sharedInstance] valueForKey:kMCMCoreKeyAdWhirlUrl] stringByAppendingString:kMCMAdConfigPath];
    return [NSURL URLWithString:url];
}

- (NSURL *)adWhirlImpMetricURL{
    NSString *url = [[[MCMCoreManager sharedInstance] valueForKey:kMCMCoreKeyAdWhirlUrl] stringByAppendingString:kMCMAdImpMetricPath];
    return [NSURL URLWithString:url];

}

- (NSURL *)adWhirlClickMetricURL{
    NSString *url = [[[MCMCoreManager sharedInstance] valueForKey:kMCMCoreKeyAdWhirlUrl] stringByAppendingString:kMCMAdClickMetricPath];
    return [NSURL URLWithString:url];

}

- (NSURL *)adWhirlCustomAdURL{
    NSString *url = [[[MCMCoreManager sharedInstance] valueForKey:kMCMCoreKeyAdWhirlUrl] stringByAppendingString:kMCMAdCustomAdPath];
    return [NSURL URLWithString:url];
}

- (void)adWhirlDidReceiveAd:(AdWhirlView *)adWhirlView{

    [MCMLog log:[NSString stringWithFormat:@"Malcom Ad- AdWhirl banner received. Ad: %@", [adWhirlView description]]
         inLine:__LINE__ fromMethod:[NSString stringWithCString:__PRETTY_FUNCTION__ encoding:NSUTF8StringEncoding]];
    //Change size if the banner is not standard
    CGSize adSize = [adWhirlView actualAdSize];

    CGRect rect = CGRectMake((adWhirlView.superview.frame.size.width-adSize.width)/2, adWhirlView.superview.frame.size.height-adSize.height, adSize.width, adSize.height);

//    if ([[MCMAdManager sharedInstance] frameChanged]) {
//
//        rect = [[MCMAdManager sharedInstance] getAdWhirlFrame];
//
//    }

    [adWhirlView setFrame:rect];
    //Make it visible
    [adWhirlView setHidden:NO];
    [adWhirlView.superview performSelectorOnMainThread:@selector(bringSubviewToFront:) withObject:adWhirlView waitUntilDone:YES];

}

- (void)adWhirlDidFailToReceiveAd:(AdWhirlView *)adWhirlView usingBackup:(BOOL)yesOrNo{

    [MCMLog log:[NSString stringWithFormat:@"Malcom Ad - AdWhirl failed to receive an ad. Check your appId is correct. Ad: %@", [adWhirlView description]]
         inLine:__LINE__ fromMethod:[NSString stringWithCString:__PRETTY_FUNCTION__ encoding:NSUTF8StringEncoding]];
}

- (void)adWhirlReceivedNotificationAdsAreOff:(AdWhirlView *)adWhirlView {

    [MCMLog log:[NSString stringWithFormat:@"Malcom Ad - AdWhirl failed to show an ad because they are off. Ad: %@", [adWhirlView description]]
         inLine:__LINE__ fromMethod:[NSString stringWithCString:__PRETTY_FUNCTION__ encoding:NSUTF8StringEncoding]];

}

- (BOOL)adWhirlTestMode{
    return [[MCMCoreManager sharedInstance] developmentMode];
}

@end


text:
from __future__ import unicode_literals

MESSAGES = {
    "Also available in": "Disponible aussi en",
    "Archive": "Archives",
    "LANGUAGE": "Français",
    "More posts about": "Plus de billets sur",
    "Newer posts": "Billets récents",
    "Next post": "Billet suivant",
    "Older posts": "Anciens billets",
    "Original site": "Site d'origine",
    "Posted": "Publié",
    "Posts about %s": "Billets sur %s",
    "Posts for year %s": "Billets de l'année %s",
    "Posts for {month} {year}": "Billets de {month} {year}",
    "Previous post": "Billet précédent",
    "Read in English": "Lire en français",
    "Read more": "Lire la suite",
    "Source": "Source",
    "Tags": "Étiquettes",
    "old posts page %d": "anciens billets page %d",
}


text:
/*	$NetBSD: exec_subr.c,v 1.71 2014/03/29 09:31:11 maxv Exp $	*/

/*
 * Copyright (c) 1993, 1994, 1996 Christopher G. Demetriou
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *      This product includes software developed by Christopher G. Demetriou.
 * 4. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: exec_subr.c,v 1.71 2014/03/29 09:31:11 maxv Exp $");

#include "opt_pax.h"

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/proc.h>
#include <sys/kmem.h>
#include <sys/vnode.h>
#include <sys/filedesc.h>
#include <sys/exec.h>
#include <sys/mman.h>
#include <sys/resourcevar.h>
#include <sys/device.h>

#if defined(PAX_ASLR) || defined(PAX_MPROTECT)
#include <sys/pax.h>
#endif /* PAX_ASLR || PAX_MPROTECT */

#include <uvm/uvm_extern.h>

#define	VMCMD_EVCNT_DECL(name)					\
static struct evcnt vmcmd_ev_##name =				\
    EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "vmcmd", #name);	\
EVCNT_ATTACH_STATIC(vmcmd_ev_##name)

#define	VMCMD_EVCNT_INCR(name)					\
    vmcmd_ev_##name.ev_count++

VMCMD_EVCNT_DECL(calls);
VMCMD_EVCNT_DECL(extends);
VMCMD_EVCNT_DECL(kills);

#ifdef DEBUG_STACK
#define DPRINTF(a) uprintf a
#else
#define DPRINTF(a)
#endif

/*
 * new_vmcmd():
 *	create a new vmcmd structure and fill in its fields based
 *	on function call arguments.  make sure objects ref'd by
 *	the vmcmd are 'held'.
 */

void
new_vmcmd(struct exec_vmcmd_set *evsp,
    int (*proc)(struct lwp * l, struct exec_vmcmd *),
    vsize_t len, vaddr_t addr, struct vnode *vp, u_long offset,
    u_int prot, int flags)
{
	struct exec_vmcmd *vcp;

	VMCMD_EVCNT_INCR(calls);
	KASSERT(proc != vmcmd_map_pagedvn || (vp->v_iflag & VI_TEXT));
	KASSERT(vp == NULL || vp->v_usecount > 0);

	if (evsp->evs_used >= evsp->evs_cnt)
		vmcmdset_extend(evsp);
	vcp = &evsp->evs_cmds[evsp->evs_used++];
	vcp->ev_proc = proc;
	vcp->ev_len = len;
	vcp->ev_addr = addr;
	if ((vcp->ev_vp = vp) != NULL)
		vref(vp);
	vcp->ev_offset = offset;
	vcp->ev_prot = prot;
	vcp->ev_flags = flags;
}

void
vmcmdset_extend(struct exec_vmcmd_set *evsp)
{
	struct exec_vmcmd *nvcp;
	u_int ocnt;

#ifdef DIAGNOSTIC
	if (evsp->evs_used < evsp->evs_cnt)
		panic("vmcmdset_extend: not necessary");
#endif

	/* figure out number of entries in new set */
	if ((ocnt = evsp->evs_cnt) != 0) {
		evsp->evs_cnt += ocnt;
		VMCMD_EVCNT_INCR(extends);
	} else
		evsp->evs_cnt = EXEC_DEFAULT_VMCMD_SETSIZE;

	/* allocate it */
	nvcp = kmem_alloc(evsp->evs_cnt * sizeof(struct exec_vmcmd), KM_SLEEP);

	/* free the old struct, if there was one, and record the new one */
	if (ocnt) {
		memcpy(nvcp, evsp->evs_cmds,
		    (ocnt * sizeof(struct exec_vmcmd)));
		kmem_free(evsp->evs_cmds, ocnt * sizeof(struct exec_vmcmd));
	}
	evsp->evs_cmds = nvcp;
}

void
kill_vmcmds(struct exec_vmcmd_set *evsp)
{
	struct exec_vmcmd *vcp;
	u_int i;

	VMCMD_EVCNT_INCR(kills);

	if (evsp->evs_cnt == 0)
		return;

	for (i = 0; i < evsp->evs_used; i++) {
		vcp = &evsp->evs_cmds[i];
		if (vcp->ev_vp != NULL)
			vrele(vcp->ev_vp);
	}
	kmem_free(evsp->evs_cmds, evsp->evs_cnt * sizeof(struct exec_vmcmd));
	evsp->evs_used = evsp->evs_cnt = 0;
}

/*
 * vmcmd_map_pagedvn():
 *	handle vmcmd which specifies that a vnode should be mmap'd.
 *	appropriate for handling demand-paged text and data segments.
 */

int
vmcmd_map_pagedvn(struct lwp *l, struct exec_vmcmd *cmd)
{
	struct uvm_object *uobj;
	struct vnode *vp = cmd->ev_vp;
	struct proc *p = l->l_proc;
	int error;
	vm_prot_t prot, maxprot;

	KASSERT(vp->v_iflag & VI_TEXT);

	/*
	 * map the vnode in using uvm_map.
	 */

	if (cmd->ev_len == 0)
		return 0;
	if (cmd->ev_offset & PAGE_MASK)
		return EINVAL;
	if (cmd->ev_addr & PAGE_MASK)
		return EINVAL;
	if (cmd->ev_len & PAGE_MASK)
		return EINVAL;

	prot = cmd->ev_prot;
	maxprot = UVM_PROT_ALL;
#ifdef PAX_MPROTECT
	pax_mprotect(l, &prot, &maxprot);
#endif /* PAX_MPROTECT */

	/*
	 * check the file system's opinion about mmapping the file
	 */

	error = VOP_MMAP(vp, prot, l->l_cred);
	if (error)
		return error;

	if ((vp->v_vflag & VV_MAPPED) == 0) {
		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
		vp->v_vflag |= VV_MAPPED;
		VOP_UNLOCK(vp);
	}

	/*
	 * do the map, reference the object for this map entry
	 */
	uobj = &vp->v_uobj;
	vref(vp);

	error = uvm_map(&p->p_vmspace->vm_map, &cmd->ev_addr, cmd->ev_len,
		uobj, cmd->ev_offset, 0,
		UVM_MAPFLAG(prot, maxprot, UVM_INH_COPY,
			UVM_ADV_NORMAL, UVM_FLAG_COPYONW|UVM_FLAG_FIXED));
	if (error) {
		uobj->pgops->pgo_detach(uobj);
	}
	return error;
}

/*
 * vmcmd_map_readvn():
 *	handle vmcmd which specifies that a vnode should be read from.
 *	appropriate for non-demand-paged text/data segments, i.e. impure
 *	objects (a la OMAGIC and NMAGIC).
 */
int
vmcmd_map_readvn(struct lwp *l, struct exec_vmcmd *cmd)
{
	struct proc *p = l->l_proc;
	int error;
	long diff;

	if (cmd->ev_len == 0)
		return 0;

	diff = cmd->ev_addr - trunc_page(cmd->ev_addr);
	cmd->ev_addr -= diff;			/* required by uvm_map */
	cmd->ev_offset -= diff;
	cmd->ev_len += diff;

	error = uvm_map(&p->p_vmspace->vm_map, &cmd->ev_addr,
			round_page(cmd->ev_len), NULL, UVM_UNKNOWN_OFFSET, 0,
			UVM_MAPFLAG(UVM_PROT_ALL, UVM_PROT_ALL, UVM_INH_COPY,
			UVM_ADV_NORMAL,
			UVM_FLAG_FIXED|UVM_FLAG_OVERLAY|UVM_FLAG_COPYONW));

	if (error)
		return error;

	return vmcmd_readvn(l, cmd);
}

int
vmcmd_readvn(struct lwp *l, struct exec_vmcmd *cmd)
{
	struct proc *p = l->l_proc;
	int error;
	vm_prot_t prot, maxprot;

	error = vn_rdwr(UIO_READ, cmd->ev_vp, (void *)cmd->ev_addr,
	    cmd->ev_len, cmd->ev_offset, UIO_USERSPACE, IO_UNIT,
	    l->l_cred, NULL, l);
	if (error)
		return error;

	prot = cmd->ev_prot;
	maxprot = VM_PROT_ALL;
#ifdef PAX_MPROTECT
	pax_mprotect(l, &prot, &maxprot);
#endif /* PAX_MPROTECT */

#ifdef PMAP_NEED_PROCWR
	/*
	 * we had to write the process, make sure the pages are synched
	 * with the instruction cache.
	 */
	if (prot & VM_PROT_EXECUTE)
		pmap_procwr(p, cmd->ev_addr, cmd->ev_len);
#endif

	/*
	 * we had to map in the area at PROT_ALL so that vn_rdwr()
	 * could write to it.   however, the caller seems to want
	 * it mapped read-only, so now we are going to have to call
	 * uvm_map_protect() to fix up the protection.  ICK.
	 */
	if (maxprot != VM_PROT_ALL) {
		error = uvm_map_protect(&p->p_vmspace->vm_map,
				trunc_page(cmd->ev_addr),
				round_page(cmd->ev_addr + cmd->ev_len),
				maxprot, true);
		if (error)
			return error;
	}

	if (prot != maxprot) {
		error = uvm_map_protect(&p->p_vmspace->vm_map,
				trunc_page(cmd->ev_addr),
				round_page(cmd->ev_addr + cmd->ev_len),
				prot, false);
		if (error)
			return error;
	}

	return 0;
}

/*
 * vmcmd_map_zero():
 *	handle vmcmd which specifies a zero-filled address space region.  The
 *	address range must be first allocated, then protected appropriately.
 */

int
vmcmd_map_zero(struct lwp *l, struct exec_vmcmd *cmd)
{
	struct proc *p = l->l_proc;
	int error;
	long diff;
	vm_prot_t prot, maxprot;

	diff = cmd->ev_addr - trunc_page(cmd->ev_addr);
	cmd->ev_addr -= diff;			/* required by uvm_map */
	cmd->ev_len += diff;

	prot = cmd->ev_prot;
	maxprot = UVM_PROT_ALL;
#ifdef PAX_MPROTECT
	pax_mprotect(l, &prot, &maxprot);
#endif /* PAX_MPROTECT */

	error = uvm_map(&p->p_vmspace->vm_map, &cmd->ev_addr,
			round_page(cmd->ev_len), NULL, UVM_UNKNOWN_OFFSET, 0,
			UVM_MAPFLAG(prot, maxprot, UVM_INH_COPY,
			UVM_ADV_NORMAL,
			UVM_FLAG_FIXED|UVM_FLAG_COPYONW));
	if (cmd->ev_flags & VMCMD_STACK)
		curproc->p_vmspace->vm_issize += atop(round_page(cmd->ev_len));
	return error;
}

/*
 * exec_read_from():
 *
 *	Read from vnode into buffer at offset.
 */
int
exec_read_from(struct lwp *l, struct vnode *vp, u_long off, void *bf,
    size_t size)
{
	int error;
	size_t resid;

	if ((error = vn_rdwr(UIO_READ, vp, bf, size, off, UIO_SYSSPACE,
	    0, l->l_cred, &resid, NULL)) != 0)
		return error;
	/*
	 * See if we got all of it
	 */
	if (resid != 0)
		return ENOEXEC;
	return 0;
}

/*
 * exec_setup_stack(): Set up the stack segment for an elf
 * executable.
 *
 * Note that the ep_ssize parameter must be set to be the current stack
 * limit; this is adjusted in the body of execve() to yield the
 * appropriate stack segment usage once the argument length is
 * calculated.
 *
 * This function returns an int for uniformity with other (future) formats'
 * stack setup functions.  They might have errors to return.
 */

int
exec_setup_stack(struct lwp *l, struct exec_package *epp)
{
	vsize_t max_stack_size;
	vaddr_t access_linear_min;
	vsize_t access_size;
	vaddr_t noaccess_linear_min;
	vsize_t noaccess_size;

#ifndef	USRSTACK32
#define USRSTACK32	(0x00000000ffffffffL&~PGOFSET)
#endif
#ifndef MAXSSIZ32
#define MAXSSIZ32	(MAXSSIZ >> 2)
#endif

	if (epp->ep_flags & EXEC_32) {
		epp->ep_minsaddr = USRSTACK32;
		max_stack_size = MAXSSIZ32;
	} else {
		epp->ep_minsaddr = USRSTACK;
		max_stack_size = MAXSSIZ;
	}

	DPRINTF(("ep_minsaddr=%llx max_stack_size=%llx\n",
	    (unsigned long long)epp->ep_minsaddr,
	    (unsigned long long)max_stack_size));

	epp->ep_ssize = MIN(l->l_proc->p_rlimit[RLIMIT_STACK].rlim_cur,
	    max_stack_size);

#ifdef PAX_ASLR
	pax_aslr_stack(l, epp, &max_stack_size);
#endif /* PAX_ASLR */

	l->l_proc->p_stackbase = epp->ep_minsaddr;

	epp->ep_maxsaddr = (vaddr_t)STACK_GROW(epp->ep_minsaddr,
		max_stack_size);

	DPRINTF(("ep_ssize=%llx ep_maxsaddr=%llx\n",
	    (unsigned long long)epp->ep_ssize,
	    (unsigned long long)epp->ep_maxsaddr));

	/*
	 * set up commands for stack.  note that this takes *two*, one to
	 * map the part of the stack which we can access, and one to map
	 * the part which we can't.
	 *
	 * arguably, it could be made into one, but that would require the
	 * addition of another mapping proc, which is unnecessary
	 */
	access_size = epp->ep_ssize;
	access_linear_min = (vaddr_t)STACK_ALLOC(epp->ep_minsaddr, access_size);
	noaccess_size = max_stack_size - access_size;
	noaccess_linear_min = (vaddr_t)STACK_ALLOC(STACK_GROW(epp->ep_minsaddr,
	    access_size), noaccess_size);

	DPRINTF(("access_size=%llx, access_linear_min=%llx, "
	    "noaccess_size=%llx, noaccess_linear_min=%llx\n",
	    (unsigned long long)access_size,
	    (unsigned long long)access_linear_min,
	    (unsigned long long)noaccess_size,
	    (unsigned long long)noaccess_linear_min));

	if (noaccess_size > 0 && noaccess_size <= MAXSSIZ) {
		NEW_VMCMD2(&epp->ep_vmcmds, vmcmd_map_zero, noaccess_size,
		    noaccess_linear_min, NULL, 0, VM_PROT_NONE, VMCMD_STACK);
	}
	KASSERT(access_size > 0 && access_size <= MAXSSIZ);
	NEW_VMCMD2(&epp->ep_vmcmds, vmcmd_map_zero, access_size,
	    access_linear_min, NULL, 0, VM_PROT_READ | VM_PROT_WRITE,
	    VMCMD_STACK);

	return 0;
}


text:
package org.apache.spark.mllib.stat.distribution

import breeze.linalg.{Vector => BV, Matrix => BM}
import breeze.linalg._
import breeze.math._
import breeze.numerics._
import org.apache.spark.mllib.linalg.{Vector, Matrix}
//import org.apache.spark.mllib.stat.distribution.{MultivariateGaussian,Wishart}

/**
 * This class provides basic functionality for the mutlivariate Student's T distribution.
 * The MV Student's T distribution is a distribution over a real-valued vector
 *
 * @param mu The mean vector
 * @param W The precision matrix, DxD positive definite matrix
 * @param nu Degrees of freedom parameter, double
 */

class MultivariateStudentsT(
    mu: Vector,
    W: Matrix,
    nu: Double) extends Serializable {
  require(nu > 0, "Degrees of freedom must be positive")

  private val muBreeze = mu.toBreeze.toDenseVector
  private val WBreeze = W.toBreeze.toDenseMatrix

  val D = muBreeze.length

  private lazy val WBreezeInv = inv(WBreeze)

  private lazy val WLogDet = logdet(WBreeze)._2

  private def pdf(x: BV[Double]): Double = {
    math.exp(logpdf(x))
  }

  /** Returns the log-density  at given point, x */
  private def logpdf(x: BV[Double]): Double = {
    val normConstant = lgamma((nu + D) / 2.0) - lgamma(nu / 2.0)
    -D * 0.5 * math.log(math.Pi * nu)
    +0.5 * WLogDet
    val xDenseMinusMu = x.toDenseVector - muBreeze.toDenseVector
    normConstant - ((nu + D) / 2.0) * math.log(1.0 + (xDenseMinusMu.t * WBreeze * xDenseMinusMu) / nu)
  }

  def pdf(x: Vector): Double = {
    pdf(x.toBreeze)
  }

  def logpdf(x: Vector): Double = {
    logpdf(x.toBreeze)
  }
}


text:
#include <stdio.h>

/**
 * This is a simple test method to verify that the contents of a buffer created in JavaScript can be
 * passed into a C function.
 */
void bufferTest(const void* source, unsigned int sourceLen) {
    int i = 0;
    unsigned char* src = (unsigned char*)source;

    printf("in test method: size of source buffer = %d\n", sourceLen);

    for (i = 0; i < sourceLen; i++) {
        printf("source[%d] = %d\n", i, src[i]);
    }
}


text:
package org.ice4j.ice.harvest;

import org.ice4j.*;
import org.ice4j.ice.*;

import java.util.*;
import java.util.logging.*;

/**
 * Uses a list of addresses as a predefined static mask in order to generate
 * {@link TransportAddress}es. This harvester is meant for use in situations
 * where servers are deployed behind a NAT or in a DMZ with static port mapping.
 *

 * Every time the {@link #harvest(Component)} method is called, the mapping
 * harvester will return a list of candidates that provide masked alternatives
 * for every host candidate in the component. Kind of like a STUN server.
 *

 * Example: You run this on a server with address 192.168.0.1, that is behind
 * a NAT with public IP: 93.184.216.119. You allocate a host candidate
 * 192.168.0.1/UDP/5000. This harvester is going to then generate an address
 * 93.184.216.119/UDP/5000
 *

 * This harvester is instant and does not introduce any harvesting latency.
 *
 * @author Emil Ivov
 */
public class MappingCandidateHarvester
    extends AbstractCandidateHarvester
{
    /**
     * The <tt>Logger</tt> used by the <tt>StunCandidateHarvester</tt> class and
     * its instances for logging output.
     */
    private static final Logger logger
        = Logger.getLogger(StunCandidateHarvester.class.getName());

    /**
     * The addresses that we will use as a mask
     */
    protected TransportAddress mask;

    /**
     * The addresses that we will be masking
     */
    protected TransportAddress face;

    /**
     * Creates a mapping harvester with the specified <tt>mask</tt>
     *
     * @param mask the <tt>TransportAddress</tt>es that would be used as a mask.
     * @param face the <tt>TransportAddress</tt>es that we will be masking.
     */
    public MappingCandidateHarvester(TransportAddress mask,
                                     TransportAddress face)
    {
        this.mask = Objects.requireNonNull(mask);
        this.face = Objects.requireNonNull(face);
    }

    /**
     * Initializes a {@link MappingCandidateHarvester} instance without
     * specified addresses (only useful in subclasses which override
     * {@link #getMask()} and {@link #getFace()}).
     */
    protected MappingCandidateHarvester()
    {
    }

    /**
     * Maps all candidates to this harvester's mask and adds them to
     * <tt>component</tt>.
     *
     * @param component the {@link Component} that we'd like to map candidates
     * to.
     * @return  the <tt>LocalCandidate</tt>s gathered by this
     * <tt>CandidateHarvester</tt> or <tt>null</tt> if no mask is specified.
     */
    @Override
    public Collection<LocalCandidate> harvest(Component component)
    {
        TransportAddress mask = getMask();
        TransportAddress face = getFace();
        if (face == null || mask == null)
        {
            logger.warning("Harvester not configured: face=" + face
                           + ", mask=" + mask);
            return null;
        }

         // Report the LocalCandidates gathered by this CandidateHarvester so
         // that the harvest is sure to be considered successful.
        Collection<LocalCandidate> candidates = new HashSet<>();

        for (Candidate<?> cand : component.getLocalCandidates())
        {
            if (!(cand instanceof HostCandidate)
                || !cand.getTransportAddress().getHostAddress()
                            .equals(face.getHostAddress())
                || cand.getTransport() != face.getTransport())
            {
                continue;
            }

            HostCandidate hostCandidate = (HostCandidate) cand;
            TransportAddress mappedAddress = new TransportAddress(
                mask.getHostAddress(),
                hostCandidate.getHostAddress().getPort(),
                hostCandidate.getHostAddress().getTransport());

            ServerReflexiveCandidate mappedCandidate
                = new ServerReflexiveCandidate(
                    mappedAddress,
                    hostCandidate,
                    hostCandidate.getStunServerAddress(),
                    CandidateExtendedType.STATICALLY_MAPPED_CANDIDATE);
            if (hostCandidate.isSSL())
                mappedCandidate.setSSL(true);

            //try to add the candidate to the component and then
            //only add it to the harvest not redundant
            if( !candidates.contains(mappedCandidate)
                && component.addLocalCandidate(mappedCandidate))
            {
                candidates.add(mappedCandidate);
            }
        }

        return candidates;
    }

    /**
     * Returns the public (mask) address, or null.
     * @return the public (mask) address, or null.
     */
    public TransportAddress getMask()
    {
        return mask;
    }

    /**
     * Returns the local (face) address, or null.
     * @return the local (face) address, or null.
     */
    public TransportAddress getFace()
    {
        return face;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString()
    {
        TransportAddress face = getFace();
        TransportAddress mask = getMask();
        return
            this.getClass().getName()
                    + ", face=" + (face == null ? "null" : face.getAddress())
                    + ", mask=" + (mask == null ? "null" : mask.getAddress());
    }
}


text:
<?php

use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;

// This file has been auto-generated by the Symfony Dependency Injection Component for internal use.
// Returns the private 'form.type_extension.form.validator' shared service.

return $this->services['form.type_extension.form.validator'] = new \Symfony\Component\Form\Extension\Validator\Type\FormTypeValidatorExtension(${($_ = isset($this->services['validator']) ? $this->services['validator'] : $this->load(__DIR__.'/getValidatorService.php')) && false ?: '_'});


text:
WidgetRegistration GroupWidget::s_GroupWidgetRegistration("Group", &GroupWidget::CreateWidget, &GroupWidget::CreateWidgetXML);

//===========================================================================================================
///----------------------------------------------------------------------------------------------------------
///constructors

GroupWidget::GroupWidget(){
	//do nothing

}

GroupWidget::GroupWidget(const std::string& name) : BaseWidget(name){

}

GroupWidget::GroupWidget(const XMLNode& node) : BaseWidget(node){

}

GroupWidget::~GroupWidget(){
	//do nothing

	ClearAllChildren();

}

//-----------------------------------------------------------------------------------------------------------

void GroupWidget::ClearAllChildren() {
	for (Widgets::iterator it = m_children.begin(); it != m_children.end(); ) {
		BaseWidget* widget = (*it);
		if (widget) {
			delete widget;
			widget = NULL;
		}
		it = m_children.erase(it);
	}
}

//-----------------------------------------------------------------------------------------------------------

void GroupWidget::StartUp() {
	BaseWidget::StartUp();

	CreateAllChildren();

	DoResizeToFitChildren();
}

//-----------------------------------------------------------------------------------------------------------

void GroupWidget::DoResizeToFitChildren() {
	if (m_resizeToFitChildren) {
		Vector2 myResizedDimensions;

		AABB2 resizedGroupBounds = ResizeGroupToFitChildren();
		myResizedDimensions = resizedGroupBounds.CalcLengthOfSides();

		Vector2 myResizedOffset = resizedGroupBounds.CalcCenter();

		m_widgetDefaultProperties.Set("offset", myResizedOffset);

		m_widgetDefaultProperties.Set("dimensions", myResizedDimensions);

		//UpdateRenderComponent(0.0);
	}
}

//-----------------------------------------------------------------------------------------------------------

void GroupWidget::LoadBaseAttributesFromXML(const XMLNode& node) {

	BaseWidget::LoadBaseAttributesFromXML(node);

	XMLNode childrenNode = node.getChildNode("Children");

	LoadAllChildDefinitions(childrenNode);

}

//-----------------------------------------------------------------------------------------------------------

void GroupWidget::LoadAllChildDefinitions(const XMLNode& node) {

	int num = node.nChildNode("Child");
	for (int i = 0; i < num; i++) {
		XMLNode tempNode = node.getChildNode("Child", i);
		//get name and offset
		std::string childName = ReadXMLAttributeAsString(tempNode, "name");

		Vector2 childOffset = ReadXMLAttributeAsVec2(tempNode, "offset");

		std::string childAnchorStr = ReadXMLAttributeAsString(tempNode, "anchor");
		UIAnchorID childAnchor = GetUIAnchorForString(childAnchorStr);

		std::string childText = ReadXMLAttributeAsString(tempNode, "text");

		m_childDefs.push_back(ChildDefinition(childName, childOffset, childAnchor, childText));
	}

}

//-----------------------------------------------------------------------------------------------------------

void GroupWidget::CreateAllChildren() {

	for(ChildDefinition& childDef : m_childDefs){

		std::string childName = childDef.name;
		Vector2 childOffset = childDef.offset;
		UIAnchorID childAnchor = childDef.anchorID;
		std::string childText = childDef.text;

		//create a new one and stuff it in m_children
		BaseWidget* childWidget = theUISystem->CreateWidget(childName, childOffset);
		childWidget->SetParent(this);
		childWidget->SetAnchorID(childAnchor);
		//override text attrib
		if (childText != "") {
			WidgetStateProperties& childProp = childWidget->GetCurrentStateProperties();
			if (childProp.m_defaultProperties->HasProperty("text")) {
				childProp.m_defaultProperties->Set("text", childText);
			}
		}

		m_children.push_back(childWidget);
	}

}

//-----------------------------------------------------------------------------------------------------------

//upkeep
void GroupWidget::Update(double deltaSeconds) {

	BaseWidget::Update(deltaSeconds);

	for (BaseWidget* child : m_children) {
		if (child) {
			child->Update(deltaSeconds);
		}
	}

}

//render
void GroupWidget::Render(OpenGLRenderer* renderer) {

	BaseWidget::Render(renderer);

	if (m_isHidden)
		return;

	for (BaseWidget* child : m_children) {
		if(child)
		   child->Render(renderer);
	}

}

//===========================================================================================================


text:
<?php
namespace Mongator\Query;

class ChunkResult extends \ArrayObject
{
    private $total;

    public function setTotal($total)
    {
        $this->total = $total;
    }

    public function getData() { return $this->getArrayCopy(); }
    public function getTotal()
    {
        if ($this->total instanceOf \Closure) {
            $this->total = $this->total->__invoke();
        }

        return $this->total;
    }
}


text:
namespace PeinearyDevelopment.Framework.BaseClassLibraries.Apis.Clients
{
    using Contracts;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Serialization;
    using System;
    using System.Configuration;
    using System.IO;
    using System.Linq;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Threading.Tasks;

    public static class ApiInvoker
    {
        /// <summary>
        /// Used to invoke an api endpoint that will return the uniquely identifier resource of type T located at the route.
        /// </summary>
        /// <typeparam name="TContract">The type of the object to return from the api call.</typeparam>
        /// <typeparam name="TId">The type of the id property of T.</typeparam>
        /// <param name="endpointKey">Identifies the endpoint. Used by the endpoint resolver to determine the base path of the api to invoke.</param>
        /// <param name="route">The part of the Uri that is used by the api to determine where to route the request.</param>
        /// <param name="resourceIdentifier">The value that uniquely identifies the resource to be returned.</param>
        /// <returns>Object of type T deserialized from JSON object.</returns>
        public static async Task<TContract> Get<TContract, TId>(string endpointKey, string route, TId resourceIdentifier)
        {
            return await Get<TContract>(GenerateUri(endpointKey, route, resourceIdentifier.ToString()));
        }

        /// <summary>
        /// Used to invoke an api endpoint that will delete the uniquely identified resource located at the route.
        /// </summary>
        /// <typeparam name="TId">The type of the id property of the resource to delete.</typeparam>
        /// <param name="endpointKey">Identifies the endpoint. Used by the endpoint resolver to determine the base path of the api to invoke.</param>
        /// <param name="route">The part of the Uri that is used by the api to determine where to route the request.</param>
        /// <param name="resourceIdentifier">The value that uniquely identifies the resource to be deleted.</param>
        public static async Task Delete<TId>(string endpointKey, string route, TId resourceIdentifier)
        {
            await Delete(GenerateUri(endpointKey, route, resourceIdentifier.ToString()));
        }

        /// <summary>
        /// Used to invoke an api endpoint that will create a given resource.
        /// </summary>
        /// <typeparam name="TContract">The type of the resource to being created and returned.</typeparam>
        /// <param name="endpointKey">Identifies the endpoint. Used by the endpoint resolver to determine the base path of the api to invoke.</param>
        /// <param name="route">The part of the Uri that is used by the api to determine where to route the request.</param>
        /// <param name="postBodyContent">The resource to be created.</param>
        /// <returns>The created resource.</returns>
        public static async Task<TContract> Create<TContract>(string endpointKey, string route, TContract postBodyContent)
        {
            return await Post<TContract, TContract>(GenerateUri(endpointKey, route), postBodyContent);
        }

        /// <summary>
        /// Used to invoke an api endpoint that will update a given resource.
        /// </summary>
        /// <typeparam name="TContract">The type of the resource to being created and returned.</typeparam>
        /// <param name="endpointKey">Identifies the endpoint. Used by the endpoint resolver to determine the base path of the api to invoke.</param>
        /// <param name="route">The part of the Uri that is used by the api to determine where to route the request.</param>
        /// <param name="putBodyContent">The resource containing the updated values. Must contain a field that uniquely identifies the resource to be updated.</param>
        /// <returns>The updated resource.</returns>
        public static async Task<TContract> Update<TContract>(string endpointKey, string route, TContract putBodyContent)
        {
            return await Update(GenerateUri(endpointKey, route), putBodyContent);
        }

        private static Uri GenerateUri(string endpointKey, params string[] routeParts)
        {
            return new Uri(Path.Combine(new[] { ConfigurationManager.AppSettings[endpointKey] }.Concat(routeParts).ToArray()));
        }

        private static async Task<TResponse> Post<TBodyContent, TResponse>(Uri uri, TBodyContent postBodyContent)
        {
            var content = new StringContent(JsonConvert.SerializeObject(postBodyContent, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }));
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            using (var client = new HttpClient())
            {
                using (var response = await client.PostAsync(uri, content).ConfigureAwait(false))
                {
                    return await GetContentObject<TResponse>(response);
                }
            }
        }

        private static async Task<T> Get<T>(Uri uri)
        {
            using (var client = new HttpClient())
            {
                using (var response = await client.GetAsync(uri).ConfigureAwait(false))
                {
                    return await GetContentObject<T>(response);
                }
            }
        }

        private static async Task<T> Update<T>(Uri uri, T putBodyContent)
        {
            var content = new StringContent(JsonConvert.SerializeObject(putBodyContent, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }));
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            using (var client = new HttpClient())
            {
                using (var response = await client.PutAsync(uri, content).ConfigureAwait(false))
                {
                    return await GetContentObject<T>(response);
                }
            }
        }

        private static async Task Delete(Uri uri)
        {
            using (var client = new HttpClient())
            {
                using (var response = await client.DeleteAsync(uri).ConfigureAwait(false))
                {
                    if (!response.IsSuccessStatusCode) throw new ApiInvokerException(response);
                }
            }
        }

        private static async Task<T> GetContentObject<T>(HttpResponseMessage response)
        {
            var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            if (response.IsSuccessStatusCode)
            {
                return JsonConvert.DeserializeObject<T>(responseContent);
            }

            throw new ApiInvokerException(response);
        }
    }
}


text:
module SecureHeaders
  class ClearSiteDataConfigError < StandardError; end
  class ClearSiteData
    HEADER_NAME = "Clear-Site-Data".freeze

    # Valid `types`
    CACHE = "cache".freeze
    COOKIES = "cookies".freeze
    STORAGE = "storage".freeze
    EXECUTION_CONTEXTS = "executionContexts".freeze
    ALL_TYPES = [CACHE, COOKIES, STORAGE, EXECUTION_CONTEXTS]

    class << self
      # Public: make an Clear-Site-Data header name, value pair
      #
      # Returns nil if not configured, returns header name and value if configured.
      def make_header(config = nil, user_agent = nil)
        case config
        when nil, OPT_OUT, []
          # noop
        when Array
          [HEADER_NAME, make_header_value(config)]
        when true
          [HEADER_NAME, make_header_value(ALL_TYPES)]
        end
      end

      def validate_config!(config)
        case config
        when nil, OPT_OUT, true
          # valid
        when Array
          unless config.all? { |t| t.is_a?(String) }
            raise ClearSiteDataConfigError.new("types must be Strings")
          end
        else
          raise ClearSiteDataConfigError.new("config must be an Array of Strings or `true`")
        end
      end

      # Public: Transform a Clear-Site-Data config (an Array of Strings) into a
      # String that can be used as the value for the Clear-Site-Data header.
      #
      # types - An Array of String of types of data to clear.
      #
      # Returns a String of quoted values that are comma separated.
      def make_header_value(types)
        types.map { |t| %("#{t}") }.join(", ")
      end
    end
  end
end