text:
<?xml version="1.0" encoding="utf-8"?>
<!--

-->

<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false"
     android:zAdjustment="top">
  <alpha android:fromAlpha="1.0" android:toAlpha="0.0"
  		 android:startOffset="100"
         android:fillEnabled="true"
         android:fillBefore="true" android:fillAfter="true"
         android:interpolator="@android:interpolator/linear"
         android:duration="50"/>
</set>

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types=1);

namespace Valkyrja\Log;

use Throwable;
use Valkyrja\Support\Manager\Driver as Contract;

/**
 * Interface Driver.
 *
 * @author Melech Mizrachi
 */
interface Driver extends Contract
{
    /**
     * Log a debug message.
     *
     * @param string $message The message
     * @param array  $context [optional] The context
     *
     * @return void
     */
    public function debug(string $message, array $context = []): void;

    /**
     * Log an info message.
     *
     * @param string $message The message
     * @param array  $context [optional] The context
     *
     * @return void
     */
    public function info(string $message, array $context = []): void;

    /**
     * Log a notice message.
     *
     * @param string $message The message
     * @param array  $context [optional] The context
     *
     * @return void
     */
    public function notice(string $message, array $context = []): void;

    /**
     * Log a warning message.
     *
     * @param string $message The message
     * @param array  $context [optional] The context
     *
     * @return void
     */
    public function warning(string $message, array $context = []): void;

    /**
     * Log a error message.
     *
     * @param string $message The message
     * @param array  $context [optional] The context
     *
     * @return void
     */
    public function error(string $message, array $context = []): void;

    /**
     * Log a critical message.
     *
     * @param string $message The message
     * @param array  $context [optional] The context
     *
     * @return void
     */
    public function critical(string $message, array $context = []): void;

    /**
     * Log a alert message.
     *
     * @param string $message The message
     * @param array  $context [optional] The context
     *
     * @return void
     */
    public function alert(string $message, array $context = []): void;

    /**
     * Log a emergency message.
     *
     * @param string $message The message
     * @param array  $context [optional] The context
     *
     * @return void
     */
    public function emergency(string $message, array $context = []): void;

    /**
     * Log a message.
     *
     * @param string $level   The log level
     * @param string $message The message
     * @param array  $context [optional] The context
     *
     * @return void
     */
    public function log(string $level, string $message, array $context = []): void;

    /**
     * Log an exception or throwable.
     *
     * @param Throwable $exception The exception
     * @param string    $message   The message
     * @param array     $context   [optional] The context
     *
     * @return void
     */
    public function exception(Throwable $exception, string $message, array $context = []): void;
}


text:
Click on the green flag to see the expected output of your program.

{iframe link="https://scratch.mit.edu/projects/embed/152939066/?autostart=false"}

{panel type="help"}

# Recommended blocks for solution 1

```scratch
when green flag clicked
```

```scratch
go to x: (50) y: (0)

move (50) steps

turn cw (120) degrees

move (50) steps

turn ccw (60) degrees

turn cw (60) degrees

move (50) steps

```

```scratch
clear

set pen size to (3)

set pen color to (0)

pen down

change pen color by (50)

pen up
```

```scratch
repeat (6)
end

repeat (6)
end
```

{panel end}

{panel type="help"}

# Recommended blocks for solution 2

```scratch
when green flag clicked
```

```scratch
go to x: (50) y: (0)

point in direction (0 v)

move (50) steps

turn ccw (60) degrees

turn ccw ((360) / (3)) degrees

move (50) steps
```

```scratch
clear

set pen size to (3)

change pen color by (30)

pen up

pen down
```

```scratch
repeat (6)
end

repeat (3)
end
```

```scratch
define triangle

triangle :: custom
```

{panel end}

{panel type="help"}

# Recommended blocks for solution 3

```scratch
when green flag clicked
```

```scratch
go to x: (0) y: (0)

move (150) steps

turn cw (120) degrees

move (150) steps

turn ccw (120) degrees

point in direction (90 v)

go to x: (75) y: (-45)

turn ccw (120) degrees
```

```scratch
clear

set pen size to (3)

set pen color to (0)

pen down

pen up

change pen color by (50)

pen down

pen up
```

```scratch
repeat (3)
end

repeat (3)
end
```

{panel end}


text:
Content

About

Contact

Products

Follow Us

Facebook

Twitter

YouTube

Legal

Terms and Conditions

Privacy Policy

Disclaimer area lorem ipsum dolor sit amet, consectetur adipisicing elit. Rerum, nostrum repudiandae saepe.


text:
package com.openxc.openxcdiagnostic.diagnostic;

public interface DiagnosticManager {

    /**
     * Update the current state of the manager.
     *
     * @param displayCommands
     *            If true, the activity wants to switch to a command
     *            sending/receiving state. If false, the activity wants to
     *            switch to a request sending/receiving state.
     */
    public void setRequestCommandState(boolean displayCommands);

}


text:
package org.collin.dashboard.ds;

import java.util.logging.Logger;

import org.condast.commons.authentication.core.ILoginProvider;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;

@Component(
	name = AuthenticationComponent.COMPONENT_NAME
)
public class AuthenticationComponent{

	public static final String COMPONENT_NAME = "org.collin.dashboard.service.login";

	private AuthenticationDispatcher dispatcher = AuthenticationDispatcher.getInstance();

    private static final Logger logger = Logger.getLogger( AuthenticationComponent.class.getName());

	@Activate
	public void activate(){
		logger.info("Activating the " + COMPONENT_NAME);
	}

	@Deactivate
	public void deactivate(){
		logger.info("Deactivating the" + COMPONENT_NAME);
	}

	@Reference
	public void setFactory( ILoginProvider factory ){
		dispatcher.setFactory(factory);
	}

	public void unsetFactory( ILoginProvider factory ){
		dispatcher.unsetFactory(factory);
	}
}


text:
package com.conveyal.gtfs.loader;

import com.conveyal.gtfs.error.NewGTFSErrorType;
import com.conveyal.gtfs.storage.StorageException;
import org.junit.Test;

import static org.hamcrest.MatcherAssert.assertThat;

/**
 * Unit tests to verify functionality of classes that load fields from GTFS tables.
 */
public class FieldTests {

    /**
     * Make sure our date field reader catches bad dates and accepts correct ones.
     */
    @Test
    public void dateFieldParseTest() {

        String[] badDates = {
                "20170733", // 33rd day of the month
                "20171402", // 14th months of the year
                "12252016", // month day year format
                "14921212",  // Year very far in the past
                "2015/03/11", // Slashes separating fields
                "2011-07-16", // Dashes separating fields
                "23000527", // Very distant future year
                "790722" // Two digit year
        };

        for (String badDate : badDates) {
            try {
                new DateField("date", Requirement.REQUIRED).validateAndConvert(badDate);
                assertThat("Parsing bad dates should throw an exception and never reach this point.", false);
            } catch (StorageException ex) {
                assertThat("Error type should be date-related.",
                        ex.errorType == NewGTFSErrorType.DATE_FORMAT || ex.errorType == NewGTFSErrorType.DATE_RANGE);
                assertThat("Error's bad value should be the input value (the bad date).", ex.badValue.equals(badDate));
            }
        }

        String[] goodDates = { "20160522", "20180717", "20221212", "20190505" };

        for (String goodDate : goodDates) {
            String convertedValue = new DateField("date", Requirement.REQUIRED).validateAndConvert(goodDate);
            assertThat("Returned value matches the well-formed date.", convertedValue.equals(goodDate));
        }

    }
}


text:
package com.github.quiram.buildhotspots.clients;

import java.util.List;

public interface CiClient {
    List<String> getAllBuildConfigurations();

    List<String> getDependenciesFor(String jobName);
}


text:
<!DOCTYPE HTML>
<html i18n-values="dir:textdirection">
<head>
<link rel="stylesheet" href="chrome://resources/css/chrome_shared.css">
<link rel="stylesheet" href="chrome://resources/css/list.css">
<link rel="stylesheet" href="chrome://resources/css/widgets.css">

<link rel="stylesheet" href="../options2/options_page.css">
<link rel="stylesheet" href="../options2/chromeos/internet_detail.css">
<link rel="stylesheet" href="proxy_settings.css">
<script src="chrome://resources/js/cr.js"></script>
<script src="chrome://resources/js/event_tracker.js"></script>
<script src="chrome://resources/js/cr/event_target.js"></script>
<script src="chrome://resources/js/cr/ui.js"></script>
<script src="chrome://resources/js/cr/ui/touch_handler.js"></script>
<script src="chrome://resources/js/cr/ui/array_data_model.js"></script>
<script src="chrome://resources/js/cr/ui/list_selection_model.js"></script>
<script src="chrome://resources/js/cr/ui/list_selection_controller.js"></script>
<script src="chrome://resources/js/cr/ui/list_single_selection_model.js"></script>
<script src="chrome://resources/js/cr/ui/list_item.js"></script>
<script src="chrome://resources/js/cr/ui/list.js"></script>
<script src="chrome://resources/js/local_strings.js"></script>
<script src="chrome://resources/js/util.js"></script>

<script src="../options2/preferences.js"></script>
<script src="../options2/pref_ui.js"></script>
<script src="../options2/options_page.js"></script>
<script src="../options2/chromeos/internet_detail.js"></script>
<script src="../options2/chromeos/proxy_rules_list.js"></script>

<script src="proxy_settings.js"></script>
</head>

<body i18n-values=".style.fontFamily:fontfamily;.style.fontSize:fontsize">
<include src="../options2/chromeos/internet_detail.html">
</body>
</html>


text:
<!DOCTYPE html>
<html>
<!--
Copyright 2011 The Closure Library Authors. All Rights Reserved.

Use of this source code is governed by the Apache License, Version 2.0.
See the COPYING file for details.
-->
<!--
-->
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Closure Unit Tests - goog.style.transition</title>
<script src="../base.js"></script>
<script>
  goog.require('goog.style.transition');
  goog.require('goog.testing.jsunit');
  goog.require('goog.userAgent');
</script>
</head>
<body>
<script>

/** Fake element. */
var element;

function setUp() {
  element = {'style': {}};
}

function testSetWithNoProperty() {
  try {
    goog.style.transition.set(element, []);
  } catch (e) {
    return;
  }
  fail('Should fail when no property is given.');
}

function testSetWithString() {
  goog.style.transition.set(element, 'opacity 1s ease-in 0.125s');
  assertEquals('opacity 1s ease-in 0.125s', element.style.WebkitTransition);
  assertEquals('opacity 1s ease-in 0.125s', element.style.MozTransition);
  assertEquals('opacity 1s ease-in 0.125s', element.style.OTransition);
}

function testSetWithSingleProperty() {
  goog.style.transition.set(element,
      {property: 'opacity', duration: 1, timing: 'ease-in', delay: 0.125});
  assertEquals('opacity 1s ease-in 0.125s', element.style.WebkitTransition);
  assertEquals('opacity 1s ease-in 0.125s', element.style.MozTransition);
  assertEquals('opacity 1s ease-in 0.125s', element.style.OTransition);
}

function testSetWithMultipleStrings() {
  goog.style.transition.set(element, [
    'width 1s ease-in',
    'height 0.5s linear 1s'
  ]);
  assertEquals('width 1s ease-in,height 0.5s linear 1s',
      element.style.WebkitTransition);
  assertEquals('width 1s ease-in,height 0.5s linear 1s',
      element.style.MozTransition);
  assertEquals('width 1s ease-in,height 0.5s linear 1s',
      element.style.OTransition);
}

function testSetWithMultipleProperty() {
  goog.style.transition.set(element, [
    {property: 'width', duration: 1, timing: 'ease-in', delay: 0},
    {property: 'height', duration: 0.5, timing: 'linear', delay: 1}
  ]);
  assertEquals('width 1s ease-in 0s,height 0.5s linear 1s',
      element.style.WebkitTransition);
  assertEquals('width 1s ease-in 0s,height 0.5s linear 1s',
      element.style.MozTransition);
  assertEquals('width 1s ease-in 0s,height 0.5s linear 1s',
      element.style.OTransition);
}

function testRemoveAllForWebkit() {
  element.style.WebkitTransition = 'opacity 1s ease-in';
  goog.style.transition.removeAll(element);
  assertEquals('', element.style.WebkitTransition);
}

function testRemoveAllForGecko() {
  element.style.MozTransition = 'opacity 1s ease-in';
  goog.style.transition.removeAll(element);
  assertEquals('', element.style.MozTransition);
}

function testRemoveAllForIE() {
  element.style.MSTransition = 'opacity 1s ease-in';
  goog.style.transition.removeAll(element);
  assertEquals('', element.style.MSTransition);
}

function testRemoveAllForOpera() {
  element.style.OTransition = 'opacity 1s ease-in';
  goog.style.transition.removeAll(element);
  assertEquals('', element.style.OTransition);
}

function testRemoveAllForUnprefixed() {
  element.style.transition = 'opacity 1s ease-in';
  goog.style.transition.removeAll(element);
  assertEquals('', element.style.transition);
}

function testSanityDetectionOfCss3Transition() {
  var support = goog.style.transition.isSupported();

  // IE support starts at IE10.
  if (goog.userAgent.IE) {
    assertEquals(goog.userAgent.isVersion('10.0'), support);
  }

  // FF support start at FF4 (Gecko 2.0)
  if (goog.userAgent.GECKO) {
    assertEquals(goog.userAgent.isVersion('2.0'), support);
  }

  // Webkit support has existed for a long time, we assume support on
  // most webkit version in used today.
  if (goog.userAgent.WEBKIT) {
    assertTrue(support);
  }
}

</script>

</body>
</html>


text:
package com.streamsets.datacollector.runner.preview;

import com.streamsets.pipeline.api.Batch;
import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.api.base.BaseTarget;

public class PreviewPlugTarget extends BaseTarget {

  @Override
  public void write(Batch batch) throws StageException {
  }

}


text:
namespace Bakery.Composition.Microsoft
{
	using global::Microsoft.Extensions.DependencyInjection;

	public interface IModule
	{
		void Compose(IServiceCollection serviceCollection);
	}
}


text:
typedef struct Quadrilateral {
    CGPoint upperLeft;
    CGPoint upperRight;
    CGPoint lowerRight;
    CGPoint lowerLeft;
} Quadrilateral;

@interface OpenCVWrapper: NSObject
+ (CATransform3D)findHomographyFromQuadrilateral:(Quadrilateral)origin
                                 toQuadrilateral:(Quadrilateral)destination;
+ (CATransform3D)perspectiveTransform:(Quadrilateral)origin
                      toQuadrilateral:(Quadrilateral)destination;
@end


text:
#ifndef SecurityOrigin_h
#define SecurityOrigin_h

#include "weborigin/WebOriginExport.h"
#include "wtf/ThreadSafeRefCounted.h"
#include "wtf/text/WTFString.h"

namespace WebCore {

class KURL;
class SecurityOriginCache;

class WEBORIGIN_EXPORT SecurityOrigin : public ThreadSafeRefCounted<SecurityOrigin> {
public:
    enum Policy {
        AlwaysDeny = 0,
        AlwaysAllow,
        Ask
    };

    static PassRefPtr<SecurityOrigin> create(const KURL&);
    static PassRefPtr<SecurityOrigin> createUnique();

    static PassRefPtr<SecurityOrigin> createFromString(const String&);
    static PassRefPtr<SecurityOrigin> create(const String& protocol, const String& host, int port);

    static void setCache(SecurityOriginCache*);

    // Some URL schemes use nested URLs for their security context. For example,
    // filesystem URLs look like the following:
    //
    //   filesystem:http://example.com/temporary/path/to/file.png
    //
    // We're supposed to use "http://example.com" as the origin.
    //
    // Generally, we add URL schemes to this list when WebKit support them. For
    // example, we don't include the "jar" scheme, even though Firefox
    // understands that "jar" uses an inner URL for it's security origin.
    static bool shouldUseInnerURL(const KURL&);
    static KURL extractInnerURL(const KURL&);

    // Create a deep copy of this SecurityOrigin. This method is useful
    // when marshalling a SecurityOrigin to another thread.
    PassRefPtr<SecurityOrigin> isolatedCopy() const;

    // Set the domain property of this security origin to newDomain. This
    // function does not check whether newDomain is a suffix of the current
    // domain. The caller is responsible for validating newDomain.
    void setDomainFromDOM(const String& newDomain);
    bool domainWasSetInDOM() const { return m_domainWasSetInDOM; }

    String protocol() const { return m_protocol; }
    String host() const { return m_host; }
    String domain() const { return m_domain; }
    unsigned short port() const { return m_port; }

    // Returns true if a given URL is secure, based either directly on its
    // own protocol, or, when relevant, on the protocol of its "inner URL"
    // Protocols like blob: and filesystem: fall into this latter category.
    static bool isSecure(const KURL&);

    // Returns true if this SecurityOrigin can script objects in the given
    // SecurityOrigin. For example, call this function before allowing
    // script from one security origin to read or write objects from
    // another SecurityOrigin.
    bool canAccess(const SecurityOrigin*) const;

    // Returns true if this SecurityOrigin can read content retrieved from
    // the given URL. For example, call this function before issuing
    // XMLHttpRequests.
    bool canRequest(const KURL&) const;

    // Returns true if drawing an image from this URL taints a canvas from
    // this security origin. For example, call this function before
    // drawing an image onto an HTML canvas element with the drawImage API.
    bool taintsCanvas(const KURL&) const;

    // Returns true if this SecurityOrigin can receive drag content from the
    // initiator. For example, call this function before allowing content to be
    // dropped onto a target.
    bool canReceiveDragData(const SecurityOrigin* dragInitiator) const;

    // Returns true if |document| can display content from the given URL (e.g.,
    // in an iframe or as an image). For example, web sites generally cannot
    // display content from the user's files system.
    bool canDisplay(const KURL&) const;

    // Returns true if this SecurityOrigin can load local resources, such
    // as images, iframes, and style sheets, and can link to local URLs.
    // For example, call this function before creating an iframe to a
    // file:// URL.
    //
    // Note: A SecurityOrigin might be allowed to load local resources
    //       without being able to issue an XMLHttpRequest for a local URL.
    //       To determine whether the SecurityOrigin can issue an
    //       XMLHttpRequest for a URL, call canRequest(url).
    bool canLoadLocalResources() const { return m_canLoadLocalResources; }

    // Explicitly grant the ability to load local resources to this
    // SecurityOrigin.
    //
    // Note: This method exists only to support backwards compatibility
    //       with older versions of WebKit.
    void grantLoadLocalResources();

    // Explicitly grant the ability to access very other SecurityOrigin.
    //
    // WARNING: This is an extremely powerful ability. Use with caution!
    void grantUniversalAccess();

    bool canAccessDatabase() const { return !isUnique(); };
    bool canAccessLocalStorage() const { return !isUnique(); };
    bool canAccessSharedWorkers() const { return !isUnique(); }
    bool canAccessCookies() const { return !isUnique(); }
    bool canAccessPasswordManager() const { return !isUnique(); }
    bool canAccessFileSystem() const { return !isUnique(); }
    Policy canShowNotifications() const;

    // Technically, we should always allow access to sessionStorage, but we
    // currently don't handle creating a sessionStorage area for unique
    // origins.
    bool canAccessSessionStorage() const { return !isUnique(); }

    // The local SecurityOrigin is the most privileged SecurityOrigin.
    // The local SecurityOrigin can script any document, navigate to local
    // resources, and can set arbitrary headers on XMLHttpRequests.
    bool isLocal() const;

    // The origin is a globally unique identifier assigned when the Document is
    // created. http://www.whatwg.org/specs/web-apps/current-work/#sandboxOrigin
    //
    // There's a subtle difference between a unique origin and an origin that
    // has the SandboxOrigin flag set. The latter implies the former, and, in
    // addition, the SandboxOrigin flag is inherited by iframes.
    bool isUnique() const { return m_isUnique; }

    // Marks a file:// origin as being in a domain defined by its path.
    // FIXME 81578: The naming of this is confusing. Files with restricted access to other local files
    // still can have other privileges that can be remembered, thereby not making them unique.
    void enforceFilePathSeparation();

    // Convert this SecurityOrigin into a string. The string
    // representation of a SecurityOrigin is similar to a URL, except it
    // lacks a path component. The string representation does not encode
    // the value of the SecurityOrigin's domain property.
    //
    // When using the string value, it's important to remember that it might be
    // "null". This happens when this SecurityOrigin is unique. For example,
    // this SecurityOrigin might have come from a sandboxed iframe, the
    // SecurityOrigin might be empty, or we might have explicitly decided that
    // we shouldTreatURLSchemeAsNoAccess.
    String toString() const;

    // Similar to toString(), but does not take into account any factors that
    // could make the string return "null".
    String toRawString() const;

    // This method checks for equality between SecurityOrigins, not whether
    // one origin can access another. It is used for hash table keys.
    // For access checks, use canAccess().
    // FIXME: If this method is really only useful for hash table keys, it
    // should be refactored into SecurityOriginHash.
    bool equal(const SecurityOrigin*) const;

    // This method checks for equality, ignoring the value of document.domain
    // (and whether it was set) but considering the host. It is used for postMessage.
    bool isSameSchemeHostPort(const SecurityOrigin*) const;

    bool needsDatabaseIdentifierQuirkForFiles() const { return m_needsDatabaseIdentifierQuirkForFiles; }

    static const String& urlWithUniqueSecurityOrigin();

private:
    SecurityOrigin();
    explicit SecurityOrigin(const KURL&);
    explicit SecurityOrigin(const SecurityOrigin*);

    // FIXME: Rename this function to something more semantic.
    bool passesFileCheck(const SecurityOrigin*) const;

    String m_protocol;
    String m_host;
    String m_domain;
    String m_filePath;
    unsigned short m_port;
    bool m_isUnique;
    bool m_universalAccess;
    bool m_domainWasSetInDOM;
    bool m_canLoadLocalResources;
    bool m_enforceFilePathSeparation;
    bool m_needsDatabaseIdentifierQuirkForFiles;
};

} // namespace WebCore

#endif // SecurityOrigin_h


text:
require "resolv"
require_relative "../util/choria"
require_relative "../util/natswrapper"

module MCollective
  module Connector
    class Nats < Base
      attr_reader :connection

      def initialize # rubocop:disable Lint/MissingSuper
        @config = Config.instance
        @subscriptions = []
        @connection = Util::NatsWrapper.new

        Log.info("Choria NATS.io connector using pure ruby nats/io/client %s with protocol version %s" % [NATS::IO::VERSION, NATS::IO::PROTOCOL])
      end

      # Determines if the NATS connection is active
      #
      # @return [Boolean]
      def connected?
        connection.connected?
      end

      # Current connected server
      #
      # @return [String,nil]
      def connected_server
        connection.connected_server
      end

      # Retrieves the NATS connection stats
      #
      # @return [Hash]
      def stats
        connection.stats
      end

      # Client library version
      #
      # @return [String]
      def client_version
        connection.client_version
      end

      # Client library flavour
      #
      # @return [String]
      def client_flavour
        connection.client_flavour
      end

      # Connection options from the NATS gem
      #
      # @return [Hash]
      def active_options
        connection.active_options
      end

      # Attempts to connect to the middleware, noop when already connected
      #
      # @return [void]
      # @raise [StandardError] when SSL files are not readable
      def connect
        if connection && connection.started?
          Log.debug("Already connection, not re-initializing connection")
          return
        end

        parameters = {
          :max_reconnect_attempts => -1,
          :reconnect_time_wait => 1,
          :dont_randomize_servers => !choria.randomize_middleware_servers?,
          :name => @config.identity
        }

        parameters[:user_credentials] = choria.credential_file if choria.credential_file?

        if $choria_unsafe_disable_nats_tls # rubocop:disable Style/GlobalVars
          Log.warn("Disabling TLS in NATS connector, this is not a production supported setup")
        elsif choria.ngs?
          configure_ngs(parameters)
        else
          configure_tls(parameters)
        end

        servers = server_list

        unless servers.empty?
          Log.debug("Connecting to servers: %s" % servers.join(", "))
          parameters[:servers] = servers
        end

        connection.start(parameters)

        nil
      end

      def configure_tls(parameters)
        parameters[:tls] = {:context => choria.ssl_context}
        choria.check_ssl_setup
      end

      def configure_ngs(parameters)
        Log.debug("Disabling specific TLS during connection to NGS")

        raise("nkeys rubygem is required for connections with credentials") unless choria.nkeys?

        tls = OpenSSL::SSL::SSLContext.new
        tls.ssl_version = :TLSv1_2 # rubocop:disable Naming/VariableNumber

        parameters[:tls] = {:context => tls}
      end

      # Disconnects from NATS
      def disconnect
        connection.stop
      end

      # Creates the middleware headers needed for a given message
      #
      # @param msg [Message]
      # @return [Hash]
      def headers_for(msg)
        # mc_sender is only passed bacause M::Message incorrectly assumed this is some required
        # part of messages when its just some internals of the stomp based connectors that bled out
        headers = {
          "mc_sender" => @config.identity
        }

        headers["seen-by"] = [] if msg.headers.include?("seen-by")

        if [:request, :direct_request].include?(msg.type)
          if msg.reply_to
            headers["reply-to"] = msg.reply_to
          else
            # if its a request/direct_request style message and its not
            # one we're replying to - ie. its a new message we're making
            # we'll need to set a reply-to target that the daemon will
            # subscribe to
            headers["reply-to"] = make_target(msg.agent, :reply, msg.collective)
          end

          headers["seen-by"] << [@config.identity, connected_server.to_s] if msg.headers.include?("seen-by")
        elsif msg.type == :reply
          if msg.request.headers.include?("seen-by")
            headers["seen-by"] = msg.request.headers["seen-by"]
            headers["seen-by"].last << connected_server.to_s
          end
        end

        headers
      end

      # Create a target structure for a message
      #
      # @example data
      #
      #     {
      #       :name => "nats.name",
      #       :headers => { headers... }
      #     }
      #
      # @param msg [Message]
      # @param identity [String,nil] override identity
      # @return [Hash]
      def target_for(msg, identity=nil)
        target = nil

        if msg.type == :reply
          raise("Do not know how to reply, no reply-to header has been set on message %s" % msg.requestid) unless msg.request.headers["reply-to"]

          target = {:name => msg.request.headers["reply-to"], :headers => {}}

        elsif [:request, :direct_request].include?(msg.type)
          target = {:name => make_target(msg.agent, msg.type, msg.collective, identity), :headers => {}}

        else
          raise("Don't now how to create a target for message type %s" % msg.type)

        end

        target[:headers].merge!(headers_for(msg))

        target
      end

      # Retrieves the current process pid
      #
      # @note mainly used for testing
      # @return [Fixnum]
      def current_pid
        $$
      end

      # Creates a target structure
      #
      # @param agent [String] agent name
      # @param type [:directed, :broadcast, :reply, :request, :direct_request]
      # @param collective [String] target collective name
      # @param identity [String,nil] identity for the request, else node configured identity
      # @return [String] target name
      # @raise [StandardError] on invalid input
      def make_target(agent, type, collective, identity=nil)
        raise("Unknown target type %s" % type) unless [:directed, :broadcast, :reply, :request, :direct_request].include?(type)

        raise("Unknown collective '%s' known collectives are '%s'" % [collective, @config.collectives.join(", ")]) unless @config.collectives.include?(collective)

        identity ||= @config.identity

        case type
        when :reply
          "%s.reply.%s.%d.%d" % [collective, Digest::MD5.hexdigest(choria.callerid), current_pid, Client.request_sequence]

        when :broadcast, :request
          "%s.broadcast.agent.%s" % [collective, agent]

        when :direct_request, :directed
          "%s.node.%s" % [collective, identity]
        end
      end

      # Publishes a message to the middleware
      #
      # @param msg [Message]
      def publish(msg)
        msg.base64_encode!

        if choria.federated?
          msg.type == :direct_request ? publish_federated_directed(msg) : publish_federated_broadcast(msg)
        else
          msg.type == :direct_request ? publish_connected_directed(msg) : publish_connected_broadcast(msg)
        end
      end

      # Publish a directed request via a Federation Broker
      #
      # @param msg [Message]
      def publish_federated_directed(msg)
        messages = []
        target = target_for(msg, msg.discovered_hosts[0])

        msg.discovered_hosts.in_groups_of(200) do |nodes|
          node_targets = nodes.compact.map do |node|
            target_for(msg, node)[:name]
          end

          data = {
            "protocol" => "choria:transport:1",
            "data" => msg.payload,
            "headers" => {
              "federation" => {
                "target" => node_targets,
                "req" => msg.requestid
              }
            }.merge(target[:headers])
          }

          messages << JSON.dump(data)
        end

        choria.federation_collectives.each do |network|
          messages.each do |data|
            network_target = "choria.federation.%s.federation" % network

            Log.debug("Sending a federated direct message via NATS target '%s' for message type %s" % [network_target, msg.type])

            connection.publish(network_target, data, target[:headers]["reply-to"])
          end
        end
      end

      # Publish a directed request to a connected collective
      #
      # @param msg [Message]
      def publish_connected_directed(msg)
        msg.discovered_hosts.each do |node|
          target = target_for(msg, node)
          data = {
            "protocol" => "choria:transport:1",
            "data" => msg.payload,
            "headers" => target[:headers]
          }

          Log.debug("Sending a direct message to %s via NATS target '%s' for message type %s" % [node, target.inspect, msg.type])

          connection.publish(target[:name], data.to_json, target[:headers]["reply-to"])
        end
      end

      # Publish a broadcast message to via a Federation Broker
      #
      # @param msg [Message]
      def publish_federated_broadcast(msg)
        target = target_for(msg)
        data = {
          "protocol" => "choria:transport:1",
          "data" => msg.payload,
          "headers" => {
            "federation" => {
              "target" => [target[:name]],
              "req" => msg.requestid
            }
          }.merge(target[:headers])
        }

        data = JSON.dump(data)

        choria.federation_collectives.each do |network|
          target[:name] = "choria.federation.%s.federation" % network

          Log.debug("Sending a federated broadcast message to NATS target '%s' for message type %s" % [target.inspect, msg.type])

          connection.publish(target[:name], data, target[:headers]["reply-to"])
        end
      end

      # Publish a broadcast message to a connected collective
      #
      # @param msg [Message]
      def publish_connected_broadcast(msg)
        target = target_for(msg)
        data = {
          "protocol" => "choria:transport:1",
          "data" => msg.payload,
          "headers" => target[:headers]
        }

        # only happens when replying
        received_message = msg.request
        data["headers"]["federation"] = received_message.headers["federation"] if received_message && received_message.headers.include?("federation")

        Log.debug("Sending a broadcast message to NATS target '%s' for message type %s" % [target.inspect, msg.type])

        connection.publish(target[:name], JSON.dump(data), target[:headers]["reply-to"])
      end

      # Unsubscribe from the target for a agent
      #
      # @see make_target
      # @param agent [String] agent name
      # @param type [:reply, :broadcast, :request, :direct_request, :directed] type of message you want a subscription for
      # @param collective [String] the collective to subscribe for
      # @return [void]
      def unsubscribe(agent, type, collective)
        target = make_target(agent, type, collective)
        Log.debug("Unsubscribing from %s" % target)

        connection.unsubscribe(target)
      end

      # Subscribes to the topics/queues needed for a particular agent
      #
      # @see make_target
      # @param agent [String] agent name
      # @param type [:reply, :broadcast, :request, :direct_request, :directed] type of message you want a subscription for
      # @param collective [String] the collective to subscribe for
      # @return [void]
      def subscribe(agent, type, collective)
        target = make_target(agent, type, collective)

        connection.subscribe(target)
      end

      # Receives a message from the middleware
      #
      # @note blocks until one is received
      # @return [Message]
      def receive
        msg = nil

        until msg
          received = connection.receive

          Thread.pass

          begin
            msg = JSON.parse(received)
          rescue
            Log.warn("Got non JSON data from the broker: %s" % [received])
            msg = nil
          end
        end

        msg["headers"]["seen-by"] << [connected_server.to_s, @config.identity] if msg["headers"].include?("seen-by")

        Message.new(msg["data"], msg, :base64 => true, :headers => msg["headers"])
      end

      # Retrieves the list of server and port combos to attempt to connect to
      #
      # Configured servers are checked, then SRV records and finally a fall
      # back to puppet:4222 is done
      #
      # @return [Array<String>] list of servers in form of a URI
      def server_list
        uris = choria.middleware_servers("puppet", "4222").map do |host, port|
          URI("nats://%s:%s" % [host, port])
        end

        decorate_servers_with_users(uris).map(&:to_s)
      end

      # Add user and pass to a series of URIs
      #
      # @param servers [Array<URI>] list of URI's to decorate
      # @return [Array<URI>]
      def decorate_servers_with_users(servers)
        user = get_option("nats.user", environment["MCOLLECTIVE_NATS_USERNAME"])
        pass = get_option("nats.pass", environment["MCOLLECTIVE_NATS_PASSWORD"])

        if choria.anon_tls?
          user = PluginManager["security_plugin"].request_signer.token
          pass = nil
        end

        if user || pass
          servers.each do |uri|
            uri.user = user
            uri.password = pass
          end
        end

        servers
      end

      # Retrieves the environment, mainly used for testing
      def environment
        ENV
      end

      # Gets a config option
      #
      # @param opt [String] config option to look up
      # @param default [Object] default to return when not found
      # @return [Object] the found data or default
      # @raise [StandardError] when no default is given and option is not found
      def get_option(opt, default=:_unset)
        return @config.pluginconf[opt] if @config.pluginconf.include?(opt)
        return default unless default == :_unset

        raise("No plugin.%s configuration option given" % opt)
      end

      def choria
        @_choria ||= Util::Choria.new(false)
      end
    end
  end
end


text:
typedef NS_ENUM(NSInteger,RequestMethod){
    GET,
    POST,
    DOWNLOAD,
    UPLOAD
};
static NSString         *base_url = nil;
static NSTimeInterval   time_out = 60.0f;
static NSDictionary     *common_params = nil;

@implementation NetworkTool

+ (void)setBaseUrl:(NSString *)url {
    base_url = url;
}

+ (void)setTimeout:(NSTimeInterval)timeout {
    time_out = timeout;
}

+ (void)setCommonParams:(NSDictionary *)params {
    common_params = params;
}

+ (NSString *)print:(NSString *)url params:(NSDictionary *)params
{
    NSMutableString *absURL = [NSMutableString string];
    [absURL appendString:url];
    __block BOOL first = YES;
    [params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        NSString *keyvalue;
        if (first == YES)
        {
            keyvalue = [NSString stringWithFormat:@"?%@=%@",key,obj];
            first = NO;
        }
        else
        {
            keyvalue = [NSString stringWithFormat:@"&%@=%@",key,obj];
        }

        [absURL appendString:keyvalue];
    }];
    return absURL;
}

+ (NSURLSessionTask *)GET:(NSString *)url Params:(NSDictionary *)params Success:(RequestSuccess)success Failure:(RequestFailure)failure {
    return [self RequestWithUrl:url RequestMethod:GET Params:params FileArray:nil Success:(RequestSuccess)success Failure:(RequestFailure)failure];
}

+ (NSURLSessionTask *)POST:(NSString *)url Params:(NSDictionary *)params Success:(RequestSuccess)success Failure:(RequestFailure)failure {
    return [self RequestWithUrl:url RequestMethod:POST Params:params FileArray:nil Success:success Failure:failure];
}

+ (NSURLSessionTask *)UPLOADSINGLEFILE:(NSString *)url Params:(NSDictionary *)params FileData:(NSData *)filedata Name:(NSString *)name FileName:(NSString *)filename MimeType:(NSString *)mimeType Success:(RequestSuccess)success Failure:(RequestFailure)failure {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"data"] = filedata;
    dict[@"name"] = name;
    dict[@"filename"] = filename;
    dict[@"mimeType"] = mimeType;
    return [self RequestWithUrl:url RequestMethod:UPLOAD Params:params FileArray:@[dict] Success:success Failure:failure];
}

+ (NSURLSessionTask *)UPLOADMULTIFILE:(NSString *)url Params:(NSDictionary *)params FileArray:(NSArray *)fileArray Success:(RequestSuccess)success Failure:(RequestFailure)failure {
    return [self RequestWithUrl:url RequestMethod:UPLOAD Params:params FileArray:fileArray Success:success Failure:failure];
}

+ (NSURLSessionTask *)RequestWithUrl:(NSString *)url RequestMethod:(RequestMethod)method Params:(NSDictionary *)params FileArray:(NSArray *)fileArray Success:(RequestSuccess)success Failure:(RequestFailure)failure{

    AFHTTPSessionManager *manager = nil;
    if (base_url != nil) {
        manager = [[AFHTTPSessionManager alloc]initWithBaseURL:[NSURL URLWithString:base_url]];
    }else {
        manager = [AFHTTPSessionManager manager];
    }
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = time_out;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[@"application/json",@"text/html",@"text/json",@"text/plain",@"text/javascript",@"text/xml",@"image/*"]];
    manager.operationQueue.maxConcurrentOperationCount = 6;

    NSMutableDictionary *requestParams = [NSMutableDictionary dictionary];
    if (common_params != nil) {
        [requestParams addEntriesFromDictionary:common_params];
    }
    if (params != nil) {
        [requestParams addEntriesFromDictionary:params];
    }

    NSURLSessionTask *session = nil;
    NSString *requestUrl = [NSString stringWithFormat:@"%@",manager.baseURL];
    requestUrl = [requestUrl stringByAppendingString:url];

    NSLog(@"%@ = %@",url,[self print:requestUrl params:requestParams]);

    if (method == GET) {

        session = [manager GET:url parameters:requestParams progress:^(NSProgress * _Nonnull downloadProgress) {

        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            success(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            failure([error code],error);
        }];
    }else if (method == POST) {
        session = [manager POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {

        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            success(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            failure([error code],error);
        }];
    }else if (method == UPLOAD) {

        session = [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            NSError *error;
            if (fileArray == nil || fileArray.count == 0) {
                failure([error code],error);
            }else {
                [fileArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    NSDictionary *dict = obj;
                    NSData *filedata = dict[@"data"];
                    NSString *name = dict[@"name"];
                    NSString *filename = dict[@"filename"];
                    NSString *mimeType = dict[@"mimeType"];
                    [formData appendPartWithFileData:filedata name:name fileName:filename mimeType:mimeType];
                }];
            }
        } progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            success(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            failure([error code],error);
        }];
    }
    return session;
}

@end


text:
import subprocess
#v3

#Command 1
def uname_func():

    uname = "uname"
    uname_arg = "-a"
    print( "Gathering system information with %s command:\n" % uname)
    subprocess.call([uname, uname_arg])

#Command 2
def disk_func():

    diskspace = "df"
    diskspace_arg = "-h"
    print ("Gathering diskspace information %s command:\n" % diskspace)
    subprocess.call([diskspace, diskspace_arg])

#Main function that call other functions
def main():
    uname_func()
    disk_func()

if __name__ == "__main__":
    main()


text:
require 'openssl'
require 'base64'

require_relative '../log'
require_relative 'certificate_retriever'

module Alexa
  # Verifies that the request comes from the alexa service by retrieving a
  # signing certificate from a valid location and using it to verify that
  # the request was signed with it.
  class RequestVerifier
    attr_reader :request_body

    def initialize(certificate_url, signature, request)
      Log.logger.debug 'Creating request verifier'

      @url = certificate_url
      @certificate = CertificateRetriever.new(@url).retrieve
      @signature = signature
      @request_body = request
    end

    def verify
      Log.logger.debug 'Verifying request...'
      if valid_certificate? && valid_signature?
        Log.logger.debug 'Request verification passed!'
        return self
      end
      Log.logger.error 'Request verification failed!'
      msg = "Unable to verify request [#{@request_body}] against signature \
             [#{@signature}] with key from certificate at [#{@url}]"
      fail(Alexa::RequestVerificationError, msg)
    end

    def valid_certificate?
      (
        Time.now.between?(@certificate.not_before, @certificate.not_after) &&
        OpenSSL::SSL.verify_certificate_identity(
          @certificate,
          Alexa::CERTIFICATE_SANS_CN
        )
      )
    end

    def valid_signature?
      sha1 = OpenSSL::Digest::SHA1.new
      decoded_signature = Base64.decode64(@signature)
      @certificate.public_key.verify(sha1, decoded_signature, @request_body)
    rescue OpenSSL::PKey::RSAError => e
      Log.logger.error e.message
      raise(
        Alexa::RequestVerificationError,
        "Error verifying signature: #{e.message}"
      )
    end

    private :valid_certificate?, :valid_signature?
  end

  class RequestVerificationError < StandardError; end
end


text:
"""Tests for Bundle.

"""

import pandas as pd
import numpy as np
import pytest
import os
import shutil
import py

import datreant as dtr
from datreant.tests import test_data

def do_stuff(cont):
    return cont.name + cont.uuid

def return_nothing(cont):
    b = cont.name + cont.uuid

class CollectionTests():
    """Tests for common elements of Group.members and Bundle"""

    @pytest.fixture
    def testtreant(self, tmpdir, request):
        with tmpdir.as_cwd():
            t = dtr.Treant('dummytreant')
        return t

    @pytest.fixture
    def testgroup(self, tmpdir, request):
        with tmpdir.as_cwd():
            g = dtr.Group('dummygroup')
            g.members.add(dtr.Treant('bark'), dtr.Treant('leaf'))
        return g

    def test_additive(self, tmpdir, testtreant, testgroup, collection):
        """Test that addition of treants and collections give Bundles.

        """
        with tmpdir.as_cwd():
            assert isinstance(testtreant + testgroup, dtr.Bundle)
            assert len(testtreant + testgroup) == 2

            # subtle, but important; Group.members is a collection,
            # while Group is a treant
            assert len(testtreant + testgroup.members) != 2
            assert (len(testtreant + testgroup.members) ==
                    len(testgroup.members) + 1)

            assert isinstance(testtreant + testgroup.members, dtr.Bundle)

            b = collection + testtreant + testgroup

            # beating a dead horse
            assert len(b) == 2
            assert (len(b + testgroup.members) ==
                    len(b) + len(testgroup.members))
            assert isinstance(b + testgroup.members, dtr.Bundle)

    def test_add_members(self, collection, tmpdir):
        """Try adding members in a number of ways"""
        with tmpdir.as_cwd():
            s1 = dtr.Treant('lark')
            s2 = dtr.Treant('hark')
            g3 = dtr.Group('linus')

            collection.add(s1, [g3, s2])

            for cont in (s1, s2, g3):
                assert cont in collection

            s4 = dtr.Treant('snoopy')
            collection.add([[s4], s2])
            assert s4 in collection

            # the group won't add members it alrady has
            # (operates as an ordered set)
            assert len(collection) == 4

    def test_add_members_glob(self, collection, tmpdir):
        """Try adding members with globbing"""
        with tmpdir.as_cwd():
            t1 = dtr.Treant('lark')
            t2 = dtr.Treant('hark')
            g3 = dtr.Group('linus')

            collection.add('*ark')

            for treant in (t1, t2):
                assert treant in collection

            assert g3 not in collection

    def test_get_members(self, collection, tmpdir):
        """Access members with indexing and slicing"""
        with tmpdir.as_cwd():
            s1 = dtr.Treant('larry')
            g2 = dtr.Group('curly')
            s3 = dtr.Treant('moe')

            collection.add([[[s1, [g2, [s3]]]]])

            assert collection[1] == g2

            c4 = dtr.treants.Treant('shemp')
            collection.add(c4)

            for member in (s1, g2, s3):
                assert member in collection[:3]

            assert c4 not in collection[:3]
            assert c4 == collection[-1]

    def test_remove_members(self, collection, tmpdir):
        """Try removing members"""
        with tmpdir.as_cwd():
            g1 = dtr.Group('lion-o')
            s2 = dtr.Treant('cheetara')
            s3 = dtr.Treant('snarf')

            collection.add(s3, g1, s2)

            for cont in (g1, s2, s3):
                assert cont in collection

            collection.remove(1)
            assert g1 not in collection

            collection.remove(s2)
            assert s2 not in collection

    def test_remove_members_name(self, collection, tmpdir):
        """Try removing members with names and globbing"""
        with tmpdir.as_cwd():
            t1 = dtr.Treant('lark')
            t2 = dtr.Treant('elsewhere/lark')
            t3 = dtr.Treant('hark')
            g = dtr.Group('linus')

            stuff = [t1, t2, t3, g]

            # test removal by name
            collection.add(stuff)
            for item in stuff:
                assert item in collection

            # should remove both treants with name 'lark'
            collection.remove('lark')

            for item in (t3, g):
                assert item in collection

            for item in (t1, t2):
                assert item not in collection

            # test removal by a unix-style glob pattern
            collection.add(stuff)
            for item in stuff:
                assert item in collection

            # should remove 'lark' and 'hark' treants
            collection.remove('*ark')

            assert g in collection

            for item in (t1, t2, t3):
                assert item not in collection

    def test_member_attributes(self, collection, tmpdir):
        """Get member uuids, names, and treanttypes"""
        with tmpdir.as_cwd():
            c1 = dtr.treants.Treant('bigger')
            g2 = dtr.Group('faster')
            s3 = dtr.Treant('stronger')

        collection.add(c1, g2, s3)

        uuids = [cont.uuid for cont in [c1, g2, s3]]
        assert collection.uuids == uuids

        names = [cont.name for cont in [c1, g2, s3]]
        assert collection.names == names

        treanttypes = [cont.treanttype for cont in [c1, g2, s3]]
        assert collection.treanttypes == treanttypes

    def test_map(self, collection, tmpdir):
        with tmpdir.as_cwd():
            s1 = dtr.Treant('lark')
            s2 = dtr.Treant('hark')
            g3 = dtr.Group('linus')

        collection.add(s1, s2, g3)

        comp = [cont.name + cont.uuid for cont in collection]
        assert collection.map(do_stuff) == comp
        assert collection.map(do_stuff, processes=2) == comp

        assert collection.map(return_nothing) is None
        assert collection.map(return_nothing, processes=2) is None

    class TestMemberData:
        """Test member data functionality"""

        @pytest.fixture
        def collection(self, collection, tmpdir):
            with tmpdir.as_cwd():
                s1 = dtr.Treant('lark')
                s2 = dtr.Treant('hark')
                g3 = dtr.Group('linus')

            collection.add(s1, [g3, s2])
            return collection

        class DataMixin:
            """Mixin class for data storage tests.

            Contains general tests to be used for all storable data formats.

            """
            handle = 'testdata'

            def test_retrieve_data(self, collection, datastruct):
                agg = dict()
                for member in collection:
                    member.data.add(self.handle, datastruct)
                    agg[member.uuid] = datastruct

                np.testing.assert_equal(collection.data.retrieve(self.handle),
                                        agg)
                np.testing.assert_equal(collection.data[self.handle],
                                        agg)

        class PanelMixin:
            """Mixin class for pandas structures that don't support
            MultiIndexing.

            """
            handle = 'testdata'

            def test_retrieve_data(self, collection, datastruct):
                agg = dict()
                for member in collection:
                    member.data.add(self.handle, datastruct)
                    agg[member.uuid] = datastruct

                stored = collection.data.retrieve(self.handle)
                for item in agg:
                    np.testing.assert_equal(stored[item].values,
                                            agg[item].values)

                stored = collection.data[self.handle]
                for item in agg:
                    np.testing.assert_equal(stored[item].values,
                                            agg[item].values)

        class MultiIndexMixin(DataMixin):
            """Mixin class for pandas structures that support MultiIndexes"""

            def test_retrieve_data(self, collection, datastruct):
                agg = dict()
                for member in collection:
                    member.data.add(self.handle, datastruct)
                    agg[member.uuid] = datastruct

                def dict2multiindex(agg):
                    agg_mi = None
                    for member in agg:
                        d = agg[member].copy(deep=True)
                        label = len(d.index)*[member]
                        index = pd.MultiIndex.from_arrays([label, d.index])
                        d.index = index

                        if agg_mi is not None:
                            agg_mi = agg_mi.append(d)
                        else:
                            agg_mi = d

                    return agg_mi

                np.testing.assert_equal(
                        collection.data.retrieve(self.handle).values,
                        dict2multiindex(agg).values)
                np.testing.assert_equal(
                        collection.data[self.handle].values,
                        dict2multiindex(agg).values)

        class Test_Series(test_data.Series, MultiIndexMixin):
            pass

        class Test_DataFrame(test_data.DataFrame, MultiIndexMixin):
            pass

        class Test_Blank_DataFrame(test_data.Blank_DataFrame, MultiIndexMixin):
            pass

        class Test_Wide_Blank_DataFrame(test_data.Wide_Blank_DataFrame,
                                        MultiIndexMixin):
            pass

        class Test_Thin_Blank_DataFrame(test_data.Thin_Blank_DataFrame,
                                        MultiIndexMixin):
            pass

        class Test_Panel(test_data.Panel, PanelMixin):
            pass

        class Test_Panel4D(test_data.Panel4D, PanelMixin):
            pass

        class Test_NumpyScalar(test_data.NumpyScalar, DataMixin):
            pass

        class Test_Numpy1D(test_data.Numpy1D, DataMixin):
            pass

        class Test_Numpy2D(test_data.Numpy2D, DataMixin):
            pass

        class Test_Wide_Numpy2D(test_data.Wide_Numpy2D, DataMixin):
            pass

        class Test_Thin_Numpy2D(test_data.Thin_Numpy2D, DataMixin):
            pass

        class Test_Numpy3D(test_data.Numpy3D, DataMixin):
            pass

        class Test_Numpy4D(test_data.Numpy4D, DataMixin):
            pass

        class Test_List(test_data.List, DataMixin):
            pass

        class Test_Dict(test_data.Dict, DataMixin):
            pass

        class Test_Tuple(test_data.Tuple, DataMixin):
            pass

        class Test_Set(test_data.Set, DataMixin):
            pass

        class Test_Dict_Mix(test_data.Dict_Mix, DataMixin):
            pass

class TestBundle(CollectionTests):
    """Test Bundle features"""

    @pytest.fixture
    def collection(self):
        return dtr.Bundle()


text:
(function(doc) {

  var defaults = {
        node: null,
        pattern: null,
        tagName: 'strong',
        className: null,
        wordsOnly: false,
        caseSensitive: false
      };

  window.bearhug = function bearhug(o) {
    var regex;

    o = mixin({}, defaults, o);

    if (!o.node || !o.pattern) {
      throw new Error('both node and pattern must be set');
    }

    // support wrapping multiple patterns
    o.pattern = isArray(o.pattern) ? o.pattern : [o.pattern];

    regex = getRegex(o.pattern, o.caseSensitive, o.wordsOnly);
    traverse(o.node, bearhugTextNode);

    function bearhugTextNode(textNode) {
      var match, patternNode;

      if (match = regex.exec(textNode.data)) {
        wrapperNode = doc.createElement(o.tagName);
        o.className && (wrapperNode.className = o.className);

        patternNode = textNode.splitText(match.index);
        patternNode.splitText(match[0].length);
        wrapperNode.appendChild(patternNode.cloneNode(true));

        textNode.parentNode.replaceChild(wrapperNode, patternNode);
      }

      return !!match;
    }

    function traverse(el, bearhugTextNode) {
      var childNode, TEXT_NODE_TYPE = 3;

      for (var i = 0; i < el.childNodes.length; i++) {
        childNode = el.childNodes[i];

        if (childNode.nodeType === TEXT_NODE_TYPE) {
          i += bearhugTextNode(childNode) ? 1 : 0;
        }

        else {
          traverse(childNode, bearhugTextNode);
        }
      }
    }
  };

  function getRegex(patterns, caseSensitive, wordsOnly) {
    var escapedPatterns = [], regexStr;

    for (var i = 0; i < patterns.length; i++) {
      escapedPatterns.push(escapeRegexChars(patterns[i]));
    }

    regexStr = wordsOnly ?
      '\\b(' + escapedPatterns.join('|') + ')\\b' :
      '(' + escapedPatterns.join('|') + ')';

    return caseSensitive ? new RegExp(regexStr) : new RegExp(regexStr, 'i');
  }

  function mixin(target) {
    var objs = [].slice.call(arguments, 1), obj;

    for (var i = 0; i < objs.length; i++) {
      obj = objs[i];

      for (var key in obj) {
        obj.hasOwnProperty(key) && (target[key] = obj[key]);
      }
    }

    return target;
  }

  // http://stackoverflow.com/a/6969486
  function escapeRegexChars(str) {
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
  }

  function isArray(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
  }

})(window.document);


text:
Persistent<FunctionTemplate> Palette::constructor;

void Palette::Initialize(Handle<Object> target) {
    HandleScope scope;

    constructor = Persistent<FunctionTemplate>::New(FunctionTemplate::New(Palette::New));
    constructor->InstanceTemplate()->SetInternalFieldCount(1);
    constructor->SetClassName(String::NewSymbol("Palette"));

    NODE_SET_PROTOTYPE_METHOD(constructor, "toString", ToString);
    NODE_SET_PROTOTYPE_METHOD(constructor, "toBuffer", ToBuffer);

    target->Set(String::NewSymbol("Palette"), constructor->GetFunction());
}

Palette::Palette(std::string const& palette, mapnik::rgba_palette::palette_type type) :
    ObjectWrap(),
    palette_(boost::make_shared<mapnik::rgba_palette>(palette, type)) {}

Palette::~Palette() {
}

Handle<Value> Palette::New(const Arguments& args) {
    HandleScope scope;

    if (!args.IsConstructCall()) {
        return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));
    }

    std::string palette;
    mapnik::rgba_palette::palette_type type = mapnik::rgba_palette::PALETTE_RGBA;
    if (args.Length() >= 1) {
        if (args[0]->IsString()) {
            String::AsciiValue obj(args[0]->ToString());
            palette = std::string(*obj, obj.length());
        }
        else if (node::Buffer::HasInstance(args[0])) {
            Local<Object> obj = args[0]->ToObject();
            palette = std::string(node::Buffer::Data(obj), node::Buffer::Length(obj));
        }
    }
    if (args.Length() >= 2) {
        if (args[1]->IsString()) {
            std::string obj = std::string(TOSTR(args[1]));
            if (obj == "rgb") type = mapnik::rgba_palette::PALETTE_RGB;
            else if (obj == "act") type = mapnik::rgba_palette::PALETTE_ACT;
        }
    }

    if (!palette.length()) {
        return ThrowException(Exception::TypeError(
                                  String::New("First parameter must be a palette string")));
    }

    try
    {
        Palette* p = new Palette(palette, type);
        p->Wrap(args.This());
        return args.This();
    }
    catch (std::exception const& ex)
    {
        return ThrowException(Exception::Error(String::New(ex.what())));
    }
}

Handle<Value> Palette::ToString(const Arguments& args)
{
    HandleScope scope;
    palette_ptr p = node::ObjectWrap::Unwrap<Palette>(args.This())->palette_;

    const std::vector<mapnik::rgb>& colors = p->palette();
    unsigned length = colors.size();
    const std::vector<unsigned>& alpha = p->alphaTable();
    unsigned alphaLength = alpha.size();

    std::ostringstream str("");
    str << "[Palette " << length;
    if (length == 1) str << " color";
    else str << " colors";

    str << std::hex << std::setfill('0');

    for (unsigned i = 0; i < length; i++) {
        str << " #";
        str << std::setw(2) << (unsigned)colors[i].r;
        str << std::setw(2) << (unsigned)colors[i].g;
        str << std::setw(2) << (unsigned)colors[i].b;
        if (i < alphaLength) str << std::setw(2) << alpha[i];
    }

    str << "]";
    return scope.Close(String::New(str.str().c_str()));
}

Handle<Value> Palette::ToBuffer(const Arguments& args)
{
    HandleScope scope;

    palette_ptr p = node::ObjectWrap::Unwrap<Palette>(args.This())->palette_;

    const std::vector<mapnik::rgb>& colors = p->palette();
    unsigned length = colors.size();
    const std::vector<unsigned>& alpha = p->alphaTable();
    unsigned alphaLength = alpha.size();

    char palette[256 * 4];
    for (unsigned i = 0, pos = 0; i < length; i++) {
        palette[pos++] = colors[i].r;
        palette[pos++] = colors[i].g;
        palette[pos++] = colors[i].b;
        palette[pos++] = (i < alphaLength) ? alpha[i] : 0xFF;
    }
    #if NODE_VERSION_AT_LEAST(0, 11, 0)
    return scope.Close(node::Buffer::New(palette, length * 4));
    #else
    return scope.Close(node::Buffer::New(palette, length * 4)->handle_);
    #endif
}


text:
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using Windows.Devices.Sensors;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace SDKTemplate
{
    public sealed partial class Scenario3_Calibration : Page
    {
        // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
        // as NotifyUser()
        MainPage rootPage = MainPage.Current;
        CalibrationBar calibrationBar = new CalibrationBar();

        public Scenario3_Calibration()
        {
            this.InitializeComponent();

            if (rootPage.SensorReadingType == SensorReadingType.Relative)
            {
                EnabledContent.Visibility = Visibility.Collapsed;
                DisabledContent.Visibility = Visibility.Visible;
            }
        }

        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            calibrationBar.Hide();
        }

        /// <summary>
        /// This is the click handler for high accuracy. Acceptable accuracy met, so
        /// hide the calibration bar.
        /// </summary>
        private void OnHighAccuracy()
        {
            calibrationBar.Hide();
        }

        /// <summary>
        /// This is the click handler for approximate accuracy. Acceptable accuracy met, so
        /// hide the calibration bar.
        /// </summary>
        private void OnApproximateAccuracy()
        {
            calibrationBar.Hide();
        }

        /// <summary>
        /// This is the click handler for unreliable accuracy. Sensor does not meet accuracy
        /// requirements. Request to show the calibration bar per the calibration guidance.
        /// </summary>
        private void OnUnreliableAccuracy()
        {
            calibrationBar.RequestCalibration(MagnetometerAccuracy.Unreliable);
        }
    }
}


text:
using System;
using System.Web.UI;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TypeMock.ArrangeActAssert;

namespace Nucleo.Web.ValidationControls
{
	[TestClass]
	public class ValidationResultsRendererTest
	{
		#region " Tests "

		[TestMethod]
		public void RenderingControlWithNoItemsRendersAsHidden()
		{
			//Arrange
			var renderer = new ValidationResultsRenderer();
			var control = new ValidationResults();
			control.Page = new Page();
			var writer = new StringControlWriter();

			//Act
			renderer.Initialize(control, control.Page);

			renderer.Render(writer);
			var output = writer.ToString();

			//Assert

		}

		#endregion
	}
}


text:
namespace Microsoft.PythonTools.Options {
    partial class PythonAnalysisOptionsControl {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

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

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent() {
            this.components = new System.ComponentModel.Container();
            System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PythonAnalysisOptionsControl));
            System.Windows.Forms.Label diagnosticModeLabel;
            System.Windows.Forms.Label logLevelLabel;
            System.Windows.Forms.Label typeCheckingModeLabel;
            System.Windows.Forms.Label stubsPathsLabel;
            this._diagnosticsModeCombo = new System.Windows.Forms.ComboBox();
            this._logLevelCombo = new System.Windows.Forms.ComboBox();
            this._typeCheckingMode = new System.Windows.Forms.ComboBox();
            this._stubsPath = new System.Windows.Forms.TextBox();
            this._searchPathsLabel = new System.Windows.Forms.Label();
            this._searchPaths = new System.Windows.Forms.TextBox();
            this._typeShedPathsLabel = new System.Windows.Forms.Label();
            this._typeshedPaths = new System.Windows.Forms.TextBox();
            this._autoSearchPath = new System.Windows.Forms.CheckBox();
            this._diagnosticModeToolTip = new System.Windows.Forms.ToolTip(this.components);
            this._logLevelToolTip = new System.Windows.Forms.ToolTip(this.components);
            this._typeCheckingToolTip = new System.Windows.Forms.ToolTip(this.components);
            this._stubsPathToolTip = new System.Windows.Forms.ToolTip(this.components);
            this._searchPathsToolTip = new System.Windows.Forms.ToolTip(this.components);
            this._typeshedPathsToolTip = new System.Windows.Forms.ToolTip(this.components);
            this._commonSearchPathsToolTip = new System.Windows.Forms.ToolTip(this.components);
            this._searchPathsLabelToolTip = new System.Windows.Forms.ToolTip(this.components);
            this._typeshedPathsLabelToolTip = new System.Windows.Forms.ToolTip(this.components);
            tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
            diagnosticModeLabel = new System.Windows.Forms.Label();
            logLevelLabel = new System.Windows.Forms.Label();
            typeCheckingModeLabel = new System.Windows.Forms.Label();
            stubsPathsLabel = new System.Windows.Forms.Label();
            tableLayoutPanel1.SuspendLayout();
            this.SuspendLayout();
            //
            // tableLayoutPanel1
            //
            resources.ApplyResources(tableLayoutPanel1, "tableLayoutPanel1");
            tableLayoutPanel1.Controls.Add(diagnosticModeLabel, 0, 0);
            tableLayoutPanel1.Controls.Add(this._diagnosticsModeCombo, 1, 0);
            tableLayoutPanel1.Controls.Add(logLevelLabel, 0, 1);
            tableLayoutPanel1.Controls.Add(this._logLevelCombo, 1, 1);
            tableLayoutPanel1.Controls.Add(typeCheckingModeLabel, 0, 2);
            tableLayoutPanel1.Controls.Add(this._typeCheckingMode, 1, 2);
            tableLayoutPanel1.Controls.Add(stubsPathsLabel, 0, 3);
            tableLayoutPanel1.Controls.Add(this._stubsPath, 1, 3);
            tableLayoutPanel1.Controls.Add(this._searchPathsLabel, 0, 4);
            tableLayoutPanel1.Controls.Add(this._searchPaths, 1, 4);
            tableLayoutPanel1.Controls.Add(this._typeShedPathsLabel, 0, 5);
            tableLayoutPanel1.Controls.Add(this._typeshedPaths, 1, 5);
            tableLayoutPanel1.Controls.Add(this._autoSearchPath, 0, 7);
            tableLayoutPanel1.Name = "tableLayoutPanel1";
            //
            // diagnosticModeLabel
            //
            resources.ApplyResources(diagnosticModeLabel, "diagnosticModeLabel");
            diagnosticModeLabel.Name = "diagnosticModeLabel";
            //
            // _diagnosticsModeCombo
            //
            this._diagnosticsModeCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this._diagnosticsModeCombo.FormattingEnabled = true;
            resources.ApplyResources(this._diagnosticsModeCombo, "_diagnosticsModeCombo");
            this._diagnosticsModeCombo.Name = "_diagnosticsModeCombo";
            //
            // logLevelLabel
            //
            resources.ApplyResources(logLevelLabel, "logLevelLabel");
            logLevelLabel.Name = "logLevelLabel";
            //
            // _logLevelCombo
            //
            this._logLevelCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this._logLevelCombo.FormattingEnabled = true;
            resources.ApplyResources(this._logLevelCombo, "_logLevelCombo");
            this._logLevelCombo.Name = "_logLevelCombo";
            //
            // typeCheckingModeLabel
            //
            resources.ApplyResources(typeCheckingModeLabel, "typeCheckingModeLabel");
            typeCheckingModeLabel.Name = "typeCheckingModeLabel";
            //
            // _typeCheckingMode
            //
            this._typeCheckingMode.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this._typeCheckingMode.FormattingEnabled = true;
            resources.ApplyResources(this._typeCheckingMode, "_typeCheckingMode");
            this._typeCheckingMode.Name = "_typeCheckingMode";
            //
            // stubsPathsLabel
            //
            resources.ApplyResources(stubsPathsLabel, "stubsPathsLabel");
            stubsPathsLabel.Name = "stubsPathsLabel";
            //
            // _stubsPath
            //
            resources.ApplyResources(this._stubsPath, "_stubsPath");
            this._stubsPath.Name = "_stubsPath";
            //
            // _searchPathsLabel
            //
            resources.ApplyResources(this._searchPathsLabel, "_searchPathsLabel");
            this._searchPathsLabel.Name = "_searchPathsLabel";
            //
            // _searchPaths
            //
            this._searchPaths.AcceptsReturn = true;
            resources.ApplyResources(this._searchPaths, "_searchPaths");
            this._searchPaths.Name = "_searchPaths";
            //
            // _typeShedPathsLabel
            //
            resources.ApplyResources(this._typeShedPathsLabel, "_typeShedPathsLabel");
            this._typeShedPathsLabel.Name = "_typeShedPathsLabel";
            //
            // _typeshedPaths
            //
            this._typeshedPaths.AcceptsReturn = true;
            resources.ApplyResources(this._typeshedPaths, "_typeshedPaths");
            this._typeshedPaths.Name = "_typeshedPaths";
            //
            // _autoSearchPath
            //
            resources.ApplyResources(this._autoSearchPath, "_autoSearchPath");
            tableLayoutPanel1.SetColumnSpan(this._autoSearchPath, 2);
            this._autoSearchPath.Name = "_autoSearchPath";
            this._autoSearchPath.UseVisualStyleBackColor = true;
            //
            // PythonAnalysisOptionsControl
            //
            resources.ApplyResources(this, "$this");
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(tableLayoutPanel1);
            this.Name = "PythonAnalysisOptionsControl";
            tableLayoutPanel1.ResumeLayout(false);
            tableLayoutPanel1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion
        private System.Windows.Forms.ComboBox _diagnosticsModeCombo;
        private System.Windows.Forms.ComboBox _logLevelCombo;
        private System.Windows.Forms.TextBox _stubsPath;
        private System.Windows.Forms.ComboBox _typeCheckingMode;
        private System.Windows.Forms.TextBox _searchPaths;
        private System.Windows.Forms.TextBox _typeshedPaths;
        private System.Windows.Forms.ToolTip _diagnosticModeToolTip;
        private System.Windows.Forms.ToolTip _logLevelToolTip;
        private System.Windows.Forms.ToolTip _typeCheckingToolTip;
        private System.Windows.Forms.ToolTip _stubsPathToolTip;
        private System.Windows.Forms.ToolTip _searchPathsToolTip;
        private System.Windows.Forms.ToolTip _typeshedPathsToolTip;
        private System.Windows.Forms.ToolTip _commonSearchPathsToolTip;
        private System.Windows.Forms.CheckBox _autoSearchPath;
        private System.Windows.Forms.ToolTip _searchPathsLabelToolTip;
        private System.Windows.Forms.ToolTip _typeshedPathsLabelToolTip;
        private System.Windows.Forms.Label _typeShedPathsLabel;
        private System.Windows.Forms.Label _searchPathsLabel;
    }
}


text: from .service import Instagram


text:
package rms.common.entity;

import java.time.LocalDateTime;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.seasar.doma.Column;
import org.seasar.doma.Entity;
import org.seasar.doma.Id;
import org.seasar.doma.Table;
import org.seasar.doma.Version;

/**
 * MUserクラス
 */
@Entity(listener = MUserListener.class)
@Table(name = "m_user")
public class MUser {
    /** ユーザID */
    @Id
    @Column(name = "user_id")
    private String userId;
    /** ユーザ名 */
    @Column(name = "user_nm")
    private String userNm;
    /** パスワード */
    @Column(name = "password")
    private String password;
    /** メールアドレス */
    @Column(name = "email")
    private String email;
    /** 部署ID コードマスタ:D001 */
    @Column(name = "department_id")
    private String departmentId;
    /** バージョン */
    @Version
    @Column(name = "version")
    private Integer version;
    /** 削除フラグ */
    @Column(name = "del_flg")
    private Integer delFlg;
    /** 登録日時 */
    @Column(name = "ins_date")
    private LocalDateTime insDate;
    /** 登録ID */
    @Column(name = "ins_id")
    private String insId;
    /** 更新日時 */
    @Column(name = "upd_date")
    private LocalDateTime updDate;
    /** 更新ID */
    @Column(name = "upd_id")
    private String updId;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserNm() {
        return userNm;
    }

    public void setUserNm(String userNm) {
        this.userNm = userNm;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getDepartmentId() {
        return departmentId;
    }

    public void setDepartmentId(String departmentId) {
        this.departmentId = departmentId;
    }

    public Integer getVersion() {
        return version;
    }

    public void setVersion(Integer version) {
        this.version = version;
    }

    public Integer getDelFlg() {
        return delFlg;
    }

    public void setDelFlg(Integer delFlg) {
        this.delFlg = delFlg;
    }

    public LocalDateTime getInsDate() {
        return insDate;
    }

    public void setInsDate(LocalDateTime insDate) {
        this.insDate = insDate;
    }

    public String getInsId() {
        return insId;
    }

    public void setInsId(String insId) {
        this.insId = insId;
    }

    public LocalDateTime getUpdDate() {
        return updDate;
    }

    public void setUpdDate(LocalDateTime updDate) {
        this.updDate = updDate;
    }

    public String getUpdId() {
        return updId;
    }

    public void setUpdId(String updId) {
        this.updId = updId;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
    }
}


text:
package com.lauren.newwithnetdata20161214.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.lauren.newwithnetdata20161214.model.RecommondInfo;

import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by Lauren on 16/12/6.
 */

public class InfoDaoUtils {

    private MySQliteOpenHelper mySqliteOpenHelper;
    public InfoDaoUtils(Context context){
        //创建一个帮助类对象
        mySqliteOpenHelper = new MySQliteOpenHelper(context);

    }

    public int del(){

        //执行sql语句需要sqliteDatabase对象
        //调用getReadableDatabase方法,来初始化数据库的创建
        SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();
        //table :表名, whereClause: 删除条件, whereArgs:条件的占位符的参数 ; 返回值:成功删除多少行
        int result = db.delete("info", null,null );
        Log.e("del result:",result+"");
        if (result == 1)
            Log.e("删除成功","删除成功");
        else
            Log.e("删除失败","删除失败");
        //关闭数据库对象
        db.close();
        return result;
    }

    public void add(ArrayList<RecommondInfo> arraylist){

        //执行sql语句需要sqliteDatabase对象
        //调用getReadableDatabase方法,来初始化数据库的创建
        SQLiteDatabase 	db = mySqliteOpenHelper.getReadableDatabase();

        //循环保存
        for (int index = 0;index < arraylist. size();index++){

            RecommondInfo recommondInfo = arraylist.get(index);

            ContentValues values = new ContentValues();//是用map封装的对象,用来存放值
            values.put("Logo", recommondInfo.Logo);
            values.put("CustomerName", recommondInfo.CustomerName);
            values.put("Intro", recommondInfo.Intro);
            values.put("TypeName", recommondInfo.TypeName);
            values.put("ReturnCredit", recommondInfo.ReturnCredit);
            values.put("SoloCreditPercent", recommondInfo.SoloCreditPercent);

            //table: 表名 , nullColumnHack:可以为空,标示添加一个空行, values:数据一行的值 , 返回值:代表添加这个新行的Id ,-1代表添加失败
            long result = db.insert("info", null, values);//底层是在拼装sql语句
            Log.e("插入数据库操作",result+"");

        }

        //关闭数据库对象
        db.close();
    }

    public ArrayList<RecommondInfo> query(){

        //执行sql语句需要sqliteDatabase对象
        //调用getReadableDatabase方法,来初始化数据库的创建
        SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();

        //table:表名, columns:查询的列名,如果null代表查询所有列; selection:查询条件, selectionArgs:条件占位符的参数值,
        //groupBy:按什么字段分组, having:分组的条件, orderBy:按什么字段排序
        Cursor cursor = db.query("info", null, null, null, null, null, null);

        ArrayList<RecommondInfo> arrayList = new ArrayList<RecommondInfo>();
        //解析Cursor中的数据
        if(cursor != null && cursor.getCount() >0){//判断cursor中是否存在数据

            //循环遍历结果集,获取每一行的内容
            while(cursor.moveToNext()){//条件,游标能否定位到下一行
                //获取数据
                int id = cursor.getInt(0);
                String Logo = cursor.getString(0);
                String CustomerName = cursor.getString(1);
                String Intro = cursor.getString(2);
                String TypeName = cursor.getString(3);
                String ReturnCredit = cursor.getString(4);
                String SoloCreditPercent = cursor.getString(5);

                System.out.println("_id:"+id
                        +";Logo:"+Logo
                        +";CustomerName:"+CustomerName
                        +";Intro:"+Intro
                        +";TypeName:"+TypeName
                        +";ReturnCredit:"+ReturnCredit
                        +";SoloCreditPercent:"+SoloCreditPercent);

                RecommondInfo recommondInfo = new RecommondInfo();
                recommondInfo.Logo = Logo;
                recommondInfo.CustomerName = CustomerName;
                recommondInfo.Intro = Intro;
                recommondInfo.TypeName = TypeName;
                recommondInfo.ReturnCredit = ReturnCredit;
                recommondInfo.SoloCreditPercent = SoloCreditPercent;

                arrayList.add(recommondInfo);

            }
            cursor.close();//关闭结果集

        }
        //关闭数据库对象
        db.close();

        return  arrayList;
    }

}


text:
//
//  Copyright 2014 Gustavo J Knuppe (https://github.com/knuppe)
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//
//   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//   - May you do good and not evil.                                         -
//   - May you find forgiveness for yourself and forgive others.             -
//   - May you share freely, never taking more than you give.                -
//   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using SharpNL.Utility;

namespace SharpNL.NameFind {
    /// <summary>
    /// Name finder based on a series of regular expressions.
    /// </summary>
    public class RegexNameFinder : ITokenNameFinder {
        private readonly string type;
        private readonly Regex[] regexList;
        private readonly Dictionary<string, Regex[]> mapping;

        #region + Constructors .
        /// <summary>
        /// Initializes a new instance of the <see cref="RegexNameFinder"/> with the given regex mapping dictionary.
        /// </summary>
        /// <param name="mapping">The regex mapping dictionary.</param>
        /// <exception cref="System.ArgumentNullException">mapping</exception>
        /// <exception cref="System.ArgumentOutOfRangeException">The regex mapping is empty.</exception>
        public RegexNameFinder(Dictionary<string, Regex[]> mapping) {
            if (mapping == null)
                throw new ArgumentNullException(nameof(mapping));

            if (mapping.Count == 0)
                throw new ArgumentOutOfRangeException(nameof(mapping), @"The regex mapping is empty.");

            this.mapping = mapping;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="RegexNameFinder"/> with the given expressions and annotation type.
        /// </summary>
        /// <param name="regexList">The regex list.</param>
        /// <param name="type">The annotation type.</param>
        /// <exception cref="System.ArgumentNullException">regexList</exception>
        /// <exception cref="System.ArgumentOutOfRangeException">The regex list is empty.</exception>
        public RegexNameFinder(Regex[] regexList, string type) {
            if (regexList == null)
                throw new ArgumentNullException(nameof(regexList));

            if (regexList.Length == 0)
                throw new ArgumentOutOfRangeException(nameof(regexList), @"The regex list is empty.");

            this.regexList = regexList;
            this.type = type;
        }
        #endregion

        #region + Find .

        /// <summary>
        /// Generates name tags for the given sequence, typically a sentence, returning token spans for any identified names.
        /// </summary>
        /// <param name="tokens">An array of the tokens or words of the sequence, typically a sentence.</param>
        /// <returns>An array of spans for each of the names identified.</returns>
        public Span[] Find(string[] tokens) {
            var map = new Dictionary<int, int>();
            var sb = new StringBuilder(tokens.Length*10);

            for (var i = 0; i < tokens.Length; i++) {

                map[sb.Length] = i;

                sb.Append(tokens[i]);

                map[sb.Length] = i + 1;

                if (i < tokens.Length - 1)
                    sb.Append(' ');

            }

            var sentence = sb.ToString();
            var spans = new List<Span>();

            if (regexList == null && mapping != null) {
                foreach (var pair in mapping) {
                    foreach (var regex in pair.Value) {
                        var match = regex.Match(sentence);
                        while (match.Success) {
                            var end = match.Index + match.Length;
                            var tokenStart = map.ContainsKey(match.Index) ? map[match.Index] : -1;
                            var tokenEnd = map.ContainsKey(end) ? map[end] : -1;

                            if (tokenStart != -1 && tokenEnd != -1) {
                                spans.Add(new Span(tokenStart, tokenEnd, pair.Key));
                            }
                            match = match.NextMatch();
                        }
                    }
                }
                return spans.ToArray();
            }

            if (regexList == null)
                throw new InvalidOperationException(); // make the compiler happy... its impossible to be null here

            foreach (var regex in regexList) {
                var match = regex.Match(sentence);
                while (match.Success) {
                    var end = match.Index + match.Length;
                    var tokenStart = map.ContainsKey(match.Index) ? map[match.Index] : -1;
                    var tokenEnd = map.ContainsKey(end) ? map[end] : -1;

                    if (tokenStart != -1 && tokenEnd != -1) {
                        spans.Add(new Span(tokenStart, tokenEnd, type));
                    }
                    match = match.NextMatch();
                }

            }
            return spans.ToArray();
        }

        /// <summary>
        /// Generates name tags for the given sequence, returning token spans for any identified names.
        /// </summary>
        /// <param name="text">The text to be analyzed, typically a sentence.</param>
        /// <returns>An array of spans for each of the names identified.</returns>
        public Span[] Find(string text) {
            var spans = new List<Span>();

            if (regexList == null && mapping != null) {
                foreach (var pair in mapping) {
                    foreach (var regex in pair.Value) {
                        var match = regex.Match(text);
                        while (match.Success) {
                            var end = match.Index + match.Length;

                            spans.Add(new Span(match.Index, end, pair.Key));

                            match = match.NextMatch();
                        }
                    }
                }
                return spans.ToArray();
            }

            if (regexList == null)
                throw new InvalidOperationException(); // make the compiler happy... its impossible to be null here

            foreach (var regex in regexList) {
                var match = regex.Match(text);
                while (match.Success) {
                    var end = match.Index + match.Length;

                    spans.Add(new Span(match.Index, end, type));

                    match = match.NextMatch();
                }

            }

            return spans.ToArray();
        }

        #endregion

        #region . ClearAdaptiveData .
        /// <summary>
        /// Forgets all adaptive data which was collected during previous calls to one of the find methods.
        /// </summary>
        /// <remarks>This method is typical called at the end of a document.</remarks>
        public void ClearAdaptiveData() {
            // nothing to clear.
        }
        #endregion

    }
}