text:
namespace DRVEngine {

//=============================================================================
class Q3ScriptParser {
public:
                        Q3ScriptParser( std::string&& data );
    char*               ParseToken();

private:
    void                SkipWhitespace();
    void                SkipLine();

private:
    static const int    MaxToken = 1024;

    std::string         m_data;
    const char*         m_cur;
    char                m_token[MaxToken];
};

}

redpajama_set_name: RedPajamaGithub


text:
name             'nfsmount'
maintainer       'YOUR_COMPANY_NAME'
maintainer_email 'YOUR_EMAIL'
license          'All rights reserved'
description      'Installs/Configures nfsmount'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          '0.1.0'


text:
require 'spec_helper'

describe "AllRoutesCheckAuthentication" do

  after(:each) do
    response.status.should eq(201)
  end

  it "POST /app_supports; empty email address" do
    post '/app_supports', { app_support: { body: "text" } }
  end

end

describe "AllRoutesCheckAuthorization" do

  after(:each) do
    response.status.should eq(403)
  end

  it "PATCH /users/password; checks route for proper auth response" do
    patch "/users/password"
  end

  it "POST /users/password; checks route for proper auth response" do
    post "/users/password"
  end

  it "PUT /users/password; checks route for proper auth response" do
    put "/users/password"
  end

end

describe "AllRoutesCheckAuthentication" do

  after(:each) do
    response.status.should eq(401)
  end

  it "DELETE /event_bookmarks/:id; checks route for proper auth response" do
    delete "/event_bookmarks/1"
  end

  it "DELETE /event_followers/:id; checks route for proper auth response" do
    delete "/event_followers/1"
  end

  it "DELETE /event_notes/:id; checks route for proper auth response" do
    delete "/event_notes/1"
  end

  it "DELETE /event_user_schedules/:id; checks route for proper auth response" do
    delete "/event_user_schedules/1"
  end

  it "DELETE /event_users/:event_user_id; checks route for proper auth response" do
    delete "/event_users/1"
  end

  it "DELETE /group_invites/:id; checks route for proper auth response" do
    delete "/group_invites/1"
  end

  it "DELETE /group_members/:group_member_id; checks route for proper auth response" do
    delete "/group_members/1"
  end

  it "DELETE /group_requests/:id; checks route for proper auth response" do
    delete "/group_requests/1"
  end

  it "DELETE /messages/:message_id; checks route for proper auth response" do
    delete "/messages/1"
  end

  it "DELETE /messages/conversation/:user_id; checks route for proper auth response" do
    delete "/messages/conversation/1"
  end

  it "DELETE /post_comments/:id; checks route for proper auth response" do
    delete "/post_comments/1"
  end

  it "DELETE /post_likes/:id; checks route for proper auth response" do
    delete "/post_likes/1"
  end

  it "DELETE /posts/:id; checks route for proper auth response" do
    delete "/posts/1"
  end

  it "DELETE /user_connections/:id; checks route for proper auth response" do
    delete "/user_connections/1"
  end

  it "DELETE /users/sign_out; checks route for proper auth response" do
    delete "/users/sign_out"
  end

  it "GET /app/labels/:page; checks route for proper auth response" do
    app_label_dictionary = create(:app_label_dictionary, :auth_required)
    get "/app/labels/#{app_label_dictionary.app_label_page.name}"
  end

  it "GET /app_setting_options/:id; checks route for proper auth response" do
    get "/app_setting_options/1"
  end

  it "GET /event_bookmarks; checks route for proper auth response" do
    get "/event_bookmarks"
  end

  it "GET /event_bookmarks/:id; checks route for proper auth response" do
    get "/event_bookmarks/1"
  end

  it "GET /event_bookmarks/event/:event_id; checks route for proper auth response" do
    get "/event_bookmarks/event/1"
  end

  it "GET /event_evaluations/:id; checks route for proper auth response" do
    get "/event_evaluations/1"
  end

  # it "GET /featured_posts/event/event_id; checks route for proper auth response" do
  #   get "/featured_posts/event/1"
  # end

  # it "GET /featured_posts/group/group_id; checks route for proper auth response" do
  #   get "/featured_posts/group/1"
  # end

  # it "GET /event_followers/events/:user_id; checks route for proper auth response" do
  #   get "/event_followers/events/1"
  # end

  it "GET /event_followers/users/:event_id; checks route for proper auth response" do
    get "/event_followers/users/1"
  end

  it "GET /event_notes/:id; checks route for proper auth response" do
    get "/event_notes/1"
  end

  it "GET /event_notes/event/:event_id; checks route for proper auth response" do
    get "/event_notes/event/1"
  end

  it "GET /event_session_evaluations/:id; checks route for proper auth response" do
    get "/event_session_evaluations/1"
  end

  it "GET /event_sessions/:id; checks route for proper auth response" do
    get "/event_sessions/1"
  end

  it "GET /event_sessions/event/:event_id; checks route for proper auth response" do
    get "/event_sessions/event/1"
  end

  it "GET /event_sessions/my_schedule/:event_id; checks route for proper auth response" do
    get "/event_sessions/my_schedule/1"
  end

  it "GET /event_speakers/:id; checks route for proper auth response" do
    get "/event_speakers/1"
  end

  it "GET /event_speakers/event/:event_id; checks route for proper auth response" do
    get "/event_speakers/event/1"
  end

  it "GET /event_speakers/event_session/:event_session_id; checks route for proper auth response" do
    get "/event_speakers/event_session/1"
  end

  it "GET /event_users/attendees/:event_id; checks route for proper auth response" do
    get "/event_users/attendees/1"
  end

  it "GET /event_users/events/:user_id; checks route for proper auth response" do
    get "/event_users/events/1"
  end

  it "GET /event_users/users/:event_id; checks route for proper auth response" do
    get "/event_users/users/1"
  end

  it "GET /events/:id; checks route for proper auth response" do
    get "/events/1"
  end

  it "GET /events/all; checks route for proper auth response" do
    get "/events/all"
  end

  it "GET /events/past; checks route for proper auth response" do
    get "/events/past"
  end

  it "GET /events/upcoming; checks route for proper auth response" do
    get "/events/upcoming"
  end

  it "GET /group_invites/groups; checks route for proper auth response" do
    get "/group_invites/groups"
  end

  it "GET /group_invites/user_search/:group_id; checks route for proper auth response" do
    get "/group_invites/user_search/1"
  end

  it "GET /group_invites/users/:group_id; checks route for proper auth response" do
    get "/group_invites/users/1"
  end

  it "GET /group_members/groups/:user_id; checks route for proper auth response" do
    get "/group_members/groups/1"
  end

  it "GET /group_members/users/:group_id; checks route for proper auth response" do
    get "/group_members/users/1"
  end

  it "GET /group_requests/groups; checks route for proper auth response" do
    get "/group_requests/groups"
  end

  it "GET /group_requests/users/:group_id; checks route for proper auth response" do
    get "/group_requests/users/1"
  end

  it "GET /groups; checks route for proper auth response" do
    get "/groups"
  end

  it "GET /groups/:id; checks route for proper auth response" do
    get "/groups/1"
  end

  it "GET /messages; checks route for proper auth response" do
    get "/messages"
  end

  it "GET /messages/conversation/:user_id; checks route for proper auth response" do
    get "/messages/conversation/1"
  end

  it "GET /navigation/left; checks route for proper auth response" do
    get "/navigation/left"
  end

  it "GET /navigation/right/:event_id; checks route for proper auth response" do
    get "/navigation/right/1"
  end

  it "GET /notifications/:id; checks route for proper auth response" do
    get "/notifications/1"
  end

  it "GET /notifications/user/:user_id; checks route for proper auth response" do
    get "/notifications/user/1"
  end

  it "GET /options_test; checks route for proper auth response" do
    get "/options_test"
  end

  it "GET /post_comments/:id; checks route for proper auth response" do
    get "/post_comments/1"
  end

  it "GET /post_comments/post/:post_id; checks route for proper auth response" do
    get "/post_comments/post/1"
  end

  it "GET /post_likes/:id; checks route for proper auth response" do
    get "/post_likes/1"
  end

  it "GET /post_likes/posts/:user_id; checks route for proper auth response" do
    get "/post_likes/posts/1"
  end

  it "GET /post_likes/users/:post_id; checks route for proper auth response" do
    get "/post_likes/users/1"
  end

  it "GET /posts/:id; checks route for proper auth response" do
    get "/posts/1"
  end

  it "GET /posts/event/:event_id; checks route for proper auth response" do
    get "/posts/event/1"
  end

  it "GET /posts/group/:group_id; checks route for proper auth response" do
    get "/posts/group/1"
  end

  it "GET /posts/user/:user_id; checks route for proper auth response" do
    get "/posts/user/1"
  end

  it "GET /sponsors; checks route for proper auth response" do
    get "/sponsors"
  end

  it "GET /sponsors/:id; checks route for proper auth response" do
    get "/sponsors/1"
  end

  it "GET /sponsors/app; checks route for proper auth response" do
    get "/sponsors/app"
  end

  it "GET /sponsors/event; checks route for proper auth response" do
    get "/sponsors/event"
  end

  it "GET /sponsors/group; checks route for proper auth response" do
    get "/sponsors/group"
  end

  it "GET /user_connections/pending; checks route for proper auth response" do
    get "/user_connections/pending"
  end

  it "GET /users/connections/:user_id; checks route for proper auth response" do
    get "/users/connections/1"
  end

  it "GET /users/post_options; checks route for proper auth response" do
    get "/users/post_options"
  end

  it "GET /users/profile; checks route for proper auth response" do
    get "/users/profile"
  end

  it "GET /users/profile/:id; checks route for proper auth response" do
    get "/users/profile/1"
  end

  it "GET /users/sign_in; checks route for proper auth response" do
    get "/users/sign_in"
  end

  it "PATCH /event_notes/:id; checks route for proper auth response" do
    patch "/event_notes/1"
  end

  it "PATCH /group_requests/:id; checks route for proper auth response" do
    patch "/group_requests/1"
  end

  it "PATCH /groups/:id; checks route for proper auth response" do
    patch "/groups/1"
  end

  it "PATCH /post_comments/:id; checks route for proper auth response" do
    patch "/post_comments/1"
  end

  it "PATCH /posts/:id; checks route for proper auth response" do
    patch "/posts/1"
  end

  it "PATCH /user_connections/:id; checks route for proper auth response" do
    patch "/user_connections/1"
  end

  it "PATCH /users/profile; checks route for proper auth response" do
    patch "/users/profile"
  end

  it "POST /event_bookmarks; checks route for proper auth response" do
    post "/event_bookmarks"
  end

  it "POST /event_followers; checks route for proper auth response" do
    post "/event_followers"
  end

  it "POST /event_notes; checks route for proper auth response" do
    post "/event_notes"
  end

  it "POST /event_user_schedules; checks route for proper auth response" do
    post "/event_user_schedules"
  end

  it "POST /event_users; checks route for proper auth response" do
    post "/event_users"
  end

  it "POST /group_invites; checks route for proper auth response" do
    post "/group_invites"
  end

  it "POST /group_members; checks route for proper auth response" do
    post "/group_members"
  end

  it "POST /group_requests; checks route for proper auth response" do
    post "/group_requests"
  end

  it "POST /groups; checks route for proper auth response" do
    post "/groups"
  end

  it "POST /messages; checks route for proper auth response" do
    post "/messages"
  end

  it "POST /post_comments; checks route for proper auth response" do
    post "/post_comments"
  end

  it "POST /post_likes; checks route for proper auth response" do
    post "/post_likes"
  end

  it "POST /posts; checks route for proper auth response" do
    post "/posts"
  end

  it "POST /user_connections; checks route for proper auth response" do
    post "/user_connections"
  end

  it "POST /users/sign_in; checks route for proper auth response" do
    post "/users/sign_in"
  end

  it "PUT /event_notes/:id; checks route for proper auth response" do
    put "/event_notes/1"
  end

  it "PUT /group_requests/:id; checks route for proper auth response" do
    put "/group_requests/1"
  end

  it "PUT /groups/:id; checks route for proper auth response" do
    put "/groups/1"
  end

  it "PUT /post_comments/:id; checks route for proper auth response" do
    put "/post_comments/1"
  end

  it "PUT /posts/:id; checks route for proper auth response" do
    put "/posts/1"
  end

  it "PUT /user_connections/:id; checks route for proper auth response" do
    put "/user_connections/1"
  end

end


text:
class Maker::Trait < Maker::App
  has_many :in, :concepts, model_class: Maker::Concept, origin: :traits
end


text:
package org.nem.core.model.primitive;

import net.minidev.json.JSONObject;
import org.hamcrest.core.IsEqual;
import org.junit.*;
import org.nem.core.serialization.*;
import org.nem.core.test.Utils;

import java.math.BigInteger;

public class BlockDifficultyTest {

	//region constants

	@Test
	public void constantsAreInitializedCorrectly() {
		// Assert:
		Assert.assertThat(
				BlockDifficulty.INITIAL_DIFFICULTY,
				IsEqual.equalTo(new BlockDifficulty(100_000_000_000_000L)));
	}

	//endregion

	//region constructor

	@Test
	public void valueInDifficultyRangeIsNotChanged() {
		// Arrange:
		final BlockDifficulty difficulty = new BlockDifficulty(79_876_543_211_237L);

		// Assert:
		Assert.assertThat(difficulty.getRaw(), IsEqual.equalTo(79_876_543_211_237L));
	}

	@Test
	public void valueBelowMinDifficultyIsIncreasedToMinDifficulty() {
		// Arrange:
		final BlockDifficulty difficulty = new BlockDifficulty(1_654_321_123_000L);

		// Assert:
		Assert.assertThat(difficulty.getRaw(), IsEqual.equalTo(10_000_000_000_000L));
	}

	@Test
	public void valueAboveMaxDifficultyIsDecreasedToMaxDifficulty() {
		// Arrange:
		final BlockDifficulty difficulty = new BlockDifficulty(1_987_654_321_123_000L);

		// Assert:
		Assert.assertThat(difficulty.getRaw(), IsEqual.equalTo(1_000_000_000_000_000L));
	}

	//endregion

	//region converters

	@Test
	public void valueCanBeReturnedAsBigInteger() {
		// Arrange:
		final BlockDifficulty difficulty = new BlockDifficulty(79_876_543_211_237L);

		// Assert:
		Assert.assertThat(difficulty.asBigInteger(), IsEqual.equalTo(new BigInteger("79876543211237")));
	}

	//endregion

	//region inline serialization

	@Test
	public void canWriteBlockDifficulty() {
		// Arrange:
		final JsonSerializer serializer = new JsonSerializer();
		final BlockDifficulty difficulty = new BlockDifficulty(79_876_543_211_237L);

		// Act:
		BlockDifficulty.writeTo(serializer, "difficulty", difficulty);

		// Assert:
		final JSONObject object = serializer.getObject();
		Assert.assertThat(object.size(), IsEqual.equalTo(1));
		Assert.assertThat(object.get("difficulty"), IsEqual.equalTo(79_876_543_211_237L));
	}

	@Test
	public void canRoundtripBlockHeight() {
		// Arrange:
		final JsonSerializer serializer = new JsonSerializer();
		final BlockDifficulty originalDifficulty = new BlockDifficulty(79_876_543_211_237L);

		// Act:
		BlockDifficulty.writeTo(serializer, "difficulty", originalDifficulty);

		final JsonDeserializer deserializer = Utils.createDeserializer(serializer.getObject());
		final BlockDifficulty difficulty = BlockDifficulty.readFrom(deserializer, "difficulty");

		// Assert:
		Assert.assertThat(difficulty, IsEqual.equalTo(originalDifficulty));
	}

	//endregion
}


text:
define([
  'dojo/_base/declare',
  '../BaseFeatureAction',
  '../exportUtils'
], function(declare, BaseFeatureAction, exportUtils){
  var clazz = declare(BaseFeatureAction, {
    name: 'ExportToCSV',
    iconClass: 'icon-export',

    isFeatureSupported: function(featureSet){
      return featureSet.features.length > 0;
    },

    onExecute: function(featureSet){
      var ds = exportUtils.createDataSource({
        type: exportUtils.TYPE_FEATURESET,
        filename: 'features',
        data: featureSet
      });

      ds.setFormat(exportUtils.FORMAT_CSV);
      ds.download();
    }

  });
  return clazz;
});


text:
package airbrake;

public class ValidBacktraces {

	public static boolean isValidBacktrace(String string) {
		return string.matches("[^:]*:\\d+.*");
	}

	public static boolean notValidBacktrace(String string) {
		return !isValidBacktrace(string);
	}

}


text:
def greet(dict):
    if 'name' in dict:
        name = dict['name']
    else:
        name = 'stranger'
    greeting = 'Hello ' + name + '!'
    return {'greeting': greeting}


text:
import logging
import config

RX_BYTES = 'rx_bytes'
TX_BYTES = 'tx_bytes'
RX_PACKETS = 'rx_packets'
TX_PACKETS = 'tx_packets'
SDN_RX_BYTES = 'sdn_rx_bytes'
SDN_TX_BYTES = 'sdn_tx_bytes'
SDN_RX_PACKETS = 'sdn_rx_packets'
SDN_TX_PACKETS = 'sdn_tx_packets'
IS_VIRTUAL = 'is_virtual'
PORT_NAME = 'name'

PORT_STATS = {RX_BYTES, TX_BYTES,
              RX_PACKETS, TX_PACKETS,
              SDN_RX_BYTES, SDN_TX_BYTES,
              SDN_RX_PACKETS, SDN_TX_PACKETS}

IP_PARTNER_PORT_NUMBER = 'ip_partner_port_number'

log = logging.getLogger('oshi_monitoring')

class SwitchStats:
    def __init__(self, datapath):
        log.debug("Initializing SwitchStat for %s datapath", datapath.id)
        self.data_path = datapath
        self.data_path_id = datapath.id
        self.device_name = ''
        self.ports = {}
        self.__seconds_from_start = 0

    def add_port(self, port_number, is_virtual=False, port_name=''):
        """
        Add a single port to stats.

        :param port_number: port number of the port to add
        """
        self.ports[port_number] = {}
        self.ports[port_number][RX_BYTES] = 0
        self.ports[port_number][TX_BYTES] = 0
        self.ports[port_number][RX_PACKETS] = 0
        self.ports[port_number][TX_PACKETS] = 0
        self.ports[port_number][SDN_RX_BYTES] = 0
        self.ports[port_number][SDN_TX_BYTES] = 0
        self.ports[port_number][SDN_RX_PACKETS] = 0
        self.ports[port_number][SDN_TX_PACKETS] = 0
        self.ports[port_number][IS_VIRTUAL] = is_virtual
        self.ports[port_number][PORT_NAME] = port_name

    def get_port_name(self, port_number):
        """
        Return the name of the specified port.

        :param port_number:
        :return: port name
        :rtype: str
        """
        return self.ports[port_number][PORT_NAME]

    def set_ip_partner_port_number(self, port_number, partner_port_number):
        """
        Set the port number of the IP partner for a given port.

        This can be used to match ports between partners like:
            ss.set_ip_partner_port_number(in_port, out_port)
            ss.set_ip_partner_port_number(out_port, in_port)

        :param port_number:
        :param partner_port_number:
        """
        log.debug("Setting partner port number for port %s. Partner: %s", self.get_port_name(port_number),
                  self.get_port_name(partner_port_number))
        self.ports[port_number][IP_PARTNER_PORT_NUMBER] = partner_port_number

    def get_ip_partner_port_number(self, port_number):
        """
        Return the port number of the IP partner, given a port number.

        :param port_number:
        :return: Partner port number or -1 if no relationship has been defined for the specified port number.
        """
        return self.ports[port_number][IP_PARTNER_PORT_NUMBER]

    def get_rx_bytes(self, port_number):
        """
        Return received bytes count for the specified port.

        :param port_number:
        :return: bytes count
        """
        return self.ports[port_number][RX_BYTES]

    def get_tx_bytes(self, port_number):
        """
        Return transmitted bytes count for the specified port.

        :param port_number:
        :return: bytes count
        """
        return self.ports[port_number][TX_BYTES]

    def get_rx_packets(self, port_number):
        """
        Return received packet count for the specified port.

        :param port_number:
        :return: packet count
        """
        return self.ports[port_number][RX_PACKETS]

    def get_tx_packets(self, port_number):
        """
        Return transmitted packet count for the specified port.

        :param port_number:
        :return: packet count
        """
        return self.ports[port_number][TX_PACKETS]

    def get_sdn_rx_bytes(self, port_number):
        return self._get_sdn_stat(port_number, SDN_RX_BYTES)

    def get_sdn_tx_bytes(self, port_number):
        return self._get_sdn_stat(port_number, SDN_TX_BYTES)

    def get_sdn_rx_packets(self, port_number):
        return self._get_sdn_stat(port_number, SDN_RX_PACKETS)

    def get_sdn_tx_packets(self, port_number):
        return self._get_sdn_stat(port_number, SDN_TX_PACKETS)

    def _get_sdn_stat(self, port_number, stat_key):
        return self.ports[port_number][stat_key]

    def _update_stat(self, port_number, stat_key, stat_value, lldp_noise=0):
        """
        Update stat value filling a circular buffer of config.DELTA_WINDOW for the specified port.

        :param port_number:
        :param stat_value:
        :param lldp_noise: LLDP traffic to subtract to rx_bytes, defaults to 0
        :return:
        """
        log.debug("Update %s stat for %s, port %s with value: %s", stat_key, self.device_name,
                  self.get_port_name(port_number), stat_value)
        port = self.ports[port_number]
        log.debug("Current values for port %s, stat %s. Value: %s", self.get_port_name(port_number), stat_key,
                  port[stat_key])
        updated_value = stat_value - lldp_noise
        log.debug("Updating %s for port %s with value: %s", stat_key, self.get_port_name(port_number),
                  updated_value)
        port[stat_key] += updated_value
        log.debug("New value for %s for port %s with value: %s", stat_key, self.get_port_name(port_number),
                  port[stat_key])
        log.debug("Current values for port %s, stat %s. Current value: %s", self.get_port_name(port_number), stat_key,
                  port[stat_key])

    def set_rx_bytes(self, port_number, rx_bytes, lldp_noise=0):
        """
        Update received byte count filling a circular buffer of config.DELTA_WINDOW for the specified port.

        :param port_number:
        :param rx_bytes:
        :param lldp_noise: LLDP traffic to subtract to rx_bytes, defaults to 0
        :return:
        """
        self._update_stat(port_number, RX_BYTES, rx_bytes, lldp_noise)

    def set_tx_bytes(self, port_number, tx_bytes, lldp_noise=0):
        """
        Update transmitted byte count filling a circular buffer of config.DELTA_WINDOW for the specified port.

        :param port_number:
        :param tx_bytes:
        :param lldp_noise: LLDP traffic to subtract to rx_bytes, defaults to 0
        :return:
        """
        self._update_stat(port_number, TX_BYTES, tx_bytes, lldp_noise)

    def set_rx_packets(self, port_number, rx_packets, lldp_noise=0):
        """
        Update received packet count filling a circular buffer of config.DELTA_WINDOW for the specified port.

        :param port_number:
        :param rx_packets:
        :param lldp_noise: LLDP traffic to subtract to rx_bytes, defaults to 0
        :return:
        """
        self._update_stat(port_number, RX_PACKETS, rx_packets, lldp_noise)

    def set_tx_packets(self, port_number, tx_packets, lldp_noise=0):
        """
        Update transmitted packet count filling a circular buffer of config.DELTA_WINDOW for the specified port.

        :param port_number:
        :param tx_packets:
        :param lldp_noise: LLDP traffic to subtract to rx_bytes, defaults to 0
        :return:
        """
        self._update_stat(port_number, TX_PACKETS, tx_packets, lldp_noise)

    def __compute_sdn_rx_bytes(self, port_number):
        """
        Compute and return received SDN traffic for the specified port.

        :param port_number:
        :return: Received SDN traffic in bytes
        """
        # received total - ip sent to partner
        return self.__compute_sdn_stat(port_number, RX_BYTES, TX_BYTES)

    def __compute_sdn_rx_packets(self, port_number):
        """
        Compute and return received SDN traffic for the specified port.

        :param port_number:
        :return: Received SDN traffic in packets
        """
        return self.__compute_sdn_stat(port_number, RX_PACKETS, TX_PACKETS)

    def __compute_sdn_tx_bytes(self, port_number):
        """
        Compute and return transmitted SDN traffic for the specified port.

        :param port_number:
        :return: Transmitted SDN traffic in bytes
        """
        return self.__compute_sdn_stat(port_number, TX_BYTES, RX_BYTES)

    def __compute_sdn_tx_packets(self, port_number):
        """
        Compute and return transmitted SDN traffic for the specified port.

        :param port_number:
        :return: Transmitted SDN traffic in packets
        """
        # sent total - ip received by partner
        return self.__compute_sdn_stat(port_number, TX_PACKETS, RX_PACKETS)

    def __compute_sdn_stat(self, port_number, grand_total_stat, stat_to_subtract):
        try:
            # compute SDN stats for PHY ports only, not for virtual
            port_name = self.get_port_name(port_number)
            if port_name.lower().startswith('vi'):
                return 0
            else:
                ip_partner_port_number = self.get_ip_partner_port_number(port_number)
                res = self.ports[port_number][grand_total_stat] - self.ports[ip_partner_port_number][stat_to_subtract]
                log.debug("Computing SDN stat for port %s: %s (%s:%s:%s) - %s (%s:%s:%s) = %s",
                          port_name,
                          self.ports[port_number][grand_total_stat], port_number, port_name, grand_total_stat,
                          self.ports[ip_partner_port_number][stat_to_subtract], port_number, port_name,
                          stat_to_subtract, res)
                return res
        except KeyError:
            return 0

    @staticmethod
    def _has_rx_lldp_noise(port_name, port_number):
        if port_name[0:3] == 'cro':
            return 0
        elif port_number != 1:
            return 1
        return 0

    def update_sdn_stats(self):
        """
        Update SDN stats for every port registered in this SwitchStats

        :return:
        """
        self.__seconds_from_start += 1
        log.debug("Updating SDN stats for all ports of %s. Seconds from start: %s", self.device_name,
                  self.__seconds_from_start)
        for port_number in self.ports:
            port_name = self.get_port_name(port_number)
            log.debug("Updating SDN stats for port %s", port_name)
            port = self.ports[port_number]
            log.debug("Current stats for port %s: %s", port_name, str(port))
            if self.ports[port_number][IS_VIRTUAL]:
                log.debug("Skip SDN stats update for port %s because it's a virtual port", port_name)
            else:
                # initialization
                rx_noise = SwitchStats._has_rx_lldp_noise(self.get_port_name(port_number), port_number)
                lldp_noise_bytes = self.__seconds_from_start * config.LLDP_NOISE_BYTE_S
                lldp_noise_packets = self.__seconds_from_start * config.LLDP_NOISE_PACK_S
                log.debug("LLDP Noise for port %s. LLDP Noise BYTES: %s, Packets: %s. RX_NOISE: %s", port_name,
                          lldp_noise_bytes, lldp_noise_packets, rx_noise)
                # update SDN stats
                port[SDN_RX_BYTES] = self.__compute_sdn_rx_bytes(port_number) + lldp_noise_bytes * rx_noise
                port[SDN_TX_BYTES] = self.__compute_sdn_tx_bytes(port_number) - lldp_noise_bytes
                port[SDN_RX_PACKETS] = self.__compute_sdn_rx_packets(port_number) + lldp_noise_packets * rx_noise
                port[SDN_TX_PACKETS] = self.__compute_sdn_tx_packets(port_number) - lldp_noise_packets
                log.debug("Updated stats for port %s: %s", port_name, str(port))

    def get_current_values(self, port_number):
        return {RX_BYTES: self.get_rx_bytes(port_number),
                TX_BYTES: self.get_tx_bytes(port_number),
                RX_PACKETS: self.get_rx_packets(port_number),
                TX_PACKETS: self.get_tx_packets(port_number),
                SDN_RX_BYTES: self.get_sdn_rx_bytes(port_number),
                SDN_TX_BYTES: self.get_sdn_tx_bytes(port_number),
                SDN_RX_PACKETS: self.get_sdn_rx_packets(port_number),
                SDN_TX_PACKETS: self.get_sdn_tx_bytes(port_number)}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.IO;
using System.Reflection;
using System.Globalization;

using Microsoft.Build.Framework;
using Microsoft.Build.Tasks;
using Microsoft.Build.Utilities;
using Microsoft.Build.Shared;
using Xunit;

namespace Microsoft.Build.UnitTests
{
    sealed public class CreateCSharpManifestResourceName_Tests
    {
        /// <summary>
        /// Test the basic functionality.
        /// </summary>
        [Fact]
        public void Basic()
        {
            string result =
            CreateCSharpManifestResourceName.CreateManifestNameImpl
                (
                    @"f:\myproject\SubFolder\MyForm.resx",
                    null,
                    true,
                    null,    // Root namespace
                    null,
                    null,
                    StreamHelpers.StringToStream("namespace MyStuff.Namespace { class Class {} }"),
                    null
                );

            Assert.Equal("MyStuff.Namespace.Class", result);
        }

        /// <summary>
        /// Test for a namespace that has ANSI but non-ascii characters.
        ///
        /// NOTE: namespace dÃa {} get's compiled into different IL depending on the language of the OS
        /// that its running on. This is because 'Ã' is a high ANSI character which is interpretted differently
        /// for different codepages.
        /// </summary>
        [Fact]
        public void Regress172107()
        {
            // Can't embed the 'Ã' directly because the string is Unicode already and the Unicode<-->ANSI transform
            // isn't bidirectional.
            MemoryStream sourcesStream = (MemoryStream)StreamHelpers.StringToStream("namespace d?a { class Class {} }");

            // Instead, directly write the ANSI character into the memory buffer.
            sourcesStream.Seek(11, SeekOrigin.Begin);
            sourcesStream.WriteByte(0xc3);    // Plug the 'Ã' in
            sourcesStream.Seek(0, SeekOrigin.Begin);

            string result =
            CreateCSharpManifestResourceName.CreateManifestNameImpl
                (
                    @"irrelevent",
                    null,
                    true,
                    null,    // Root namespace
                    null,
                    null,
                    sourcesStream,
                    null
                );

            MemoryStream m = new MemoryStream();
            m.Write(new byte[] { 0x64, 0xc3, 0x61, 0x2e, 0x43, 0x6c, 0x61, 0x73, 0x73 }, 0, 9); // dÃa.Class in ANSI
            m.Flush();
            m.Seek(0, SeekOrigin.Begin);

            StreamReader r = new StreamReader(m, System.Text.Encoding.Default, true); // HIGHCHAR: Test reads ANSI because that's the scenario.
            string className = r.ReadToEnd();

            Assert.Equal(className, result);
        }

        /// <summary>
        /// Test for a namespace that has UTF8 characters but there's no BOM at the start.
        ///
        /// </summary>
        [Fact]
        public void Regress249540()
        {
            // Special character is 'Ä' in UTF8: 0xC3 84
            MemoryStream sourcesStream = (MemoryStream)StreamHelpers.StringToStream("namespace d??a { class Class {} }");

            // Instead, directly write the ANSI character into the memory buffer.
            sourcesStream.Seek(11, SeekOrigin.Begin);
            sourcesStream.WriteByte(0xc3);    // Plug the first byte of 'Ä' in.
            sourcesStream.WriteByte(0x84);    // Plug the second byte of 'Ä' in.
            sourcesStream.Seek(0, SeekOrigin.Begin);

            string result =
            CreateCSharpManifestResourceName.CreateManifestNameImpl
                (
                    @"irrelevent",
                    null,
                    true,
                    null,    // Root namespace
                    null,
                    null,
                    sourcesStream,
                    null
                );

            Assert.Equal("d\u00C4a.Class", result);
        }

        /// <summary>
        /// Test a dependent with a relative path
        /// </summary>
        [Fact]
        public void RelativeDependentUpon()
        {
            string result =
            CreateCSharpManifestResourceName.CreateManifestNameImpl
                (
                    @"f:\myproject\SubFolder\MyForm.resx",
                    null,
                    true,
                    null,    // Root namespace
                    null,
                    null,
                    StreamHelpers.StringToStream("namespace Namespace { class Class {} }"),
                    null
                );

            Assert.Equal("Namespace.Class", result);
        }

        /// <summary>
        /// Test a dependent with a relative path
        /// </summary>
        [Fact]
        public void AbsoluteDependentUpon()
        {
            string result =
            CreateCSharpManifestResourceName.CreateManifestNameImpl
                (
                    @"f:\myproject\SubFolder\MyForm.resx",
                    null,
                    true,
                    "RootNamespace",    // Root namespace (will be ignored because it's dependent)
                    null,
                    null,
                    StreamHelpers.StringToStream("namespace MyStuff.Namespace { class Class {} }"),
                    null
                );

            Assert.Equal("MyStuff.Namespace.Class", result);
        }

        /// <summary>
        /// A dependent class plus there is a culture.
        /// </summary>
        [Fact]
        public void DependentWithCulture()
        {
            string result =
            CreateCSharpManifestResourceName.CreateManifestNameImpl
                (
                    @"f:\myproject\SubFolder\MyForm.en-GB.resx",
                    null,
                    true,
                    "RootNamespace",    // Root namespace (will be ignored because it's dependent)
                    null,
                    null,
                    StreamHelpers.StringToStream("namespace MyStuff.Namespace { class Class {} }"),
                    null
                );

            Assert.Equal("MyStuff.Namespace.Class.en-GB", result);
        }

        /// <summary>
        /// A dependent class plus there is a culture that was expressed in the metadata of the
        /// item rather than the filename.
        /// </summary>
        [Fact]
        public void DependentWithCultureMetadata()
        {
            string result =
            CreateCSharpManifestResourceName.CreateManifestNameImpl
                (
                    @"f:\myproject\SubFolder\MyForm.resx",
                    null,
                    true,
                    "RootNamespace",    // Root namespace (will be ignored because it's dependent)
                    null,
                    "en-GB",
                    StreamHelpers.StringToStream("namespace MyStuff.Namespace { class Class {} }"),
                    null
                );

            Assert.Equal("MyStuff.Namespace.Class.en-GB", result);
        }

        /// <summary>
        /// A dependent class plus there is a culture embedded in the .RESX filename.
        /// </summary>
        [Fact]
        public void DependentWithEmbeddedCulture()
        {
            string result =
            CreateCSharpManifestResourceName.CreateManifestNameImpl
                (
                    @"f:\myproject\SubFolder\MyForm.fr-fr.resx",
                    null,
                    true,
                    "RootNamespace",    // Root namespace (will be ignored because it's dependent)
                    null,
                    null,
                    StreamHelpers.StringToStream("namespace MyStuff.Namespace { class Class {} }"),
                    null
                );

            Assert.Equal("MyStuff.Namespace.Class.fr-fr", result);
        }

        /// <summary>
        /// No dependent class, but there is a root namespace place.  Also, the .resx
        /// extension contains some upper-case characters.
        /// </summary>
        [Fact]
        public void RootnamespaceWithCulture()
        {
            string result =
            CreateCSharpManifestResourceName.CreateManifestNameImpl
                (
                    @"SubFolder\MyForm.en-GB.ResX",
                    null,
                    true,
                    "RootNamespace",        // Root namespace
                    null,
                    null,
                    null,
                    null
                );

            Assert.Equal("RootNamespace.SubFolder.MyForm.en-GB", result);
        }

        /// <summary>
        /// If there is a link file name then it is preferred over the main file name.
        /// </summary>
        [Fact]
        public void Regress222308()
        {
            string result =
            CreateCSharpManifestResourceName.CreateManifestNameImpl
                (
                    @"..\..\XmlEditor\Setup\XmlEditor.rgs",
                    @"XmlEditor.rgs",
                    true,
                    "RootNamespace",        // Root namespace
                    null,
                    null,
                    null,
                    null
                );

            Assert.Equal("RootNamespace.XmlEditor.rgs", result);
        }

        /// <summary>
        /// A non-resx file in a subfolder, with a root namespace.
        /// </summary>
        [Fact]
        public void BitmapWithRootNamespace()
        {
            string result =
            CreateCSharpManifestResourceName.CreateManifestNameImpl
                (
                    @"SubFolder\SplashScreen.bmp",
                    null,
                    true,
                    "RootNamespace",        // Root namespace
                    null,
                    null,
                    null,
                    null
                );

            Assert.Equal("RootNamespace.SubFolder.SplashScreen.bmp", result);
        }

        /// <summary>
        /// A culture-specific non-resx file in a subfolder, with a root namespace.
        /// </summary>
        [Fact]
        public void CulturedBitmapWithRootNamespace()
        {
            string result =
            CreateCSharpManifestResourceName.CreateManifestNameImpl
                (
                    @"SubFolder\SplashScreen.fr.bmp",
                    null,
                    true,
                    "RootNamespace",        // Root namespace
                    null,
                    null,
                    null,
                    null
                );

            Assert.Equal(@"fr\RootNamespace.SubFolder.SplashScreen.bmp", result);
        }

        /// <summary>
        /// A culture-specific non-resx file in a subfolder, with a root namespace, but no culture directory prefix
        /// </summary>
        [Fact]
        public void CulturedBitmapWithRootNamespaceNoDirectoryPrefix()
        {
            string result =
            CreateCSharpManifestResourceName.CreateManifestNameImpl
                (
                    @"SubFolder\SplashScreen.fr.bmp",
                    null,    // Link file name
                    false,
                    "RootNamespace",        // Root namespace
                    null,
                    null,
                    null,
                    null
                );

            Assert.Equal(@"RootNamespace.SubFolder.SplashScreen.bmp", result);
        }

        /// <summary>
        /// If the filename passed in as the "DependentUpon" file doesn't end in .cs then
        /// we want to fall back to the RootNamespace+FileName logic.
        /// </summary>
        [Fact]
        public void Regress188319()
        {
            CreateCSharpManifestResourceName t = new CreateCSharpManifestResourceName();

            t.BuildEngine = new MockEngine();
            ITaskItem i = new TaskItem("SR1.resx");
            i.SetMetadata("BuildAction", "EmbeddedResource");
            i.SetMetadata("DependentUpon", "SR1.strings");        // Normally, this would be a C# file.
            t.ResourceFiles = new ITaskItem[] { i };
            t.RootNamespace = "CustomToolTest";
            bool success = t.Execute
            (
                new Microsoft.Build.Tasks.CreateFileStream(CreateFileStream)
            );

            Assert.True(success); // "Expected the task to succceed."

            ITaskItem[] resourceNames = t.ManifestResourceNames;

            Assert.Equal(1, resourceNames.Length);
            Assert.Equal(@"CustomToolTest.SR1", resourceNames[0].ItemSpec);
        }

        /// <summary>
        /// helper method for verifying manifest resource names
        /// </summary>
        private void VerifyExpectedManifestResourceName(string resourcePath, string expectedName)
        {
            string result = CreateCSharpManifestResourceName.CreateManifestNameImpl(resourcePath, null, true, "Root", null, null, null, null);
            string expected = "Root." + expectedName;

            Assert.Equal(result, expected);
        }

        /// <summary>
        /// Need to convert any spaces in the directory name of embedded resource files to underscores.
        /// Leave spaces in the file name itself alone. That's how Everett did it.
        /// </summary>
        [Fact]
        public void Regress309027()
        {
            VerifyExpectedManifestResourceName(
                @"SubFolder With Spaces\Splash Screen.bmp", "SubFolder_With_Spaces.Splash Screen.bmp");
        }

        /// <summary>
        /// The folder part of embedded resource names (not the file name though) needs to be a proper identifier,
        /// since that's how Everett used to do this
        /// </summary>
        [Fact]
        public void Regress311473()
        {
            // First char must be a letter or a connector (underscore), others must be a letter/digit/connector or a combining mark
            // If the first character is not a valid first character but valid subsequent character, the name is prepended
            // with an underscore. Invalid subsequent characters are replaced with an underscore.
            VerifyExpectedManifestResourceName(@"1abc()\pic.bmp", "_1abc__.pic.bmp");

            // if the first character is not a valid id character at all, it's replaced with an underscore instead of
            // prepending an underscore to it
            VerifyExpectedManifestResourceName(@"@abc\pic.bmp", "_abc.pic.bmp");

            // Each folder name is processed independently
            VerifyExpectedManifestResourceName(@"1234\1abc\pic.bmp", "_1234._1abc.pic.bmp");

            // Each part of folder name separated by dots is processed independently as well
            VerifyExpectedManifestResourceName(@"1abc.@abc@._1234()\pic.bmp", "_1abc._abc_._1234__.pic.bmp");
            VerifyExpectedManifestResourceName(@"1abc\@abc@\_1234()\pic.bmp", "_1abc._abc_._1234__.pic.bmp");

            // Combination of dots and folders
            VerifyExpectedManifestResourceName(@"@Ab2.=gh\1hl.l=a1\pic.bmp", "_Ab2._gh._1hl.l_a1.pic.bmp");

            // A single underscore folder name is expanded to two underscores
            VerifyExpectedManifestResourceName(@"_\pic.bmp", "__.pic.bmp");

            // A more complex example of the last rule
            VerifyExpectedManifestResourceName(@"_\__\_.__\_\pic.bmp", "__.__._.__.__.pic.bmp");
        }

        /// <summary>
        /// If the dependent upon filename and the resource filename both contain what looks like
        /// a culture, do not treat it as a culture identifier.  E.g.:
        ///
        ///     Form1.ro.resx == DependentUpon ==> Form1.ro.vb
        ///
        /// In this case, we don't include "ro" as the culture because it's in both filenames.  In
        /// the case of:
        ///
        ///     Form1.ro.resx == DependentUpon ==> Form1.vb
        ///
        /// we continue to treat "ro" as the culture.
        /// </summary>
        [Fact]
        public void Regress419591()
        {
            string result =
            CreateCSharpManifestResourceName.CreateManifestNameImpl
                (
                    "MyForm.en-GB.resx",
                    null,
                    true,
                    "RootNamespace",    // Root namespace (will be ignored because it's dependent)
                    "MyForm.en-GB.cs",
                    null,
                    StreamHelpers.StringToStream("namespace ClassLibrary1 { class MyForm {} }"),
                    null
                );

            Assert.Equal("ClassLibrary1.MyForm", result);
        }

        /// <summary>
        /// If the dependent upon filename and the resource filename both contain what looks like
        /// a culture, do not treat it as a culture identifier.  E.g.:
        ///
        ///     Form1.ro.resx == DependentUpon ==> Form1.ro.vb
        ///
        /// In this case, we don't include "ro" as the culture because it's in both filenames.  If
        /// The parent source file doesn't have a class name in it, we just use the culture neutral
        /// filename of the resource file.
        /// </summary>
        [Fact]
        public void Regress419591_EmptySource()
        {
            string result =
            CreateCSharpManifestResourceName.CreateManifestNameImpl
                (
                    "MyForm.en-GB.resx",
                    null,
                    true,
                    "RootNamespace",
                    "MyForm.en-GB.cs",
                    null,
                    StreamHelpers.StringToStream(""),
                    null
                );

            Assert.Equal("RootNamespace.MyForm.en-GB", result);
        }

        /// <summary>
        /// If we encounter a class or namespace name within a conditional compilation directive,
        /// we need to warn because we do not try to resolve the correct manifest name depending
        /// on conditional compilation of code.
        /// </summary>
        [Fact]
        public void Regress459265()
        {
            MockEngine m = new MockEngine();
            CreateCSharpManifestResourceName c = new CreateCSharpManifestResourceName();
            c.BuildEngine = m;

            string result =
            CreateCSharpManifestResourceName.CreateManifestNameImpl
                (
                    "MyForm.resx",
                    null,
                    true,
                    "RootNamespace",    // Root namespace (will be ignored because it's dependent)
                    "MyForm.cs",
                    null,
                    StreamHelpers.StringToStream(
@"using System;
#if false
namespace ClassLibrary1
#endif
#if Debug
namespace ClassLibrary2
#else
namespace ClassLibrary3
#endif
{
    class MyForm
    {
    }
}"
                    ),
                    c.Log
                );

            Assert.True(
                m.Log.Contains
                (
                    String.Format(AssemblyResources.GetString("CreateManifestResourceName.DefinitionFoundWithinConditionalDirective"), "MyForm.cs", "MyForm.resx")
                )
            );
        }

        /// <summary>
        /// Given a file path, return a stream on top of that path.
        /// </summary>
        /// <param name="path">Path to the file</param>
        /// <param name="mode">File mode</param>
        /// <param name="access">Access type</param>
        /// <returns>The Stream</returns>
        private Stream CreateFileStream(string path, FileMode mode, FileAccess access)
        {
            if (String.Compare(path, "SR1.strings", StringComparison.OrdinalIgnoreCase) == 0)
            {
                return StreamHelpers.StringToStream("namespace MyStuff.Namespace { class Class {} }");
            }
            Assert.True(false, String.Format("Encountered a new path {0}, needs unittesting support", path));
            return null;
        }

        /// <summary>
        /// Tests to ensure that the ResourceFilesWithManifestResourceNames contains everything that
        /// the ResourceFiles property on the task contains, but with additional metadata called ManifestResourceName
        /// </summary>
        [Fact]
        public void ResourceFilesWithManifestResourceNamesContainsAdditionalMetadata()
        {
            CreateCSharpManifestResourceName t = new CreateCSharpManifestResourceName();

            t.BuildEngine = new MockEngine();
            ITaskItem i = new TaskItem("strings.resx");

            t.ResourceFiles = new ITaskItem[] { i };
            t.RootNamespace = "ResourceRoot";
            bool success = t.Execute();

            Assert.True(success); // "Expected the task to succceed."

            ITaskItem[] resourceFiles = t.ResourceFilesWithManifestResourceNames;

            Assert.Equal(1, resourceFiles.Length);
            Assert.Equal(@"strings.resx", resourceFiles[0].ItemSpec);
            Assert.Equal(@"ResourceRoot.strings", resourceFiles[0].GetMetadata("ManifestResourceName"));
        }

        /// <summary>
        /// Ensure that if no LogicalName is specified, that the same ManifestResourceName metadata
        /// gets applied as LogicalName
        /// </summary>
        [Fact]
        public void AddLogicalNameForNonResx()
        {
            CreateCSharpManifestResourceName t = new CreateCSharpManifestResourceName();

            t.BuildEngine = new MockEngine();
            ITaskItem i = new TaskItem("pic.bmp");
            i.SetMetadata("Type", "Non-Resx");

            t.ResourceFiles = new ITaskItem[] { i };
            t.RootNamespace = "ResourceRoot";
            bool success = t.Execute();

            Assert.True(success); // "Expected the task to succceed."

            ITaskItem[] resourceFiles = t.ResourceFilesWithManifestResourceNames;

            Assert.Equal(1, resourceFiles.Length);
            Assert.Equal(@"pic.bmp", resourceFiles[0].ItemSpec);
            Assert.Equal(@"ResourceRoot.pic.bmp", resourceFiles[0].GetMetadata("LogicalName"));
        }

        /// <summary>
        /// Ensure that a LogicalName that is already present is preserved during manifest name generation
        /// </summary>
        [Fact]
        public void PreserveLogicalNameForNonResx()
        {
            CreateCSharpManifestResourceName t = new CreateCSharpManifestResourceName();

            t.BuildEngine = new MockEngine();
            ITaskItem i = new TaskItem("pic.bmp");
            i.SetMetadata("LogicalName", "foo");
            i.SetMetadata("Type", "Non-Resx");

            t.ResourceFiles = new ITaskItem[] { i };
            t.RootNamespace = "ResourceRoot";
            bool success = t.Execute();

            Assert.True(success); // "Expected the task to succceed."

            ITaskItem[] resourceFiles = t.ResourceFilesWithManifestResourceNames;

            Assert.Equal(1, resourceFiles.Length);
            Assert.Equal(@"pic.bmp", resourceFiles[0].ItemSpec);
            Assert.Equal(@"foo", resourceFiles[0].GetMetadata("LogicalName"));
        }

        /// <summary>
        /// Resx resources should not get ManifestResourceName metadata copied to the LogicalName value
        /// </summary>
        [Fact]
        public void NoLogicalNameAddedForResx()
        {
            CreateCSharpManifestResourceName t = new CreateCSharpManifestResourceName();

            t.BuildEngine = new MockEngine();
            ITaskItem i = new TaskItem("strings.resx");
            i.SetMetadata("Type", "Resx");

            t.ResourceFiles = new ITaskItem[] { i };
            t.RootNamespace = "ResourceRoot";
            bool success = t.Execute();

            Assert.True(success); // "Expected the task to succceed."

            ITaskItem[] resourceFiles = t.ResourceFilesWithManifestResourceNames;

            Assert.Equal(1, resourceFiles.Length);
            Assert.Equal(@"strings.resx", resourceFiles[0].ItemSpec);
            Assert.Equal(String.Empty, resourceFiles[0].GetMetadata("LogicalName"));
        }

        /// <summary>
        /// A culture-specific resources file in a subfolder, with a root namespace
        /// </summary>
        [Fact]
        public void CulturedResourcesFileWithRootNamespaceWithinSubfolder()
        {
            string result =
            CreateCSharpManifestResourceName.CreateManifestNameImpl
                (
                    @"SubFolder\MyResource.fr.resources",
                    null,    // Link file name
                    false,
                    "RootNamespace",        // Root namespace
                    null,
                    null,
                    null,
                    null
                );

            Assert.Equal(@"RootNamespace.SubFolder.MyResource.fr.resources", result);
        }

        /// <summary>
        /// A culture-specific resources file with a root namespace
        /// </summary>
        [Fact]
        public void CulturedResourcesFileWithRootNamespace()
        {
            string result =
            CreateCSharpManifestResourceName.CreateManifestNameImpl
                (
                    @"MyResource.fr.resources",
                    null,    // Link file name
                    false,
                    "RootNamespace",        // Root namespace
                    null,
                    null,
                    null,
                    null
                );

            Assert.Equal(@"RootNamespace.MyResource.fr.resources", result);
        }

        /// <summary>
        /// A non-culture-specific resources file with a root namespace
        /// </summary>
        [Fact]
        public void ResourcesFileWithRootNamespace()
        {
            string result =
            CreateCSharpManifestResourceName.CreateManifestNameImpl
                (
                    @"MyResource.resources",
                    null,    // Link file name
                    false,
                    "RootNamespace",        // Root namespace
                    null,
                    null,
                    null,
                    null
                );

            Assert.Equal(@"RootNamespace.MyResource.resources", result);
        }
    }
}


text:
using Chemistry;
using EngineLayer;
using EngineLayer.ClassicSearch;
using EngineLayer.Indexing;
using EngineLayer.ModernSearch;
using MassSpectrometry;
using MzLibUtil;
using NUnit.Framework;
using Proteomics;
using Proteomics.Fragmentation;
using Proteomics.ProteolyticDigestion;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using TaskLayer;
using UsefulProteomicsDatabases;

namespace Test
{
    [TestFixture]
    internal static class AddCompIonsTest
    {
        [Test]
        public static void TestAddCompIonsClassic()
        {
            var myMsDataFile = new TestDataFile();
            var variableModifications = new List<Modification>();
            var fixedModifications = new List<Modification>();
            var proteinList = new List<Protein> { new Protein("QXQ", null) };

            var productMassTolerance = new AbsoluteTolerance(0.01);
            var searchModes = new OpenSearchMode();

            Tolerance DeconvolutionMassTolerance = new PpmTolerance(5);

            var listOfSortedms2Scans = MetaMorpheusTask.GetMs2Scans(myMsDataFile, null, new CommonParameters()).OrderBy(b => b.PrecursorMass).ToArray();

            List<DigestionMotif> motifs = new List<DigestionMotif> { new DigestionMotif("K", null, 1, null) };
            Protease protease = new Protease("Custom Protease3", CleavageSpecificity.Full, null, null, motifs);
            ProteaseDictionary.Dictionary.Add(protease.Name, protease);

            CommonParameters CommonParameters = new CommonParameters(
                digestionParams: new DigestionParams(protease: protease.Name, maxMissedCleavages: 0, minPeptideLength: 1),
                scoreCutoff: 1,
                addCompIons: false);
            var fsp = new List<(string fileName, CommonParameters fileSpecificParameters)>();
            fsp.Add(("", CommonParameters));
            PeptideSpectralMatch[] allPsmsArray = new PeptideSpectralMatch[listOfSortedms2Scans.Length];

            bool writeSpectralLibrary = false;
            new ClassicSearchEngine(allPsmsArray, listOfSortedms2Scans, variableModifications, fixedModifications, null, null, null,
                proteinList, searchModes, CommonParameters, fsp, null, new List<string>(), writeSpectralLibrary).Run();

            CommonParameters CommonParameters2 = new CommonParameters(
                digestionParams: new DigestionParams(protease: protease.Name, maxMissedCleavages: 0, minPeptideLength: 1),
                scoreCutoff: 1,
                addCompIons: true);
            var fsp2 = new List<(string fileName, CommonParameters fileSpecificParameters)>();
            fsp2.Add(("", CommonParameters2));
            PeptideSpectralMatch[] allPsmsArray2 = new PeptideSpectralMatch[listOfSortedms2Scans.Length];

            new ClassicSearchEngine(allPsmsArray2, listOfSortedms2Scans, variableModifications, fixedModifications, null, null, null,
                proteinList, searchModes, CommonParameters2, fsp2, null, new List<string>(), writeSpectralLibrary).Run();

            double scoreT = allPsmsArray2[0].Score;
            double scoreF = allPsmsArray[0].Score;

            // Single search mode
            Assert.AreEqual(allPsmsArray.Length, allPsmsArray2.Length);

            // Single ms2 scan
            Assert.AreEqual(allPsmsArray.Length, allPsmsArray2.Length);

            Assert.IsTrue(scoreT > 1);

            Assert.AreEqual(allPsmsArray[0].ScanNumber, allPsmsArray2[0].ScanNumber);

            Assert.IsTrue(scoreT == scoreF * 3 && scoreT > scoreF + 2);
        }

        [Test]
        public static void TestCompIons_ModernSearch()
        {
            var myMsDataFile = new TestDataFile();
            var variableModifications = new List<Modification>();
            var fixedModifications = new List<Modification>();
            var localizeableModifications = new List<Modification>();
            Dictionary<Modification, ushort> modsDictionary = new Dictionary<Modification, ushort>();
            foreach (var mod in fixedModifications)
            {
                modsDictionary.Add(mod, 0);
            }

            int ii = 1;
            foreach (var mod in variableModifications)
            {
                modsDictionary.Add(mod, (ushort)ii);
                ii++;
            }
            foreach (var mod in localizeableModifications)
            {
                modsDictionary.Add(mod, (ushort)ii);
                ii++;
            }

            var proteinList = new List<Protein> { new Protein("MNNNKQQQ", null) };

            SearchParameters SearchParameters = new SearchParameters
            {
                MassDiffAcceptorType = MassDiffAcceptorType.Exact,
                SearchTarget = true,
            };
            List<DigestionMotif> motifs = new List<DigestionMotif> { new DigestionMotif("K", null, 1, null) };
            Protease protease = new Protease("singleN4", CleavageSpecificity.Full, null, null, motifs);
            ProteaseDictionary.Dictionary.Add(protease.Name, protease);
            CommonParameters CommonParameters = new CommonParameters(digestionParams: new DigestionParams(protease: protease.Name, minPeptideLength: 1), scoreCutoff: 1);
            var fsp = new List<(string fileName, CommonParameters fileSpecificParameters)>();
            fsp.Add(("", CommonParameters));

            CommonParameters withCompIons = new CommonParameters(digestionParams: new DigestionParams(protease: protease.Name, minPeptideLength: 1), scoreCutoff: 1, addCompIons: true);
            var fspComp = new List<(string fileName, CommonParameters fileSpecificParameters)>();
            fspComp.Add(("", CommonParameters));

            var indexEngine = new IndexingEngine(proteinList, variableModifications, fixedModifications, null, null, null,
                 1, DecoyType.Reverse, CommonParameters, fsp, SearchParameters.MaxFragmentSize, false, new List<FileInfo>(), TargetContaminantAmbiguity.RemoveContaminant, new List<string>());

            var indexResults = (IndexingResults)indexEngine.Run();

            Tolerance DeconvolutionMassTolerance = new PpmTolerance(5);

            var listOfSortedms2Scans = MetaMorpheusTask.GetMs2Scans(myMsDataFile, null, new CommonParameters()).OrderBy(b => b.PrecursorMass).ToArray();

            MassDiffAcceptor massDiffAcceptor = SearchTask.GetMassDiffAcceptor(CommonParameters.PrecursorMassTolerance, SearchParameters.MassDiffAcceptorType, SearchParameters.CustomMdac);

            // without complementary ions
            PeptideSpectralMatch[] allPsmsArray = new PeptideSpectralMatch[listOfSortedms2Scans.Length];
            new ModernSearchEngine(allPsmsArray, listOfSortedms2Scans, indexResults.PeptideIndex, indexResults.FragmentIndex, 0, CommonParameters, fsp, massDiffAcceptor, SearchParameters.MaximumMassThatFragmentIonScoreIsDoubled, new List<string>()).Run();

            // with complementary ions
            PeptideSpectralMatch[] allPsmsArray2 = new PeptideSpectralMatch[listOfSortedms2Scans.Length];
            new ModernSearchEngine(allPsmsArray2, listOfSortedms2Scans, indexResults.PeptideIndex, indexResults.FragmentIndex, 0, withCompIons, fspComp, massDiffAcceptor, SearchParameters.MaximumMassThatFragmentIonScoreIsDoubled, new List<string>()).Run();

            // Single search mode
            Assert.AreEqual(allPsmsArray.Length, allPsmsArray2.Length);

            // Single ms2 scan
            Assert.AreEqual(allPsmsArray.Length, allPsmsArray2.Length);
            Assert.That(allPsmsArray[0] != null);
            Assert.That(allPsmsArray2[0] != null);

            Assert.IsTrue(allPsmsArray2[0].Score > 1);

            Assert.AreEqual(allPsmsArray[0].ScanNumber, allPsmsArray2[0].ScanNumber);

            Assert.IsTrue(allPsmsArray2[0].Score <= allPsmsArray[0].Score * 2 && allPsmsArray2[0].Score > allPsmsArray[0].Score + 3);
        }

        public static void TestCompIons_MatchIonsScore()
        {
            TestDataFile t = new TestDataFile();
            Tolerance productMassTolerance = new AbsoluteTolerance(0.01);
            double precursorMass = 300;
            //The below theoretical does not accurately represent B-Y ions
            double[] sorted_theoretical_product_masses_for_this_peptide = new double[] { precursorMass + (2 * Constants.ProtonMass) - 275.1350, precursorMass + (2 * Constants.ProtonMass) - 258.127, precursorMass + (2 * Constants.ProtonMass) - 257.1244, 50, 60, 70, 147.0764, precursorMass + (2 * Constants.ProtonMass) - 147.0764, precursorMass + (2 * Constants.ProtonMass) - 70, precursorMass + (2 * Constants.ProtonMass) - 60, precursorMass + (2 * Constants.ProtonMass) - 50, 257.1244, 258.127, 275.1350 }; //{ 50, 60, 70, 147.0764, 257.1244, 258.127, 275.1350 }
            List<Product> productsWithLocalizedMassDiff = new List<Product>();
            foreach (double d in sorted_theoretical_product_masses_for_this_peptide)
            {
                productsWithLocalizedMassDiff.Add(new Product(ProductType.b, FragmentationTerminus.Both, d, 1, 1, 0));
            }
            CommonParameters commonParametersNoComp = new CommonParameters { ProductMassTolerance = new AbsoluteTolerance(0.01) };
            CommonParameters commonParametersWithComp = new CommonParameters(productMassTolerance: new AbsoluteTolerance(0.01), addCompIons: true);

            MsDataScan scan = t.GetOneBasedScan(2);
            var scanWithMass = new Ms2ScanWithSpecificMass(scan, precursorMass.ToMz(1), 1, "", new CommonParameters());
            List<MatchedFragmentIon> matchedIons = MetaMorpheusEngine.MatchFragmentIons(scanWithMass, productsWithLocalizedMassDiff, commonParametersNoComp);

            List<MatchedFragmentIon> matchedCompIons = MetaMorpheusEngine.MatchFragmentIons(scanWithMass, productsWithLocalizedMassDiff, commonParametersWithComp);
            matchedCompIons.AddRange(matchedIons);

            // score when the mass-diff is on this residue
            double localizedScore = MetaMorpheusEngine.CalculatePeptideScore(scan, matchedIons);
            double scoreNormal = MetaMorpheusEngine.CalculatePeptideScore(scan, matchedIons);
            double scoreComp = MetaMorpheusEngine.CalculatePeptideScore(scan, matchedCompIons);
            Assert.IsTrue(scoreNormal * 2 == scoreComp && scoreComp > scoreNormal + 1);
        }

        [Test]
        public static void TestCompIons_MatchIons()
        {
            TestDataFile t = new TestDataFile(0.0001);
            Tolerance productMassTolerance = new AbsoluteTolerance(0.01);
            double precursorMass = 402.18629720155;
            //The below theoretical does not accurately represent B-Y ions
            double[] sorted_theoretical_product_masses_for_this_peptide = new double[] { 50, 60, 70, 147.0764 - Constants.ProtonMass, 200, 215, 230, 245, precursorMass + Constants.ProtonMass - 147.0764, 258.127, 275.1350, precursorMass + (2 * Constants.ProtonMass) - 70, precursorMass + (2 * Constants.ProtonMass) - 60, precursorMass + (2 * Constants.ProtonMass) - 50 }; //{ 50, 60, 70, 147.0764, 257.1244, 258.127, 275.1350 }
            List<double> matchedIonMassesT = new List<double>();
            List<double> matchedDaErrorT = new List<double>();
            List<double> matchedPpmErrorT = new List<double>();
            List<double> matchedIonIntensityT = new List<double>();
            List<double> matchedIonMassesF = new List<double>();
            List<double> matchedDaErrorF = new List<double>();
            List<double> matchedPpmErrorF = new List<double>();
            List<double> matchedIonIntensityF = new List<double>();

            List<int> matchedIonSeriesT = new List<int>();
            List<int> matchedIonSeriesF = new List<int>();

            //MetaMorpheusEngine.MatchIons(t.GetOneBasedScan(2), productMassTolerance, sorted_theoretical_product_masses_for_this_peptide, matchedIonSeriesT, matchedIonMassesT, matchedDaErrorT, matchedPpmErrorT, matchedIonIntensityT, precursorMass, ProductType.B, true);
            //MetaMorpheusEngine.MatchIons(t.GetOneBasedScan(2), productMassTolerance, sorted_theoretical_product_masses_for_this_peptide, matchedIonSeriesF, matchedIonMassesF, matchedDaErrorF, matchedPpmErrorF, matchedIonIntensityF, precursorMass, ProductType.B, false);

            //Test the number of series is doubled
            Assert.IsTrue(matchedIonSeriesT.Count == matchedIonSeriesF.Count * 2);
            //Test the number of ions is doubled
            Assert.IsTrue(matchedIonMassesT.Count == matchedIonMassesF.Count * 2);
            //Test the number of da errors is doubled
            Assert.IsTrue(matchedDaErrorT.Count == matchedDaErrorF.Count * 2);
            //test the number of ppm errors is doubled
            Assert.IsTrue(matchedPpmErrorT.Count == matchedPpmErrorF.Count * 2);
            //test the number of the intensity values is doubled
            Assert.IsTrue(matchedIonIntensityT.Count == matchedIonIntensityF.Count * 2);
            foreach (double d in matchedDaErrorF)
            {
                Assert.IsTrue(d <= 0.01);
            }

            foreach (double d in matchedDaErrorT)
            {
                Assert.IsTrue(d <= 0.01);
            }
        }

        [Test]
        public static void AddCompIonsCommonParams()
        {
            CommonParameters cp = new CommonParameters(null, DissociationType.HCD, DissociationType.Unknown, DissociationType.Unknown, null, true, true, 3, 12, true, true, 1,
                5, 200, 0.01, null, null, false, false, true, false, null, null, null, -1, null, null, null, 1, 1, true, 4, 1);

            var myMsDataFile = new TestDataFile();
            var variableModifications = new List<Modification>();
            var fixedModifications = new List<Modification>();
            var localizeableModifications = new List<Modification>();
            Dictionary<Modification, ushort> modsDictionary = new Dictionary<Modification, ushort>();
            foreach (var mod in fixedModifications)
            {
                modsDictionary.Add(mod, 0);
            }

            int ii = 1;
            foreach (var mod in variableModifications)
            {
                modsDictionary.Add(mod, (ushort)ii);
                ii++;
            }
            foreach (var mod in localizeableModifications)
            {
                modsDictionary.Add(mod, (ushort)ii);
                ii++;
            }

            var proteinList = new List<Protein> { new Protein("MNNNKQQQ", null) };

            SearchParameters SearchParameters = new SearchParameters
            {
                MassDiffAcceptorType = MassDiffAcceptorType.Exact,
                SearchTarget = true,
            };
            List<DigestionMotif> motifs = new List<DigestionMotif> { new DigestionMotif("K", null, 1, null) };
            Protease protease = new Protease("Test", CleavageSpecificity.Full, null, null, motifs);
            ProteaseDictionary.Dictionary.Add(protease.Name, protease);

            var fsp = new List<(string fileName, CommonParameters fileSpecificParameters)>();
            fsp.Add(("", cp));

            var indexEngine = new IndexingEngine(proteinList, variableModifications, fixedModifications, new List<SilacLabel>(), null, null,
                 1, DecoyType.Reverse, cp, fsp, SearchParameters.MaxFragmentSize, false, new List<FileInfo>(), TargetContaminantAmbiguity.RemoveContaminant, new List<string>());

            var indexResults = (IndexingResults)indexEngine.Run();

            Tolerance DeconvolutionMassTolerance = new PpmTolerance(5);

            var listOfSortedms2Scans = MetaMorpheusTask.GetMs2Scans(myMsDataFile, null, new CommonParameters()).OrderBy(b => b.PrecursorMass).ToArray();

            MassDiffAcceptor massDiffAcceptor = SearchTask.GetMassDiffAcceptor(cp.PrecursorMassTolerance, SearchParameters.MassDiffAcceptorType, SearchParameters.CustomMdac);

            // without complementary ions
            PeptideSpectralMatch[] allPsmsArray = new PeptideSpectralMatch[listOfSortedms2Scans.Length];
            var mse = new ModernSearchEngine(allPsmsArray, listOfSortedms2Scans, indexResults.PeptideIndex, indexResults.FragmentIndex, 0, cp, fsp, massDiffAcceptor, SearchParameters.MaximumMassThatFragmentIonScoreIsDoubled, new List<string>()).Run();
        }

        [Test]
        public static void AddCompIonsMzOutput()
        {
            PeptideWithSetModifications pwsm = new PeptideWithSetModifications("ASDFASDF",null);
            Ms2ScanWithSpecificMass testScan = MetaMorpheusTask.GetMs2Scans(new TestDataFile(pwsm), null, new CommonParameters()).OrderBy(b => b.PrecursorMass).First();

            CommonParameters cp = new CommonParameters(addCompIons: true);
            List<Product> theoreticalIons = new List<Product>();
            pwsm.Fragment(cp.DissociationType, FragmentationTerminus.Both, theoreticalIons);
            List<MatchedFragmentIon> matchedIons = MetaMorpheusEngine.MatchFragmentIons(testScan, theoreticalIons, cp);

            //check that the matchedIons have m/z values that are similar to their neutral mass.
            //There was an "issue" where the saved m/z was the original experimental peak (which is the complementary of the added ion).
            //A fix was introduced to save a "fake" m/z for the added ion
            foreach(MatchedFragmentIon ion in matchedIons)
            {
                Assert.IsTrue(ion.NeutralTheoreticalProduct.NeutralMass < ion.Mz);
                Assert.IsTrue(ion.NeutralTheoreticalProduct.NeutralMass + 2 > ion.Mz);
            }

        }
    }
}


text: from .utils import load_zones


text:
//
//  InAppPurchaseManager.m
//  RoN
//
//  Created by CoA Studio on 13-3-18.
//
//
#import "InAppPurchase_oc.h"
#import <Foundation/Foundation.h>
#include "IAPDefine.h"

@implementation InAppPurchase_oc
-(void)initIAP
{
    //监听购买状态
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    NSArray<SKPaymentTransaction *> *arr = [[SKPaymentQueue defaultQueue] transactions];
    for (SKPaymentTransaction *transaction in arr){
        NSLog(@"-----[EZIAP InAppPurchase_oc] initIAP finishTransaction productID = %@, transactionIdentifier = %@",transaction.payment.productIdentifier, transaction.transactionIdentifier);
        [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
    }
    _billNo = nil;
    _productId = nil;
}

-(void)buy:(NSString *)product andBillNO:(NSString*)bNo{
    if ([SKPaymentQueue canMakePayments]){
        _billNo = [bNo copy];
        _productId = [product copy];
        NSLog(@"-----[EZIAP InAppPurchase_oc] start buy productyID = %@ ,billNO = %@",_productId,_billNo);
        NSArray *productArray = [[NSArray alloc] initWithObjects:_productId, nil];
        NSSet *nsset = [NSSet setWithArray:productArray];
        SKProductsRequest *request=[[SKProductsRequest alloc] initWithProductIdentifiers: nsset];
        request.delegate=self;
        [request start];
    }else
    {
        NSLog(@"-----[EZIAP InAppPurchase_oc] This device is not able or allowed to make payments.");
        [self.delegate errorHandler:[self errorWithCode:ErrorPaymentNotAllowed andDesc:@"This device is not able or allowed to make payments."] withProductID:product andBillNO:bNo];
    }
}

-(void)getProductList:(NSArray *)productIds
{
    _productId = nil;
    _billNo = nil;
    NSSet *nsset = [NSSet setWithArray:productIds];
    SKProductsRequest *request=[[SKProductsRequest alloc] initWithProductIdentifiers: nsset];
    request.delegate=self;
    [request start];
}

///<SKProductsRequestDelegate> 请求协议
#pragma mark -
#pragma mark SKProductsRequestDelegate
//收到的产品信息
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
    NSLog(@"-----[EZIAP InAppPurchase_oc] Begin *************** ");
    NSArray *myProduct = response.products;
    if ([response.invalidProductIdentifiers count] > 0){
        NSLog(@"invalidProductIdentifiers :%@",response.invalidProductIdentifiers);
    }
    NSLog(@"productlist count: %lu", (unsigned long)[myProduct count]);
    SKProduct *cproduct = nil;
    for(SKProduct *product in myProduct){
//        NSLog(@"SKProduct 描述信息%@", [product description]);
        NSLog(@"");
        NSLog(@"title %@" , [product localizedTitle]);
        NSLog(@"localizedDescription: %@" , [product localizedDescription]);
        NSLog(@"price: %@" , [product price]);
        NSLog(@"productIdentifier: %@" , [product productIdentifier]);
        NSString *pId = [product productIdentifier];
        if (  _productId != nil && [_productId isEqualToString:pId] ){
            cproduct = product;
        }
        NSLog(@"");
    }
    if (cproduct!=nil)
    {
        SKMutablePayment *payment = [SKMutablePayment paymentWithProduct:cproduct];
        if (_billNo != nil){
            payment.applicationUsername = _billNo;
        }
        NSLog(@" start pay productId = %@ billNO = %@ ------------", _productId ,_billNo);
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    }else if ( _productId == nil )
    {
        NSMutableArray *plistArray = [[NSMutableArray alloc] init];
        for(SKProduct *product in myProduct){
            NSString *title= product.localizedTitle;
            NSString *description= product.localizedDescription;
            NSString *price= [NSString stringWithFormat:@"%f",product.price.doubleValue];
            NSString *productid= product.productIdentifier;
            NSDictionary *pdata = [NSDictionary dictionaryWithObjectsAndKeys:title,@"title", description,@"description", price ,@"price", productid ,@"productid",nil];
            [plistArray addObject:pdata];
        }
        [self.delegate productList:plistArray];
//        if ( [NSJSONSerialization isValidJSONObject:plistArray] ){
//            NSError *error;
//            NSData * data = [NSJSONSerialization dataWithJSONObject:plistArray options:0 error:&error];
//            NSString * jsonString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//            NSLog(@"[InAppPurchase_oc] skproducts info: %@",jsonString);
//        }
    }else{
        NSLog(@"The selected item cannot be purchased.check your appstoreconnect ! productId = %@------------", _productId );
        [self.delegate errorHandler:[self errorWithCode:ErrorStoreProductNotAvailable andDesc:@"The selected item cannot be purchased."] withProductID:_productId andBillNO:self.billNo];
    }
    NSLog(@"-----[EZIAP InAppPurchase_oc] End ***************");
}

#pragma mark -
#pragma mark SKRequestDelegate
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    NSLog(@"-----[EZIAP InAppPurchase_oc]  SKRequest didFailWithError ----------");
    [self.delegate errorHandler:error withProductID:_productId andBillNO:self.billNo];
}

-(void) requestDidFinish:(SKRequest *)request
{
    NSLog(@"-----[EZIAP InAppPurchase_oc] SKRequest requestDidFinish----");
    [self.delegate productRequestFinishWithProductID:_productId andBillNO:self.billNo];
}

#pragma mark —— return a NSError
- (NSError *)errorWithCode:(int)code andDesc:(NSString*)localizedDescription{
    NSDictionary * userInfo = [NSDictionary dictionaryWithObject:localizedDescription forKey:NSLocalizedDescriptionKey];
    NSError * aError = [NSError errorWithDomain:NSCocoaErrorDomain code:code userInfo:userInfo];
    return aError;
}

-(void) PurchasedTransaction: (SKPaymentTransaction *)transaction
{
    NSLog(@"-----[EZIAP InAppPurchase_oc] PurchasedTransaction----");
    NSArray *transactions =[[NSArray alloc] initWithObjects:transaction, nil];
    [self paymentQueue:[SKPaymentQueue defaultQueue] updatedTransactions:transactions];
}

/**** 监听交易状态  ***/
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions//交易结果
{
    NSLog(@"-----[EZIAP InAppPurchase_oc] paymentQueue updatedTransactions --------");
    for (SKPaymentTransaction *transaction in transactions)
    {
        switch (transaction.transactionState)
        {
            case SKPaymentTransactionStatePurchased://交易完成
            {
                NSLog(@"-----[EZIAP InAppPurchase_oc] SKPaymentTransactionStatePurchased --------");
                [self completeTransaction:transaction];
                break;
            }
            case SKPaymentTransactionStateFailed://交易失败
            {
                NSError *error = transaction.error;
                NSLog(@"-----[EZIAP InAppPurchase_oc] SKPaymentTransactionStateFailed errorCode = %ld; msg = %@ ",error.code,[error localizedDescription]);
                [self failedTransaction:transaction];
                break;
            }
            case SKPaymentTransactionStateRestored://已经购买过该商品
            {
                NSLog(@"-----[EZIAP InAppPurchase_oc] SKPaymentTransactionStateRestored --------");
                [self restoreTransaction:transaction];
                break;
            }
            case SKPaymentTransactionStatePurchasing:      //商品添加进列表
            {
                NSLog(@"-----[EZIAP InAppPurchase_oc] SKPaymentTransactionStatePurchasing --------");
                break;
            }
            default:
                NSLog(@"-----[EZIAP InAppPurchase_oc] transactionState %ld--------",(long)transaction.transactionState);
                break;
        }
    }
}

-(void) paymentQueueRestoreCompletedTransactionsFinished: (SKPaymentTransaction *)transaction{
    NSLog(@"-----[EZIAP InAppPurchase_oc] paymentQueueRestoreCompletedTransactionsFinished  ----");
    [self.delegate receiveTransaction:transaction andBillNO:self.billNo];
}

-(void) paymentQueue:(SKPaymentQueue *) paymentQueue restoreCompletedTransactionsFailedWithError:(NSError *)error{
    NSLog(@"-----[EZIAP InAppPurchase_oc] restoreCompletedTransactionsFailedWithError----");
    if (error != nil){
        [self.delegate errorHandler:error withProductID:self.productId andBillNO:self.billNo];
    }
}

- (void) completeTransaction: (SKPaymentTransaction *)transaction
{
    [self.delegate receiveTransaction:transaction andBillNO:self.billNo];
    // Remove the transaction from the payment queue.
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    _productId = nil;
    _billNo = nil;
}

- (void) restoreTransaction: (SKPaymentTransaction *)transaction
{
    [self.delegate receiveTransaction:transaction andBillNO:self.billNo];
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

- (void) failedTransaction: (SKPaymentTransaction *)transaction{
    [self.delegate receiveErrorTransaction:transaction andBillNO:self.billNo ];
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    _productId = nil;
    _billNo = nil;
}

-(void)dealloc
{
    _delegate = nil;
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}
@end


text:
package com.jumblar.core.spiral;

import java.util.HashSet;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

public class SpiralTest extends TestCase{

	public SpiralTest(String testName){
		super(testName);
	}

	public static Test suite(){
		return new TestSuite (SpiralTest.class);
	}

	public void testDoubleSpiral() throws Exception{
		int[] point1 = new int[]{0,0};
		int[] point2 = new int[]{0,0};
		HashSet<String> hSet = new HashSet<String>();

		DoubleSpiral ds = new DoubleSpiral(point1, point2);
		int amt = 2000;
		for (int i=0; i<amt; i++){
			int[][] item = ds.nextItem();
			hSet.add(str(item));
		}
		assertEquals(hSet.size(), amt);
	}

	public static String str(int[][] item){
		return item[0][0]+","+item[0][1]+"  "+item[1][0]+","+item[1][1];
	}

	public static void println(int[][] item){
		if(item == null){
			println("null");
			return;
		}
		String b = str(item);
		println (b);
	}

	public static void println(Object ob){
		System.out.println(""+ob);
	}
}


text:
require "message_store/version"
require 'securerandom'

module MessageStore
  module Backends
    autoload :File, 'message_store/backends/file'
    autoload :Rest, 'message_store/backends/rest'
  end

  def self.new(options = {})
    BackendsPool.new(options)
  end

  class BackendsPool
    def initialize(options = {})
      @backends_pool = {}
      options.each do |backend, options|
        @backends_pool[backend] = ::MessageStore::Backends.const_get(backend).new(options)
      end
    end

    def post(message = {})
      message_id = message.keys.first || SecureRandom.hex(16)

      threads = []
      @backends_pool.each_value do |store|
        threads  << Thread.new {
          store.post(message_id, message.values.first)
        }
      end
      threads.each(&:join)

      message_id
    end

    def []=(id, message)
      post(id => message)
    end
  end
end


text:
<?php

namespace Joindin\Api\Model;

use Exception;
use PDO;

class LanguageMapper extends ApiMapper
{
    /**
     * @return array
     */
    public function getDefaultFields()
    {
        return [
            'name' => 'lang_name',
            'code' => 'lang_abbr',
        ];
    }

    /**
     * @return array
     */
    public function getVerboseFields()
    {
        return [
            'name' => 'lang_name',
            'code' => 'lang_abbr',
        ];
    }

    /**
     * @param int  $language_id
     * @param bool $verbose
     *
     * @return false|array
     */
    public function getLanguageById($language_id, $verbose = false)
    {
        $results = $this->getLanguages(1, 0, ['ID' => (int)$language_id]);
        if ($results) {
            return $this->transformResults($results, $verbose);
        }

        return false;
    }

    /**
     * @param int  $resultsperpage
     * @param int  $start
     * @param bool $verbose
     *
     * @return false|array
     */
    public function getLanguageList($resultsperpage, $start = 0, $verbose = false)
    {
        $results = $this->getLanguages($resultsperpage, $start);
        if ($results) {
            return $this->transformResults($results, $verbose);
        }

        return false;
    }

    /**
     * @inheritdoc
     */
    public function transformResults(array $results, $verbose)
    {
        $total = $results['total'];
        unset($results['total']);

        $list = parent::transformResults($results, $verbose);

        $base    = $this->_request->base;
        $version = $this->_request->version;

        if (is_array($list) && count($list)) {
            foreach ($results as $key => $row) {
                $list[$key]['uri']         = $base . '/' . $version . '/languages/' . $row['ID'];
                $list[$key]['verbose_uri'] = $base . '/' . $version . '/languages/' . $row['ID'] . '?verbose=yes';
            }
        }

        return [
            'languages' => $list,
            'meta'      => $this->getPaginationLinks($list, $total)
        ];
    }

    /**
     * @param int   $resultsperpage
     * @param int   $start
     * @param array $params
     *
     * @return false|array
     */
    protected function getLanguages($resultsperpage, $start, array $params = [])
    {
        $sql = 'select l.ID, l.lang_name, l.lang_abbr ' .
               'from lang as l ';

        if (count($params) > 0) {
            $value = reset($params);
            $key   = key($params);

            $sql .= 'where l.' . $key . ' = :' . $key . ' ';

            if (count($params) > 1) {
                foreach ($params as $key => $value) {
                    $sql .= 'and l.' . $key . ' = :' . $key . ' ';
                }
            }
        }

        $sql .= 'order by l.lang_name ';
        $sql .= $this->buildLimit($resultsperpage, $start);

        $stmt     = $this->_db->prepare($sql);
        $response = $stmt->execute($params);
        if ($response) {
            $results          = $stmt->fetchAll(PDO::FETCH_ASSOC);
            $results['total'] = $this->getTotalCount($sql, $params);

            return $results;
        }

        return false;
    }

    /**
     * Check whether the given language is known to joindin
     *
     * @param string $language
     *
     * @return boolean
     */
    public function isLanguageValid($language)
    {
        $sql = 'select * from lang where lang_name = :language';

        $stmt = $this->_db->prepare($sql);
        try {
            $stmt->execute([':language' => $language]);
        } catch (Exception $e) {
            return false;
        }

        return count($stmt->fetchAll()) > 0;
    }
}


text:
using System;
using System.Collections.Generic;
using GalaSoft.MvvmLight.Command;
using Meridian.Resources.Localization;
using Meridian.Services;
using Neptune.Messages;
using VkLib.Core.Users;

namespace Meridian.ViewModel.People
{
    public class SubscriptionsViewModel : ViewModelBase
    {
        private List<VkProfile> _subscrptions;

        #region

        public RelayCommand<VkProfile> GoToSubscriptionCommand { get; private set; }

        #endregion

        public List<VkProfile> Subscriptions
        {
            get { return _subscrptions; }
            set
            {
                if (_subscrptions == value)
                    return;

                _subscrptions = value;
                RaisePropertyChanged("Subscriptions");
            }
        }

        public void Activate()
        {
            if (Subscriptions == null || Subscriptions.Count == 0)
                LoadSubscriptions();
        }

        public SubscriptionsViewModel()
        {
            RegisterTasks("subscriptions");

            InitializeCommands();
        }

        private void InitializeCommands()
        {
            GoToSubscriptionCommand = new RelayCommand<VkProfile>(subscription =>
            {
                MessengerInstance.Send(new NavigateToPageMessage()
                {
                    Page = "/People.FriendAudioView",
                    Parameters = new Dictionary<string, object>()
                    {
                        {"friend", subscription}
                    }
                });
            });
        }

        private async void LoadSubscriptions()
        {
            OnTaskStarted("subscriptions");

            try
            {
                var subscriptions = await DataService.GetSubscriptions(0, 0, "photo,photo_100,photo_400_orig");
                if (subscriptions.Items != null && subscriptions.Items.Count > 0)
                {
                    Subscriptions = subscriptions.Items;
                }
                else
                {
                    OnTaskError("subscriptions", ErrorResources.LoadSubscriptionsErrorEmpty);
                }
            }
            catch (Exception ex)
            {
                LoggingService.Log(ex);
                OnTaskError("subscriptions", ErrorResources.LoadSubscriptionsErrorCommon);
            }

            OnTaskFinished("subscriptions");
        }
    }
}


text:
using System.Web;
using System.Web.Optimization;

namespace ReverseProxy {
    public class BundleMobileConfig {
        public static void RegisterBundles(BundleCollection bundles) {
            bundles.Add(new ScriptBundle("~/bundles/jquerymobile")
                .Include("~/Scripts/jquery.mobile-{version}.js"));

            bundles.Add(new StyleBundle("~/Content/Mobile/css")
                .Include("~/Content/Site.Mobile.css"));

            bundles.Add(new StyleBundle("~/Content/jquerymobile/css")
                .Include("~/Content/jquery.mobile-{version}.css"));
        }
    }
}